Files
StudyDiary/.obsidian/plugins/copilot/main.js
T

5571 lines
5.1 MiB
Plaintext
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
// Polyfill for import.meta in CommonJS context
if (typeof import_meta === 'undefined') {
var import_meta = {
url: typeof __filename !== 'undefined' ? 'file://' + __filename : 'file:///obsidian-plugin'
};
}
// Minimal `process` shim so the bundle survives MODULE EVALUATION on Obsidian
// mobile, whose WebView has no Node `process` global. Desktop-only code (Agent
// Mode) is statically imported and therefore evaluated on every platform; many
// of those modules — and bundled Node deps — read `process.platform`/`.env` at
// module scope, which throws "Can't find variable: process" on mobile and kills
// the whole plugin at load. On desktop (Electron) `globalThis.process` exists
// and is used as-is, so this only stubs mobile, where those code paths never run.
var process = globalThis.process || {
env: {},
platform: '',
arch: '',
argv: [],
version: '',
versions: {},
cwd: function () { return '/'; },
nextTick: function (cb) { Promise.resolve().then(cb); },
on: function () {},
off: function () {},
once: function () {},
emit: function () { return false; },
};
var MTn=Object.create;var j5=Object.defineProperty;var OTn=Object.getOwnPropertyDescriptor;var NTn=Object.getOwnPropertyNames;var RTn=Object.getPrototypeOf,LTn=Object.prototype.hasOwnProperty;var lct=t=>{throw TypeError(t)};var $Tn=(t,e,n)=>e in t?j5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var b=(t,e)=>()=>(t&&(e=t(t=0)),e);var wi=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),sr=(t,e)=>{for(var n in e)j5(t,n,{get:e[n],enumerable:!0})},cct=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of NTn(e))!LTn.call(t,o)&&o!==n&&j5(t,o,{get:()=>e[o],enumerable:!(r=OTn(e,o))||r.enumerable});return t};var L=(t,e,n)=>(n=t!=null?MTn(RTn(t)):{},cct(e||!t||!t.__esModule?j5(n,"default",{value:t,enumerable:!0}):n,t)),DTn=t=>cct(j5({},"__esModule",{value:!0}),t);var M=(t,e,n)=>$Tn(t,typeof e!="symbol"?e+"":e,n),HPe=(t,e,n)=>e.has(t)||lct("Cannot "+n);var re=(t,e,n)=>(HPe(t,e,"read from private field"),n?n.call(t):e.get(t)),Rt=(t,e,n)=>e.has(t)?lct("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),Et=(t,e,n,r)=>(HPe(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),Je=(t,e,n)=>(HPe(t,e,"access private method"),n);var Hoe=(t,e,n,r)=>({set _(o){Et(t,e,o,n)},get _(){return re(t,e,r)}});function B5(t,e){return`${WPe}${t}/${encodeURIComponent(e)}`}function HF(t){return t.startsWith(WPe)}function z5(t){if(!HF(t))return null;let e=t.slice(WPe.length),n=e.indexOf("/");if(n<=0||n===e.length-1)return null;try{return{backendId:e.slice(0,n),sessionId:decodeURIComponent(e.slice(n+1))}}catch{return null}}var WPe,H5=b(()=>{WPe="copilot-agent-session://"});function uct(t,e=0){return(id[t[e+0]]+id[t[e+1]]+id[t[e+2]]+id[t[e+3]]+"-"+id[t[e+4]]+id[t[e+5]]+"-"+id[t[e+6]]+id[t[e+7]]+"-"+id[t[e+8]]+id[t[e+9]]+"-"+id[t[e+10]]+id[t[e+11]]+id[t[e+12]]+id[t[e+13]]+id[t[e+14]]+id[t[e+15]]).toLowerCase()}var id,dct=b(()=>{id=[];for(let t=0;t<256;++t)id.push((t+256).toString(16).slice(1))});function qPe(){if(!VPe){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");VPe=crypto.getRandomValues.bind(crypto)}return VPe(FTn)}var VPe,FTn,fct=b(()=>{FTn=new Uint8Array(16)});var UTn,KPe,pct=b(()=>{UTn=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),KPe={randomUUID:UTn}});function jTn(t,e,n){if(KPe.randomUUID&&!e&&!t)return KPe.randomUUID();t=t||{};let r=t.random??t.rng?.()??qPe();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return uct(r)}var Co,mct=b(()=>{pct();fct();dct();Co=jTn});var Gf=b(()=>{mct()});var oy,mw=b(()=>{oy=(r=>(r.LLM_CHAIN="llm_chain",r.VAULT_QA_CHAIN="vault_qa",r.COPILOT_PLUS_CHAIN="copilot_plus",r))(oy||{})});var W5=b(()=>{});var gct,q5,K5,Jp,Fs,Vd,WF,iT,oT,GPe,ZPe,yct,ar,pl,R_,VF,BTn,zTn,HTn,WTn,VTn,yC,qTn,Woe,YPe,vct,wct,G5,Xp,qF,Z5,FO,Y5,JPe,J5,XPe,QPe,Voe,eAe,vC,qoe,tAe,nAe,Koe,KTn,rAe,bct,gh,hw,_ct,V5,xct,L_,KF,UO,X5,oAe,Qp,Goe,GF,ht,jO,BO,iAe,Sct,Zoe,Cct,Yn,cs,gt=b(()=>{Gf();mw();W5();gct="https://www.obsidiancopilot.com/en/dashboard/token-usage",q5="https://www.miyo.md/",K5="https://api.brevilabs.com/v1",Jp="https://models.brevilabs.com/v1",Fs="copilot-chat-view",Vd="copilot-agent-chat-view",WF="agent",iT="copilot-relevant-notes-view",oT="copilot-agent",GPe="translate(0 8.2) scale(0.6579) translate(-4 -4)",ZPe="M75.9 6.9c-6.8 1.4-12.5 6-35.5 29.3-33.5 33.8-33.5 33.9-34.2 62.2-0.3 12.4 0 20.2 0.7 22.7 2.4 7.8 10.8 11.2 17.6 7.1 1.7-1.1 14.9-14.1 29.5-29.1 14.5-14.9 26.7-27 27-26.9 0.3 0.2 12.4 12.4 27 27.3 14.6 14.8 27.6 27.8 29 28.7 5.1 3.6 13.6 1.4 16.5-4.2 1.2-2.3 1.5-6.9 1.5-22.3 0-22.9-1.2-28.6-8.3-37.9-7.6-10.2-50-52.3-54.9-54.6-5.1-2.4-10.9-3.2-15.9-2.3z",yct=`<g transform="${GPe}"><path fill="currentColor" d="${ZPe}"/></g>`,ar="user",pl="ai",R_="copilot",VF=R_,BTn=`${R_}/copilot-conversations`,zTn=`${R_}/copilot-custom-prompts`,HTn=`${R_}/memory`,WTn=`${R_}/system-prompts`,VTn=`${R_}/projects`,yC=`${R_}/skills`,qTn="",Woe="copilot-conversation",YPe=R_,vct=`You are Obsidian Copilot, a helpful assistant that integrates AI to Obsidian note-taking.
1. Never mention that you do not have access to something. Always rely on the user provided context.
2. Always answer to the best of your knowledge. If you are unsure about something, say so and ask the user to provide more context.
3. If the user mentions "note", it most likely means an Obsidian note in the vault, not the generic meaning of a note.
4. If the user mentions "@vault", it means the user wants you to search the Obsidian vault for information relevant to the query. The search results will be provided to you in the context along with the user query, read it carefully and answer the question based on the information provided. If there's no relevant information in the vault, just say so.
5. If the user mentions any other tool with the @ symbol, check the context for their results. If nothing is found, just ignore the @ symbol in the query.
6. Always use $'s instead of \\[ etc. for LaTeX equations.
7. When showing note titles, use [[title]] format and do not wrap them in \` \`.
8. When showing **Obsidian internal** image links, use ![[link]] format and do not wrap them in \` \`.
9. When showing **web** image links, use ![link](url) format and do not wrap them in \` \`.
10. When generating a table, format as github markdown tables, however, for table headings, immediately add ' |' after the table heading.
11. Always respond in the language of the user's query.
12. Do NOT mention the additional context provided such as getCurrentTime and getTimeRangeMs if it's irrelevant to the user message.
13. If the user mentions "tags", it most likely means tags in Obsidian note properties.
14. YouTube URLs: If the user provides YouTube URLs in their message, transcriptions will be automatically fetched and provided to you. You don't need to do anything special - just use the transcription content if available.
15. For markdown lists, always use '- ' (hyphen followed by exactly one space) for bullet points, with no leading spaces before the hyphen. Never use '*' (asterisk) for bullets.`,wct=`Return the new note content or canvas JSON in <writeFile> tags.
# Steps to find the the target notes
1. Extract the target note information from user message and find out the note path from the context below.
2. If target note is not specified, use the <active_note> as the target note.
3. If still failed to find the target note or the note path, ask the user to specify the target note.
# Examples
Input: Add a new section to note A
Output:
<writeFile>
<path>path/to/file.md</path>
<content>The FULL CONTENT of the note A with added section goes here</content>
</writeFile>
Input: Create a new canvas with "Hello, world!"
Output:
<writeFile>
<path>path/to/file.canvas</path>
<content>
{
"nodes": [
{
"id": "1",
"type": "text",
"text": "Hello, world!",
"x": 0,
"y": 0,
"width": 200,
"height": 50
}
],
"edges": []
}
</content>
</writeFile>
Input: Create a canvas with a file node and a group
Output:
<writeFile>
<path>path/to/file.canvas</path>
<content>
{
"nodes": [
{"id": "1", "type": "file", "file": "note.md", "subpath": "#heading", "x": 100, "y": 100, "width": 300, "height": 200, "color": "2"},
{"id": "2", "type": "group", "label": "My Group", "x": 50, "y": 50, "width": 400, "height": 300, "color": "1"},
{"id": "3", "type": "link", "url": "https://example.com", "x": 500, "y": 100, "width": 200, "height": 100, "color": "#FF5733"}
],
"edges": [
{"id": "e1-2", "fromNode": "1", "toNode": "3", "fromSide": "right", "toSide": "left", "fromEnd": "arrow", "toEnd": "none", "color": "3", "label": "references"}
]
}
</content>
</writeFile>
# Canvas JSON Format (JSON Canvas spec 1.0)
Required node fields: id, type, x, y, width, height
Node types: "text" (needs text), "file" (needs file), "link" (needs url), "group" (optional label)
Optional node fields: color (hex #FF0000 or preset "1"-"6"), subpath (file nodes, starts with #)
Required edge fields: id, fromNode, toNode
Optional edge fields: fromSide/toSide ("top"/"right"/"bottom"/"left"), fromEnd/toEnd ("none"/"arrow"), color, label
All IDs must be unique. Edge nodes must reference existing node IDs.
Position nodes with reasonable spacing and logical visual flow.
`,G5="note_context",Xp="selected_text",qF="web_selected_text",Z5="variable",FO="variable_note",Y5="embedded_pdf",JPe="embedded_note",J5="dataview_block",XPe="retrieved_document",QPe="web_tab_context",Voe="active_web_tab",eAe="youtube_video_context",vC="{activeWebTab}",qoe=6e3,tAe=.4,nAe=448e3,Koe=3e4,KTn=30,rAe=5*60*1e3,bct=16,gh={DEFAULT:"",READING_FILES:"Reading files",SEARCHING_WEB:"Searching the web",READING_FILE_TREE:"Reading file tree",COMPACTING:"Compacting"},hw={SETTINGS:"settings",EXPIRED_MODAL:"expired_modal",CHAT_MODE_SELECT:"chat_mode_select",MODE_SELECT_TOOLTIP:"mode_select_tooltip",MULTI_AGENT:"multi_agent"},_ct=2e4,V5={TEMPERATURE:.1,REASONING_EFFORT:"low",VERBOSITY:"medium"},xct=131072,L_=(h=>(h.OPENROUTERAI="openrouterai",h.OPENAI="openai",h.OPENAI_FORMAT="3rd party (openai-format)",h.ANTHROPIC="anthropic",h.GOOGLE="google",h.XAI="xai",h.AZURE_OPENAI="azure openai",h.GROQ="groq",h.OLLAMA="ollama",h.LM_STUDIO="lm-studio",h.COPILOT_PLUS="copilot-plus",h.MISTRAL="mistralai",h.DEEPSEEK="deepseek",h.COHEREAI="cohereai",h.SILICONFLOW="siliconflow",h))(L_||{}),KF=[{name:"copilot-plus-flash",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,core:!0,plusExclusive:!0,capabilities:["vision"]},{name:"google/gemini-2.5-flash",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"google/gemini-3.5-flash",provider:"openrouterai",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gpt-5.5",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-5.4-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"claude-sonnet-4-6",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-3.5-flash",provider:"google",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-3.1-flash-lite",provider:"google",enabled:!0,isBuiltIn:!0,capabilities:["vision"]},{name:"gemini-2.5-flash",provider:"google",enabled:!0,isBuiltIn:!0,capabilities:["vision"]},{name:"google/gemini-3.1-pro-preview",provider:"openrouterai",enabled:!1,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"google/gemini-2.5-pro",provider:"openrouterai",enabled:!1,isBuiltIn:!0,core:!1,capabilities:["vision"]},{name:"openai/gpt-5.5",provider:"openrouterai",enabled:!1,isBuiltIn:!0,core:!1,capabilities:["vision"]},{name:"openai/gpt-5.4-mini",provider:"openrouterai",enabled:!1,isBuiltIn:!0,core:!1,capabilities:["vision"]},{name:"grok-4.3",provider:"xai",enabled:!1,isBuiltIn:!0,core:!1,capabilities:["vision"]},{name:"x-ai/grok-4.3",provider:"openrouterai",enabled:!1,isBuiltIn:!0,core:!1,capabilities:["vision"]},{name:"gpt-4.1",provider:"openai",enabled:!1,isBuiltIn:!0,core:!1,capabilities:["vision"]},{name:"gpt-4.1-mini",provider:"openai",enabled:!1,isBuiltIn:!0,core:!1,capabilities:["vision"]},{name:"claude-opus-4-7",provider:"anthropic",enabled:!1,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"claude-haiku-4-5",provider:"anthropic",enabled:!1,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-3.1-pro-preview",provider:"google",enabled:!1,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-2.5-pro",provider:"google",enabled:!1,isBuiltIn:!0,capabilities:["vision"]},{name:"deepseek-chat",provider:"deepseek",enabled:!1,isBuiltIn:!0},{name:"deepseek-reasoner",provider:"deepseek",enabled:!1,isBuiltIn:!0,capabilities:["reasoning"]},{name:"deepseek-ai/DeepSeek-V3",provider:"siliconflow",enabled:!1,isBuiltIn:!1,baseUrl:"https://api.siliconflow.com/v1"},{name:"deepseek-ai/DeepSeek-R1",provider:"siliconflow",enabled:!1,isBuiltIn:!1,baseUrl:"https://api.siliconflow.com/v1",capabilities:["reasoning"]}],UO=(d=>(d.OPENAI="openai",d.OPENROUTERAI="openrouterai",d.COHEREAI="cohereai",d.GOOGLE="google",d.AZURE_OPENAI="azure openai",d.OLLAMA="ollama",d.LM_STUDIO="lm-studio",d.OPENAI_FORMAT="3rd party (openai-format)",d.COPILOT_PLUS="copilot-plus",d.COPILOT_PLUS_JINA="copilot-plus-jina",d.SILICONFLOW="siliconflow",d))(UO||{}),X5=[{name:"copilot-plus-small",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0},{name:"copilot-plus-large",provider:"copilot-plus-jina",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0,believerExclusive:!0,dimensions:1024},{name:"copilot-plus-multilingual",provider:"copilot-plus-jina",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0,dimensions:512},{name:"openai/text-embedding-3-small",provider:"openrouterai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0},{name:"text-embedding-3-small",provider:"openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0},{name:"text-embedding-3-large",provider:"openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"embed-multilingual-light-v3.0",provider:"cohereai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"text-embedding-004",provider:"google",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"gemini-embedding-001",provider:"google",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0},{name:"gemini-embedding-2-preview",provider:"google",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0},{name:"azure-openai",provider:"azure openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"Qwen/Qwen3-Embedding-0.6B",provider:"siliconflow",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,baseUrl:"https://api.siliconflow.com/v1"}],oAe="nomic-embed-text",Qp={openrouterai:{label:"OpenRouter",host:"https://openrouter.ai/api/v1/",curlBaseURL:"https://openrouter.ai/api/v1",keyManagementURL:"https://openrouter.ai/keys",testModel:"openai/gpt-5.4-mini"},google:{label:"Gemini",host:"https://generativelanguage.googleapis.com",curlBaseURL:"https://generativelanguage.googleapis.com/v1beta",keyManagementURL:"https://makersuite.google.com/app/apikey",testModel:"gemini-2.5-flash"},anthropic:{label:"Anthropic",host:"https://api.anthropic.com/",curlBaseURL:"https://api.anthropic.com",keyManagementURL:"https://console.anthropic.com/settings/keys",testModel:"claude-sonnet-4-6"},openai:{label:"OpenAI",host:"https://api.openai.com",curlBaseURL:"https://api.openai.com/v1",keyManagementURL:"https://platform.openai.com/api-keys",testModel:"gpt-5.5"},xai:{label:"XAI",host:"https://api.x.ai/v1",curlBaseURL:"https://api.x.ai/v1",keyManagementURL:"https://console.x.ai",testModel:"grok-4.3"},"azure openai":{label:"Azure",host:"https://<resource>.services.ai.azure.com/models",curlBaseURL:"https://<resource>.services.ai.azure.com/models",keyManagementURL:"https://ai.azure.com"},groq:{label:"Groq",host:"https://api.groq.com/openai",curlBaseURL:"https://api.groq.com/openai/v1",keyManagementURL:"https://console.groq.com/keys",testModel:"llama3-8b-8192"},cohereai:{label:"Cohere",host:"https://api.cohere.ai/compatibility/v1",curlBaseURL:"https://api.cohere.ai/compatibility/v1",keyManagementURL:"https://dashboard.cohere.ai/api-keys",testModel:"command-r"},siliconflow:{label:"SiliconFlow",host:"https://api.siliconflow.com/v1",curlBaseURL:"https://api.siliconflow.com/v1",keyManagementURL:"https://cloud.siliconflow.com/me/account/ak",testModel:"deepseek-ai/DeepSeek-V3"},ollama:{label:"Ollama",host:"http://localhost:11434/v1/",curlBaseURL:"http://localhost:11434",keyManagementURL:""},"lm-studio":{label:"LM Studio",host:"http://localhost:1234/v1",curlBaseURL:"http://localhost:1234/v1",keyManagementURL:""},"3rd party (openai-format)":{label:"OpenAI Format",host:"https://api.example.com/v1",curlBaseURL:"https://api.example.com/v1",keyManagementURL:""},mistralai:{label:"Mistral",host:"https://api.mistral.ai/v1",curlBaseURL:"https://api.mistral.ai/v1",keyManagementURL:"https://console.mistral.ai/api-keys",testModel:"mistral-tiny-latest"},deepseek:{label:"DeepSeek",host:"https://api.deepseek.com/",curlBaseURL:"https://api.deepseek.com",keyManagementURL:"https://platform.deepseek.com/api-keys",testModel:"deepseek-chat"},"copilot-plus":{label:"Copilot",host:Jp,curlBaseURL:Jp,keyManagementURL:""},"copilot-plus-jina":{label:"Copilot",host:Jp,curlBaseURL:Jp,keyManagementURL:""}},Goe={anthropic:"anthropicApiKey",openai:"openAIApiKey","azure openai":"azureOpenAIApiKey",google:"googleApiKey",groq:"groqApiKey",openrouterai:"openRouterAiApiKey",cohereai:"cohereApiKey",xai:"xaiApiKey","copilot-plus":"plusLicenseKey",mistralai:"mistralApiKey",deepseek:"deepseekApiKey",siliconflow:"siliconflowApiKey"},GF=(n=>(n.ENTER="enter",n.SHIFT_ENTER="shift+enter",n))(GF||{}),ht={TRIGGER_QUICK_COMMAND:"trigger-quick-command",CLEAR_LOCAL_COPILOT_INDEX:"clear-local-copilot-index",CLEAR_COPILOT_CACHE:"clear-copilot-cache",COUNT_WORD_AND_TOKENS_SELECTION:"count-word-and-tokens-selection",COUNT_TOTAL_VAULT_TOKENS:"count-total-vault-tokens",DEBUG_WORD_COMPLETION:"debug-word-completion",FORCE_REINDEX_VAULT_TO_COPILOT_INDEX:"force-reindex-vault-to-copilot-index",GARBAGE_COLLECT_COPILOT_INDEX:"garbage-collect-copilot-index",INDEX_VAULT_TO_COPILOT_INDEX:"index-vault-to-copilot-index",INSPECT_COPILOT_INDEX_BY_NOTE_PATHS:"copilot-inspect-index-by-note-paths",LIST_INDEXED_FILES:"copilot-list-indexed-files",LOAD_COPILOT_CHAT_CONVERSATION:"load-copilot-chat-conversation",NEW_CHAT:"new-chat",NEW_AGENT_CHAT:"new-agent-chat",OPEN_COPILOT_CHAT_WINDOW:"chat-open-window",OPEN_AGENT_CHAT_WINDOW:"agent-chat-open-window",OPEN_RELEVANT_NOTES_VIEW:"open-relevant-notes-view",SEARCH_ORAMA_DB:"copilot-search-orama-db",TOGGLE_COPILOT_CHAT_WINDOW:"chat-toggle-window",TOGGLE_AGENT_CHAT_WINDOW:"agent-chat-toggle-window",ADD_SELECTION_TO_CHAT_CONTEXT:"add-selection-to-chat-context",ADD_WEB_SELECTION_TO_CHAT_CONTEXT:"add-web-selection-to-chat-context",ADD_CUSTOM_COMMAND:"add-custom-command",APPLY_CUSTOM_COMMAND:"apply-custom-command",OPEN_LOG_FILE:"open-log-file",CLEAR_LOG_FILE:"clear-log-file",DOWNLOAD_YOUTUBE_SCRIPT:"download-youtube-script",PUBLISH_FILE_TO_SYMPOSIUM:"publish-file-to-symposium",TRIGGER_QUICK_ASK:"trigger-quick-ask"},jO={[ht.TRIGGER_QUICK_COMMAND]:"Trigger quick command",[ht.CLEAR_LOCAL_COPILOT_INDEX]:"Clear local Copilot index",[ht.CLEAR_COPILOT_CACHE]:"Clear Copilot cache",[ht.COUNT_TOTAL_VAULT_TOKENS]:"Count total tokens in your vault",[ht.COUNT_WORD_AND_TOKENS_SELECTION]:"Count words and tokens in selection",[ht.DEBUG_WORD_COMPLETION]:"Word completion: Debug",[ht.FORCE_REINDEX_VAULT_TO_COPILOT_INDEX]:"Force reindex vault",[ht.GARBAGE_COLLECT_COPILOT_INDEX]:"Garbage collect Copilot index (remove files that no longer exist in vault)",[ht.INDEX_VAULT_TO_COPILOT_INDEX]:"Index (refresh) vault",[ht.INSPECT_COPILOT_INDEX_BY_NOTE_PATHS]:"Inspect Copilot index by note paths (debug)",[ht.LIST_INDEXED_FILES]:"List all indexed files (debug)",[ht.LOAD_COPILOT_CHAT_CONVERSATION]:"Load Copilot chat conversation",[ht.NEW_CHAT]:"New Copilot Quick Chat",[ht.NEW_AGENT_CHAT]:"New Copilot Agent Chat",[ht.OPEN_COPILOT_CHAT_WINDOW]:"Open Copilot Chat Window",[ht.OPEN_AGENT_CHAT_WINDOW]:"Open Copilot Agent Chat Window",[ht.OPEN_RELEVANT_NOTES_VIEW]:"Open Relevant Notes",[ht.SEARCH_ORAMA_DB]:"Search semantic index (debug)",[ht.TOGGLE_COPILOT_CHAT_WINDOW]:"Toggle Copilot Chat Window",[ht.TOGGLE_AGENT_CHAT_WINDOW]:"Toggle Copilot Agent Chat Window",[ht.ADD_SELECTION_TO_CHAT_CONTEXT]:"Add selection to chat context",[ht.ADD_WEB_SELECTION_TO_CHAT_CONTEXT]:"Add web selection to chat context",[ht.ADD_CUSTOM_COMMAND]:"Add new custom command",[ht.APPLY_CUSTOM_COMMAND]:"Apply custom command",[ht.OPEN_LOG_FILE]:"Create log file",[ht.CLEAR_LOG_FILE]:"Clear log file",[ht.DOWNLOAD_YOUTUBE_SCRIPT]:"Download YouTube Script (plus)",[ht.PUBLISH_FILE_TO_SYMPOSIUM]:"Publish file to Symposium",[ht.TRIGGER_QUICK_ASK]:"Quick Ask"},BO={[ht.NEW_CHAT]:"message-square-plus",[ht.NEW_AGENT_CHAT]:oT,[ht.OPEN_COPILOT_CHAT_WINDOW]:"message-square",[ht.OPEN_AGENT_CHAT_WINDOW]:oT,[ht.OPEN_RELEVANT_NOTES_VIEW]:"files",[ht.TOGGLE_COPILOT_CHAT_WINDOW]:"message-square",[ht.TOGGLE_AGENT_CHAT_WINDOW]:oT,[ht.LOAD_COPILOT_CHAT_CONVERSATION]:"history",[ht.TRIGGER_QUICK_COMMAND]:"terminal-square",[ht.TRIGGER_QUICK_ASK]:"sparkles",[ht.ADD_SELECTION_TO_CHAT_CONTEXT]:"text-cursor-input",[ht.ADD_WEB_SELECTION_TO_CHAT_CONTEXT]:"globe",[ht.ADD_CUSTOM_COMMAND]:"plus-circle",[ht.APPLY_CUSTOM_COMMAND]:"play-circle",[ht.INDEX_VAULT_TO_COPILOT_INDEX]:"refresh-cw",[ht.FORCE_REINDEX_VAULT_TO_COPILOT_INDEX]:"rotate-cw",[ht.CLEAR_LOCAL_COPILOT_INDEX]:"trash-2",[ht.CLEAR_COPILOT_CACHE]:"eraser",[ht.GARBAGE_COLLECT_COPILOT_INDEX]:"filter-x",[ht.COUNT_TOTAL_VAULT_TOKENS]:"calculator",[ht.COUNT_WORD_AND_TOKENS_SELECTION]:"hash",[ht.OPEN_LOG_FILE]:"file-text",[ht.CLEAR_LOG_FILE]:"file-x",[ht.DOWNLOAD_YOUTUBE_SCRIPT]:"youtube",[ht.PUBLISH_FILE_TO_SYMPOSIUM]:"share-2"},iAe=["md","canvas","base"],Sct=[...iAe,"pdf"],Zoe={NON_MARKDOWN_FILES_RESTRICTED:"Non-markdown files are only available in Copilot Plus mode. Please upgrade to access this file type.",URL_PROCESSING_RESTRICTED:"URL processing is only available in Copilot Plus mode. URLs will not be processed for context.",UNSUPPORTED_FILE_TYPE:t=>`${t.toUpperCase()} files are not supported in the current mode.`},Cct="https://api.github.com/repos/sst/opencode/releases/tags/v{version}",Yn={userId:Co(),isPaidUser:!1,isPlusUser:!1,entitlementToken:"",entitlementExpiresAt:0,plusLicenseKey:"",openAIApiKey:"",openAIOrgId:"",huggingfaceApiKey:"",cohereApiKey:"",anthropicApiKey:"",azureOpenAIApiKey:"",azureOpenAIApiInstanceName:"",azureOpenAIApiDeploymentName:"",azureOpenAIApiVersion:"",azureOpenAIApiEmbeddingDeploymentName:"",googleApiKey:"",openRouterAiApiKey:"",xaiApiKey:"",mistralApiKey:"",deepseekApiKey:"",siliconflowApiKey:"",defaultChainType:"llm_chain",defaultModelKey:"google/gemini-2.5-flash|openrouterai",embeddingModelKey:"openai/text-embedding-3-small|openrouterai",temperature:V5.TEMPERATURE,contextTurns:15,userSystemPrompt:"",openAIProxyBaseUrl:"",openAIEmbeddingProxyBaseUrl:"",stream:!0,copilotFolder:VF,copilotRootHistory:[],upgradedToV8FromLegacy:!1,defaultSaveFolder:BTn,defaultConversationTag:"copilot-conversation",autosaveChat:!0,autoAddActiveContentToContext:!0,defaultOpenArea:"view",defaultSendShortcut:"enter",customPromptsFolder:zTn,indexVaultToVectorStore:"ON MODE SWITCH",qaExclusions:YPe,qaInclusions:"",chatNoteContextPath:"",chatNoteContextTags:[],enableIndexSync:!0,debug:!1,maxSourceChunks:KTn,enableInlineCitations:!0,groqApiKey:"",activeModels:KF,activeEmbeddingModels:X5,embeddingRequestsPerMin:60,embeddingBatchSize:16,disableIndexOnMobile:!0,numPartitions:1,lexicalSearchRamLimit:100,promptUsageTimestamps:{},promptSortStrategy:"timestamp",chatHistorySortStrategy:"recent",projectsFolder:VTn,defaultConversationNoteName:"{$topic}@{$date}_{$time}",inlineEditCommands:[],projectList:[],lastDismissedVersion:null,passMarkdownImages:!0,enableAutonomousAgent:!0,enableCustomPromptTemplating:!0,enableSemanticSearchV3:!1,enableSelfHostMode:!1,enableMiyo:!1,enableMiyoSearchSkill:!1,miyoSearchAll:!1,miyoServerUrl:"",miyoSyncedExclusions:"",selfHostSearchProvider:"firecrawl",firecrawlApiKey:"",perplexityApiKey:"",supadataApiKey:"",docProcessorBackend:"plus",enableLexicalBoosts:!0,suggestedDefaultCommands:!1,autonomousAgentMaxIterations:4,autonomousAgentEnabledToolIds:["localSearch","readNote","webSearch","pomodoro","youtubeTranscription","writeFile","editFile","updateMemory"],reasoningEffort:V5.REASONING_EFFORT,verbosity:V5.VERBOSITY,memoryFolderName:HTn,enableRecentConversations:!0,maxRecentConversations:30,enableSavedMemory:!0,quickCommandModelKey:void 0,quickCommandIncludeNoteContext:!0,autoIncludeTextSelection:!1,autoAddSelectionToContext:!1,autoAcceptEdits:!1,diffViewMode:"split",userSystemPromptsFolder:WTn,defaultSystemPromptTitle:"",autoCompactThreshold:128e3,convertedDocOutputFolder:qTn,agentMode:{byok:{},activeBackend:"opencode",backends:{},debugFullFrames:!0,welcomeDismissed:!1,skills:{folder:yC}},providers:{},configuredModels:[],backends:{}},cs={CHAT_IS_VISIBLE:"chat-is-visible",ACTIVE_LEAF_CHANGE:"active-leaf-change",ABORT_STREAM:"abort-stream",INSERT_TEXT_TO_CHAT:"insert-text-to-chat"}});var kct={};sr(kct,{CustomError:()=>Nr,MissingApiKeyError:()=>ZF,MissingModelKeyError:()=>YF,MissingPlusLicenseError:()=>sT,TimeoutError:()=>Q5});var Nr,Q5,ZF,sT,YF,iy=b(()=>{Nr=class t extends Error{constructor(e,n){super(e),this.code=n,Object.setPrototypeOf(this,t.prototype)}},Q5=class t extends Error{constructor(e,n){super(`${e} timed out after ${n}ms`),this.name="TimeoutError",Object.setPrototypeOf(this,t.prototype)}},ZF=class t extends Error{constructor(e="API key is not configured."){super(e),this.name="MissingApiKeyError",Object.setPrototypeOf(this,t.prototype)}},sT=class t extends Error{constructor(e="Copilot Plus license key is not configured."){super(e),this.name="MissingPlusLicenseError",Object.setPrototypeOf(this,t.prototype)}},YF=class t extends Error{constructor(e="No model key found. Please select a model in settings."){super(e),this.name="MissingModelKeyError",Object.setPrototypeOf(this,t.prototype)}}});function Jn(t){let e=`${t.name}|${t.provider}`;return t._backendId?`${t._backendId}:${e}`:e}var eK=b(()=>{});function yo(t,e){let n=`atom${++GTn}`,r={toString(){return(ca.env?ca.env.MODE:void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?r.read=t:(r.init=t,r.read=ZTn,r.write=YTn),e&&(r.write=e),r}function ZTn(t){return t(this)}function YTn(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}var ca,GTn,Ict,sAe,aAe,Joe,cAe,JTn,XTn,uAe,Tct,Yoe,Ect,Pct,JF,lAe,QTn,ePn,Act,aT,Mct,sy,tK,Oct,dAe=b(()=>{ca={},GTn=0;Ict=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,sAe=t=>"init"in t,aAe=t=>!!t.write,Joe=new WeakMap,cAe=t=>{var e;return uAe(t)&&!((e=Joe.get(t))!=null&&e[1])},JTn=(t,e)=>{let n=Joe.get(t);if(n)n[1]=!0,n[0].forEach(r=>r(e));else if((ca.env?ca.env.MODE:void 0)!=="production")throw new Error("[Bug] cancelable promise not found")},XTn=t=>{if(Joe.has(t))return;let e=[new Set,!1];Joe.set(t,e);let n=()=>{e[1]=!0};t.then(n,n),t.onCancel=r=>{e[0].add(r)}},uAe=t=>typeof t?.then=="function",Tct=t=>"v"in t||"e"in t,Yoe=t=>{if("e"in t)throw t.e;if((ca.env?ca.env.MODE:void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},Ect=(t,e,n)=>{n.p.has(t)||(n.p.add(t),e.then(()=>{n.p.delete(t)},()=>{n.p.delete(t)}))},Pct=(t,e,n,r,o)=>{var i;if((ca.env?ca.env.MODE:void 0)!=="production"&&r===e)throw new Error("[Bug] atom cannot depend on itself");n.d.set(r,o.n),cAe(n.v)&&Ect(e,n.v,o),(i=o.m)==null||i.t.add(e),t&&QTn(t,r,e)},JF=()=>[new Map,new Map,new Set],lAe=(t,e,n)=>{t[0].has(e)||t[0].set(e,new Set),t[1].set(e,n)},QTn=(t,e,n)=>{let r=t[0].get(e);r&&r.add(n)},ePn=(t,e)=>t[0].get(e),Act=(t,e)=>{t[2].add(e)},aT=t=>{let e,n=!1,r=o=>{try{o()}catch(i){n||(e=i,n=!0)}};for(;t[1].size||t[2].size;){t[0].clear();let o=new Set(t[1].values());t[1].clear();let i=new Set(t[2]);t[2].clear(),o.forEach(s=>{var a;return(a=s.m)==null?void 0:a.l.forEach(r)}),i.forEach(r)}if(n)throw e},Mct=(...[t,e,n,r])=>{let o;(ca.env?ca.env.MODE:void 0)!=="production"&&(o=new Set);let i=(w,_,S)=>{let I="v"in _,C=_.v,k=cAe(_.v)?_.v:null;if(uAe(S)){XTn(S);for(let T of _.d.keys())Ect(w,S,t(T));_.v=S,delete _.e}else _.v=S,delete _.e;(!I||!Object.is(C,_.v))&&(++_.n,k&&JTn(k,S))},s=(w,_,S)=>{var I;let C=t(_);if(Tct(C)&&(C.m&&!S?.has(_)||Array.from(C.d).every(([$,U])=>s(w,$,S).n===U)))return C;C.d.clear();let k=!0,T=$=>{if(Ict(_,$)){let V=t($);if(!Tct(V))if(sAe($))i($,V,$.init);else throw new Error("no atom init");return Yoe(V)}let U=s(w,$,S);try{return Yoe(U)}finally{if(k)Pct(w,_,C,$,U);else{let V=JF();Pct(V,_,C,$,U),p(V,_,C),aT(V)}}},P,E,O={get signal(){return P||(P=new AbortController),P.signal},get setSelf(){return(ca.env?ca.env.MODE:void 0)!=="production"&&!aAe(_)&&console.warn("setSelf function cannot be used with read-only atom"),!E&&aAe(_)&&(E=(...$)=>{if((ca.env?ca.env.MODE:void 0)!=="production"&&k&&console.warn("setSelf function cannot be called in sync"),!k)return f(_,...$)}),E}};try{let $=e(_,T,O);if(i(_,C,$),uAe($)){(I=$.onCancel)==null||I.call($,()=>P?.abort());let U=()=>{if(C.m){let V=JF();p(V,_,C),aT(V)}};$.then(U,U)}return C}catch($){return delete C.v,C.e=$,++C.n,C}finally{k=!1}},a=w=>Yoe(s(void 0,w)),l=(w,_,S)=>{var I,C;let k=new Map;for(let T of((I=S.m)==null?void 0:I.t)||[])k.set(T,t(T));for(let T of S.p)k.set(T,t(T));return(C=ePn(w,_))==null||C.forEach(T=>{k.set(T,t(T))}),k};function c(w,_,S){let I=[],C=new Set,k=new Set,T=[[_,S]];for(;T.length>0;){let[P,E]=T[T.length-1];if(k.has(P)){T.pop();continue}if(C.has(P)){I.push([P,E,E.n]),k.add(P),T.pop();continue}C.add(P);for(let[O,$]of l(w,P,E))P!==O&&!C.has(O)&&T.push([O,$])}return[I,k]}let u=(w,_,S)=>{let[I,C]=c(w,_,S),k=new Set([_]);for(let T=I.length-1;T>=0;--T){let[P,E,O]=I[T],$=!1;for(let U of E.d.keys())if(U!==P&&k.has(U)){$=!0;break}$&&(s(w,P,C),p(w,P,E),O!==E.n&&(lAe(w,P,E),k.add(P))),C.delete(P)}},d=(w,_,...S)=>{let I=!0,C=T=>Yoe(s(w,T)),k=(T,...P)=>{let E=t(T);try{if(Ict(_,T)){if(!sAe(T))throw new Error("atom not writable");let O=E.n,$=P[0];i(T,E,$),p(w,T,E),O!==E.n&&(lAe(w,T,E),u(w,T,E));return}else return d(w,T,...P)}finally{I||aT(w)}};try{return n(_,C,k,...S)}finally{I=!1}},f=(w,..._)=>{let S=JF();try{return d(S,w,..._)}finally{aT(S)}},p=(w,_,S)=>{if(S.m&&!cAe(S.v)){for(let I of S.d.keys())S.m.d.has(I)||(m(w,I,t(I)).t.add(_),S.m.d.add(I));for(let I of S.m.d||[])if(!S.d.has(I)){S.m.d.delete(I);let C=h(w,I,t(I));C?.t.delete(_)}}},m=(w,_,S)=>{if(!S.m){s(w,_);for(let I of S.d.keys())m(w,I,t(I)).t.add(_);if(S.m={l:new Set,d:new Set(S.d.keys()),t:new Set},(ca.env?ca.env.MODE:void 0)!=="production"&&o.add(_),aAe(_)){let I=S.m,C,k=(T,P)=>{let E=!0;C=(...O)=>{try{return d(T,_,...O)}finally{E||aT(T)}};try{return P()}finally{E=!1}};Act(w,()=>{let T=k(w,()=>r(_,(...P)=>C(...P)));T&&(I.u=P=>k(P,T))})}}return S.m},h=(w,_,S)=>{if(S.m&&!S.m.l.size&&!Array.from(S.m.t).some(I=>{var C;return(C=t(I).m)==null?void 0:C.d.has(_)})){let I=S.m.u;I&&Act(w,()=>I(w)),delete S.m,(ca.env?ca.env.MODE:void 0)!=="production"&&o.delete(_);for(let C of S.d.keys()){let k=h(w,C,t(C));k?.t.delete(_)}return}return S.m},y={get:a,set:f,sub:(w,_)=>{let S=JF(),I=t(w),k=m(S,w,I).l;return k.add(_),aT(S),()=>{k.delete(_);let T=JF();h(T,w,I),aT(T)}},unstable_derive:w=>Mct(...w(t,e,n,r))};return(ca.env?ca.env.MODE:void 0)!=="production"&&Object.assign(y,{dev4_get_internal_weak_map:()=>({get:_=>{let S=t(_);if(S.n!==0)return S}}),dev4_get_mounted_atoms:()=>o,dev4_restore_atoms:_=>{let S=JF();for(let[I,C]of _)if(sAe(I)){let k=t(I),T=k.n;i(I,k,C),p(S,I,k),T!==k.n&&(lAe(S,I,k),u(S,I,k))}aT(S)}}),y},sy=()=>{let t=new WeakMap;return Mct(n=>{if((ca.env?ca.env.MODE:void 0)!=="production"&&!n)throw new Error("Atom is undefined or null");let r=t.get(n);return r||(r={d:new Map,p:new Set,n:0},t.set(n,r)),r},(n,...r)=>n.read(...r),(n,...r)=>n.write(...r),(n,...r)=>{var o;return(o=n.onMount)==null?void 0:o.call(n,...r)})},Oct=()=>(tK||(tK=sy(),(ca.env?ca.env.MODE:void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=tK),globalThis.__JOTAI_DEFAULT_STORE__!==tK&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),tK)});var Hct=wi(Ao=>{"use strict";var nK=Symbol.for("react.element"),tPn=Symbol.for("react.portal"),nPn=Symbol.for("react.fragment"),rPn=Symbol.for("react.strict_mode"),oPn=Symbol.for("react.profiler"),iPn=Symbol.for("react.provider"),sPn=Symbol.for("react.context"),aPn=Symbol.for("react.forward_ref"),lPn=Symbol.for("react.suspense"),cPn=Symbol.for("react.memo"),uPn=Symbol.for("react.lazy"),Nct=Symbol.iterator;function dPn(t){return t===null||typeof t!="object"?null:(t=Nct&&t[Nct]||t["@@iterator"],typeof t=="function"?t:null)}var $ct={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Dct=Object.assign,Fct={};function XF(t,e,n){this.props=t,this.context=e,this.refs=Fct,this.updater=n||$ct}XF.prototype.isReactComponent={};XF.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};XF.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function Uct(){}Uct.prototype=XF.prototype;function pAe(t,e,n){this.props=t,this.context=e,this.refs=Fct,this.updater=n||$ct}var mAe=pAe.prototype=new Uct;mAe.constructor=pAe;Dct(mAe,XF.prototype);mAe.isPureReactComponent=!0;var Rct=Array.isArray,jct=Object.prototype.hasOwnProperty,hAe={current:null},Bct={key:!0,ref:!0,__self:!0,__source:!0};function zct(t,e,n){var r,o={},i=null,s=null;if(e!=null)for(r in e.ref!==void 0&&(s=e.ref),e.key!==void 0&&(i=""+e.key),e)jct.call(e,r)&&!Bct.hasOwnProperty(r)&&(o[r]=e[r]);var a=arguments.length-2;if(a===1)o.children=n;else if(1<a){for(var l=Array(a),c=0;c<a;c++)l[c]=arguments[c+2];o.children=l}if(t&&t.defaultProps)for(r in a=t.defaultProps,a)o[r]===void 0&&(o[r]=a[r]);return{$$typeof:nK,type:t,key:i,ref:s,props:o,_owner:hAe.current}}function fPn(t,e){return{$$typeof:nK,type:t.type,key:e,ref:t.ref,props:t.props,_owner:t._owner}}function gAe(t){return typeof t=="object"&&t!==null&&t.$$typeof===nK}function pPn(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(n){return e[n]})}var Lct=/\/+/g;function fAe(t,e){return typeof t=="object"&&t!==null&&t.key!=null?pPn(""+t.key):e.toString(36)}function Qoe(t,e,n,r,o){var i=typeof t;(i==="undefined"||i==="boolean")&&(t=null);var s=!1;if(t===null)s=!0;else switch(i){case"string":case"number":s=!0;break;case"object":switch(t.$$typeof){case nK:case tPn:s=!0}}if(s)return s=t,o=o(s),t=r===""?"."+fAe(s,0):r,Rct(o)?(n="",t!=null&&(n=t.replace(Lct,"$&/")+"/"),Qoe(o,e,n,"",function(c){return c})):o!=null&&(gAe(o)&&(o=fPn(o,n+(!o.key||s&&s.key===o.key?"":(""+o.key).replace(Lct,"$&/")+"/")+t)),e.push(o)),1;if(s=0,r=r===""?".":r+":",Rct(t))for(var a=0;a<t.length;a++){i=t[a];var l=r+fAe(i,a);s+=Qoe(i,e,n,l,o)}else if(l=dPn(t),typeof l=="function")for(t=l.call(t),a=0;!(i=t.next()).done;)i=i.value,l=r+fAe(i,a++),s+=Qoe(i,e,n,l,o);else if(i==="object")throw e=String(t),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.");return s}function Xoe(t,e,n){if(t==null)return t;var r=[],o=0;return Qoe(t,r,"","",function(i){return e.call(n,i,o++)}),r}function mPn(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(n){(t._status===0||t._status===-1)&&(t._status=1,t._result=n)},function(n){(t._status===0||t._status===-1)&&(t._status=2,t._result=n)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var Zf={current:null},eie={transition:null},hPn={ReactCurrentDispatcher:Zf,ReactCurrentBatchConfig:eie,ReactCurrentOwner:hAe};Ao.Children={map:Xoe,forEach:function(t,e,n){Xoe(t,function(){e.apply(this,arguments)},n)},count:function(t){var e=0;return Xoe(t,function(){e++}),e},toArray:function(t){return Xoe(t,function(e){return e})||[]},only:function(t){if(!gAe(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};Ao.Component=XF;Ao.Fragment=nPn;Ao.Profiler=oPn;Ao.PureComponent=pAe;Ao.StrictMode=rPn;Ao.Suspense=lPn;Ao.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=hPn;Ao.cloneElement=function(t,e,n){if(t==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+t+".");var r=Dct({},t.props),o=t.key,i=t.ref,s=t._owner;if(e!=null){if(e.ref!==void 0&&(i=e.ref,s=hAe.current),e.key!==void 0&&(o=""+e.key),t.type&&t.type.defaultProps)var a=t.type.defaultProps;for(l in e)jct.call(e,l)&&!Bct.hasOwnProperty(l)&&(r[l]=e[l]===void 0&&a!==void 0?a[l]:e[l])}var l=arguments.length-2;if(l===1)r.children=n;else if(1<l){a=Array(l);for(var c=0;c<l;c++)a[c]=arguments[c+2];r.children=a}return{$$typeof:nK,type:t.type,key:o,ref:i,props:r,_owner:s}};Ao.createContext=function(t){return t={$$typeof:sPn,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},t.Provider={$$typeof:iPn,_context:t},t.Consumer=t};Ao.createElement=zct;Ao.createFactory=function(t){var e=zct.bind(null,t);return e.type=t,e};Ao.createRef=function(){return{current:null}};Ao.forwardRef=function(t){return{$$typeof:aPn,render:t}};Ao.isValidElement=gAe;Ao.lazy=function(t){return{$$typeof:uPn,_payload:{_status:-1,_result:t},_init:mPn}};Ao.memo=function(t,e){return{$$typeof:cPn,type:t,compare:e===void 0?null:e}};Ao.startTransition=function(t){var e=eie.transition;eie.transition={};try{t()}finally{eie.transition=e}};Ao.unstable_act=function(){throw Error("act(...) is not supported in production builds of React.")};Ao.useCallback=function(t,e){return Zf.current.useCallback(t,e)};Ao.useContext=function(t){return Zf.current.useContext(t)};Ao.useDebugValue=function(){};Ao.useDeferredValue=function(t){return Zf.current.useDeferredValue(t)};Ao.useEffect=function(t,e){return Zf.current.useEffect(t,e)};Ao.useId=function(){return Zf.current.useId()};Ao.useImperativeHandle=function(t,e,n){return Zf.current.useImperativeHandle(t,e,n)};Ao.useInsertionEffect=function(t,e){return Zf.current.useInsertionEffect(t,e)};Ao.useLayoutEffect=function(t,e){return Zf.current.useLayoutEffect(t,e)};Ao.useMemo=function(t,e){return Zf.current.useMemo(t,e)};Ao.useReducer=function(t,e,n){return Zf.current.useReducer(t,e,n)};Ao.useRef=function(t){return Zf.current.useRef(t)};Ao.useState=function(t){return Zf.current.useState(t)};Ao.useSyncExternalStore=function(t,e,n){return Zf.current.useSyncExternalStore(t,e,n)};Ao.useTransition=function(){return Zf.current.useTransition()};Ao.version="18.2.0"});var B=wi((l6r,Wct)=>{"use strict";Wct.exports=Hct()});function Ar(t,e){let n=qct(e),[[r,o,i],s]=(0,qd.useReducer)(c=>{let u=n.get(t);return Object.is(c[0],u)&&c[1]===n&&c[2]===t?c:[u,n,t]},void 0,()=>[n.get(t),n,t]),a=r;(o!==n||i!==t)&&(s(),a=n.get(t));let l=e?.delay;if((0,qd.useEffect)(()=>{let c=n.sub(t,()=>{if(typeof l=="number"){let u=n.get(t);vAe(u)&&Kct(Vct(u)),setTimeout(s,l);return}s()});return s(),c},[n,t,l]),(0,qd.useDebugValue)(a),vAe(a)){let c=Vct(a);return yPn(c)}return a}function vPn(t,e){let n=qct(e);return(0,qd.useCallback)((...o)=>{if((tie.env?tie.env.MODE:void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return n.set(t,...o)},[n,t])}function zO(t,e){return[Ar(t,e),vPn(t,e)]}var qd,tie,gPn,qct,vAe,Kct,yPn,yAe,Vct,Gct=b(()=>{"use client";qd=L(B(),1);dAe();tie={},gPn=(0,qd.createContext)(void 0),qct=t=>{let e=(0,qd.useContext)(gPn);return t?.store||e||Oct()},vAe=t=>typeof t?.then=="function",Kct=t=>{t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e})},yPn=qd.default.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(Kct(t),t)}),yAe=new WeakMap,Vct=t=>{let e=yAe.get(t);return e||(e=new Promise((n,r)=>{let o=t,i=l=>c=>{o===l&&n(c)},s=l=>c=>{o===l&&r(c)},a=l=>{"onCancel"in l&&typeof l.onCancel=="function"&&l.onCancel(c=>{if((tie.env?tie.env.MODE:void 0)!=="production"&&c===l)throw new Error("[Bug] p is not updated even after cancelation");vAe(c)?(yAe.set(c,e),o=c,c.then(i(c),s(c)),a(c)):n(c)})};t.then(i(t),s(t)),a(t)}),yAe.set(t,e)),e}});var Us=b(()=>{dAe();Gct()});function HO(t){let e=t.toLowerCase();return e.replace(/[_-]/g,"").includes("apikey")||e.endsWith("token")||e.endsWith("accesstoken")||e.endsWith("secret")||e.endsWith("password")||e.endsWith("licensekey")}function rie(t){for(let e of Object.keys(t)){if(!HO(e))continue;let n=t[e];if(typeof n=="string"&&n.length>0)return!0}for(let e of["activeModels","activeEmbeddingModels"]){let n=t[e];if(Array.isArray(n))for(let r of n){if(!r||typeof r!="object")continue;let o=r;for(let i of lT){let s=o[i];if(typeof s=="string"&&s.length>0)return!0}}}return!1}function QF(t){let e={...t};for(let n of Object.keys(e))HO(n)&&(e[n]="");return"activeModels"in e&&(e.activeModels=Zct(t.activeModels??[])),"activeEmbeddingModels"in e&&(e.activeEmbeddingModels=Zct(t.activeEmbeddingModels??[])),e}function Zct(t){return t?.length?t.map(e=>{let n={...e};for(let r of lT)n[r]="";return n}):t}function e2(t){let e={...t};if(delete e.enableEncryption,delete e._keychainMigrated,delete e._keychainMigratedAt,delete e._migrationModalDismissed,delete e._diskSecretsCleared,delete e._keychainOnly,delete e.githubCopilotAccessToken,delete e.githubCopilotToken,delete e.githubCopilotTokenExpiresAt,e.agentMode&&typeof e.agentMode=="object"&&!Array.isArray(e.agentMode)){let n={...e.agentMode};delete n.mcpServers,e.agentMode=n}return e}var lT,nie,WO=b(()=>{gt();lT=["apiKey"];nie=Object.freeze(Object.keys(Yn).filter(HO))});function Yct(t){return typeof t=="string"&&wPn.includes(t)}function bPn(t){return typeof t=="string"?t.trim():""}function oie(t){if(typeof t=="number"&&Number.isFinite(t)&&t>0)return t;if(typeof t=="string"){let e=Number(t);if(Number.isFinite(e)&&e>0)return e;let n=Date.parse(t);if(Number.isFinite(n))return n}return null}function _Pn(t,e){let n=new Intl.Collator(void 0),r=l=>bPn(e.getName(l)),o=l=>{let c=e.getCreatedAtMs(l);return Number.isFinite(c)?c:0},i=l=>{let c=o(l);return oie(e.getLastUsedAtMs(l))??c},s=typeof e.getManualOrder=="function"?l=>{let c=e.getManualOrder?.(l);return typeof c=="number"&&Number.isFinite(c)?c:0}:null,a=t==="manual"&&!s?"name":t;return(l,c)=>{let u=r(l),d=r(c),f=o(l),p=o(c),m=i(l),h=i(c);if(a==="manual"){let w=s(l),_=s(c);if(w!==_)return w-_}else if(a==="name"){let w=n.compare(u,d);if(w!==0)return w}else if(a==="created"){let w=p-f;if(w!==0)return w}else{let w=h-m;if(w!==0)return w}let g=n.compare(u,d);if(g!==0)return g;let v=p-f;if(v!==0)return v;let y=h-m;return y!==0?y:0}}function ay(t,e,n){return[...t].sort(_Pn(e,n))}var wPn,t2,wC=b(()=>{wPn=["recent","created","name","manual"];t2=class{constructor(e={}){this.lastTouchedAtMsByKey=new Map;this.lastPersistedAtMsByKey=new Map;this.revision=0;this.listeners=new Set;this.minIntervalMs=e.minIntervalMs??3e4,this.nowMs=e.nowMs??(()=>Date.now())}notifyChange(){this.revision+=1;for(let e of this.listeners)e()}getRevision(){return this.revision}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}touch(e){let n=this.nowMs();return this.lastTouchedAtMsByKey.set(e,n),this.notifyChange(),n}shouldPersist(e,n){let r=this.lastTouchedAtMsByKey.get(e);if(!r)return null;let o=oie(n),i=this.lastPersistedAtMsByKey.get(e),s=Math.max(o??0,i??0);return s===0?r:r-s<this.minIntervalMs?null:r}markPersisted(e,n){let r=oie(n);if(!r)return;let o=this.lastPersistedAtMsByKey.get(e)??0;this.lastPersistedAtMsByKey.set(e,Math.max(o,r))}getLastTouchedAt(e){return this.lastTouchedAtMsByKey.get(e)??null}getEffectiveLastUsedAt(e,n){let r=this.lastTouchedAtMsByKey.get(e),o=oie(n);return Math.max(r??0,o??0)}clear(e){if(e){this.lastTouchedAtMsByKey.delete(e),this.lastPersistedAtMsByKey.delete(e),this.notifyChange();return}this.lastTouchedAtMsByKey.clear(),this.lastPersistedAtMsByKey.clear(),this.notifyChange()}}});var SC={};sr(SC,{ENV_VAR_NAME_RE:()=>rK,getModelKeyFromModel:()=>Jn,getSettings:()=>Y,normalizeModelProvider:()=>nut,normalizeRootFolders:()=>_C,resetSettings:()=>bAe,sanitizeEnvOverrides:()=>VO,sanitizeQaExclusions:()=>eut,sanitizeSettings:()=>_Ae,setSettings:()=>En,settingsAtom:()=>yh,settingsStore:()=>on,subscribeToSettingsChange:()=>zr,updateAgentModeBackendFields:()=>xC,updateSetting:()=>At,useSettingsValue:()=>xt,validateCopilotFolder:()=>n2,validateSkillsFolder:()=>rut});function _C(t){let e=new Set,n=[];for(let r of t){if(typeof r!="string")continue;let o=r.trim().replace(/\\/g,"/").replace(/\/+/g,"/").split("/").filter(s=>s!==".").join("/").replace(/\/+$/,"");o.length===0||/(^|\/)\.\.(\/|$)/.test(o)||/^[a-zA-Z]:/.test(o)||o.startsWith("/")||e.has(o)||(e.add(o),n.push(o))}return n.length>0?n:SPn}function CPn(t){let e=new Set((t.activeEmbeddingModels||[]).map(n=>Jn(n)));return t.embeddingModelKey&&e.has(t.embeddingModelKey)?t.embeddingModelKey:Yn.embeddingModelKey}function En(t){on.set(yh,e=>{let n=typeof t=="function"?t(e):t,r=zPn({...e,...n});return r.embeddingModelKey=CPn(r),r})}function eut(t){let n=(typeof t=="string"?t:YPe).split(",").map(o=>decodeURIComponent(o.trim())).filter(o=>o.length>0),r=new Map;return n.forEach(o=>{let i=o.replace(/\/+$/,""),s=i.length>0?i:o;if(!r.has(s)){let a=i.length>0&&o.endsWith("/")?`${i}/`:o;r.set(s,a)}}),Array.from(r.values()).map(o=>encodeURIComponent(o)).join(",")}function At(t,e){En(n=>({...n,[t]:e}))}function xC(t,e){En(n=>({agentMode:{...n.agentMode,backends:{...n.agentMode.backends,[t]:{...n.agentMode.backends?.[t]??{},...e}}}}))}function Y(){return on.get(yh)}function tut(t,e){return t==="enableCors"?typeof e=="boolean":typeof e=="string"&&e.length>0}function APn(t,e){let n={...t},r=e;for(let o of kPn){let i=r[o];tut(o,i)&&(n[o]=i)}return n}function Jct(t,e){let n=new Map(e.map(s=>[Jn(s),s])),r=new Set(t.map(s=>Jn(s))),o=t.map(s=>{let a=n.get(Jn(s));return a?APn(s,a):s}),i=e.filter(s=>!r.has(Jn(s)));return[...o,...i]}function EPn(t){let e=Object.entries(t??{}).filter(([,n])=>!!n?.apiKeyKeychainId);return e.length>0?Object.fromEntries(e):Qct}function MPn(t,e){if(!Array.isArray(t)||t.length===0)return wAe;let n=t.filter(r=>e.has(r.providerId));return n.length>0?n:wAe}function bAe(){let t=Y(),e=t,n=_C([...Array.isArray(t.copilotRootHistory)?t.copilotRootHistory:[],t.copilotFolder]),r={};for(let a of PPn){let l=e[a];tut(a,l)&&(r[a]=l)}let o=EPn(t.providers),i=new Set(Object.keys(o)),s={...Yn,...r,isPaidUser:t.isPaidUser,entitlementExpiresAt:t.entitlementExpiresAt,activeModels:Jct(KF.map(a=>({...a,enabled:!0})),t.activeModels??[]),activeEmbeddingModels:Jct(X5.map(a=>({...a,enabled:!0})),t.activeEmbeddingModels??[]),providers:o,configuredModels:MPn(t.configuredModels,i),copilotRootHistory:n};En(s)}function zr(t){let e=Y();return on.sub(yh,()=>{let n=Y();t(e,n),e=n})}function xt(){return Ar(yh,{store:on})}function nut(t){return t==="azure_openai"?"azure openai":t}function _Ae(t){let e=t||Yn,n=e,{enableSelfHostedSearch:r,enableMiyoSearch:o}=n;e.userId||(e.userId=Co()),e.activeEmbeddingModels?e.activeEmbeddingModels=e.activeEmbeddingModels.map(T=>({...T,provider:nut(T.provider)})):e.activeEmbeddingModels=X5.map(T=>({...T,enabled:!0}));let i={...e},s=i;delete s.miyoRemoteVaultPath,delete s.miyoVaultName,delete s.enableMiyoSearch,delete s.amazonBedrockApiKey,delete s.amazonBedrockRegion,delete s.maxTokens,r!==void 0&&i.enableSelfHostMode===void 0&&(i.enableSelfHostMode=r),o!==void 0&&i.enableMiyo===void 0&&(i.enableMiyo=o),typeof i.isPaidUser!="boolean"&&typeof n.isPlusUser=="boolean"&&(i.isPaidUser=n.isPlusUser);let a=Number(e.temperature);i.temperature=isNaN(a)?Yn.temperature:a;let l=Number(e.contextTurns);i.contextTurns=isNaN(l)?Yn.contextTurns:l;let c=Number(e.embeddingRequestsPerMin);i.embeddingRequestsPerMin=isNaN(c)?Yn.embeddingRequestsPerMin:c;let u=Number(e.embeddingBatchSize);i.embeddingBatchSize=isNaN(u)?Yn.embeddingBatchSize:u;let d=Number(e.lexicalSearchRamLimit);if(isNaN(d)?i.lexicalSearchRamLimit=Yn.lexicalSearchRamLimit:i.lexicalSearchRamLimit=Math.min(1e3,Math.max(20,d)),typeof i.autoAddActiveContentToContext!="boolean"){let T=e.includeActiveNoteAsContext;typeof T=="boolean"?i.autoAddActiveContentToContext=T:i.autoAddActiveContentToContext=Yn.autoAddActiveContentToContext}typeof i.enableMiyo!="boolean"&&(i.enableMiyo=Yn.enableMiyo),typeof i.enableMiyoSearchSkill!="boolean"&&(i.enableMiyoSearchSkill=Yn.enableMiyoSearchSkill),typeof i.miyoSearchAll!="boolean"&&(i.miyoSearchAll=Yn.miyoSearchAll),typeof i.miyoServerUrl!="string"&&(i.miyoServerUrl=Yn.miyoServerUrl),typeof i.miyoSyncedExclusions!="string"&&(i.miyoSyncedExclusions=Yn.miyoSyncedExclusions),["firecrawl","perplexity"].includes(i.selfHostSearchProvider)||(i.selfHostSearchProvider=Yn.selfHostSearchProvider),["plus","miyo"].includes(i.docProcessorBackend)||(i.docProcessorBackend=Yn.docProcessorBackend),typeof i.passMarkdownImages!="boolean"&&(i.passMarkdownImages=Yn.passMarkdownImages),typeof i.enableInlineCitations!="boolean"&&(i.enableInlineCitations=Yn.enableInlineCitations),typeof i.enableCustomPromptTemplating!="boolean"&&(i.enableCustomPromptTemplating=Yn.enableCustomPromptTemplating);let m=Number(e.autonomousAgentMaxIterations);isNaN(m)||m<4||m>bct?i.autonomousAgentMaxIterations=Yn.autonomousAgentMaxIterations:i.autonomousAgentMaxIterations=m,Array.isArray(i.autonomousAgentEnabledToolIds)||(i.autonomousAgentEnabledToolIds=Yn.autonomousAgentEnabledToolIds);let h={writeToFile:"writeFile",replaceInFile:"editFile"};i.autonomousAgentEnabledToolIds=i.autonomousAgentEnabledToolIds.map(T=>h[T]??T),(!i.memoryFolderName||typeof i.memoryFolderName!="string")&&(i.memoryFolderName=Yn.memoryFolderName),typeof i.enableRecentConversations!="boolean"&&(i.enableRecentConversations=Yn.enableRecentConversations),typeof i.enableSavedMemory!="boolean"&&(i.enableSavedMemory=Yn.enableSavedMemory);let g=Number(e.maxRecentConversations);isNaN(g)||g<10||g>50?i.maxRecentConversations=Yn.maxRecentConversations:i.maxRecentConversations=g,typeof i.autosaveChat!="boolean"&&(i.autosaveChat=Yn.autosaveChat);let v=Number(e.autoCompactThreshold);if(isNaN(v)?i.autoCompactThreshold=Yn.autoCompactThreshold:i.autoCompactThreshold=Math.min(1e6,Math.max(64e3,v)),typeof i.quickCommandIncludeNoteContext!="boolean"&&(i.quickCommandIncludeNoteContext=Yn.quickCommandIncludeNoteContext),e.quickCommandModelKey!==void 0&&typeof e.quickCommandModelKey!="string"&&(i.quickCommandModelKey=Yn.quickCommandModelKey),typeof i.autoAddSelectionToContext!="boolean"){let T=e.autoIncludeTextSelection;typeof T=="boolean"?i.autoAddSelectionToContext=T:i.autoAddSelectionToContext=Yn.autoAddSelectionToContext}typeof i.autoAcceptEdits!="boolean"&&(i.autoAcceptEdits=Yn.autoAcceptEdits),Object.values(GF).includes(i.defaultSendShortcut)||(i.defaultSendShortcut=Yn.defaultSendShortcut);let y=n2(typeof e.copilotFolder=="string"?e.copilotFolder:"");i.copilotFolder=y.ok?y.folder:Yn.copilotFolder;let w=Array.isArray(e.copilotRootHistory)?e.copilotRootHistory:[];i.copilotRootHistory=_C([...w,i.copilotFolder]),typeof i.upgradedToV8FromLegacy!="boolean"&&(i.upgradedToV8FromLegacy=Yn.upgradedToV8FromLegacy);let _=(e.defaultSaveFolder||"").trim();i.defaultSaveFolder=_.length>0?_:Yn.defaultSaveFolder;let S=(e.customPromptsFolder||"").trim();i.customPromptsFolder=S.length>0?S:Yn.customPromptsFolder;let I=(e.projectsFolder||"").trim(),C=/(^|[/\\])\.\.[/\\]?/.test(I)||/^[a-zA-Z]:/.test(I)||/^[/\\]/.test(I);i.projectsFolder=I.length>0&&!C?I:Yn.projectsFolder,(!Yct(i.chatHistorySortStrategy)||i.chatHistorySortStrategy==="manual")&&(i.chatHistorySortStrategy=Yn.chatHistorySortStrategy),Object.values(oy).includes(i.defaultChainType)||(i.defaultChainType=Yn.defaultChainType);let k=(e.userSystemPromptsFolder||"").trim();return i.userSystemPromptsFolder=k.length>0?k:Yn.userSystemPromptsFolder,i.qaExclusions=eut(e.qaExclusions),i.agentMode=OPn(i.agentMode),(!i.providers||typeof i.providers!="object"||Array.isArray(i.providers))&&(i.providers=Qct),Array.isArray(i.configuredModels)||(i.configuredModels=wAe),(!i.backends||typeof i.backends!="object"||Array.isArray(i.backends))&&(i.backends=xPn),i}function OPn(t){if(!t||typeof t!="object")return{...Yn.agentMode};let e=t,n=e.byok&&typeof e.byok=="object"?e.byok:{},r=typeof e.activeBackend=="string"?e.activeBackend:Yn.agentMode.activeBackend,o=e.backends&&typeof e.backends=="object"?e.backends:{},i=o.opencode,s=o.claude,a=o.codex,l=i?UPn(i):void 0,c=s?DPn(s):void 0,u=a?FPn(a):void 0,d={};l&&(d.opencode=l),c&&(d.claude=c),u&&(d.codex=u);let f=BPn(e.deviceProfiles),p=typeof e.debugFullFrames=="boolean"?e.debugFullFrames:Yn.agentMode.debugFullFrames,m=typeof e.welcomeDismissed=="boolean"?e.welcomeDismissed:Yn.agentMode.welcomeDismissed,h=e.claudeCli&&typeof e.claudeCli=="object"?e.claudeCli:null,g=h&&typeof h.path=="string"?h.path:void 0,v=g?{path:g}:void 0,y=e.skills&&typeof e.skills=="object"?e.skills:null,w=y&&typeof y.folder=="string"?y.folder:"",_=rut(w),S=y&&typeof y.suppressMigrationConfirm=="boolean"?y.suppressMigrationConfirm:void 0,I={folder:_.ok?_.folder:Yn.agentMode.skills.folder,...S!==void 0?{suppressMigrationConfirm:S}:{}};return{byok:n,activeBackend:r,backends:d,debugFullFrames:p,welcomeDismissed:m,skills:I,...v?{claudeCli:v}:{},...f?{deviceProfiles:f}:{}}}function rut(t){if(typeof t!="string"||t.trim().length===0)return{ok:!0,folder:yC};let e=t.trim().replace(/\\/g,"/");for(;e.startsWith("./");)e=e.slice(2);if(e.startsWith("/")&&(e=e.replace(/^\/+/,"")),e=e.replace(/\/+$/,""),e.length===0)return{ok:!0,folder:yC};let n=e.split("/");for(let r of n){if(r.length===0)return{ok:!1,reason:"Folder path cannot contain empty segments (//)."};if(r==="..")return{ok:!1,reason:'Folder path cannot contain ".." segments.'};if(r===".")return{ok:!1,reason:'Folder path cannot contain "." segments.'};if(xAe.test(r))return{ok:!1,reason:"Folder path contains illegal control characters."};if(/[<>:"|?*]/.test(r))return{ok:!1,reason:'Folder path contains characters not allowed in folder names (< > : " | ? *).'}}return{ok:!0,folder:e}}function n2(t,e){if(typeof t!="string"||t.trim().length===0)return{ok:!1,reason:"Folder name cannot be empty."};let n=t.trim();if(/^[/\\]/.test(n)||/^[a-zA-Z]:/.test(n))return{ok:!1,reason:"Folder path must be relative to the vault root."};let r=n.replace(/\\/g,"/").replace(/\/+$/,"");if(r.length===0)return{ok:!1,reason:"Folder name cannot be empty."};let o=e?.trim().replace(/\\/g,"/").replace(/^\/+|\/+$/g,"").toLowerCase(),i=r.toLowerCase();if(o&&(i===o||i.startsWith(`${o}/`)||o.startsWith(`${i}/`)))return{ok:!1,reason:"Folder path cannot use the Obsidian config folder."};for(let s of r.split("/")){if(s.length===0)return{ok:!1,reason:"Folder path cannot contain empty segments (//)."};if(s==="..")return{ok:!1,reason:'Folder path cannot contain ".." segments.'};if(s===".")return{ok:!1,reason:'Folder path cannot contain "." segments.'};if(xAe.test(s))return{ok:!1,reason:"Folder path contains illegal control characters."};if(/[<>:"|?*]/.test(s))return{ok:!1,reason:'Folder path contains characters not allowed in folder names (< > : " | ? *).'};if(/[. ]$/.test(s))return{ok:!1,reason:"Folder names cannot end with a dot or space."};if(NPn.test(s))return{ok:!1,reason:`"${s}" is a name reserved by Windows.`}}return{ok:!0,folder:r}}function bC(t){return typeof t=="string"&&t?t:void 0}function SAe(t){if(!t||typeof t!="object")return;let e=t,n=typeof e.baseModelId=="string"&&e.baseModelId?e.baseModelId:null;if(!n)return;let r=typeof e.effort=="string"&&e.effort?e.effort:null;return{baseModelId:n,effort:r}}function CAe(t){return typeof t=="string"&&RPn.includes(t)?t:void 0}function VO(t){if(!t||typeof t!="object")return;let e={};for(let[n,r]of Object.entries(t))if(typeof n=="string"&&rK.test(n)&&typeof r=="string"&&!xAe.test(r)&&(e[n]=r,Object.keys(e).length>=64))break;return Object.keys(e).length>0?e:void 0}function $Pn(t){return typeof t=="string"&&LPn.includes(t)?t:void 0}function DPn(t){if(!t||typeof t!="object")return{};let e=t;return{defaultModel:SAe(e.defaultModel),defaultMode:CAe(e.defaultMode),autoModePermission:$Pn(e.autoModePermission),enableThinking:typeof e.enableThinking=="boolean"?e.enableThinking:void 0,envOverrides:VO(e.envOverrides)}}function FPn(t){if(!t||typeof t!="object")return{};let e=t;return{binaryPath:bC(e.binaryPath),defaultModel:SAe(e.defaultModel),defaultMode:CAe(e.defaultMode),envOverrides:VO(e.envOverrides)}}function UPn(t){if(!t||typeof t!="object")return{};let e=t,n=bC(e.binaryPath),r=bC(e.binaryVersion),o=e.binarySource,i;return o==="managed"||o==="custom"?i=n?o:void 0:i=n?"managed":void 0,{binaryPath:n,binaryVersion:r,binarySource:i,defaultModel:SAe(e.defaultModel),defaultMode:CAe(e.defaultMode),probeSessionId:bC(e.probeSessionId),envOverrides:VO(e.envOverrides)}}function jPn(t){if(!t||typeof t!="object")return;let e=t,n={},r=bC(e.claudeCliPath);r&&(n.claudeCliPath=r);let o=e.codex&&typeof e.codex=="object"?e.codex:null;if(o){let a={},l=bC(o.binaryPath);l&&(a.binaryPath=l);let c=VO(o.envOverrides);c&&(a.envOverrides=c),Object.keys(a).length>0&&(n.codex=a)}let i=e.opencode&&typeof e.opencode=="object"?e.opencode:null;if(i){let a={},l=bC(i.binaryPath);l&&(a.binaryPath=l);let c=bC(i.binaryVersion);if(c&&(a.binaryVersion=c),l){let f=i.binarySource;a.binarySource=f==="custom"?"custom":"managed"}let u=bC(i.probeSessionId);u&&(a.probeSessionId=u);let d=VO(i.envOverrides);d&&(a.envOverrides=d),Object.keys(a).length>0&&(n.opencode=a)}let s=e.claude&&typeof e.claude=="object"?e.claude:null;if(s){let a=VO(s.envOverrides);a&&(n.claude={envOverrides:a})}return Object.keys(n).length>0?n:void 0}function BPn(t){if(!t||typeof t!="object")return;let e={};for(let[n,r]of Object.entries(t)){if(typeof n!="string"||n.length===0)continue;let o=jPn(r);o&&(e[n]=o)}return Object.keys(e).length>0?e:void 0}function zPn(t){return t.activeModels=Xct(t.activeModels,KF),t.activeEmbeddingModels=HPn(Xct(t.activeEmbeddingModels,X5)),t}function Xct(t,e){let n=new Map;return e.filter(r=>r.core).forEach(r=>{n.set(Jn(r),{...r})}),t.forEach(r=>{let o=Jn(r),i=n.get(o);if(i){let s=e.find(a=>a.name===r.name&&a.provider===r.provider);s?n.set(o,{...s,...r,isBuiltIn:!0,believerExclusive:s.believerExclusive}):n.set(o,{...r,isBuiltIn:i.isBuiltIn})}else n.set(o,r)}),Array.from(n.values())}function HPn(t){let e=new Set(Object.values(UO));return t.filter(n=>e.has(n.provider))}var on,yh,Qct,wAe,xPn,SPn,kPn,IPn,TPn,PPn,NPn,xAe,RPn,rK,LPn,Se=b(()=>{eK();Us();Gf();mw();WO();wC();gt();eK();on=sy(),yh=yo(Yn),Qct=Object.freeze({}),wAe=Object.freeze([]),xPn=Object.freeze({}),SPn=Object.freeze([]);kPn=[...lT,"baseUrl","enableCors","openAIOrgId","azureOpenAIApiInstanceName","azureOpenAIApiVersion","azureOpenAIApiEmbeddingDeploymentName"],IPn="entitlementToken",TPn=["openAIOrgId","azureOpenAIApiInstanceName","azureOpenAIApiDeploymentName","azureOpenAIApiVersion","azureOpenAIApiEmbeddingDeploymentName"],PPn=[...nie.filter(t=>t!==IPn),...TPn];NPn=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i,xAe=/[\u0000-\u001f\u007f]/;RPn=["default","plan","auto"];rK=/^[A-Za-z_][A-Za-z0-9_]*$/;LPn=["acceptEdits","auto","bypassPermissions"]});function kt(t,e=!1){try{if(t instanceof Error){let r=t.cause,o=r instanceof Error?r.message:r!=null?typeof r=="string"?r:JSON.stringify(r)??"":"",i=e&&t.stack?t.stack:"",s=[t.message];return o&&s.push(`more message: ${o}`),i&&s.push(i),s.join(`
`)}return JSON.stringify(t)??String(t)}catch{return String(t)}}var oK=b(()=>{});var IAe=wi(iie=>{"use strict";iie.byteLength=VPn;iie.toByteArray=KPn;iie.fromByteArray=YPn;var $_=[],ly=[],WPn=typeof Uint8Array<"u"?Uint8Array:Array,kAe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(qO=0,out=kAe.length;qO<out;++qO)$_[qO]=kAe[qO],ly[kAe.charCodeAt(qO)]=qO;var qO,out;ly[45]=62;ly[95]=63;function iut(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function VPn(t){var e=iut(t),n=e[0],r=e[1];return(n+r)*3/4-r}function qPn(t,e,n){return(e+n)*3/4-n}function KPn(t){var e,n=iut(t),r=n[0],o=n[1],i=new WPn(qPn(t,r,o)),s=0,a=o>0?r-4:r,l;for(l=0;l<a;l+=4)e=ly[t.charCodeAt(l)]<<18|ly[t.charCodeAt(l+1)]<<12|ly[t.charCodeAt(l+2)]<<6|ly[t.charCodeAt(l+3)],i[s++]=e>>16&255,i[s++]=e>>8&255,i[s++]=e&255;return o===2&&(e=ly[t.charCodeAt(l)]<<2|ly[t.charCodeAt(l+1)]>>4,i[s++]=e&255),o===1&&(e=ly[t.charCodeAt(l)]<<10|ly[t.charCodeAt(l+1)]<<4|ly[t.charCodeAt(l+2)]>>2,i[s++]=e>>8&255,i[s++]=e&255),i}function GPn(t){return $_[t>>18&63]+$_[t>>12&63]+$_[t>>6&63]+$_[t&63]}function ZPn(t,e,n){for(var r,o=[],i=e;i<n;i+=3)r=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(t[i+2]&255),o.push(GPn(r));return o.join("")}function YPn(t){for(var e,n=t.length,r=n%3,o=[],i=16383,s=0,a=n-r;s<a;s+=i)o.push(ZPn(t,s,s+i>a?a:s+i));return r===1?(e=t[n-1],o.push($_[e>>2]+$_[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],o.push($_[e>>10]+$_[e>>4&63]+$_[e<<2&63]+"=")),o.join("")}});var sut=wi(TAe=>{TAe.read=function(t,e,n,r,o){var i,s,a=o*8-r-1,l=(1<<a)-1,c=l>>1,u=-7,d=n?o-1:0,f=n?-1:1,p=t[e+d];for(d+=f,i=p&(1<<-u)-1,p>>=-u,u+=a;u>0;i=i*256+t[e+d],d+=f,u-=8);for(s=i&(1<<-u)-1,i>>=-u,u+=r;u>0;s=s*256+t[e+d],d+=f,u-=8);if(i===0)i=1-c;else{if(i===l)return s?NaN:(p?-1:1)*(1/0);s=s+Math.pow(2,r),i=i-c}return(p?-1:1)*s*Math.pow(2,i-r)};TAe.write=function(t,e,n,r,o,i){var s,a,l,c=i*8-o-1,u=(1<<c)-1,d=u>>1,f=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?0:i-1,m=r?1:-1,h=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=u):(s=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-s))<1&&(s--,l*=2),s+d>=1?e+=f/l:e+=f*Math.pow(2,1-d),e*l>=2&&(s++,l/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(e*l-1)*Math.pow(2,o),s=s+d):(a=e*Math.pow(2,d-1)*Math.pow(2,o),s=0));o>=8;t[n+p]=a&255,p+=m,a/=256,o-=8);for(s=s<<o|a,c+=o;c>0;t[n+p]=s&255,p+=m,s/=256,c-=8);t[n+p-m]|=h*128}});var $Ae=wi(s2=>{"use strict";var PAe=IAe(),o2=sut(),aut=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;s2.Buffer=Me;s2.SlowBuffer=nAn;s2.INSPECT_MAX_BYTES=50;var sie=2147483647;s2.kMaxLength=sie;Me.TYPED_ARRAY_SUPPORT=JPn();!Me.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function JPn(){try{let t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch{return!1}}Object.defineProperty(Me.prototype,"parent",{enumerable:!0,get:function(){if(Me.isBuffer(this))return this.buffer}});Object.defineProperty(Me.prototype,"offset",{enumerable:!0,get:function(){if(Me.isBuffer(this))return this.byteOffset}});function CC(t){if(t>sie)throw new RangeError('The value "'+t+'" is invalid for option "size"');let e=new Uint8Array(t);return Object.setPrototypeOf(e,Me.prototype),e}function Me(t,e,n){if(typeof t=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return OAe(t)}return dut(t,e,n)}Me.poolSize=8192;function dut(t,e,n){if(typeof t=="string")return QPn(t,e);if(ArrayBuffer.isView(t))return eAn(t);if(t==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(D_(t,ArrayBuffer)||t&&D_(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(D_(t,SharedArrayBuffer)||t&&D_(t.buffer,SharedArrayBuffer)))return EAe(t,e,n);if(typeof t=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let r=t.valueOf&&t.valueOf();if(r!=null&&r!==t)return Me.from(r,e,n);let o=tAn(t);if(o)return o;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof t[Symbol.toPrimitive]=="function")return Me.from(t[Symbol.toPrimitive]("string"),e,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}Me.from=function(t,e,n){return dut(t,e,n)};Object.setPrototypeOf(Me.prototype,Uint8Array.prototype);Object.setPrototypeOf(Me,Uint8Array);function fut(t){if(typeof t!="number")throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function XPn(t,e,n){return fut(t),t<=0?CC(t):e!==void 0?typeof n=="string"?CC(t).fill(e,n):CC(t).fill(e):CC(t)}Me.alloc=function(t,e,n){return XPn(t,e,n)};function OAe(t){return fut(t),CC(t<0?0:NAe(t)|0)}Me.allocUnsafe=function(t){return OAe(t)};Me.allocUnsafeSlow=function(t){return OAe(t)};function QPn(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!Me.isEncoding(e))throw new TypeError("Unknown encoding: "+e);let n=put(t,e)|0,r=CC(n),o=r.write(t,e);return o!==n&&(r=r.slice(0,o)),r}function AAe(t){let e=t.length<0?0:NAe(t.length)|0,n=CC(e);for(let r=0;r<e;r+=1)n[r]=t[r]&255;return n}function eAn(t){if(D_(t,Uint8Array)){let e=new Uint8Array(t);return EAe(e.buffer,e.byteOffset,e.byteLength)}return AAe(t)}function EAe(t,e,n){if(e<0||t.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<e+(n||0))throw new RangeError('"length" is outside of buffer bounds');let r;return e===void 0&&n===void 0?r=new Uint8Array(t):n===void 0?r=new Uint8Array(t,e):r=new Uint8Array(t,e,n),Object.setPrototypeOf(r,Me.prototype),r}function tAn(t){if(Me.isBuffer(t)){let e=NAe(t.length)|0,n=CC(e);return n.length===0||t.copy(n,0,0,e),n}if(t.length!==void 0)return typeof t.length!="number"||LAe(t.length)?CC(0):AAe(t);if(t.type==="Buffer"&&Array.isArray(t.data))return AAe(t.data)}function NAe(t){if(t>=sie)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+sie.toString(16)+" bytes");return t|0}function nAn(t){return+t!=t&&(t=0),Me.alloc(+t)}Me.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==Me.prototype};Me.compare=function(e,n){if(D_(e,Uint8Array)&&(e=Me.from(e,e.offset,e.byteLength)),D_(n,Uint8Array)&&(n=Me.from(n,n.offset,n.byteLength)),!Me.isBuffer(e)||!Me.isBuffer(n))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===n)return 0;let r=e.length,o=n.length;for(let i=0,s=Math.min(r,o);i<s;++i)if(e[i]!==n[i]){r=e[i],o=n[i];break}return r<o?-1:o<r?1:0};Me.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};Me.concat=function(e,n){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return Me.alloc(0);let r;if(n===void 0)for(n=0,r=0;r<e.length;++r)n+=e[r].length;let o=Me.allocUnsafe(n),i=0;for(r=0;r<e.length;++r){let s=e[r];if(D_(s,Uint8Array))i+s.length>o.length?(Me.isBuffer(s)||(s=Me.from(s)),s.copy(o,i)):Uint8Array.prototype.set.call(o,s,i);else if(Me.isBuffer(s))s.copy(o,i);else throw new TypeError('"list" argument must be an Array of Buffers');i+=s.length}return o};function put(t,e){if(Me.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||D_(t,ArrayBuffer))return t.byteLength;if(typeof t!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);let n=t.length,r=arguments.length>2&&arguments[2]===!0;if(!r&&n===0)return 0;let o=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return MAe(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return n*2;case"hex":return n>>>1;case"base64":return xut(t).length;default:if(o)return r?-1:MAe(t).length;e=(""+e).toLowerCase(),o=!0}}Me.byteLength=put;function rAn(t,e,n){let r=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((n===void 0||n>this.length)&&(n=this.length),n<=0)||(n>>>=0,e>>>=0,n<=e))return"";for(t||(t="utf8");;)switch(t){case"hex":return pAn(this,e,n);case"utf8":case"utf-8":return hut(this,e,n);case"ascii":return dAn(this,e,n);case"latin1":case"binary":return fAn(this,e,n);case"base64":return cAn(this,e,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return mAn(this,e,n);default:if(r)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),r=!0}}Me.prototype._isBuffer=!0;function KO(t,e,n){let r=t[e];t[e]=t[n],t[n]=r}Me.prototype.swap16=function(){let e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let n=0;n<e;n+=2)KO(this,n,n+1);return this};Me.prototype.swap32=function(){let e=this.length;if(e%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let n=0;n<e;n+=4)KO(this,n,n+3),KO(this,n+1,n+2);return this};Me.prototype.swap64=function(){let e=this.length;if(e%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let n=0;n<e;n+=8)KO(this,n,n+7),KO(this,n+1,n+6),KO(this,n+2,n+5),KO(this,n+3,n+4);return this};Me.prototype.toString=function(){let e=this.length;return e===0?"":arguments.length===0?hut(this,0,e):rAn.apply(this,arguments)};Me.prototype.toLocaleString=Me.prototype.toString;Me.prototype.equals=function(e){if(!Me.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:Me.compare(this,e)===0};Me.prototype.inspect=function(){let e="",n=s2.INSPECT_MAX_BYTES;return e=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(e+=" ... "),"<Buffer "+e+">"};aut&&(Me.prototype[aut]=Me.prototype.inspect);Me.prototype.compare=function(e,n,r,o,i){if(D_(e,Uint8Array)&&(e=Me.from(e,e.offset,e.byteLength)),!Me.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(n===void 0&&(n=0),r===void 0&&(r=e?e.length:0),o===void 0&&(o=0),i===void 0&&(i=this.length),n<0||r>e.length||o<0||i>this.length)throw new RangeError("out of range index");if(o>=i&&n>=r)return 0;if(o>=i)return-1;if(n>=r)return 1;if(n>>>=0,r>>>=0,o>>>=0,i>>>=0,this===e)return 0;let s=i-o,a=r-n,l=Math.min(s,a),c=this.slice(o,i),u=e.slice(n,r);for(let d=0;d<l;++d)if(c[d]!==u[d]){s=c[d],a=u[d];break}return s<a?-1:a<s?1:0};function mut(t,e,n,r,o){if(t.length===0)return-1;if(typeof n=="string"?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,LAe(n)&&(n=o?0:t.length-1),n<0&&(n=t.length+n),n>=t.length){if(o)return-1;n=t.length-1}else if(n<0)if(o)n=0;else return-1;if(typeof e=="string"&&(e=Me.from(e,r)),Me.isBuffer(e))return e.length===0?-1:lut(t,e,n,r,o);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?o?Uint8Array.prototype.indexOf.call(t,e,n):Uint8Array.prototype.lastIndexOf.call(t,e,n):lut(t,[e],n,r,o);throw new TypeError("val must be string, number or Buffer")}function lut(t,e,n,r,o){let i=1,s=t.length,a=e.length;if(r!==void 0&&(r=String(r).toLowerCase(),r==="ucs2"||r==="ucs-2"||r==="utf16le"||r==="utf-16le")){if(t.length<2||e.length<2)return-1;i=2,s/=2,a/=2,n/=2}function l(u,d){return i===1?u[d]:u.readUInt16BE(d*i)}let c;if(o){let u=-1;for(c=n;c<s;c++)if(l(t,c)===l(e,u===-1?0:c-u)){if(u===-1&&(u=c),c-u+1===a)return u*i}else u!==-1&&(c-=c-u),u=-1}else for(n+a>s&&(n=s-a),c=n;c>=0;c--){let u=!0;for(let d=0;d<a;d++)if(l(t,c+d)!==l(e,d)){u=!1;break}if(u)return c}return-1}Me.prototype.includes=function(e,n,r){return this.indexOf(e,n,r)!==-1};Me.prototype.indexOf=function(e,n,r){return mut(this,e,n,r,!0)};Me.prototype.lastIndexOf=function(e,n,r){return mut(this,e,n,r,!1)};function oAn(t,e,n,r){n=Number(n)||0;let o=t.length-n;r?(r=Number(r),r>o&&(r=o)):r=o;let i=e.length;r>i/2&&(r=i/2);let s;for(s=0;s<r;++s){let a=parseInt(e.substr(s*2,2),16);if(LAe(a))return s;t[n+s]=a}return s}function iAn(t,e,n,r){return aie(MAe(e,t.length-n),t,n,r)}function sAn(t,e,n,r){return aie(vAn(e),t,n,r)}function aAn(t,e,n,r){return aie(xut(e),t,n,r)}function lAn(t,e,n,r){return aie(wAn(e,t.length-n),t,n,r)}Me.prototype.write=function(e,n,r,o){if(n===void 0)o="utf8",r=this.length,n=0;else if(r===void 0&&typeof n=="string")o=n,r=this.length,n=0;else if(isFinite(n))n=n>>>0,isFinite(r)?(r=r>>>0,o===void 0&&(o="utf8")):(o=r,r=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let i=this.length-n;if((r===void 0||r>i)&&(r=i),e.length>0&&(r<0||n<0)||n>this.length)throw new RangeError("Attempt to write outside buffer bounds");o||(o="utf8");let s=!1;for(;;)switch(o){case"hex":return oAn(this,e,n,r);case"utf8":case"utf-8":return iAn(this,e,n,r);case"ascii":case"latin1":case"binary":return sAn(this,e,n,r);case"base64":return aAn(this,e,n,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return lAn(this,e,n,r);default:if(s)throw new TypeError("Unknown encoding: "+o);o=(""+o).toLowerCase(),s=!0}};Me.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function cAn(t,e,n){return e===0&&n===t.length?PAe.fromByteArray(t):PAe.fromByteArray(t.slice(e,n))}function hut(t,e,n){n=Math.min(t.length,n);let r=[],o=e;for(;o<n;){let i=t[o],s=null,a=i>239?4:i>223?3:i>191?2:1;if(o+a<=n){let l,c,u,d;switch(a){case 1:i<128&&(s=i);break;case 2:l=t[o+1],(l&192)===128&&(d=(i&31)<<6|l&63,d>127&&(s=d));break;case 3:l=t[o+1],c=t[o+2],(l&192)===128&&(c&192)===128&&(d=(i&15)<<12|(l&63)<<6|c&63,d>2047&&(d<55296||d>57343)&&(s=d));break;case 4:l=t[o+1],c=t[o+2],u=t[o+3],(l&192)===128&&(c&192)===128&&(u&192)===128&&(d=(i&15)<<18|(l&63)<<12|(c&63)<<6|u&63,d>65535&&d<1114112&&(s=d))}}s===null?(s=65533,a=1):s>65535&&(s-=65536,r.push(s>>>10&1023|55296),s=56320|s&1023),r.push(s),o+=a}return uAn(r)}var cut=4096;function uAn(t){let e=t.length;if(e<=cut)return String.fromCharCode.apply(String,t);let n="",r=0;for(;r<e;)n+=String.fromCharCode.apply(String,t.slice(r,r+=cut));return n}function dAn(t,e,n){let r="";n=Math.min(t.length,n);for(let o=e;o<n;++o)r+=String.fromCharCode(t[o]&127);return r}function fAn(t,e,n){let r="";n=Math.min(t.length,n);for(let o=e;o<n;++o)r+=String.fromCharCode(t[o]);return r}function pAn(t,e,n){let r=t.length;(!e||e<0)&&(e=0),(!n||n<0||n>r)&&(n=r);let o="";for(let i=e;i<n;++i)o+=bAn[t[i]];return o}function mAn(t,e,n){let r=t.slice(e,n),o="";for(let i=0;i<r.length-1;i+=2)o+=String.fromCharCode(r[i]+r[i+1]*256);return o}Me.prototype.slice=function(e,n){let r=this.length;e=~~e,n=n===void 0?r:~~n,e<0?(e+=r,e<0&&(e=0)):e>r&&(e=r),n<0?(n+=r,n<0&&(n=0)):n>r&&(n=r),n<e&&(n=e);let o=this.subarray(e,n);return Object.setPrototypeOf(o,Me.prototype),o};function bu(t,e,n){if(t%1!==0||t<0)throw new RangeError("offset is not uint");if(t+e>n)throw new RangeError("Trying to access beyond buffer length")}Me.prototype.readUintLE=Me.prototype.readUIntLE=function(e,n,r){e=e>>>0,n=n>>>0,r||bu(e,n,this.length);let o=this[e],i=1,s=0;for(;++s<n&&(i*=256);)o+=this[e+s]*i;return o};Me.prototype.readUintBE=Me.prototype.readUIntBE=function(e,n,r){e=e>>>0,n=n>>>0,r||bu(e,n,this.length);let o=this[e+--n],i=1;for(;n>0&&(i*=256);)o+=this[e+--n]*i;return o};Me.prototype.readUint8=Me.prototype.readUInt8=function(e,n){return e=e>>>0,n||bu(e,1,this.length),this[e]};Me.prototype.readUint16LE=Me.prototype.readUInt16LE=function(e,n){return e=e>>>0,n||bu(e,2,this.length),this[e]|this[e+1]<<8};Me.prototype.readUint16BE=Me.prototype.readUInt16BE=function(e,n){return e=e>>>0,n||bu(e,2,this.length),this[e]<<8|this[e+1]};Me.prototype.readUint32LE=Me.prototype.readUInt32LE=function(e,n){return e=e>>>0,n||bu(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};Me.prototype.readUint32BE=Me.prototype.readUInt32BE=function(e,n){return e=e>>>0,n||bu(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};Me.prototype.readBigUInt64LE=cT(function(e){e=e>>>0,i2(e,"offset");let n=this[e],r=this[e+7];(n===void 0||r===void 0)&&iK(e,this.length-8);let o=n+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,i=this[++e]+this[++e]*2**8+this[++e]*2**16+r*2**24;return BigInt(o)+(BigInt(i)<<BigInt(32))});Me.prototype.readBigUInt64BE=cT(function(e){e=e>>>0,i2(e,"offset");let n=this[e],r=this[e+7];(n===void 0||r===void 0)&&iK(e,this.length-8);let o=n*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],i=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+r;return(BigInt(o)<<BigInt(32))+BigInt(i)});Me.prototype.readIntLE=function(e,n,r){e=e>>>0,n=n>>>0,r||bu(e,n,this.length);let o=this[e],i=1,s=0;for(;++s<n&&(i*=256);)o+=this[e+s]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*n)),o};Me.prototype.readIntBE=function(e,n,r){e=e>>>0,n=n>>>0,r||bu(e,n,this.length);let o=n,i=1,s=this[e+--o];for(;o>0&&(i*=256);)s+=this[e+--o]*i;return i*=128,s>=i&&(s-=Math.pow(2,8*n)),s};Me.prototype.readInt8=function(e,n){return e=e>>>0,n||bu(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};Me.prototype.readInt16LE=function(e,n){e=e>>>0,n||bu(e,2,this.length);let r=this[e]|this[e+1]<<8;return r&32768?r|4294901760:r};Me.prototype.readInt16BE=function(e,n){e=e>>>0,n||bu(e,2,this.length);let r=this[e+1]|this[e]<<8;return r&32768?r|4294901760:r};Me.prototype.readInt32LE=function(e,n){return e=e>>>0,n||bu(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};Me.prototype.readInt32BE=function(e,n){return e=e>>>0,n||bu(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};Me.prototype.readBigInt64LE=cT(function(e){e=e>>>0,i2(e,"offset");let n=this[e],r=this[e+7];(n===void 0||r===void 0)&&iK(e,this.length-8);let o=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(r<<24);return(BigInt(o)<<BigInt(32))+BigInt(n+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24)});Me.prototype.readBigInt64BE=cT(function(e){e=e>>>0,i2(e,"offset");let n=this[e],r=this[e+7];(n===void 0||r===void 0)&&iK(e,this.length-8);let o=(n<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(o)<<BigInt(32))+BigInt(this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+r)});Me.prototype.readFloatLE=function(e,n){return e=e>>>0,n||bu(e,4,this.length),o2.read(this,e,!0,23,4)};Me.prototype.readFloatBE=function(e,n){return e=e>>>0,n||bu(e,4,this.length),o2.read(this,e,!1,23,4)};Me.prototype.readDoubleLE=function(e,n){return e=e>>>0,n||bu(e,8,this.length),o2.read(this,e,!0,52,8)};Me.prototype.readDoubleBE=function(e,n){return e=e>>>0,n||bu(e,8,this.length),o2.read(this,e,!1,52,8)};function em(t,e,n,r,o,i){if(!Me.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>o||e<i)throw new RangeError('"value" argument is out of bounds');if(n+r>t.length)throw new RangeError("Index out of range")}Me.prototype.writeUintLE=Me.prototype.writeUIntLE=function(e,n,r,o){if(e=+e,n=n>>>0,r=r>>>0,!o){let a=Math.pow(2,8*r)-1;em(this,e,n,r,a,0)}let i=1,s=0;for(this[n]=e&255;++s<r&&(i*=256);)this[n+s]=e/i&255;return n+r};Me.prototype.writeUintBE=Me.prototype.writeUIntBE=function(e,n,r,o){if(e=+e,n=n>>>0,r=r>>>0,!o){let a=Math.pow(2,8*r)-1;em(this,e,n,r,a,0)}let i=r-1,s=1;for(this[n+i]=e&255;--i>=0&&(s*=256);)this[n+i]=e/s&255;return n+r};Me.prototype.writeUint8=Me.prototype.writeUInt8=function(e,n,r){return e=+e,n=n>>>0,r||em(this,e,n,1,255,0),this[n]=e&255,n+1};Me.prototype.writeUint16LE=Me.prototype.writeUInt16LE=function(e,n,r){return e=+e,n=n>>>0,r||em(this,e,n,2,65535,0),this[n]=e&255,this[n+1]=e>>>8,n+2};Me.prototype.writeUint16BE=Me.prototype.writeUInt16BE=function(e,n,r){return e=+e,n=n>>>0,r||em(this,e,n,2,65535,0),this[n]=e>>>8,this[n+1]=e&255,n+2};Me.prototype.writeUint32LE=Me.prototype.writeUInt32LE=function(e,n,r){return e=+e,n=n>>>0,r||em(this,e,n,4,4294967295,0),this[n+3]=e>>>24,this[n+2]=e>>>16,this[n+1]=e>>>8,this[n]=e&255,n+4};Me.prototype.writeUint32BE=Me.prototype.writeUInt32BE=function(e,n,r){return e=+e,n=n>>>0,r||em(this,e,n,4,4294967295,0),this[n]=e>>>24,this[n+1]=e>>>16,this[n+2]=e>>>8,this[n+3]=e&255,n+4};function gut(t,e,n,r,o){_ut(e,r,o,t,n,7);let i=Number(e&BigInt(4294967295));t[n++]=i,i=i>>8,t[n++]=i,i=i>>8,t[n++]=i,i=i>>8,t[n++]=i;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[n++]=s,s=s>>8,t[n++]=s,s=s>>8,t[n++]=s,s=s>>8,t[n++]=s,n}function yut(t,e,n,r,o){_ut(e,r,o,t,n,7);let i=Number(e&BigInt(4294967295));t[n+7]=i,i=i>>8,t[n+6]=i,i=i>>8,t[n+5]=i,i=i>>8,t[n+4]=i;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[n+3]=s,s=s>>8,t[n+2]=s,s=s>>8,t[n+1]=s,s=s>>8,t[n]=s,n+8}Me.prototype.writeBigUInt64LE=cT(function(e,n=0){return gut(this,e,n,BigInt(0),BigInt("0xffffffffffffffff"))});Me.prototype.writeBigUInt64BE=cT(function(e,n=0){return yut(this,e,n,BigInt(0),BigInt("0xffffffffffffffff"))});Me.prototype.writeIntLE=function(e,n,r,o){if(e=+e,n=n>>>0,!o){let l=Math.pow(2,8*r-1);em(this,e,n,r,l-1,-l)}let i=0,s=1,a=0;for(this[n]=e&255;++i<r&&(s*=256);)e<0&&a===0&&this[n+i-1]!==0&&(a=1),this[n+i]=(e/s>>0)-a&255;return n+r};Me.prototype.writeIntBE=function(e,n,r,o){if(e=+e,n=n>>>0,!o){let l=Math.pow(2,8*r-1);em(this,e,n,r,l-1,-l)}let i=r-1,s=1,a=0;for(this[n+i]=e&255;--i>=0&&(s*=256);)e<0&&a===0&&this[n+i+1]!==0&&(a=1),this[n+i]=(e/s>>0)-a&255;return n+r};Me.prototype.writeInt8=function(e,n,r){return e=+e,n=n>>>0,r||em(this,e,n,1,127,-128),e<0&&(e=255+e+1),this[n]=e&255,n+1};Me.prototype.writeInt16LE=function(e,n,r){return e=+e,n=n>>>0,r||em(this,e,n,2,32767,-32768),this[n]=e&255,this[n+1]=e>>>8,n+2};Me.prototype.writeInt16BE=function(e,n,r){return e=+e,n=n>>>0,r||em(this,e,n,2,32767,-32768),this[n]=e>>>8,this[n+1]=e&255,n+2};Me.prototype.writeInt32LE=function(e,n,r){return e=+e,n=n>>>0,r||em(this,e,n,4,2147483647,-2147483648),this[n]=e&255,this[n+1]=e>>>8,this[n+2]=e>>>16,this[n+3]=e>>>24,n+4};Me.prototype.writeInt32BE=function(e,n,r){return e=+e,n=n>>>0,r||em(this,e,n,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[n]=e>>>24,this[n+1]=e>>>16,this[n+2]=e>>>8,this[n+3]=e&255,n+4};Me.prototype.writeBigInt64LE=cT(function(e,n=0){return gut(this,e,n,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});Me.prototype.writeBigInt64BE=cT(function(e,n=0){return yut(this,e,n,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function vut(t,e,n,r,o,i){if(n+r>t.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function wut(t,e,n,r,o){return e=+e,n=n>>>0,o||vut(t,e,n,4,34028234663852886e22,-34028234663852886e22),o2.write(t,e,n,r,23,4),n+4}Me.prototype.writeFloatLE=function(e,n,r){return wut(this,e,n,!0,r)};Me.prototype.writeFloatBE=function(e,n,r){return wut(this,e,n,!1,r)};function but(t,e,n,r,o){return e=+e,n=n>>>0,o||vut(t,e,n,8,17976931348623157e292,-17976931348623157e292),o2.write(t,e,n,r,52,8),n+8}Me.prototype.writeDoubleLE=function(e,n,r){return but(this,e,n,!0,r)};Me.prototype.writeDoubleBE=function(e,n,r){return but(this,e,n,!1,r)};Me.prototype.copy=function(e,n,r,o){if(!Me.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),!o&&o!==0&&(o=this.length),n>=e.length&&(n=e.length),n||(n=0),o>0&&o<r&&(o=r),o===r||e.length===0||this.length===0)return 0;if(n<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(o<0)throw new RangeError("sourceEnd out of bounds");o>this.length&&(o=this.length),e.length-n<o-r&&(o=e.length-n+r);let i=o-r;return this===e&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(n,r,o):Uint8Array.prototype.set.call(e,this.subarray(r,o),n),i};Me.prototype.fill=function(e,n,r,o){if(typeof e=="string"){if(typeof n=="string"?(o=n,n=0,r=this.length):typeof r=="string"&&(o=r,r=this.length),o!==void 0&&typeof o!="string")throw new TypeError("encoding must be a string");if(typeof o=="string"&&!Me.isEncoding(o))throw new TypeError("Unknown encoding: "+o);if(e.length===1){let s=e.charCodeAt(0);(o==="utf8"&&s<128||o==="latin1")&&(e=s)}}else typeof e=="number"?e=e&255:typeof e=="boolean"&&(e=Number(e));if(n<0||this.length<n||this.length<r)throw new RangeError("Out of range index");if(r<=n)return this;n=n>>>0,r=r===void 0?this.length:r>>>0,e||(e=0);let i;if(typeof e=="number")for(i=n;i<r;++i)this[i]=e;else{let s=Me.isBuffer(e)?e:Me.from(e,o),a=s.length;if(a===0)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<r-n;++i)this[i+n]=s[i%a]}return this};var r2={};function RAe(t,e,n){r2[t]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:e.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${t}]`,this.stack,delete this.name}get code(){return t}set code(o){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:o,writable:!0})}toString(){return`${this.name} [${t}]: ${this.message}`}}}RAe("ERR_BUFFER_OUT_OF_BOUNDS",function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError);RAe("ERR_INVALID_ARG_TYPE",function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`},TypeError);RAe("ERR_OUT_OF_RANGE",function(t,e,n){let r=`The value of "${t}" is out of range.`,o=n;return Number.isInteger(n)&&Math.abs(n)>2**32?o=uut(String(n)):typeof n=="bigint"&&(o=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(o=uut(o)),o+="n"),r+=` It must be ${e}. Received ${o}`,r},RangeError);function uut(t){let e="",n=t.length,r=t[0]==="-"?1:0;for(;n>=r+4;n-=3)e=`_${t.slice(n-3,n)}${e}`;return`${t.slice(0,n)}${e}`}function hAn(t,e,n){i2(e,"offset"),(t[e]===void 0||t[e+n]===void 0)&&iK(e,t.length-(n+1))}function _ut(t,e,n,r,o,i){if(t>n||t<e){let s=typeof e=="bigint"?"n":"",a;throw i>3?e===0||e===BigInt(0)?a=`>= 0${s} and < 2${s} ** ${(i+1)*8}${s}`:a=`>= -(2${s} ** ${(i+1)*8-1}${s}) and < 2 ** ${(i+1)*8-1}${s}`:a=`>= ${e}${s} and <= ${n}${s}`,new r2.ERR_OUT_OF_RANGE("value",a,t)}hAn(r,o,i)}function i2(t,e){if(typeof t!="number")throw new r2.ERR_INVALID_ARG_TYPE(e,"number",t)}function iK(t,e,n){throw Math.floor(t)!==t?(i2(t,n),new r2.ERR_OUT_OF_RANGE(n||"offset","an integer",t)):e<0?new r2.ERR_BUFFER_OUT_OF_BOUNDS:new r2.ERR_OUT_OF_RANGE(n||"offset",`>= ${n?1:0} and <= ${e}`,t)}var gAn=/[^+/0-9A-Za-z-_]/g;function yAn(t){if(t=t.split("=")[0],t=t.trim().replace(gAn,""),t.length<2)return"";for(;t.length%4!==0;)t=t+"=";return t}function MAe(t,e){e=e||1/0;let n,r=t.length,o=null,i=[];for(let s=0;s<r;++s){if(n=t.charCodeAt(s),n>55295&&n<57344){if(!o){if(n>56319){(e-=3)>-1&&i.push(239,191,189);continue}else if(s+1===r){(e-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(e-=3)>-1&&i.push(239,191,189),o=n;continue}n=(o-55296<<10|n-56320)+65536}else o&&(e-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((e-=1)<0)break;i.push(n)}else if(n<2048){if((e-=2)<0)break;i.push(n>>6|192,n&63|128)}else if(n<65536){if((e-=3)<0)break;i.push(n>>12|224,n>>6&63|128,n&63|128)}else if(n<1114112){if((e-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,n&63|128)}else throw new Error("Invalid code point")}return i}function vAn(t){let e=[];for(let n=0;n<t.length;++n)e.push(t.charCodeAt(n)&255);return e}function wAn(t,e){let n,r,o,i=[];for(let s=0;s<t.length&&!((e-=2)<0);++s)n=t.charCodeAt(s),r=n>>8,o=n%256,i.push(o),i.push(r);return i}function xut(t){return PAe.toByteArray(yAn(t))}function aie(t,e,n,r){let o;for(o=0;o<r&&!(o+n>=e.length||o>=t.length);++o)e[o+n]=t[o];return o}function D_(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function LAe(t){return t!==t}var bAn=function(){let t="0123456789abcdef",e=new Array(256);for(let n=0;n<16;++n){let r=n*16;for(let o=0;o<16;++o)e[r+o]=t[n]+t[o]}return e}();function cT(t){return typeof BigInt>"u"?_An:t}function _An(){throw new Error("BigInt not supported")}});var kC,lie,cie,uie,gw,a2,ja,yw,uT=b(()=>{kC=class extends Error{},lie=class extends kC{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},cie=class extends kC{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},uie=class extends kC{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},gw=class extends kC{},a2=class extends kC{constructor(e){super(`Invalid unit ${e}`)}},ja=class extends kC{},yw=class extends kC{constructor(){super("Zone is an abstract class")}}});var $t,vw,vh,dT,sK,DAe,aK,lK,cK,uK,dK,fK,pK,mK,hK,gK,yK,vK,wK,bK,FAe,_K,xK,SK,CK,kK=b(()=>{$t="numeric",vw="short",vh="long",dT={year:$t,month:$t,day:$t},sK={year:$t,month:vw,day:$t},DAe={year:$t,month:vw,day:$t,weekday:vw},aK={year:$t,month:vh,day:$t},lK={year:$t,month:vh,day:$t,weekday:vh},cK={hour:$t,minute:$t},uK={hour:$t,minute:$t,second:$t},dK={hour:$t,minute:$t,second:$t,timeZoneName:vw},fK={hour:$t,minute:$t,second:$t,timeZoneName:vh},pK={hour:$t,minute:$t,hourCycle:"h23"},mK={hour:$t,minute:$t,second:$t,hourCycle:"h23"},hK={hour:$t,minute:$t,second:$t,hourCycle:"h23",timeZoneName:vw},gK={hour:$t,minute:$t,second:$t,hourCycle:"h23",timeZoneName:vh},yK={year:$t,month:$t,day:$t,hour:$t,minute:$t},vK={year:$t,month:$t,day:$t,hour:$t,minute:$t,second:$t},wK={year:$t,month:vw,day:$t,hour:$t,minute:$t},bK={year:$t,month:vw,day:$t,hour:$t,minute:$t,second:$t},FAe={year:$t,month:vw,day:$t,weekday:vw,hour:$t,minute:$t},_K={year:$t,month:vh,day:$t,hour:$t,minute:$t,timeZoneName:vw},xK={year:$t,month:vh,day:$t,hour:$t,minute:$t,second:$t,timeZoneName:vw},SK={year:$t,month:vh,day:$t,weekday:vh,hour:$t,minute:$t,timeZoneName:vh},CK={year:$t,month:vh,day:$t,weekday:vh,hour:$t,minute:$t,second:$t,timeZoneName:vh}});var tm,GO=b(()=>{uT();tm=class{get type(){throw new yw}get name(){throw new yw}get ianaName(){return this.name}get isUniversal(){throw new yw}offsetName(e,n){throw new yw}formatOffset(e,n){throw new yw}offset(e){throw new yw}equals(e){throw new yw}get isValid(){throw new yw}}});var UAe,fT,fie=b(()=>{Yf();GO();UAe=null,fT=class t extends tm{static get instance(){return UAe===null&&(UAe=new t),UAe}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:n,locale:r}){return pie(e,n,r)}formatOffset(e,n){return pT(this.offset(e),n)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}});function xAn(t){return hie[t]||(hie[t]=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"})),hie[t]}function CAn(t,e){let n=t.format(e).replace(/\u200E/g,""),r=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(n),[,o,i,s,a,l,c,u]=r;return[s,o,i,a,l,c,u]}function kAn(t,e){let n=t.formatToParts(e),r=[];for(let o=0;o<n.length;o++){let{type:i,value:s}=n[o],a=SAn[i];i==="era"?r[a]=s:Hn(a)||(r[a]=parseInt(s,10))}return r}var hie,SAn,mie,Kd,mT=b(()=>{Yf();GO();hie={};SAn={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};mie={},Kd=class t extends tm{static create(e){return mie[e]||(mie[e]=new t(e)),mie[e]}static resetCache(){mie={},hie={}}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=t.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:n,locale:r}){return pie(e,n,r,this.name)}formatOffset(e,n){return pT(this.offset(e),n)}offset(e){let n=new Date(e);if(isNaN(n))return NaN;let r=xAn(this.name),[o,i,s,a,l,c,u]=r.formatToParts?kAn(r,n):CAn(r,n);a==="BC"&&(o=-Math.abs(o)+1);let f=l2({year:o,month:i,day:s,hour:l===24?0:l,minute:c,second:u,millisecond:0}),p=+n,m=p%1e3;return p-=m>=0?m:1e3+m,(f-p)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}});function IAn(t,e={}){let n=JSON.stringify([t,e]),r=Sut[n];return r||(r=new Intl.ListFormat(t,e),Sut[n]=r),r}function BAe(t,e={}){let n=JSON.stringify([t,e]),r=jAe[n];return r||(r=new Intl.DateTimeFormat(t,e),jAe[n]=r),r}function TAn(t,e={}){let n=JSON.stringify([t,e]),r=zAe[n];return r||(r=new Intl.NumberFormat(t,e),zAe[n]=r),r}function PAn(t,e={}){let{base:n,...r}=e,o=JSON.stringify([t,r]),i=HAe[o];return i||(i=new Intl.RelativeTimeFormat(t,e),HAe[o]=i),i}function AAn(){return IK||(IK=new Intl.DateTimeFormat().resolvedOptions().locale,IK)}function EAn(t){let e=Cut[t];if(!e){let n=new Intl.Locale(t);e="getWeekInfo"in n?n.getWeekInfo():n.weekInfo,Cut[t]=e}return e}function MAn(t){let e=t.indexOf("-x-");e!==-1&&(t=t.substring(0,e));let n=t.indexOf("-u-");if(n===-1)return[t];{let r,o;try{r=BAe(t).resolvedOptions(),o=t}catch{let l=t.substring(0,n);r=BAe(l).resolvedOptions(),o=l}let{numberingSystem:i,calendar:s}=r;return[o,i,s]}}function OAn(t,e,n){return(n||e)&&(t.includes("-u-")||(t+="-u"),n&&(t+=`-ca-${n}`),e&&(t+=`-nu-${e}`)),t}function NAn(t){let e=[];for(let n=1;n<=12;n++){let r=Wn.utc(2009,n,1);e.push(t(r))}return e}function RAn(t){let e=[];for(let n=1;n<=7;n++){let r=Wn.utc(2016,11,13+n);e.push(t(r))}return e}function gie(t,e,n,r){let o=t.listingMode();return o==="error"?null:o==="en"?n(e):r(e)}function LAn(t){return t.numberingSystem&&t.numberingSystem!=="latn"?!1:t.numberingSystem==="latn"||!t.locale||t.locale.startsWith("en")||new Intl.DateTimeFormat(t.intl).resolvedOptions().numberingSystem==="latn"}var Sut,jAe,zAe,HAe,IK,Cut,WAe,VAe,qAe,$An,ui,PK=b(()=>{Yf();wie();hT();gT();mT();Sut={};jAe={};zAe={};HAe={};IK=null;Cut={};WAe=class{constructor(e,n,r){this.padTo=r.padTo||0,this.floor=r.floor||!1;let{padTo:o,floor:i,...s}=r;if(!n||Object.keys(s).length>0){let a={useGrouping:!1,...r};r.padTo>0&&(a.minimumIntegerDigits=r.padTo),this.inf=TAn(e,a)}}format(e){if(this.inf){let n=this.floor?Math.floor(e):e;return this.inf.format(n)}else{let n=this.floor?Math.floor(e):c2(e,3);return Sa(n,this.padTo)}}},VAe=class{constructor(e,n,r){this.opts=r,this.originalZone=void 0;let o;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){let s=-1*(e.offset/60),a=s>=0?`Etc/GMT+${s}`:`Etc/GMT${s}`;e.offset!==0&&Kd.create(a).valid?(o=a,this.dt=e):(o="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,o=e.zone.name):(o="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);let i={...this.opts};i.timeZone=i.timeZone||o,this.dtf=BAe(n,i)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){let e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(n=>{if(n.type==="timeZoneName"){let r=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...n,value:r}}else return n}):e}resolvedOptions(){return this.dtf.resolvedOptions()}},qAe=class{constructor(e,n,r){this.opts={style:"long",...r},!n&&yie()&&(this.rtf=PAn(e,r))}format(e,n){return this.rtf?this.rtf.format(e,n):kut(n,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,n){return this.rtf?this.rtf.formatToParts(e,n):[]}},$An={firstDay:1,minimalDays:4,weekend:[6,7]},ui=class t{static fromOpts(e){return t.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,n,r,o,i=!1){let s=e||ci.defaultLocale,a=s||(i?"en-US":AAn()),l=n||ci.defaultNumberingSystem,c=r||ci.defaultOutputCalendar,u=TK(o)||ci.defaultWeekSettings;return new t(a,l,c,u,s)}static resetCache(){IK=null,jAe={},zAe={},HAe={}}static fromObject({locale:e,numberingSystem:n,outputCalendar:r,weekSettings:o}={}){return t.create(e,n,r,o)}constructor(e,n,r,o,i){let[s,a,l]=MAn(e);this.locale=s,this.numberingSystem=n||a||null,this.outputCalendar=r||l||null,this.weekSettings=o,this.intl=OAn(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=i,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=LAn(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),n=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&n?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:t.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,TK(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,n=!1){return gie(this,e,KAe,()=>{let r=n?{month:e,day:"numeric"}:{month:e},o=n?"format":"standalone";return this.monthsCache[o][e]||(this.monthsCache[o][e]=NAn(i=>this.extract(i,r,"month"))),this.monthsCache[o][e]})}weekdays(e,n=!1){return gie(this,e,GAe,()=>{let r=n?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},o=n?"format":"standalone";return this.weekdaysCache[o][e]||(this.weekdaysCache[o][e]=RAn(i=>this.extract(i,r,"weekday"))),this.weekdaysCache[o][e]})}meridiems(){return gie(this,void 0,()=>ZAe,()=>{if(!this.meridiemCache){let e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[Wn.utc(2016,11,13,9),Wn.utc(2016,11,13,19)].map(n=>this.extract(n,e,"dayperiod"))}return this.meridiemCache})}eras(e){return gie(this,e,YAe,()=>{let n={era:e};return this.eraCache[e]||(this.eraCache[e]=[Wn.utc(-40,1,1),Wn.utc(2017,1,1)].map(r=>this.extract(r,n,"era"))),this.eraCache[e]})}extract(e,n,r){let o=this.dtFormatter(e,n),i=o.formatToParts(),s=i.find(a=>a.type.toLowerCase()===r);return s?s.value:null}numberFormatter(e={}){return new WAe(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,n={}){return new VAe(e,this.intl,n)}relFormatter(e={}){return new qAe(this.intl,this.isEnglish(),e)}listFormatter(e={}){return IAn(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:vie()?EAn(this.locale):$An}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}}});var XAe,_u,u2=b(()=>{Yf();GO();XAe=null,_u=class t extends tm{static get utcInstance(){return XAe===null&&(XAe=new t(0)),XAe}static instance(e){return e===0?t.utcInstance:new t(e)}static parseSpecifier(e){if(e){let n=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(n)return new t(ZO(n[1],n[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${pT(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${pT(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,n){return pT(this.fixed,n)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}}});var d2,QAe=b(()=>{GO();d2=class extends tm{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}}});function ww(t,e){let n;if(Hn(t)||t===null)return e;if(t instanceof tm)return t;if(Iut(t)){let r=t.toLowerCase();return r==="default"?e:r==="local"||r==="system"?fT.instance:r==="utc"||r==="gmt"?_u.utcInstance:_u.parseSpecifier(r)||Kd.create(t)}else return bw(t)?_u.instance(t):typeof t=="object"&&"offset"in t&&typeof t.offset=="function"?t:new d2(t)}var bie=b(()=>{GO();mT();u2();QAe();Yf();fie()});function Put(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);if(t[n].search(eEe.hanidec)!==-1)e+=DAn.indexOf(t[n]);else for(let o in Tut){let[i,s]=Tut[o];r>=i&&r<=s&&(e+=r-i)}}return parseInt(e,10)}else return e}function Aut(){f2={}}function cy({numberingSystem:t},e=""){let n=t||"latn";return f2[n]||(f2[n]={}),f2[n][e]||(f2[n][e]=new RegExp(`${eEe[n]}${e}`)),f2[n][e]}var eEe,Tut,DAn,f2,tEe=b(()=>{eEe={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},Tut={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},DAn=eEe.hanidec.replace(/[\[|\]]/g,"").split("");f2={}});var Eut,Mut,Out,Nut,Rut,Lut,$ut,Dut,ci,hT=b(()=>{fie();mT();PK();gT();bie();Yf();tEe();Eut=()=>Date.now(),Mut="system",Out=null,Nut=null,Rut=null,Lut=60,Dut=null,ci=class{static get now(){return Eut}static set now(e){Eut=e}static set defaultZone(e){Mut=e}static get defaultZone(){return ww(Mut,fT.instance)}static get defaultLocale(){return Out}static set defaultLocale(e){Out=e}static get defaultNumberingSystem(){return Nut}static set defaultNumberingSystem(e){Nut=e}static get defaultOutputCalendar(){return Rut}static set defaultOutputCalendar(e){Rut=e}static get defaultWeekSettings(){return Dut}static set defaultWeekSettings(e){Dut=TK(e)}static get twoDigitCutoffYear(){return Lut}static set twoDigitCutoffYear(e){Lut=e%100}static get throwOnInvalid(){return $ut}static set throwOnInvalid(e){$ut=e}static resetCaches(){ui.resetCache(),Kd.resetCache(),Wn.resetCache(),Aut()}}});var xu,AK=b(()=>{xu=class{constructor(e,n){this.reason=e,this.explanation=n}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}});function uy(t,e){return new xu("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function _ie(t,e,n){let r=new Date(Date.UTC(t,e-1,n));t<100&&t>=0&&r.setUTCFullYear(r.getUTCFullYear()-1900);let o=r.getUTCDay();return o===0?7:o}function jut(t,e,n){return n+(JO(t)?Uut:Fut)[e-1]}function But(t,e){let n=JO(t)?Uut:Fut,r=n.findIndex(i=>i<e),o=e-n[r];return{month:r+1,day:o}}function xie(t,e){return(t-e+7)%7+1}function EK(t,e=4,n=1){let{year:r,month:o,day:i}=t,s=jut(r,o,i),a=xie(_ie(r,o,i),n),l=Math.floor((s-a+14-e)/7),c;return l<1?(c=r-1,l=YO(c,e,n)):l>YO(r,e,n)?(c=r+1,l=1):c=r,{weekYear:c,weekNumber:l,weekday:a,...OK(t)}}function nEe(t,e=4,n=1){let{weekYear:r,weekNumber:o,weekday:i}=t,s=xie(_ie(r,1,e),n),a=yT(r),l=o*7+i-s-7+e,c;l<1?(c=r-1,l+=yT(c)):l>a?(c=r+1,l-=yT(r)):c=r;let{month:u,day:d}=But(c,l);return{year:c,month:u,day:d,...OK(t)}}function Sie(t){let{year:e,month:n,day:r}=t,o=jut(e,n,r);return{year:e,ordinal:o,...OK(t)}}function rEe(t){let{year:e,ordinal:n}=t,{month:r,day:o}=But(e,n);return{year:e,month:r,day:o,...OK(t)}}function oEe(t,e){if(!Hn(t.localWeekday)||!Hn(t.localWeekNumber)||!Hn(t.localWeekYear)){if(!Hn(t.weekday)||!Hn(t.weekNumber)||!Hn(t.weekYear))throw new gw("Cannot mix locale-based week fields with ISO-based week fields");return Hn(t.localWeekday)||(t.weekday=t.localWeekday),Hn(t.localWeekNumber)||(t.weekNumber=t.localWeekNumber),Hn(t.localWeekYear)||(t.weekYear=t.localWeekYear),delete t.localWeekday,delete t.localWeekNumber,delete t.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function zut(t,e=4,n=1){let r=MK(t.weekYear),o=wh(t.weekNumber,1,YO(t.weekYear,e,n)),i=wh(t.weekday,1,7);return r?o?i?!1:uy("weekday",t.weekday):uy("week",t.weekNumber):uy("weekYear",t.weekYear)}function Hut(t){let e=MK(t.year),n=wh(t.ordinal,1,yT(t.year));return e?n?!1:uy("ordinal",t.ordinal):uy("year",t.year)}function iEe(t){let e=MK(t.year),n=wh(t.month,1,12),r=wh(t.day,1,p2(t.year,t.month));return e?n?r?!1:uy("day",t.day):uy("month",t.month):uy("year",t.year)}function sEe(t){let{hour:e,minute:n,second:r,millisecond:o}=t,i=wh(e,0,23)||e===24&&n===0&&r===0&&o===0,s=wh(n,0,59),a=wh(r,0,59),l=wh(o,0,999);return i?s?a?l?!1:uy("millisecond",o):uy("second",r):uy("minute",n):uy("hour",e)}var Fut,Uut,aEe=b(()=>{Yf();AK();uT();Fut=[0,31,59,90,120,151,181,212,243,273,304,334],Uut=[0,31,60,91,121,152,182,213,244,274,305,335]});function Hn(t){return typeof t>"u"}function bw(t){return typeof t=="number"}function MK(t){return typeof t=="number"&&t%1===0}function Iut(t){return typeof t=="string"}function Vut(t){return Object.prototype.toString.call(t)==="[object Date]"}function yie(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function vie(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function qut(t){return Array.isArray(t)?t:[t]}function lEe(t,e,n){if(t.length!==0)return t.reduce((r,o)=>{let i=[e(o),o];return r&&n(r[0],i[0])===r[0]?r:i},null)[1]}function Kut(t,e){return e.reduce((n,r)=>(n[r]=t[r],n),{})}function vT(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function TK(t){if(t==null)return null;if(typeof t!="object")throw new ja("Week settings must be an object");if(!wh(t.firstDay,1,7)||!wh(t.minimalDays,1,7)||!Array.isArray(t.weekend)||t.weekend.some(e=>!wh(e,1,7)))throw new ja("Invalid week settings");return{firstDay:t.firstDay,minimalDays:t.minimalDays,weekend:Array.from(t.weekend)}}function wh(t,e,n){return MK(t)&&t>=e&&t<=n}function FAn(t,e){return t-e*Math.floor(t/e)}function Sa(t,e=2){let n=t<0,r;return n?r="-"+(""+-t).padStart(e,"0"):r=(""+t).padStart(e,"0"),r}function IC(t){if(!(Hn(t)||t===null||t===""))return parseInt(t,10)}function wT(t){if(!(Hn(t)||t===null||t===""))return parseFloat(t)}function NK(t){if(!(Hn(t)||t===null||t==="")){let e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function c2(t,e,n=!1){let r=10**e;return(n?Math.trunc:Math.round)(t*r)/r}function JO(t){return t%4===0&&(t%100!==0||t%400===0)}function yT(t){return JO(t)?366:365}function p2(t,e){let n=FAn(e-1,12)+1,r=t+(e-n)/12;return n===2?JO(r)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][n-1]}function l2(t){let e=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second,t.millisecond);return t.year<100&&t.year>=0&&(e=new Date(e),e.setUTCFullYear(t.year,t.month-1,t.day)),+e}function Wut(t,e,n){return-xie(_ie(t,1,e),n)+e-1}function YO(t,e=4,n=1){let r=Wut(t,e,n),o=Wut(t+1,e,n);return(yT(t)-r+o)/7}function RK(t){return t>99?t:t>ci.twoDigitCutoffYear?1900+t:2e3+t}function pie(t,e,n,r=null){let o=new Date(t),i={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};r&&(i.timeZone=r);let s={timeZoneName:e,...i},a=new Intl.DateTimeFormat(n,s).formatToParts(o).find(l=>l.type.toLowerCase()==="timezonename");return a?a.value:null}function ZO(t,e){let n=parseInt(t,10);Number.isNaN(n)&&(n=0);let r=parseInt(e,10)||0,o=n<0||Object.is(n,-0)?-r:r;return n*60+o}function cEe(t){let e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new ja(`Invalid unit value ${t}`);return e}function m2(t,e){let n={};for(let r in t)if(vT(t,r)){let o=t[r];if(o==null)continue;n[e(r)]=cEe(o)}return n}function pT(t,e){let n=Math.trunc(Math.abs(t/60)),r=Math.trunc(Math.abs(t%60)),o=t>=0?"+":"-";switch(e){case"short":return`${o}${Sa(n,2)}:${Sa(r,2)}`;case"narrow":return`${o}${n}${r>0?`:${r}`:""}`;case"techie":return`${o}${Sa(n,2)}${Sa(r,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function OK(t){return Kut(t,["hour","minute","second","millisecond"])}var Yf=b(()=>{uT();hT();aEe()});function KAe(t){switch(t){case"narrow":return[...jAn];case"short":return[...uEe];case"long":return[...UAn];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}function GAe(t){switch(t){case"narrow":return[...BAn];case"short":return[...fEe];case"long":return[...dEe];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}function YAe(t){switch(t){case"narrow":return[...WAn];case"short":return[...HAn];case"long":return[...zAn];default:return null}}function Gut(t){return ZAe[t.hour<12?0:1]}function Zut(t,e){return GAe(e)[t.weekday-1]}function Yut(t,e){return KAe(e)[t.month-1]}function Jut(t,e){return YAe(e)[t.year<0?0:1]}function kut(t,e,n="always",r=!1){let o={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},i=["hours","minutes","seconds"].indexOf(t)===-1;if(n==="auto"&&i){let d=t==="days";switch(e){case 1:return d?"tomorrow":`next ${o[t][0]}`;case-1:return d?"yesterday":`last ${o[t][0]}`;case 0:return d?"today":`this ${o[t][0]}`;default:}}let s=Object.is(e,-0)||e<0,a=Math.abs(e),l=a===1,c=o[t],u=r?l?c[1]:c[2]||c[1]:l?o[t][0]:t;return s?`${a} ${u} ago`:`in ${a} ${u}`}var UAn,uEe,jAn,dEe,fEe,BAn,ZAe,zAn,HAn,WAn,wie=b(()=>{kK();Yf();UAn=["January","February","March","April","May","June","July","August","September","October","November","December"],uEe=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],jAn=["J","F","M","A","M","J","J","A","S","O","N","D"];dEe=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],fEe=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],BAn=["M","T","W","T","F","S","S"];ZAe=["AM","PM"],zAn=["Before Christ","Anno Domini"],HAn=["BC","AD"],WAn=["B","A"]});function Xut(t,e){let n="";for(let r of t)r.literal?n+=r.val:n+=e(r.val);return n}var VAn,Su,LK=b(()=>{wie();kK();Yf();VAn={D:dT,DD:sK,DDD:aK,DDDD:lK,t:cK,tt:uK,ttt:dK,tttt:fK,T:pK,TT:mK,TTT:hK,TTTT:gK,f:yK,ff:wK,fff:_K,ffff:SK,F:vK,FF:bK,FFF:xK,FFFF:CK},Su=class t{static create(e,n={}){return new t(e,n)}static parseFormat(e){let n=null,r="",o=!1,i=[];for(let s=0;s<e.length;s++){let a=e.charAt(s);a==="'"?(r.length>0&&i.push({literal:o||/^\s+$/.test(r),val:r}),n=null,r="",o=!o):o||a===n?r+=a:(r.length>0&&i.push({literal:/^\s+$/.test(r),val:r}),r=a,n=a)}return r.length>0&&i.push({literal:o||/^\s+$/.test(r),val:r}),i}static macroTokenToFormatOpts(e){return VAn[e]}constructor(e,n){this.opts=n,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,n){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...n}).format()}dtFormatter(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n})}formatDateTime(e,n){return this.dtFormatter(e,n).format()}formatDateTimeParts(e,n){return this.dtFormatter(e,n).formatToParts()}formatInterval(e,n){return this.dtFormatter(e.start,n).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,n){return this.dtFormatter(e,n).resolvedOptions()}num(e,n=0){if(this.opts.forceSimple)return Sa(e,n);let r={...this.opts};return n>0&&(r.padTo=n),this.loc.numberFormatter(r).format(e)}formatDateTimeFromString(e,n){let r=this.loc.listingMode()==="en",o=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",i=(p,m)=>this.loc.extract(e,p,m),s=p=>e.isOffsetFixed&&e.offset===0&&p.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,p.format):"",a=()=>r?Gut(e):i({hour:"numeric",hourCycle:"h12"},"dayperiod"),l=(p,m)=>r?Yut(e,p):i(m?{month:p}:{month:p,day:"numeric"},"month"),c=(p,m)=>r?Zut(e,p):i(m?{weekday:p}:{weekday:p,month:"long",day:"numeric"},"weekday"),u=p=>{let m=t.macroTokenToFormatOpts(p);return m?this.formatWithSystemDefault(e,m):p},d=p=>r?Jut(e,p):i({era:p},"era"),f=p=>{switch(p){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return s({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return s({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return s({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return a();case"d":return o?i({day:"numeric"},"day"):this.num(e.day);case"dd":return o?i({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return c("short",!0);case"cccc":return c("long",!0);case"ccccc":return c("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return c("short",!1);case"EEEE":return c("long",!1);case"EEEEE":return c("narrow",!1);case"L":return o?i({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return o?i({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return l("short",!0);case"LLLL":return l("long",!0);case"LLLLL":return l("narrow",!0);case"M":return o?i({month:"numeric"},"month"):this.num(e.month);case"MM":return o?i({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return l("short",!1);case"MMMM":return l("long",!1);case"MMMMM":return l("narrow",!1);case"y":return o?i({year:"numeric"},"year"):this.num(e.year);case"yy":return o?i({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return o?i({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return o?i({year:"numeric"},"year"):this.num(e.year,6);case"G":return d("short");case"GG":return d("long");case"GGGGG":return d("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return u(p)}};return Xut(t.parseFormat(n),f)}formatDurationFromString(e,n){let r=l=>{switch(l[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},o=l=>c=>{let u=r(c);return u?this.num(l.get(u),c.length):c},i=t.parseFormat(n),s=i.reduce((l,{literal:c,val:u})=>c?l:l.concat(u),[]),a=e.shiftTo(...s.map(r).filter(l=>l));return Xut(i,o(a))}}});function g2(...t){let e=t.reduce((n,r)=>n+r.source,"");return RegExp(`^${e}$`)}function y2(...t){return e=>t.reduce(([n,r,o],i)=>{let[s,a,l]=i(e,o);return[{...n,...s},a||r,l]},[{},null,1]).slice(0,2)}function v2(t,...e){if(t==null)return[null,null];for(let[n,r]of e){let o=n.exec(t);if(o)return r(o)}return[null,null]}function tdt(...t){return(e,n)=>{let r={},o;for(o=0;o<t.length;o++)r[t[o]]=IC(e[n+o]);return[r,null,n+o]}}function h2(t,e,n){let r=t[e];return Hn(r)?n:IC(r)}function eEn(t,e){return[{year:h2(t,e),month:h2(t,e+1,1),day:h2(t,e+2,1)},null,e+3]}function w2(t,e){return[{hours:h2(t,e,0),minutes:h2(t,e+1,0),seconds:h2(t,e+2,0),milliseconds:NK(t[e+3])},null,e+4]}function $K(t,e){let n=!t[e]&&!t[e+1],r=ZO(t[e+1],t[e+2]),o=n?null:_u.instance(r);return[{},o,e+3]}function DK(t,e){let n=t[e]?Kd.create(t[e]):null;return[{},n,e+1]}function rEn(t){let[e,n,r,o,i,s,a,l,c]=t,u=e[0]==="-",d=l&&l[0]==="-",f=(p,m=!1)=>p!==void 0&&(m||p&&u)?-p:p;return[{years:f(wT(n)),months:f(wT(r)),weeks:f(wT(o)),days:f(wT(i)),hours:f(wT(s)),minutes:f(wT(a)),seconds:f(wT(l),l==="-0"),milliseconds:f(NK(c),d)}]}function hEe(t,e,n,r,o,i,s){let a={year:e.length===2?RK(IC(e)):IC(e),month:uEe.indexOf(n)+1,day:IC(r),hour:IC(o),minute:IC(i)};return s&&(a.second=IC(s)),t&&(a.weekday=t.length>3?dEe.indexOf(t)+1:fEe.indexOf(t)+1),a}function sEn(t){let[,e,n,r,o,i,s,a,l,c,u,d]=t,f=hEe(e,o,r,n,i,s,a),p;return l?p=oEn[l]:c?p=0:p=ZO(u,d),[f,new _u(p)]}function aEn(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}function Qut(t){let[,e,n,r,o,i,s,a]=t;return[hEe(e,o,r,n,i,s,a),_u.utcInstance]}function dEn(t){let[,e,n,r,o,i,s,a]=t;return[hEe(e,a,n,r,o,i,s),_u.utcInstance]}function sdt(t){return v2(t,[fEn,idt],[pEn,gEn],[mEn,yEn],[hEn,vEn])}function adt(t){return v2(aEn(t),[iEn,sEn])}function ldt(t){return v2(t,[lEn,Qut],[cEn,Qut],[uEn,dEn])}function cdt(t){return v2(t,[nEn,rEn])}function udt(t){return v2(t,[tEn,wEn])}function ddt(t){return v2(t,[bEn,idt],[_En,xEn])}var edt,ndt,qAn,pEe,rdt,mEe,KAn,GAn,ZAn,YAn,JAn,XAn,odt,QAn,tEn,nEn,oEn,iEn,lEn,cEn,uEn,fEn,pEn,mEn,hEn,idt,gEn,yEn,vEn,wEn,bEn,_En,xEn,gEe=b(()=>{Yf();wie();u2();mT();edt=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;ndt=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,qAn=`(?:${ndt.source}?(?:\\[(${edt.source})\\])?)?`,pEe=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,rdt=RegExp(`${pEe.source}${qAn}`),mEe=RegExp(`(?:T${rdt.source})?`),KAn=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,GAn=/(\d{4})-?W(\d\d)(?:-?(\d))?/,ZAn=/(\d{4})-?(\d{3})/,YAn=tdt("weekYear","weekNumber","weekDay"),JAn=tdt("year","ordinal"),XAn=/(\d{4})-(\d\d)-(\d\d)/,odt=RegExp(`${pEe.source} ?(?:${ndt.source}|(${edt.source}))?`),QAn=RegExp(`(?: ${odt.source})?`);tEn=RegExp(`^T?${pEe.source}$`),nEn=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;oEn={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};iEn=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;lEn=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,cEn=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,uEn=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;fEn=g2(KAn,mEe),pEn=g2(GAn,mEe),mEn=g2(ZAn,mEe),hEn=g2(rdt),idt=y2(eEn,w2,$K,DK),gEn=y2(YAn,w2,$K,DK),yEn=y2(JAn,w2,$K,DK),vEn=y2(w2,$K,DK);wEn=y2(w2);bEn=g2(XAn,QAn),_En=g2(odt),xEn=y2(w2,$K,DK)});function bT(t,e,n=!1){let r={values:n?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy,matrix:e.matrix||t.matrix};return new Ca(r)}function hdt(t,e){let n=e.milliseconds??0;for(let r of kEn.slice(1))e[r]&&(n+=e[r]*t[r].milliseconds);return n}function pdt(t,e){let n=hdt(t,e)<0?-1:1;XO.reduceRight((r,o)=>{if(Hn(e[o]))return r;if(r){let i=e[r]*n,s=t[o][r],a=Math.floor(i/s);e[o]+=a*n,e[r]-=a*s*n}return o},null),XO.reduce((r,o)=>{if(Hn(e[o]))return r;if(r){let i=e[r]%1;e[r]-=i,e[o]+=i*t[r][o]}return o},null)}function IEn(t){let e={};for(let[n,r]of Object.entries(t))r!==0&&(e[n]=r);return e}var fdt,mdt,SEn,dy,b2,CEn,XO,kEn,Ca,FK=b(()=>{uT();LK();AK();PK();gEe();Yf();hT();gT();fdt="Invalid Duration",mdt={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},SEn={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3},...mdt},dy=146097/400,b2=146097/4800,CEn={years:{quarters:4,months:12,weeks:dy/7,days:dy,hours:dy*24,minutes:dy*24*60,seconds:dy*24*60*60,milliseconds:dy*24*60*60*1e3},quarters:{months:3,weeks:dy/28,days:dy/4,hours:dy*24/4,minutes:dy*24*60/4,seconds:dy*24*60*60/4,milliseconds:dy*24*60*60*1e3/4},months:{weeks:b2/7,days:b2,hours:b2*24,minutes:b2*24*60,seconds:b2*24*60*60,milliseconds:b2*24*60*60*1e3},...mdt},XO=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],kEn=XO.slice(0).reverse();Ca=class t{constructor(e){let n=e.conversionAccuracy==="longterm"||!1,r=n?CEn:SEn;e.matrix&&(r=e.matrix),this.values=e.values,this.loc=e.loc||ui.create(),this.conversionAccuracy=n?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=r,this.isLuxonDuration=!0}static fromMillis(e,n){return t.fromObject({milliseconds:e},n)}static fromObject(e,n={}){if(e==null||typeof e!="object")throw new ja(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new t({values:m2(e,t.normalizeUnit),loc:ui.fromObject(n),conversionAccuracy:n.conversionAccuracy,matrix:n.matrix})}static fromDurationLike(e){if(bw(e))return t.fromMillis(e);if(t.isDuration(e))return e;if(typeof e=="object")return t.fromObject(e);throw new ja(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,n){let[r]=cdt(e);return r?t.fromObject(r,n):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,n){let[r]=udt(e);return r?t.fromObject(r,n):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,n=null){if(!e)throw new ja("need to specify a reason the Duration is invalid");let r=e instanceof xu?e:new xu(e,n);if(ci.throwOnInvalid)throw new uie(r);return new t({invalid:r})}static normalizeUnit(e){let n={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!n)throw new a2(e);return n}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,n={}){let r={...n,floor:n.round!==!1&&n.floor!==!1};return this.isValid?Su.create(this.loc,r).formatDurationFromString(this,e):fdt}toHuman(e={}){if(!this.isValid)return fdt;let n=XO.map(r=>{let o=this.values[r];return Hn(o)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:r.slice(0,-1)}).format(o)}).filter(r=>r);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(n)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=c2(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let n=this.toMillis();return n<0||n>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},Wn.fromMillis(n,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?hdt(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let n=t.fromDurationLike(e),r={};for(let o of XO)(vT(n.values,o)||vT(this.values,o))&&(r[o]=n.get(o)+this.get(o));return bT(this,{values:r},!0)}minus(e){if(!this.isValid)return this;let n=t.fromDurationLike(e);return this.plus(n.negate())}mapUnits(e){if(!this.isValid)return this;let n={};for(let r of Object.keys(this.values))n[r]=cEe(e(this.values[r],r));return bT(this,{values:n},!0)}get(e){return this[t.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let n={...this.values,...m2(e,t.normalizeUnit)};return bT(this,{values:n})}reconfigure({locale:e,numberingSystem:n,conversionAccuracy:r,matrix:o}={}){let s={loc:this.loc.clone({locale:e,numberingSystem:n}),matrix:o,conversionAccuracy:r};return bT(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return pdt(this.matrix,e),bT(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=IEn(this.normalize().shiftToAll().toObject());return bT(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(s=>t.normalizeUnit(s));let n={},r={},o=this.toObject(),i;for(let s of XO)if(e.indexOf(s)>=0){i=s;let a=0;for(let c in r)a+=this.matrix[c][s]*r[c],r[c]=0;bw(o[s])&&(a+=o[s]);let l=Math.trunc(a);n[s]=l,r[s]=(a*1e3-l*1e3)/1e3}else bw(o[s])&&(r[s]=o[s]);for(let s in r)r[s]!==0&&(n[i]+=s===i?r[s]:r[s]/this.matrix[i][s]);return pdt(this.matrix,n),bT(this,{values:n},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;let e={};for(let n of Object.keys(this.values))e[n]=this.values[n]===0?0:-this.values[n];return bT(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function n(r,o){return r===void 0||r===0?o===void 0||o===0:r===o}for(let r of XO)if(!n(this.values[r],e.values[r]))return!1;return!0}}});function TEn(t,e){return!t||!t.isValid?TC.invalid("missing or invalid start"):!e||!e.isValid?TC.invalid("missing or invalid end"):e<t?TC.invalid("end before start",`The end of an interval must be after its start, but you had start=${t.toISO()} and end=${e.toISO()}`):null}var _2,TC,yEe=b(()=>{gT();FK();hT();uT();AK();LK();kK();_2="Invalid Interval";TC=class t{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,n=null){if(!e)throw new ja("need to specify a reason the Interval is invalid");let r=e instanceof xu?e:new xu(e,n);if(ci.throwOnInvalid)throw new cie(r);return new t({invalid:r})}static fromDateTimes(e,n){let r=x2(e),o=x2(n),i=TEn(r,o);return i??new t({start:r,end:o})}static after(e,n){let r=Ca.fromDurationLike(n),o=x2(e);return t.fromDateTimes(o,o.plus(r))}static before(e,n){let r=Ca.fromDurationLike(n),o=x2(e);return t.fromDateTimes(o.minus(r),o)}static fromISO(e,n){let[r,o]=(e||"").split("/",2);if(r&&o){let i,s;try{i=Wn.fromISO(r,n),s=i.isValid}catch{s=!1}let a,l;try{a=Wn.fromISO(o,n),l=a.isValid}catch{l=!1}if(s&&l)return t.fromDateTimes(i,a);if(s){let c=Ca.fromISO(o,n);if(c.isValid)return t.after(i,c)}else if(l){let c=Ca.fromISO(r,n);if(c.isValid)return t.before(a,c)}}return t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",n){if(!this.isValid)return NaN;let r=this.start.startOf(e,n),o;return n?.useLocaleWeeks?o=this.end.reconfigure({locale:r.locale}):o=this.end,o=o.startOf(e,n),Math.floor(o.diff(r,e).get(e))+(o.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:n}={}){return this.isValid?t.fromDateTimes(e||this.s,n||this.e):this}splitAt(...e){if(!this.isValid)return[];let n=e.map(x2).filter(s=>this.contains(s)).sort((s,a)=>s.toMillis()-a.toMillis()),r=[],{s:o}=this,i=0;for(;o<this.e;){let s=n[i]||this.e,a=+s>+this.e?this.e:s;r.push(t.fromDateTimes(o,a)),o=a,i+=1}return r}splitBy(e){let n=Ca.fromDurationLike(e);if(!this.isValid||!n.isValid||n.as("milliseconds")===0)return[];let{s:r}=this,o=1,i,s=[];for(;r<this.e;){let a=this.start.plus(n.mapUnits(l=>l*o));i=+a>+this.e?this.e:a,s.push(t.fromDateTimes(r,i)),r=i,o+=1}return s}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;let n=this.s>e.s?this.s:e.s,r=this.e<e.e?this.e:e.e;return n>=r?null:t.fromDateTimes(n,r)}union(e){if(!this.isValid)return this;let n=this.s<e.s?this.s:e.s,r=this.e>e.e?this.e:e.e;return t.fromDateTimes(n,r)}static merge(e){let[n,r]=e.sort((o,i)=>o.s-i.s).reduce(([o,i],s)=>i?i.overlaps(s)||i.abutsStart(s)?[o,i.union(s)]:[o.concat([i]),s]:[o,s],[[],null]);return r&&n.push(r),n}static xor(e){let n=null,r=0,o=[],i=e.map(l=>[{time:l.s,type:"s"},{time:l.e,type:"e"}]),s=Array.prototype.concat(...i),a=s.sort((l,c)=>l.time-c.time);for(let l of a)r+=l.type==="s"?1:-1,r===1?n=l.time:(n&&+n!=+l.time&&o.push(t.fromDateTimes(n,l.time)),n=null);return t.merge(o)}difference(...e){return t.xor([this].concat(e)).map(n=>this.intersection(n)).filter(n=>n&&!n.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:_2}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=dT,n={}){return this.isValid?Su.create(this.s.loc.clone(n),e).formatInterval(this):_2}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:_2}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:_2}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:_2}toFormat(e,{separator:n=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${n}${this.e.toFormat(e)}`:_2}toDuration(e,n){return this.isValid?this.e.diff(this.s,e,n):Ca.invalid(this.invalidReason)}mapEndpoints(e){return t.fromDateTimes(e(this.s),e(this.e))}}});var PC,vEe=b(()=>{gT();hT();PK();mT();bie();Yf();PC=class{static hasDST(e=ci.defaultZone){let n=Wn.now().setZone(e).set({month:12});return!e.isUniversal&&n.offset!==n.set({month:6}).offset}static isValidIANAZone(e){return Kd.isValidZone(e)}static normalizeZone(e){return ww(e,ci.defaultZone)}static getStartOfWeek({locale:e=null,locObj:n=null}={}){return(n||ui.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:n=null}={}){return(n||ui.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:n=null}={}){return(n||ui.create(e)).getWeekendDays().slice()}static months(e="long",{locale:n=null,numberingSystem:r=null,locObj:o=null,outputCalendar:i="gregory"}={}){return(o||ui.create(n,r,i)).months(e)}static monthsFormat(e="long",{locale:n=null,numberingSystem:r=null,locObj:o=null,outputCalendar:i="gregory"}={}){return(o||ui.create(n,r,i)).months(e,!0)}static weekdays(e="long",{locale:n=null,numberingSystem:r=null,locObj:o=null}={}){return(o||ui.create(n,r,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:n=null,numberingSystem:r=null,locObj:o=null}={}){return(o||ui.create(n,r,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return ui.create(e).meridiems()}static eras(e="short",{locale:n=null}={}){return ui.create(n,null,"gregory").eras(e)}static features(){return{relative:yie(),localeWeek:vie()}}}});function gdt(t,e){let n=o=>o.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),r=n(e)-n(t);return Math.floor(Ca.fromMillis(r).as("days"))}function PEn(t,e,n){let r=[["years",(l,c)=>c.year-l.year],["quarters",(l,c)=>c.quarter-l.quarter+(c.year-l.year)*4],["months",(l,c)=>c.month-l.month+(c.year-l.year)*12],["weeks",(l,c)=>{let u=gdt(l,c);return(u-u%7)/7}],["days",gdt]],o={},i=t,s,a;for(let[l,c]of r)n.indexOf(l)>=0&&(s=l,o[l]=c(t,e),a=i.plus(o),a>e?(o[l]--,t=i.plus(o),t>e&&(a=t,o[l]--,t=i.plus(o))):t=a);return[t,o,a,s]}function ydt(t,e,n,r){let[o,i,s,a]=PEn(t,e,n),l=e-o,c=n.filter(d=>["hours","minutes","seconds","milliseconds"].indexOf(d)>=0);c.length===0&&(s<e&&(s=o.plus({[a]:1})),s!==o&&(i[a]=(i[a]||0)+l/(s-o)));let u=Ca.fromObject(i,r);return c.length>0?Ca.fromMillis(l,r).shiftTo(...c).plus(u):u}var vdt=b(()=>{FK()});function bi(t,e=n=>n){return{regex:t,deser:([n])=>e(Put(n))}}function MEn(t){return t.replace(/\./g,"\\.?").replace(xdt,_dt)}function wdt(t){return t.replace(/\./g,"").replace(xdt," ").toLowerCase()}function _w(t,e){return t===null?null:{regex:RegExp(t.map(MEn).join("|")),deser:([n])=>t.findIndex(r=>wdt(n)===wdt(r))+e}}function bdt(t,e){return{regex:t,deser:([,n,r])=>ZO(n,r),groups:e}}function Cie(t){return{regex:t,deser:([e])=>e}}function OEn(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function NEn(t,e){let n=cy(e),r=cy(e,"{2}"),o=cy(e,"{3}"),i=cy(e,"{4}"),s=cy(e,"{6}"),a=cy(e,"{1,2}"),l=cy(e,"{1,3}"),c=cy(e,"{1,6}"),u=cy(e,"{1,9}"),d=cy(e,"{2,4}"),f=cy(e,"{4,6}"),p=g=>({regex:RegExp(OEn(g.val)),deser:([v])=>v,literal:!0}),h=(g=>{if(t.literal)return p(g);switch(g.val){case"G":return _w(e.eras("short"),0);case"GG":return _w(e.eras("long"),0);case"y":return bi(c);case"yy":return bi(d,RK);case"yyyy":return bi(i);case"yyyyy":return bi(f);case"yyyyyy":return bi(s);case"M":return bi(a);case"MM":return bi(r);case"MMM":return _w(e.months("short",!0),1);case"MMMM":return _w(e.months("long",!0),1);case"L":return bi(a);case"LL":return bi(r);case"LLL":return _w(e.months("short",!1),1);case"LLLL":return _w(e.months("long",!1),1);case"d":return bi(a);case"dd":return bi(r);case"o":return bi(l);case"ooo":return bi(o);case"HH":return bi(r);case"H":return bi(a);case"hh":return bi(r);case"h":return bi(a);case"mm":return bi(r);case"m":return bi(a);case"q":return bi(a);case"qq":return bi(r);case"s":return bi(a);case"ss":return bi(r);case"S":return bi(l);case"SSS":return bi(o);case"u":return Cie(u);case"uu":return Cie(a);case"uuu":return bi(n);case"a":return _w(e.meridiems(),0);case"kkkk":return bi(i);case"kk":return bi(d,RK);case"W":return bi(a);case"WW":return bi(r);case"E":case"c":return bi(n);case"EEE":return _w(e.weekdays("short",!1),1);case"EEEE":return _w(e.weekdays("long",!1),1);case"ccc":return _w(e.weekdays("short",!0),1);case"cccc":return _w(e.weekdays("long",!0),1);case"Z":case"ZZ":return bdt(new RegExp(`([+-]${a.source})(?::(${r.source}))?`),2);case"ZZZ":return bdt(new RegExp(`([+-]${a.source})(${r.source})?`),2);case"z":return Cie(/[a-z_+-/]{1,256}?/i);case" ":return Cie(/[^\S\n\r]/);default:return p(g)}})(t)||{invalidReason:AEn};return h.token=t,h}function LEn(t,e,n){let{type:r,value:o}=t;if(r==="literal"){let l=/^\s+$/.test(o);return{literal:!l,val:l?" ":o}}let i=e[r],s=r;r==="hour"&&(e.hour12!=null?s=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?s="hour12":s="hour24":s=n.hour12?"hour12":"hour24");let a=REn[s];if(typeof a=="object"&&(a=a[i]),a)return{literal:!1,val:a}}function $En(t){return[`^${t.map(n=>n.regex).reduce((n,r)=>`${n}(${r.source})`,"")}$`,t]}function DEn(t,e,n){let r=t.match(e);if(r){let o={},i=1;for(let s in n)if(vT(n,s)){let a=n[s],l=a.groups?a.groups+1:1;!a.literal&&a.token&&(o[a.token.val[0]]=a.deser(r.slice(i,i+l))),i+=l}return[r,o]}else return[r,{}]}function FEn(t){let e=i=>{switch(i){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},n=null,r;return Hn(t.z)||(n=Kd.create(t.z)),Hn(t.Z)||(n||(n=new _u(t.Z)),r=t.Z),Hn(t.q)||(t.M=(t.q-1)*3+1),Hn(t.h)||(t.h<12&&t.a===1?t.h+=12:t.h===12&&t.a===0&&(t.h=0)),t.G===0&&t.y&&(t.y=-t.y),Hn(t.u)||(t.S=NK(t.u)),[Object.keys(t).reduce((i,s)=>{let a=e(s);return a&&(i[a]=t[s]),i},{}),n,r]}function UEn(){return wEe||(wEe=Wn.fromMillis(1555555555555)),wEe}function jEn(t,e){if(t.literal)return t;let n=Su.macroTokenToFormatOpts(t.val),r=xEe(n,e);return r==null||r.includes(void 0)?t:r}function bEe(t,e){return Array.prototype.concat(...t.map(n=>jEn(n,e)))}function _Ee(t,e,n){return new UK(t,n).explainFromTokens(e)}function Sdt(t,e,n){let{result:r,zone:o,specificOffset:i,invalidReason:s}=_Ee(t,e,n);return[r,o,i,s]}function xEe(t,e){if(!t)return null;let r=Su.create(e,t).dtFormatter(UEn()),o=r.formatToParts(),i=r.resolvedOptions();return o.map(s=>LEn(s,t,i))}var AEn,EEn,_dt,xdt,REn,wEe,UK,Cdt=b(()=>{Yf();LK();u2();mT();gT();tEe();uT();AEn="missing Intl.DateTimeFormat.formatToParts support";EEn="\xA0",_dt=`[ ${EEn}]`,xdt=new RegExp(_dt,"g");REn={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};wEe=null;UK=class{constructor(e,n){if(this.locale=e,this.format=n,this.tokens=bEe(Su.parseFormat(n),e),this.units=this.tokens.map(r=>NEn(r,e)),this.disqualifyingUnit=this.units.find(r=>r.invalidReason),!this.disqualifyingUnit){let[r,o]=$En(this.units);this.regex=RegExp(r,"i"),this.handlers=o}}explainFromTokens(e){if(this.isValid){let[n,r]=DEn(e,this.regex,this.handlers),[o,i,s]=r?FEn(r):[null,null,void 0];if(vT(r,"a")&&vT(r,"H"))throw new gw("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:n,matches:r,result:o,zone:i,specificOffset:s}}else return{input:e,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}}});function jK(t){return new xu("unsupported zone",`the zone "${t.name}" is not supported`)}function CEe(t){return t.weekData===null&&(t.weekData=EK(t.c)),t.weekData}function kEe(t){return t.localWeekData===null&&(t.localWeekData=EK(t.c,t.loc.getMinDaysInFirstWeek(),t.loc.getStartOfWeek())),t.localWeekData}function QO(t,e){let n={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new Wn({...n,...e,old:n})}function Odt(t,e,n){let r=t-e*60*1e3,o=n.offset(r);if(e===o)return[r,e];r-=(o-e)*60*1e3;let i=n.offset(r);return o===i?[r,o]:[t-Math.min(o,i)*60*1e3,Math.max(o,i)]}function kie(t,e){t+=e*60*1e3;let n=new Date(t);return{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),second:n.getUTCSeconds(),millisecond:n.getUTCMilliseconds()}}function Tie(t,e,n){return Odt(l2(t),e,n)}function Idt(t,e){let n=t.o,r=t.c.year+Math.trunc(e.years),o=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,i={...t.c,year:r,month:o,day:Math.min(t.c.day,p2(r,o))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},s=Ca.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),a=l2(i),[l,c]=Odt(a,n,t.zone);return s!==0&&(l+=s,c=t.zone.offset(l)),{ts:l,o:c}}function S2(t,e,n,r,o,i){let{setZone:s,zone:a}=n;if(t&&Object.keys(t).length!==0||e){let l=e||a,c=Wn.fromObject(t,{...n,zone:l,specificOffset:i});return s?c:c.setZone(a)}else return Wn.invalid(new xu("unparsable",`the input "${o}" can't be parsed as ${r}`))}function Iie(t,e,n=!0){return t.isValid?Su.create(ui.create("en-US"),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(t,e):null}function IEe(t,e){let n=t.c.year>9999||t.c.year<0,r="";return n&&t.c.year>=0&&(r+="+"),r+=Sa(t.c.year,n?6:4),e?(r+="-",r+=Sa(t.c.month),r+="-",r+=Sa(t.c.day)):(r+=Sa(t.c.month),r+=Sa(t.c.day)),r}function Tdt(t,e,n,r,o,i){let s=Sa(t.c.hour);return e?(s+=":",s+=Sa(t.c.minute),(t.c.millisecond!==0||t.c.second!==0||!n)&&(s+=":")):s+=Sa(t.c.minute),(t.c.millisecond!==0||t.c.second!==0||!n)&&(s+=Sa(t.c.second),(t.c.millisecond!==0||!r)&&(s+=".",s+=Sa(t.c.millisecond,3))),o&&(t.isOffsetFixed&&t.offset===0&&!i?s+="Z":t.o<0?(s+="-",s+=Sa(Math.trunc(-t.o/60)),s+=":",s+=Sa(Math.trunc(-t.o%60))):(s+="+",s+=Sa(Math.trunc(t.o/60)),s+=":",s+=Sa(Math.trunc(t.o%60)))),i&&(s+="["+t.zone.ianaName+"]"),s}function VEn(t){let e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[t.toLowerCase()];if(!e)throw new a2(t);return e}function Pdt(t){switch(t.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return VEn(t)}}function qEn(t){return Aie[t]||(Pie===void 0&&(Pie=ci.now()),Aie[t]=t.offset(Pie)),Aie[t]}function Adt(t,e){let n=ww(e.zone,ci.defaultZone);if(!n.isValid)return Wn.invalid(jK(n));let r=ui.fromObject(e),o,i;if(Hn(t.year))o=ci.now();else{for(let l of Rdt)Hn(t[l])&&(t[l]=Ndt[l]);let s=iEe(t)||sEe(t);if(s)return Wn.invalid(s);let a=qEn(n);[o,i]=Tie(t,a,n)}return new Wn({ts:o,zone:n,loc:r,o:i})}function Edt(t,e,n){let r=Hn(n.round)?!0:n.round,o=(s,a)=>(s=c2(s,r||n.calendary?0:2,!0),e.loc.clone(n).relFormatter(n).format(s,a)),i=s=>n.calendary?e.hasSame(t,s)?0:e.startOf(s).diff(t.startOf(s),s).get(s):e.diff(t,s).get(s);if(n.unit)return o(i(n.unit),n.unit);for(let s of n.units){let a=i(s);if(Math.abs(a)>=1)return o(a,s)}return o(t>e?-0:0,n.units[n.units.length-1])}function Mdt(t){let e={},n;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],n=Array.from(t).slice(0,t.length-1)):n=Array.from(t),[e,n]}function x2(t){if(Wn.isDateTime(t))return t;if(t&&t.valueOf&&bw(t.valueOf()))return Wn.fromJSDate(t);if(t&&typeof t=="object")return Wn.fromObject(t);throw new ja(`Unknown datetime argument: ${t}, of type ${typeof t}`)}var SEe,kdt,Ndt,BEn,zEn,Rdt,HEn,WEn,Pie,Aie,Wn,gT=b(()=>{FK();yEe();hT();vEe();LK();u2();PK();Yf();bie();vdt();gEe();Cdt();aEe();kK();uT();AK();SEe="Invalid DateTime",kdt=864e13;Ndt={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},BEn={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},zEn={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Rdt=["year","month","day","hour","minute","second","millisecond"],HEn=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],WEn=["year","ordinal","hour","minute","second","millisecond"];Aie={},Wn=class t{constructor(e){let n=e.zone||ci.defaultZone,r=e.invalid||(Number.isNaN(e.ts)?new xu("invalid input"):null)||(n.isValid?null:jK(n));this.ts=Hn(e.ts)?ci.now():e.ts;let o=null,i=null;if(!r)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(n))[o,i]=[e.old.c,e.old.o];else{let a=bw(e.o)&&!e.old?e.o:n.offset(this.ts);o=kie(this.ts,a),r=Number.isNaN(o.year)?new xu("invalid input"):null,o=r?null:o,i=r?null:a}this._zone=n,this.loc=e.loc||ui.create(),this.invalid=r,this.weekData=null,this.localWeekData=null,this.c=o,this.o=i,this.isLuxonDateTime=!0}static now(){return new t({})}static local(){let[e,n]=Mdt(arguments),[r,o,i,s,a,l,c]=n;return Adt({year:r,month:o,day:i,hour:s,minute:a,second:l,millisecond:c},e)}static utc(){let[e,n]=Mdt(arguments),[r,o,i,s,a,l,c]=n;return e.zone=_u.utcInstance,Adt({year:r,month:o,day:i,hour:s,minute:a,second:l,millisecond:c},e)}static fromJSDate(e,n={}){let r=Vut(e)?e.valueOf():NaN;if(Number.isNaN(r))return t.invalid("invalid input");let o=ww(n.zone,ci.defaultZone);return o.isValid?new t({ts:r,zone:o,loc:ui.fromObject(n)}):t.invalid(jK(o))}static fromMillis(e,n={}){if(bw(e))return e<-kdt||e>kdt?t.invalid("Timestamp out of range"):new t({ts:e,zone:ww(n.zone,ci.defaultZone),loc:ui.fromObject(n)});throw new ja(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,n={}){if(bw(e))return new t({ts:e*1e3,zone:ww(n.zone,ci.defaultZone),loc:ui.fromObject(n)});throw new ja("fromSeconds requires a numerical input")}static fromObject(e,n={}){e=e||{};let r=ww(n.zone,ci.defaultZone);if(!r.isValid)return t.invalid(jK(r));let o=ui.fromObject(n),i=m2(e,Pdt),{minDaysInFirstWeek:s,startOfWeek:a}=oEe(i,o),l=ci.now(),c=Hn(n.specificOffset)?r.offset(l):n.specificOffset,u=!Hn(i.ordinal),d=!Hn(i.year),f=!Hn(i.month)||!Hn(i.day),p=d||f,m=i.weekYear||i.weekNumber;if((p||u)&&m)throw new gw("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(f&&u)throw new gw("Can't mix ordinal dates with month/day");let h=m||i.weekday&&!p,g,v,y=kie(l,c);h?(g=HEn,v=BEn,y=EK(y,s,a)):u?(g=WEn,v=zEn,y=Sie(y)):(g=Rdt,v=Ndt);let w=!1;for(let P of g){let E=i[P];Hn(E)?w?i[P]=v[P]:i[P]=y[P]:w=!0}let _=h?zut(i,s,a):u?Hut(i):iEe(i),S=_||sEe(i);if(S)return t.invalid(S);let I=h?nEe(i,s,a):u?rEe(i):i,[C,k]=Tie(I,c,r),T=new t({ts:C,zone:r,o:k,loc:o});return i.weekday&&p&&e.weekday!==T.weekday?t.invalid("mismatched weekday",`you can't specify both a weekday of ${i.weekday} and a date of ${T.toISO()}`):T.isValid?T:t.invalid(T.invalid)}static fromISO(e,n={}){let[r,o]=sdt(e);return S2(r,o,n,"ISO 8601",e)}static fromRFC2822(e,n={}){let[r,o]=adt(e);return S2(r,o,n,"RFC 2822",e)}static fromHTTP(e,n={}){let[r,o]=ldt(e);return S2(r,o,n,"HTTP",n)}static fromFormat(e,n,r={}){if(Hn(e)||Hn(n))throw new ja("fromFormat requires an input string and a format");let{locale:o=null,numberingSystem:i=null}=r,s=ui.fromOpts({locale:o,numberingSystem:i,defaultToEN:!0}),[a,l,c,u]=Sdt(s,e,n);return u?t.invalid(u):S2(a,l,r,`format ${n}`,e,c)}static fromString(e,n,r={}){return t.fromFormat(e,n,r)}static fromSQL(e,n={}){let[r,o]=ddt(e);return S2(r,o,n,"SQL",e)}static invalid(e,n=null){if(!e)throw new ja("need to specify a reason the DateTime is invalid");let r=e instanceof xu?e:new xu(e,n);if(ci.throwOnInvalid)throw new lie(r);return new t({invalid:r})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,n={}){let r=xEe(e,ui.fromObject(n));return r?r.map(o=>o?o.val:null).join(""):null}static expandFormat(e,n={}){return bEe(Su.parseFormat(e),ui.fromObject(n)).map(o=>o.val).join("")}static resetCache(){Pie=void 0,Aie={}}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?CEe(this).weekYear:NaN}get weekNumber(){return this.isValid?CEe(this).weekNumber:NaN}get weekday(){return this.isValid?CEe(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?kEe(this).weekday:NaN}get localWeekNumber(){return this.isValid?kEe(this).weekNumber:NaN}get localWeekYear(){return this.isValid?kEe(this).weekYear:NaN}get ordinal(){return this.isValid?Sie(this.c).ordinal:NaN}get monthShort(){return this.isValid?PC.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?PC.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?PC.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?PC.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];let e=864e5,n=6e4,r=l2(this.c),o=this.zone.offset(r-e),i=this.zone.offset(r+e),s=this.zone.offset(r-o*n),a=this.zone.offset(r-i*n);if(s===a)return[this];let l=r-s*n,c=r-a*n,u=kie(l,s),d=kie(c,a);return u.hour===d.hour&&u.minute===d.minute&&u.second===d.second&&u.millisecond===d.millisecond?[QO(this,{ts:l}),QO(this,{ts:c})]:[this]}get isInLeapYear(){return JO(this.year)}get daysInMonth(){return p2(this.year,this.month)}get daysInYear(){return this.isValid?yT(this.year):NaN}get weeksInWeekYear(){return this.isValid?YO(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?YO(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){let{locale:n,numberingSystem:r,calendar:o}=Su.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:n,numberingSystem:r,outputCalendar:o}}toUTC(e=0,n={}){return this.setZone(_u.instance(e),n)}toLocal(){return this.setZone(ci.defaultZone)}setZone(e,{keepLocalTime:n=!1,keepCalendarTime:r=!1}={}){if(e=ww(e,ci.defaultZone),e.equals(this.zone))return this;if(e.isValid){let o=this.ts;if(n||r){let i=e.offset(this.ts),s=this.toObject();[o]=Tie(s,i,e)}return QO(this,{ts:o,zone:e})}else return t.invalid(jK(e))}reconfigure({locale:e,numberingSystem:n,outputCalendar:r}={}){let o=this.loc.clone({locale:e,numberingSystem:n,outputCalendar:r});return QO(this,{loc:o})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let n=m2(e,Pdt),{minDaysInFirstWeek:r,startOfWeek:o}=oEe(n,this.loc),i=!Hn(n.weekYear)||!Hn(n.weekNumber)||!Hn(n.weekday),s=!Hn(n.ordinal),a=!Hn(n.year),l=!Hn(n.month)||!Hn(n.day),c=a||l,u=n.weekYear||n.weekNumber;if((c||s)&&u)throw new gw("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&s)throw new gw("Can't mix ordinal dates with month/day");let d;i?d=nEe({...EK(this.c,r,o),...n},r,o):Hn(n.ordinal)?(d={...this.toObject(),...n},Hn(n.day)&&(d.day=Math.min(p2(d.year,d.month),d.day))):d=rEe({...Sie(this.c),...n});let[f,p]=Tie(d,this.o,this.zone);return QO(this,{ts:f,o:p})}plus(e){if(!this.isValid)return this;let n=Ca.fromDurationLike(e);return QO(this,Idt(this,n))}minus(e){if(!this.isValid)return this;let n=Ca.fromDurationLike(e).negate();return QO(this,Idt(this,n))}startOf(e,{useLocaleWeeks:n=!1}={}){if(!this.isValid)return this;let r={},o=Ca.normalizeUnit(e);switch(o){case"years":r.month=1;case"quarters":case"months":r.day=1;case"weeks":case"days":r.hour=0;case"hours":r.minute=0;case"minutes":r.second=0;case"seconds":r.millisecond=0;break;case"milliseconds":break}if(o==="weeks")if(n){let i=this.loc.getStartOfWeek(),{weekday:s}=this;s<i&&(r.weekNumber=this.weekNumber-1),r.weekday=i}else r.weekday=1;if(o==="quarters"){let i=Math.ceil(this.month/3);r.month=(i-1)*3+1}return this.set(r)}endOf(e,n){return this.isValid?this.plus({[e]:1}).startOf(e,n).minus(1):this}toFormat(e,n={}){return this.isValid?Su.create(this.loc.redefaultToEN(n)).formatDateTimeFromString(this,e):SEe}toLocaleString(e=dT,n={}){return this.isValid?Su.create(this.loc.clone(n),e).formatDateTime(this):SEe}toLocaleParts(e={}){return this.isValid?Su.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:n=!1,suppressMilliseconds:r=!1,includeOffset:o=!0,extendedZone:i=!1}={}){if(!this.isValid)return null;let s=e==="extended",a=IEe(this,s);return a+="T",a+=Tdt(this,s,n,r,o,i),a}toISODate({format:e="extended"}={}){return this.isValid?IEe(this,e==="extended"):null}toISOWeekDate(){return Iie(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:n=!1,includeOffset:r=!0,includePrefix:o=!1,extendedZone:i=!1,format:s="extended"}={}){return this.isValid?(o?"T":"")+Tdt(this,s==="extended",n,e,r,i):null}toRFC2822(){return Iie(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return Iie(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?IEe(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:n=!1,includeOffsetSpace:r=!0}={}){let o="HH:mm:ss.SSS";return(n||e)&&(r&&(o+=" "),n?o+="z":e&&(o+="ZZ")),Iie(this,o,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():SEe}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};let n={...this.c};return e.includeConfig&&(n.outputCalendar=this.outputCalendar,n.numberingSystem=this.loc.numberingSystem,n.locale=this.loc.locale),n}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,n="milliseconds",r={}){if(!this.isValid||!e.isValid)return Ca.invalid("created by diffing an invalid DateTime");let o={locale:this.locale,numberingSystem:this.numberingSystem,...r},i=qut(n).map(Ca.normalizeUnit),s=e.valueOf()>this.valueOf(),a=s?this:e,l=s?e:this,c=ydt(a,l,i,o);return s?c.negate():c}diffNow(e="milliseconds",n={}){return this.diff(t.now(),e,n)}until(e){return this.isValid?TC.fromDateTimes(this,e):this}hasSame(e,n,r){if(!this.isValid)return!1;let o=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(n,r)<=o&&o<=i.endOf(n,r)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;let n=e.base||t.fromObject({},{zone:this.zone}),r=e.padding?this<n?-e.padding:e.padding:0,o=["years","months","days","hours","minutes","seconds"],i=e.unit;return Array.isArray(e.unit)&&(o=e.unit,i=void 0),Edt(n,this.plus(r),{...e,numeric:"always",units:o,unit:i})}toRelativeCalendar(e={}){return this.isValid?Edt(e.base||t.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(t.isDateTime))throw new ja("min requires all arguments be DateTimes");return lEe(e,n=>n.valueOf(),Math.min)}static max(...e){if(!e.every(t.isDateTime))throw new ja("max requires all arguments be DateTimes");return lEe(e,n=>n.valueOf(),Math.max)}static fromFormatExplain(e,n,r={}){let{locale:o=null,numberingSystem:i=null}=r,s=ui.fromOpts({locale:o,numberingSystem:i,defaultToEN:!0});return _Ee(s,e,n)}static fromStringExplain(e,n,r={}){return t.fromFormatExplain(e,n,r)}static buildFormatParser(e,n={}){let{locale:r=null,numberingSystem:o=null}=n,i=ui.fromOpts({locale:r,numberingSystem:o,defaultToEN:!0});return new UK(i,e)}static fromFormatParser(e,n,r={}){if(Hn(e)||Hn(n))throw new ja("fromFormatParser requires an input string and a format parser");let{locale:o=null,numberingSystem:i=null}=r,s=ui.fromOpts({locale:o,numberingSystem:i,defaultToEN:!0});if(!s.equals(n.locale))throw new ja(`fromFormatParser called with a locale of ${s}, but the format parser was created for ${n.locale}`);let{result:a,zone:l,specificOffset:c,invalidReason:u}=n.explainFromTokens(e);return u?t.invalid(u):S2(a,l,r,`format ${n.format}`,e,c)}static get DATE_SHORT(){return dT}static get DATE_MED(){return sK}static get DATE_MED_WITH_WEEKDAY(){return DAe}static get DATE_FULL(){return aK}static get DATE_HUGE(){return lK}static get TIME_SIMPLE(){return cK}static get TIME_WITH_SECONDS(){return uK}static get TIME_WITH_SHORT_OFFSET(){return dK}static get TIME_WITH_LONG_OFFSET(){return fK}static get TIME_24_SIMPLE(){return pK}static get TIME_24_WITH_SECONDS(){return mK}static get TIME_24_WITH_SHORT_OFFSET(){return hK}static get TIME_24_WITH_LONG_OFFSET(){return gK}static get DATETIME_SHORT(){return yK}static get DATETIME_SHORT_WITH_SECONDS(){return vK}static get DATETIME_MED(){return wK}static get DATETIME_MED_WITH_SECONDS(){return bK}static get DATETIME_MED_WITH_WEEKDAY(){return FAe}static get DATETIME_FULL(){return _K}static get DATETIME_FULL_WITH_SECONDS(){return xK}static get DATETIME_HUGE(){return SK}static get DATETIME_HUGE_WITH_SECONDS(){return CK}}});var TEe=b(()=>{gT();FK();yEe();vEe();GO();u2();mT();QAe();fie();hT()});function Ldt(t,e=0,n=new Set){if(!t||typeof t!="object"||e>GEn||n.has(t))return null;n.add(t);let r=t;if(r.type===KEn||typeof r.dashboard_url=="string"||typeof r.credits_hint=="string")return{type:typeof r.type=="string"?r.type:void 0,dashboard_url:typeof r.dashboard_url=="string"?r.dashboard_url:void 0,credits_hint:typeof r.credits_hint=="string"?r.credits_hint:void 0,message:typeof r.message=="string"?r.message:void 0};for(let i of Object.values(r)){let s=Ldt(i,e+1,n);if(s)return s}return null}function Eie(t){let e=Ldt(t);return e?`You've reached your usage cap. To keep going beyond your plan's limit, purchase credits on your usage dashboard: ${e.dashboard_url||gct}`:null}var KEn,GEn,PEe=b(()=>{gt();KEn="token_limit_error",GEn=6});function AEe(t,e){let n=t.provider,o=Object.prototype.hasOwnProperty.call(Qp,n)&&!ZEn.has(n),i=Goe[n],s=!!(t.apiKey||i&&e[i]);return o&&!s?{hasApiKey:!1,errorNotice:`Please configure API Key for ${t.name} in settings first.
Path: Settings > Copilot > BYOK`}:{hasApiKey:!0}}var ZEn,Mie=b(()=>{gt();oK();ZEn=new Set(["3rd party (openai-format)","ollama","lm-studio","azure openai","copilot-plus","copilot-plus-jina"])});function Ba(t,e,n={}){let r=n.leading??!1,o=n.trailing??!0,i,s,a,l=!1,c=()=>{let f=s;return s=void 0,l=!1,f&&(a=t(...f)),a},u=()=>{i=window.setTimeout(()=>{i=void 0,o&&l&&c()},e)},d=(...f)=>{s=f,l=!0;let p=i===void 0;return i!==void 0&&window.clearTimeout(i),p&&r&&c(),u(),a};return d.cancel=()=>{i!==void 0&&(window.clearTimeout(i),i=void 0),s=void 0,l=!1},d.flush=()=>i===void 0?a:(window.clearTimeout(i),i=void 0,l?c():a),d}var EEe=b(()=>{});var AC=b(()=>{EEe()});function tN(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Fdt(t){let e=t,n=e?.detail||{};return{status:n.status,message:n.message||e?.message,reason:n.reason}}function JEn(t){let e=Fdt(t),r=t?.message;return!!(e.reason==="Invalid license key"||r==="Invalid license key"||r?.includes("status 403")||e.status===403)}function Udt(t){if(JEn(t))return OEe.INVALID_LICENSE_KEY_USER;let e=Eie(t);if(e)return e;let n=Fdt(t);return n.message||(n.reason?`Error: ${n.reason}`:OEe.UNKNOWN_ERROR)}function C2(t){return t.replace(/^#/,"").trim()}function fy(t,e={}){let{trimStart:n=!0}=e;if(t.startsWith("---")){let r=t.indexOf("---",3);if(r!==-1){let o=t.slice(r+3);return n?o.trimStart():o.startsWith(`\r
`)?o.slice(2):o.startsWith(`
`)||o.startsWith("\r")?o.slice(1):o}}return t}function F_(t,e,n=!0){let r=t.metadataCache.getFileCache(e),o=r?.frontmatter?.tags,i=new Set;if(!n){let s=r?.tags?.map(a=>a.tag);s&&s.forEach(a=>i.add(C2(a)))}return o&&(Array.isArray(o)?o.forEach(s=>{typeof s=="string"&&i.add(C2(s))}):typeof o=="string"&&i.add(C2(o))),Array.from(i)}function Oie(t,e,n){let r=t.metadataCache.getFileCache(e)?.frontmatter;if(!r||!Object.hasOwn(r,n))return $dt;let o=r[n],s=(Array.isArray(o)?o:[o]).filter(XEn);return s.length===0?$dt:s.map(a=>String(a))}function XEn(t){let e=typeof t;return e==="string"||e==="number"||e==="boolean"}function jdt(t,e,n){let r=t.metadataCache.getFileCache(e)?.frontmatter;return r!=null&&Object.hasOwn(r,n)}function Nie(t,e,n){if(e.length===0)return[];e=e.map(i=>C2(i));let r=n&&n.length>0?n:BK(t.vault,"/"),o=[];for(let i of r){let s=F_(t,i);e.some(a=>s.includes(a))&&o.push(i)}return o}async function ao(t,e){let n=(0,Cu.normalizePath)(e).replace(/^\/+/,"").replace(/\/+$/,"");if(!n)return;let r=n.split("/").filter(Boolean),o="";for(let i of r){o=o?`${o}/${i}`:i;let s=t.getAbstractFileByPath(o);if(s){if(s instanceof Cu.TFile)throw new Error(`Path conflict: "${o}" exists as a file, expected folder.`);continue}await t.adapter.mkdir(o)}}function Rie(t){return t?iAe.includes(t.extension):!1}async function k2(t,e){return Rie(t)?await e.read(t):null}function Lie(t){return t.basename}function U_(t){return t?Sct.includes(t.extension):!1}function sd(t){return t==="copilot_plus"}function $ie(t,e){return t?Rie(t)?!0:sd(e):!1}function Bdt(t,e){return!t||!e?!1:t.includes(oAe)&&e.includes(oAe)||t==="small"&&e==="cohereai"||t==="cohereai"&&e==="small"?!0:t===e}function Die(t){let e=[],n=t.history;for(let r=0;r<n.length;r+=2){let o=n[r]?.content||"",i=n[r+1]?.content||"";e.push({role:"user",content:o},{role:"assistant",content:i})}return e}function zdt(t,e){let n=new Map;return t.forEach(r=>{let o=e.getAbstractFileByPath(r);if(o instanceof Cu.TFile)n.set(o.path,o);else{let s=e.getMarkdownFiles().filter(a=>a.basename===r);s.length>0&&(QEn(r,e)?n.set(s[0].path,s[0]):W(`Found multiple files with title "${r}". Expected a full path for duplicate titles.`))}}),Array.from(n.values())}function j_(t,e){let n=/\[\[(.*?)\]\]/g,r=t.match(n);if(!r)return[];let o=r.map(i=>i.slice(2,-2));return zdt(o,e)}function Hdt(t,e){let n=/\{\[\[(.*?)\]\]\}/g,r=t.match(n);if(!r)return[];let o=r.map(i=>i.slice(3,-3));return zdt(o,e)}function QEn(t,e){return e.getMarkdownFiles().filter(r=>r.basename===t).length===1}function Wdt(t){return t=t.trim(),t.startsWith("[[")&&t.endsWith("]]")?`${t.slice(2,-2).trim()}.md`:t}function Vdt(t){let e=new Set;return t.forEach(n=>{n.metadata?.title&&e.add(n.metadata.title)}),Array.from(e)}function NEe(t){if(!t||typeof t!="string")return{isValid:!1,error:"URL is required"};let e=t.trim();if(!e)return{isValid:!1,error:"URL cannot be empty"};let n=REe(e);return n?/^[a-zA-Z0-9_-]{11}$/.test(n)?{isValid:!0,videoId:n}:{isValid:!1,error:"Invalid YouTube video ID"}:{isValid:!1,error:"Invalid YouTube URL format"}}function REe(t){try{let e=[/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/v\/)([a-zA-Z0-9_-]{11})/,/youtube\.com\/shorts\/([a-zA-Z0-9_-]{11})/];for(let n of e){let r=t.match(n);if(r&&r[1])return r[1]}return null}catch{return null}}function qdt(t){return`https://www.youtube.com/watch?v=${t}`}function Kdt(t){return NEe(t).isValid}function Gdt(t){if(!t||typeof t!="string")return!1;try{let e=new URL(t.trim());return(e.hostname==="x.com"||e.hostname==="www.x.com"||e.hostname==="twitter.com"||e.hostname==="www.twitter.com")&&e.pathname.includes("/status/")}catch{return!1}}function Zdt(t){let e=t.matchAll(new RegExp(eMn,"g"));return Array.from(e,n=>n[0])}async function ks(t,e={}){let{throwOnHttpError:n=!0}=e,r=new Headers(e.headers),o=Object.fromEntries(r.entries());delete o["content-length"],j("safeFetch request");let i=e.method?.toUpperCase()||"POST",a=await(0,Cu.requestUrl)({url:t,contentType:"application/json",headers:o,method:i,...["POST","PUT","PATCH"].includes(i)&&typeof e.body=="string"&&{body:e.body},throw:!1});if(n&&a.status>=400){let l=null;try{l=typeof a.json=="string"?JSON.parse(a.json):a.json}catch{try{l=typeof a.text=="string"?JSON.parse(a.text):a.text}catch{l=null}}let c=new Error(OEe.REQUEST_FAILED(a.status));c.json=l;let u=l&&typeof l.detail=="object"?l.detail:void 0;if(u?.reason==="Invalid license key"||l?.reason==="Invalid license key")c.message="Invalid license key";else if(u?.message||l?.message){let d=u?.message||l?.message,f=u?.reason||l?.reason;c.message=f?`${d}: ${f}`:d??""}else l?.detail?c.message=JSON.stringify(l.detail):l&&(c.message+=". "+JSON.stringify(l));throw c}return{ok:a.status>=200&&a.status<300,status:a.status,statusText:a.status.toString(),headers:new Headers(a.headers),url:t,type:"basic",redirected:!1,bytes:()=>Promise.resolve(new Uint8Array(0)),body:tMn(a.text),bodyUsed:!0,json:()=>Promise.resolve(a.json),text:async()=>a.text,arrayBuffer:async()=>{if(a.arrayBuffer)return a.arrayBuffer;let l=a.text.replace(/^data:.*;base64,/,""),c=Ddt.Buffer.from(l,"base64");return c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength)},blob:()=>{throw new Error("not implemented")},formData:()=>{throw new Error("not implemented")},clone:()=>{throw new Error("not implemented")}}}function bh(t,e={}){return ks(t,{...e,throwOnHttpError:!1})}function tMn(t){return new ReadableStream({start(e){let r=new TextEncoder().encode(t);e.enqueue(r),e.close()}})}function Ydt(t,e){let[n,r]=t.split("|"),o=e.find(i=>i.name===n&&i.provider===r);if(!o)throw new Error(`No model configuration found for: ${t}`);return o}function Fie(t){return!!t.capabilities?.includes("vision")}function _h(t){let e=t;return e=LEe(e),e=e.replace(/```xml\s*[\s\S]*?<write(?:File|ToFile)>[\s\S]*?<\/write(?:File|ToFile)>[\s\S]*?```/g,""),e=e.replace(/<write(?:File|ToFile)>[\s\S]*?<\/write(?:File|ToFile)>/g,""),e=e.replace(/<!--TOOL_CALL_START:[^:]+:[^:]+:[^:]+:[^:]+:[^:]*:[^:]+-->[\s\S]*?<!--TOOL_CALL_END:[^:]+:[\s\S]*?-->/g,""),e=e.replace(/<!--AGENT_REASONING:\w+:\d+:.*-->/g,""),e=e.replace(/\n{3,}/g,`
`),e=e.trim(),e}async function I2(t,e){let n=t.workspace.getMostRecentLeaf();if((!n||!(n.view instanceof Cu.MarkdownView))&&(n=t.workspace.getLeaf(!1),!n||!(n.view instanceof Cu.MarkdownView)))return;let r=n.view.editor.getSelection().length>0;await zK(t,e,r)}async function zK(t,e,n=!1){let r=t.workspace.getMostRecentLeaf();if(!r){new Cu.Notice("No active leaf found.");return}if(r.view instanceof Cu.MarkdownView||(r=t.workspace.getLeaf(!1),await r.setViewState({type:"markdown",state:r.view.getState()})),!(r.view instanceof Cu.MarkdownView)){new Cu.Notice("Failed to open a markdown view.");return}let o=r.view.editor,i=o.getCursor("from"),s=o.getCursor("to"),a=_h(e),l=a.split(`
`),c=(w,_)=>{let S=_.length-1;return S===0?{line:w.line,ch:w.ch+(_[0]?.length??0)}:{line:w.line+S,ch:_[_.length-1]?.length??0}},u=()=>{let w=n?i:s;o.replaceRange(a,w,s),o.setSelection(w,c(w,l))},d=()=>{o.focus(),new Cu.Notice("Message inserted into the active note.")},f=o.cm;if(!(f?.state?.doc&&typeof f.dispatch=="function")){u(),d();return}let{from:m,to:h}=f.state.selection.main,g=n?m:h,v=f.state.toText(a),y=g+v.length;try{f.dispatch({changes:{from:g,to:h,insert:v},selection:{anchor:g,head:y}})}catch(w){W("CM6 dispatch failed, falling back to Obsidian API",w),u()}d()}function Uie(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<3;o++){if(n[o]>r[o])return!0;if(n[o]<r[o])return!1}return!1}async function Jdt(){try{return{version:(await(0,Cu.requestUrl)({url:"https://api.github.com/repos/logancyang/obsidian-copilot/releases/latest",method:"GET"})).json.tag_name.replace("v",""),error:null}}catch(t){return{version:null,error:t instanceof Error?t.message:"Failed to check for updates"}}}function HK(t){if(typeof t=="string")return t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4");let e=t,n=e.modelName||e.model||"";return n.startsWith("o1")||n.startsWith("o3")||n.startsWith("o4")}function nMn(t){if(typeof t=="string")return t.startsWith("gpt-5");let e=t;return(e.modelName||e.model||"").startsWith("gpt-5")}function WK(t){let e=t,n=typeof t=="string"?t:e.modelName||e.model||"",r=HK(n),o=nMn(n),i=n.startsWith("claude-3-7-sonnet")||n.startsWith("claude-sonnet-4")||n.startsWith("claude-opus-4"),s=n.match(/^claude-opus-4-(\d{1,2})(?:[-.]|$)/),a=s?parseInt(s[1],10)>=7:!1;return{isOSeries:r,isGPT5:o,isThinkingEnabled:i,usesAdaptiveThinking:a}}function VK(t,e="system"){return HK(t)?"human":e}function T2(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>e.text??"").join(""):""}function LEe(t){let n=T2(t).replace(/<think>[\s\S]*?<\/think>/g,"");return n=n.replace(/<think>[\s\S]*$/g,""),n.trim()}function Xdt(t){return T2(t).replace(/<errorChunk>[\s\S]*?<\/errorChunk>/g,"").trim()}function jie(){return crypto.randomUUID()}async function Jf(t){let e=console.warn;try{return console.warn=function(...n){let r=n[0];typeof r=="string"&&(r.includes("Failed to calculate number of tokens")||r.includes("Unknown model"))||e.apply(console,n)},await t()}finally{console.warn=e}}async function Bie(t,e,n="Operation"){let{TimeoutError:r}=await Promise.resolve().then(()=>(iy(),kct)),o=new AbortController,i=window.setTimeout(()=>{o.abort()},e);try{return await Promise.race([t(o.signal),new Promise((s,a)=>{o.signal.addEventListener("abort",()=>{a(new r(n,e))})})])}finally{window.clearTimeout(i)}}function qK(t){let e=t.workspace.getActiveViewOfType(Cu.MarkdownView);return e?e.getState().source===!0:!0}function xw(t){return new TextEncoder().encode(t).length}function _T(t,e){if(e<=0)return"";let n=new TextEncoder;if(n.encode(t).length<=e)return t;let o=0,i=t.length,s="";for(;o<=i;){let a=Math.floor((o+i)/2),l=t.substring(0,a);n.encode(l).length<=e?(s=l,o=a+1):i=a-1}return s}function $Ee(t){let e=t.split("/"),n=e[e.length-1];if(xw(n)<=MEe)return t;let r=n.lastIndexOf("."),o=r>=0?n.substring(r):"",i=r>=0?n.substring(0,r):n,s=xw(o),a=MEe-s;return a<=0?e[e.length-1]=_T(n,MEe):e[e.length-1]=_T(i,a)+o,e.join("/")}async function Qdt(t,e,n=!0){let r=null;t.workspace.iterateAllLeaves(o=>{if(o.view.getViewType()==="markdown"||o.view.getViewType()==="pdf"||o.view.getViewType()==="canvas"){let i=o.view.file;i&&i.path===e.path&&(r=o)}}),r&&n?t.workspace.setActiveLeaf(r,{focus:!0}):r||await t.workspace.getLeaf("tab").openFile(e)}var Ddt,Cu,OEe,BK,$dt,Cs,eMn,MEe,ut=b(()=>{Ddt=L($Ae());mw();gt();pe();TEe();Cu=require("obsidian");PEe();Mie();AC();OEe={INVALID_LICENSE_KEY_USER:"Invalid Copilot Plus license key. Please check your license key in settings.",UNKNOWN_ERROR:"An unknown error occurred",REQUEST_FAILED:t=>`Request failed, status ${t}`};BK=(t,e)=>{let n=t.getMarkdownFiles();if(e==="/")return n;let r=e.toLowerCase().replace(/^\/|\/$/g,"");return n.filter(o=>{let s=o.path.toLowerCase().split("/"),a=r.split("/"),l=0;for(let c of a){for(;l<s.length&&s[l]!==c;)l++;if(l>=s.length)return!1}return!0})};$dt=Object.freeze([]);Cs=(t,e="local")=>{let n=e==="utc"?Wn.fromJSDate(t).toUTC():Wn.fromJSDate(t);return{fileName:n.toFormat("yyyyMMdd_HHmmss"),display:n.toFormat("yyyy/MM/dd HH:mm:ss"),epoch:n.toMillis()}};eMn=/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|shorts\/)|youtu\.be\/)([^\s&]+)/;MEe=255});function eft(t){return(t.copilotFolder||"").trim()||VF}function A2(t,e){return(0,DEe.normalizePath)(`${eft(t)}/${e}`)}function zie(t){return A2(t,P2.conversations)}function EC(t){return A2(t,P2.customPrompts)}function xT(t){return A2(t,P2.systemPrompts)}function Sw(t){return A2(t,P2.skills)}function Hie(t){return A2(t,P2.memory)}function KK(t){return A2(t,P2.projects)}function GK(){return(0,DEe.normalizePath)(eft(Y()))}function ST(){return zie(Y())}function E2(){return EC(Y())}function Wie(){return xT(Y())}function M2(){return Sw(Y())}function O2(){return Hie(Y())}function Vie(){return KK(Y())}async function qie(t,e){let n=[zie,EC,xT,Sw,Hie,KK];for(let r of n){let o=r(e);try{await ao(t,o)}catch(i){W(`Could not pre-create Copilot sub-folder "${o}".`,i)}}}var DEe,P2,Is=b(()=>{gt();pe();Se();ut();DEe=require("obsidian"),P2=Object.freeze({conversations:"copilot-conversations",customPrompts:"copilot-custom-prompts",systemPrompts:"system-prompts",skills:"skills",memory:"memory",projects:"projects"})});var tft,FEe,$l,nN=b(()=>{oK();tft=require("obsidian");ut();Se();Is();WO();FEe=class t{constructor(){this.maxLines=500;this.maxLineChars=8e3;this.buffer=[];this.initialized=!1;this.flushing=!1;this.app=null}static getInstance(){return t.instance||(t.instance=new t),t.instance}setApp(e){this.app=e}getLogPath(){return`${GK()}/copilot-log.md`}async ensureInitialized(){this.initialized||(this.initialized=!0)}sanitizeForSingleLine(e){if(e instanceof Error){let n=kt(e,!0);return this.escapeAngleBrackets(this.collapseToSingleLine(n))}if(typeof e=="string")return this.escapeAngleBrackets(this.collapseToSingleLine(e));try{let n=JSON.stringify(e);return this.escapeAngleBrackets(this.collapseToSingleLine(n??String(e)))}catch{return this.escapeAngleBrackets(this.collapseToSingleLine(String(e)))}}collapseToSingleLine(e){let n=e.replace(/[\r\n]+/g,"\\n").replace(/\t/g," ");return n.length<=this.maxLineChars?n:n.slice(0,this.maxLineChars)+` \u2026 [truncated ${n.length-this.maxLineChars} chars]`}async append(e,...n){await this.ensureInitialized();let r=new Date().toISOString(),o=n.map(s=>this.sanitizeForSingleLine(s)),i=`${r} ${e} ${o.join(" ")}`.trim();this.buffer.push(i),this.buffer.length>this.maxLines&&this.buffer.splice(0,this.buffer.length-this.maxLines)}escapeAngleBrackets(e){return e.replace(/</g,"&lt;").replace(/>/g,"&gt;")}async appendMarkdownBlock(e){if(await this.ensureInitialized(),!(!Array.isArray(e)||e.length===0))for(let n of e){let r=typeof n=="string"?n:String(n??"");this.buffer.push(r),this.buffer.length>this.maxLines&&this.buffer.splice(0,this.buffer.length-this.maxLines)}}async flush(){let e=this.app;if(e?.vault?.adapter&&!this.flushing){this.flushing=!0;try{let n=this.getLogPath();if(await e.vault.adapter.exists(n)){let r=this.buffer.join(`
`)+(this.buffer.length?`
`:"");await e.vault.adapter.write(n,r)}}catch{}finally{this.flushing=!1}}}async clear(){this.buffer=[];let e=this.app;if(e?.vault?.adapter)try{let n=this.getLogPath();await e.vault.adapter.exists(n)&&await e.vault.adapter.remove(n)}catch{}}sanitizeSettingsForLog(){let e=Y();return this.removeKeysRecursive(e)}removeKeysRecursive(e){if(e==null)return e;if(Array.isArray(e))return e.map(n=>this.removeKeysRecursive(n));if(typeof e=="object"&&e.constructor===Object){let n={},r=e;for(let[o,i]of Object.entries(r))HO(o)||/orgId$/i.test(o)||/instanceName$/i.test(o)||/deploymentName$/i.test(o)||/apiVersion$/i.test(o)||(n[o]=this.removeKeysRecursive(i));return n}return e}async openLogFile(){let e=this.app;if(!e?.vault?.adapter)return;let n=this.getLogPath(),r=[...this.buffer];try{let s=this.sanitizeSettingsForLog(),l=["","## Settings","```json",...JSON.stringify(s,null,2).split(`
`),"```"];r.push(...l)}catch{}try{let s=r.join(`
`)+(r.length?`
`:""),a=n.includes("/")?n.split("/").slice(0,-1).join("/"):"";a&&await ao(e.vault,a),await e.vault.adapter.exists(n)?await e.vault.adapter.write(n,s):await e.vault.create(n,s)}catch{}let o=e.vault.getAbstractFileByPath(n),i=o instanceof tft.TFile?o:null;try{i&&await e.workspace.getLeaf(!0).openFile(i)}catch{}}},$l=FEe.getInstance()});function j(...t){Y().debug&&console.debug(...t),$l.append("INFO",...t)}function H(...t){Y().debug&&console.error(...t),$l.append("ERROR",...t)}function W(...t){Y().debug&&console.warn(...t),$l.append("WARN",...t)}function Kie(t){$l.appendMarkdownBlock(t)}var pe=b(()=>{Se();nN()});function aft(t){on.set(Gie,t)}function L2(){return on.get(Gie)}function lft(t){return on.sub(Gie,t)}function CT(){return zO(Gie,{store:on})}function B_(){return on.get(UEe)}function cft(t){return on.sub(UEe,t)}function Cw(){return zO(UEe,{store:on})}function z_(t){on.set(jEe,t)}function hy(){return on.get(jEe)}function Zie(t){let e=hy();z_(e.filter(n=>n.id!==t))}function YK(){hy().length!==0&&z_([])}function Yie(){return zO(jEe,{store:on})}function Jie(){return on.get(ZK)}function BEe(t){on.set(ZK,t)}function ad(t){on.set(ZK,e=>({...e,...t}))}function zEe(){py!==null&&(window.clearTimeout(py),py=null),N2=0,R2=0,on.set(ZK,{isActive:!1,isPaused:!1,isCancelled:!1,indexedCount:0,totalFiles:0,errors:[],completionStatus:"none"})}function uft(t){R2=t;let e=Date.now();e-N2>=oft?(N2=e,py!==null&&(window.clearTimeout(py),py=null),ad({indexedCount:R2})):py===null&&(py=window.setTimeout(()=>{N2=Date.now(),py=null,ad({indexedCount:R2})},oft-(e-N2)))}function dft(){py!==null&&(window.clearTimeout(py),py=null),ad({indexedCount:R2}),N2=0,R2=0}function kT(){return zO(ZK,{store:on})}var nft,Gie,rft,UEe,ift,sft,my,ZK,jEe,N2,R2,py,oft,es=b(()=>{Se();Us();nft=yo(null),Gie=yo(t=>{let e=t(nft);return e!==null?e:t(yh).defaultModelKey},(t,e,n)=>{e(nft,n)}),rft=yo(null),UEe=yo(t=>{let e=t(rft);return e!==null?e:t(yh).defaultChainType},(t,e,n)=>{e(rft,n)}),ift=Object.freeze([]),sft=Object.freeze([]),my=yo({}),ZK=yo({isActive:!1,isPaused:!1,isCancelled:!1,indexedCount:0,totalFiles:0,errors:[],completionStatus:"none"}),jEe=yo([]);N2=0,R2=0,py=null,oft=500});function fft(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function pft(...t){return e=>{let n=!1,r=t.map(o=>{let i=fft(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():fft(t[o],null)}}}}var rMn,mft=b(()=>{rMn=L(B(),1)});var gft=wi(Xie=>{"use strict";var oMn=B(),iMn=Symbol.for("react.element"),sMn=Symbol.for("react.fragment"),aMn=Object.prototype.hasOwnProperty,lMn=oMn.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,cMn={key:!0,ref:!0,__self:!0,__source:!0};function hft(t,e,n){var r,o={},i=null,s=null;n!==void 0&&(i=""+n),e.key!==void 0&&(i=""+e.key),e.ref!==void 0&&(s=e.ref);for(r in e)aMn.call(e,r)&&!cMn.hasOwnProperty(r)&&(o[r]=e[r]);if(t&&t.defaultProps)for(r in e=t.defaultProps,e)o[r]===void 0&&(o[r]=e[r]);return{$$typeof:iMn,type:t,key:i,ref:s,props:o,_owner:lMn.current}}Xie.Fragment=sMn;Xie.jsx=hft;Xie.jsxs=hft});var Mt=wi((wqr,yft)=>{"use strict";yft.exports=gft()});function dMn(t){return typeof t=="object"&&t!==null&&"then"in t}function vft(t){return t!=null&&typeof t=="object"&&"$$typeof"in t&&t.$$typeof===uMn&&"_payload"in t&&dMn(t._payload)}function fMn(t){let e=pMn(t),n=Dl.forwardRef((r,o)=>{let{children:i,...s}=r;vft(i)&&typeof ese=="function"&&(i=ese(i._payload));let a=Dl.Children.toArray(i),l=a.find(hMn);if(l){let c=l.props.children,u=a.map(d=>d===l?Dl.Children.count(c)>1?Dl.Children.only(null):Dl.isValidElement(c)?c.props.children:null:d);return(0,Qie.jsx)(e,{...s,ref:o,children:Dl.isValidElement(c)?Dl.cloneElement(c,void 0,u):null})}return(0,Qie.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function pMn(t){let e=Dl.forwardRef((n,r)=>{let{children:o,...i}=n;if(vft(o)&&typeof ese=="function"&&(o=ese(o._payload)),Dl.isValidElement(o)){let s=yMn(o),a=gMn(i,o.props);return o.type!==Dl.Fragment&&(a.ref=r?pft(r,s):s),Dl.cloneElement(o,a)}return Dl.Children.count(o)>1?Dl.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}function hMn(t){return Dl.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===mMn}function gMn(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function yMn(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Dl,Qie,uMn,ese,wft,mMn,bft=b(()=>{Dl=L(B(),1);mft();Qie=L(Mt(),1),uMn=Symbol.for("react.lazy"),ese=Dl[" use ".trim().toString()];wft=fMn("Slot");mMn=Symbol("radix.slottable")});function _ft(t){var e,n,r="";if(typeof t=="string"||typeof t=="number")r+=t;else if(typeof t=="object")if(Array.isArray(t)){var o=t.length;for(e=0;e<o;e++)t[e]&&(n=_ft(t[e]))&&(r&&(r+=" "),r+=n)}else for(n in t)t[n]&&(r&&(r+=" "),r+=n);return r}function tse(){for(var t,e,n=0,r="",o=arguments.length;n<o;n++)(t=arguments[n])&&(e=_ft(t))&&(r&&(r+=" "),r+=e);return r}var HEe=b(()=>{});var xft,Sft,$2,nse=b(()=>{HEe();xft=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,Sft=tse,$2=(t,e)=>n=>{var r;if(e?.variants==null)return Sft(t,n?.class,n?.className);let{variants:o,defaultVariants:i}=e,s=Object.keys(o).map(c=>{let u=n?.[c],d=i?.[c];if(u===null)return null;let f=xft(u)||xft(d);return o[c][f]}),a=n&&Object.entries(n).reduce((c,u)=>{let[d,f]=u;return f===void 0||(c[d]=f),c},{}),l=e==null||(r=e.compoundVariants)===null||r===void 0?void 0:r.reduce((c,u)=>{let{class:d,className:f,...p}=u;return Object.entries(p).every(m=>{let[h,g]=m;return Array.isArray(g)?g.includes({...i,...a}[h]):{...i,...a}[h]===g})?[...c,d,f]:c},[]);return Sft(t,s,l,n?.class,n?.className)}});function AMn(){let t=0,e,n,r="";for(;t<arguments.length;)(e=arguments[t++])&&(n=Eft(e))&&(r&&(r+=" "),r+=n);return r}function Ift(t,...e){let n,r,o,i=s;function s(l){let c=e.reduce((u,d)=>d(u),t());return n=IMn(c),r=n.cache.get,o=n.cache.set,i=a,a(l)}function a(l){let c=r(l);if(c)return c;let u=PMn(l,n);return o(l,u),u}return function(){return i(AMn.apply(null,arguments))}}var qEe,vMn,Pft,Cft,wMn,bMn,VEe,kft,_Mn,xMn,SMn,Aft,CMn,kMn,IMn,TMn,PMn,Eft,js,Mft,EMn,MMn,OMn,NMn,RMn,LMn,$Mn,MC,IT,D2,WEe,JK,DMn,eo,TT,FMn,UMn,jMn,BMn,zMn,HMn,XK,F2,WMn,Oft,VMn,qMn,Tft,KMn,QK,GMn,ZMn,Nft,Rft=b(()=>{qEe="-",vMn=t=>{let e=bMn(t),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:s=>{let a=s.split(qEe);return a[0]===""&&a.length!==1&&a.shift(),Pft(a,e)||wMn(s)},getConflictingClassGroupIds:(s,a)=>{let l=n[s]||[];return a&&r[s]?[...l,...r[s]]:l}}},Pft=(t,e)=>{if(t.length===0)return e.classGroupId;let n=t[0],r=e.nextPart.get(n),o=r?Pft(t.slice(1),r):void 0;if(o)return o;if(e.validators.length===0)return;let i=t.join(qEe);return e.validators.find(({validator:s})=>s(i))?.classGroupId},Cft=/^\[(.+)\]$/,wMn=t=>{if(Cft.test(t)){let e=Cft.exec(t)[1],n=e?.substring(0,e.indexOf(":"));if(n)return"arbitrary.."+n}},bMn=t=>{let{theme:e,prefix:n}=t,r={nextPart:new Map,validators:[]};return xMn(Object.entries(t.classGroups),n).forEach(([i,s])=>{VEe(s,r,i,e)}),r},VEe=(t,e,n,r)=>{t.forEach(o=>{if(typeof o=="string"){let i=o===""?e:kft(e,o);i.classGroupId=n;return}if(typeof o=="function"){if(_Mn(o)){VEe(o(r),e,n,r);return}e.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{VEe(s,kft(e,i),n,r)})})},kft=(t,e)=>{let n=t;return e.split(qEe).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},_Mn=t=>t.isThemeGetter,xMn=(t,e)=>e?t.map(([n,r])=>{let o=r.map(i=>typeof i=="string"?e+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,a])=>[e+s,a])):i);return[n,o]}):t,SMn=t=>{if(t<1)return{get:()=>{},set:()=>{}};let e=0,n=new Map,r=new Map,o=(i,s)=>{n.set(i,s),e++,e>t&&(e=0,r=n,n=new Map)};return{get(i){let s=n.get(i);if(s!==void 0)return s;if((s=r.get(i))!==void 0)return o(i,s),s},set(i,s){n.has(i)?n.set(i,s):o(i,s)}}},Aft="!",CMn=t=>{let{separator:e,experimentalParseClassName:n}=t,r=e.length===1,o=e[0],i=e.length,s=a=>{let l=[],c=0,u=0,d;for(let g=0;g<a.length;g++){let v=a[g];if(c===0){if(v===o&&(r||a.slice(g,g+i)===e)){l.push(a.slice(u,g)),u=g+i;continue}if(v==="/"){d=g;continue}}v==="["?c++:v==="]"&&c--}let f=l.length===0?a:a.substring(u),p=f.startsWith(Aft),m=p?f.substring(1):f,h=d&&d>u?d-u:void 0;return{modifiers:l,hasImportantModifier:p,baseClassName:m,maybePostfixModifierPosition:h}};return n?a=>n({className:a,parseClassName:s}):s},kMn=t=>{if(t.length<=1)return t;let e=[],n=[];return t.forEach(r=>{r[0]==="["?(e.push(...n.sort(),r),n=[]):n.push(r)}),e.push(...n.sort()),e},IMn=t=>({cache:SMn(t.cacheSize),parseClassName:CMn(t),...vMn(t)}),TMn=/\s+/,PMn=(t,e)=>{let{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:o}=e,i=[],s=t.trim().split(TMn),a="";for(let l=s.length-1;l>=0;l-=1){let c=s[l],{modifiers:u,hasImportantModifier:d,baseClassName:f,maybePostfixModifierPosition:p}=n(c),m=!!p,h=r(m?f.substring(0,p):f);if(!h){if(!m){a=c+(a.length>0?" "+a:a);continue}if(h=r(f),!h){a=c+(a.length>0?" "+a:a);continue}m=!1}let g=kMn(u).join(":"),v=d?g+Aft:g,y=v+h;if(i.includes(y))continue;i.push(y);let w=o(h,m);for(let _=0;_<w.length;++_){let S=w[_];i.push(v+S)}a=c+(a.length>0?" "+a:a)}return a};Eft=t=>{if(typeof t=="string")return t;let e,n="";for(let r=0;r<t.length;r++)t[r]&&(e=Eft(t[r]))&&(n&&(n+=" "),n+=e);return n};js=t=>{let e=n=>n[t]||[];return e.isThemeGetter=!0,e},Mft=/^\[(?:([a-z-]+):)?(.+)\]$/i,EMn=/^\d+\/\d+$/,MMn=new Set(["px","full","screen"]),OMn=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,NMn=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,RMn=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,LMn=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,$Mn=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,MC=t=>D2(t)||MMn.has(t)||EMn.test(t),IT=t=>F2(t,"length",WMn),D2=t=>!!t&&!Number.isNaN(Number(t)),WEe=t=>F2(t,"number",D2),JK=t=>!!t&&Number.isInteger(Number(t)),DMn=t=>t.endsWith("%")&&D2(t.slice(0,-1)),eo=t=>Mft.test(t),TT=t=>OMn.test(t),FMn=new Set(["length","size","percentage"]),UMn=t=>F2(t,FMn,Oft),jMn=t=>F2(t,"position",Oft),BMn=new Set(["image","url"]),zMn=t=>F2(t,BMn,qMn),HMn=t=>F2(t,"",VMn),XK=()=>!0,F2=(t,e,n)=>{let r=Mft.exec(t);return r?r[1]?typeof e=="string"?r[1]===e:e.has(r[1]):n(r[2]):!1},WMn=t=>NMn.test(t)&&!RMn.test(t),Oft=()=>!1,VMn=t=>LMn.test(t),qMn=t=>$Mn.test(t),Tft=()=>{let t=js("colors"),e=js("spacing"),n=js("blur"),r=js("brightness"),o=js("borderColor"),i=js("borderRadius"),s=js("borderSpacing"),a=js("borderWidth"),l=js("contrast"),c=js("grayscale"),u=js("hueRotate"),d=js("invert"),f=js("gap"),p=js("gradientColorStops"),m=js("gradientColorStopPositions"),h=js("inset"),g=js("margin"),v=js("opacity"),y=js("padding"),w=js("saturate"),_=js("scale"),S=js("sepia"),I=js("skew"),C=js("space"),k=js("translate"),T=()=>["auto","contain","none"],P=()=>["auto","hidden","clip","visible","scroll"],E=()=>["auto",eo,e],O=()=>[eo,e],$=()=>["",MC,IT],U=()=>["auto",D2,eo],V=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],K=()=>["solid","dashed","dotted","double","none"],se=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],le=()=>["start","end","center","between","around","evenly","stretch"],Q=()=>["","0",eo],ne=()=>["auto","avoid","all","avoid-page","page","left","right","column"],ee=()=>[D2,eo];return{cacheSize:500,separator:":",theme:{colors:[XK],spacing:[MC,IT],blur:["none","",TT,eo],brightness:ee(),borderColor:[t],borderRadius:["none","","full",TT,eo],borderSpacing:O(),borderWidth:$(),contrast:ee(),grayscale:Q(),hueRotate:ee(),invert:Q(),gap:O(),gradientColorStops:[t],gradientColorStopPositions:[DMn,IT],inset:E(),margin:E(),opacity:ee(),padding:O(),saturate:ee(),scale:ee(),sepia:Q(),skew:ee(),space:O(),translate:O()},classGroups:{aspect:[{aspect:["auto","square","video",eo]}],container:["container"],columns:[{columns:[TT]}],"break-after":[{"break-after":ne()}],"break-before":[{"break-before":ne()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...V(),eo]}],overflow:[{overflow:P()}],"overflow-x":[{"overflow-x":P()}],"overflow-y":[{"overflow-y":P()}],overscroll:[{overscroll:T()}],"overscroll-x":[{"overscroll-x":T()}],"overscroll-y":[{"overscroll-y":T()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[h]}],"inset-x":[{"inset-x":[h]}],"inset-y":[{"inset-y":[h]}],start:[{start:[h]}],end:[{end:[h]}],top:[{top:[h]}],right:[{right:[h]}],bottom:[{bottom:[h]}],left:[{left:[h]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",JK,eo]}],basis:[{basis:E()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",eo]}],grow:[{grow:Q()}],shrink:[{shrink:Q()}],order:[{order:["first","last","none",JK,eo]}],"grid-cols":[{"grid-cols":[XK]}],"col-start-end":[{col:["auto",{span:["full",JK,eo]},eo]}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":[XK]}],"row-start-end":[{row:["auto",{span:[JK,eo]},eo]}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",eo]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",eo]}],gap:[{gap:[f]}],"gap-x":[{"gap-x":[f]}],"gap-y":[{"gap-y":[f]}],"justify-content":[{justify:["normal",...le()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...le(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...le(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[y]}],px:[{px:[y]}],py:[{py:[y]}],ps:[{ps:[y]}],pe:[{pe:[y]}],pt:[{pt:[y]}],pr:[{pr:[y]}],pb:[{pb:[y]}],pl:[{pl:[y]}],m:[{m:[g]}],mx:[{mx:[g]}],my:[{my:[g]}],ms:[{ms:[g]}],me:[{me:[g]}],mt:[{mt:[g]}],mr:[{mr:[g]}],mb:[{mb:[g]}],ml:[{ml:[g]}],"space-x":[{"space-x":[C]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[C]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",eo,e]}],"min-w":[{"min-w":[eo,e,"min","max","fit"]}],"max-w":[{"max-w":[eo,e,"none","full","min","max","fit","prose",{screen:[TT]},TT]}],h:[{h:[eo,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[eo,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[eo,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[eo,e,"auto","min","max","fit"]}],"font-size":[{text:["base",TT,IT]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",WEe]}],"font-family":[{font:[XK]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",eo]}],"line-clamp":[{"line-clamp":["none",D2,WEe]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",MC,eo]}],"list-image":[{"list-image":["none",eo]}],"list-style-type":[{list:["none","disc","decimal",eo]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[v]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[v]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...K(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",MC,IT]}],"underline-offset":[{"underline-offset":["auto",MC,eo]}],"text-decoration-color":[{decoration:[t]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:O()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",eo]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",eo]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[v]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...V(),jMn]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",UMn]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},zMn]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[m]}],"gradient-via-pos":[{via:[m]}],"gradient-to-pos":[{to:[m]}],"gradient-from":[{from:[p]}],"gradient-via":[{via:[p]}],"gradient-to":[{to:[p]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[a]}],"border-w-x":[{"border-x":[a]}],"border-w-y":[{"border-y":[a]}],"border-w-s":[{"border-s":[a]}],"border-w-e":[{"border-e":[a]}],"border-w-t":[{"border-t":[a]}],"border-w-r":[{"border-r":[a]}],"border-w-b":[{"border-b":[a]}],"border-w-l":[{"border-l":[a]}],"border-opacity":[{"border-opacity":[v]}],"border-style":[{border:[...K(),"hidden"]}],"divide-x":[{"divide-x":[a]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[a]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[v]}],"divide-style":[{divide:K()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[o]}],"border-color-s":[{"border-s":[o]}],"border-color-e":[{"border-e":[o]}],"border-color-t":[{"border-t":[o]}],"border-color-r":[{"border-r":[o]}],"border-color-b":[{"border-b":[o]}],"border-color-l":[{"border-l":[o]}],"divide-color":[{divide:[o]}],"outline-style":[{outline:["",...K()]}],"outline-offset":[{"outline-offset":[MC,eo]}],"outline-w":[{outline:[MC,IT]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:$()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[v]}],"ring-offset-w":[{"ring-offset":[MC,IT]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",TT,HMn]}],"shadow-color":[{shadow:[XK]}],opacity:[{opacity:[v]}],"mix-blend":[{"mix-blend":[...se(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":se()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[l]}],"drop-shadow":[{"drop-shadow":["","none",TT,eo]}],grayscale:[{grayscale:[c]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[d]}],saturate:[{saturate:[w]}],sepia:[{sepia:[S]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[l]}],"backdrop-grayscale":[{"backdrop-grayscale":[c]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[u]}],"backdrop-invert":[{"backdrop-invert":[d]}],"backdrop-opacity":[{"backdrop-opacity":[v]}],"backdrop-saturate":[{"backdrop-saturate":[w]}],"backdrop-sepia":[{"backdrop-sepia":[S]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[s]}],"border-spacing-x":[{"border-spacing-x":[s]}],"border-spacing-y":[{"border-spacing-y":[s]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",eo]}],duration:[{duration:ee()}],ease:[{ease:["linear","in","out","in-out",eo]}],delay:[{delay:ee()}],animate:[{animate:["none","spin","ping","pulse","bounce",eo]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[_]}],"scale-x":[{"scale-x":[_]}],"scale-y":[{"scale-y":[_]}],rotate:[{rotate:[JK,eo]}],"translate-x":[{"translate-x":[k]}],"translate-y":[{"translate-y":[k]}],"skew-x":[{"skew-x":[I]}],"skew-y":[{"skew-y":[I]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",eo]}],accent:[{accent:["auto",t]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",eo]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":O()}],"scroll-mx":[{"scroll-mx":O()}],"scroll-my":[{"scroll-my":O()}],"scroll-ms":[{"scroll-ms":O()}],"scroll-me":[{"scroll-me":O()}],"scroll-mt":[{"scroll-mt":O()}],"scroll-mr":[{"scroll-mr":O()}],"scroll-mb":[{"scroll-mb":O()}],"scroll-ml":[{"scroll-ml":O()}],"scroll-p":[{"scroll-p":O()}],"scroll-px":[{"scroll-px":O()}],"scroll-py":[{"scroll-py":O()}],"scroll-ps":[{"scroll-ps":O()}],"scroll-pe":[{"scroll-pe":O()}],"scroll-pt":[{"scroll-pt":O()}],"scroll-pr":[{"scroll-pr":O()}],"scroll-pb":[{"scroll-pb":O()}],"scroll-pl":[{"scroll-pl":O()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",eo]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[MC,IT,WEe]}],stroke:[{stroke:[t,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},KMn=(t,{cacheSize:e,prefix:n,separator:r,experimentalParseClassName:o,extend:i={},override:s={}})=>{QK(t,"cacheSize",e),QK(t,"prefix",n),QK(t,"separator",r),QK(t,"experimentalParseClassName",o);for(let a in s)GMn(t[a],s[a]);for(let a in i)ZMn(t[a],i[a]);return t},QK=(t,e,n)=>{n!==void 0&&(t[e]=n)},GMn=(t,e)=>{if(e)for(let n in e)QK(t,n,e[n])},ZMn=(t,e)=>{if(e)for(let n in e){let r=e[n];r!==void 0&&(t[n]=(t[n]||[]).concat(r))}},Nft=(t,...e)=>typeof t=="function"?Ift(Tft,t,...e):Ift(()=>KMn(Tft(),t),...e)});function J(...t){return YMn(tse(t))}var YMn,De=b(()=>{HEe();Rft();YMn=Nft({prefix:"tw-",extend:{classGroups:{"text-color":["text-muted","text-success","text-warning","text-error","text-accent"],"font-size":["text-smallest","text-smaller","text-small","text-ui-smaller","text-ui-small","text-ui-medium","text-ui-larger","text-ui-title"]}}})});var rse,JMn,oe,yt=b(()=>{rse=L(B());bft();nse();De();JMn=$2("tw-inline-flex tw-items-center tw-justify-center tw-gap-1 tw-whitespace-nowrap tw-rounded-md tw-text-sm tw-font-medium tw-transition-colors focus-visible:tw-outline-none focus-visible:tw-ring-1 focus-visible:tw-ring-ring disabled:tw-pointer-events-none disabled:tw-opacity-50 [&_svg]:tw-shrink-0",{variants:{variant:{default:"mod-cta tw-bg-interactive-accent tw-text-on-accent tw-shadow hover:tw-bg-interactive-accent-hover",destructive:"clickable-icon tw-bg-modifier-error tw-text-on-accent hover:tw-bg-modifier-error hover:tw-text-on-accent",secondary:"tw-bg-secondary tw-text-normal tw-shadow-sm hover:tw-bg-interactive-hover",ghost:"clickable-icon tw-bg-transparent hover:tw-bg-interactive-accent hover:tw-text-on-accent",link:"tw-text-accent tw-underline-offset-4 hover:tw-underline",success:"clickable-icon tw-bg-modifier-success tw-text-on-accent hover:tw-bg-modifier-success hover:tw-text-on-accent",ghost2:"clickable-icon tw-bg-transparent tw-text-faint tw-outline-none hover:tw-bg-transparent hover:tw-bg-opacity-100 hover:tw-text-normal focus-visible:tw-text-normal focus-visible:tw-outline-none focus-visible:tw-ring-0"},size:{default:"tw-h-9 tw-px-4 tw-py-2",sm:"tw-h-6 tw-rounded-md tw-px-3 tw-text-xs",lg:"tw-h-10 tw-rounded-md tw-px-8",icon:"tw-size-7",fit:"tw-gap-1 tw-px-1 tw-text-xs"}},defaultVariants:{variant:"default",size:"default"}}),oe=rse.forwardRef(({className:t,variant:e,size:n,asChild:r=!1,...o},i)=>rse.createElement(r?wft:"button",{className:J(JMn({variant:e,size:n,className:t})),ref:i,...o}));oe.displayName="Button"});var Lft,ose,KEe=b(()=>{Lft=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),ose=(...t)=>t.filter((e,n,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===n).join(" ").trim()});var $ft,Dft=b(()=>{$ft={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"}});var eG,Fft,Uft=b(()=>{eG=L(B());Dft();KEe();Fft=(0,eG.forwardRef)(({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:i,iconNode:s,...a},l)=>(0,eG.createElement)("svg",{ref:l,...$ft,width:e,height:e,stroke:t,strokeWidth:r?Number(n)*24/Number(e):n,className:ose("lucide",o),...a},[...s.map(([c,u])=>(0,eG.createElement)(c,u)),...Array.isArray(i)?i:[i]]))});var ise,me,Ue=b(()=>{ise=L(B());KEe();Uft();me=(t,e)=>{let n=(0,ise.forwardRef)(({className:r,...o},i)=>(0,ise.createElement)(Fft,{ref:i,iconNode:e,className:ose(`lucide-${Lft(t)}`,r),...o}));return n.displayName=`${t}`,n}});var U2,jft=b(()=>{Ue();U2=me("ArrowBigUp",[["path",{d:"M9 18v-6H5l7-7 7 7h-4v6H9z",key:"1x06kx"}]])});var tG,Bft=b(()=>{Ue();tG=me("ArrowRightLeft",[["path",{d:"m16 3 4 4-4 4",key:"1x1c3m"}],["path",{d:"M20 7H4",key:"zbl0bi"}],["path",{d:"m8 21-4-4 4-4",key:"h9nckh"}],["path",{d:"M4 17h16",key:"g4d7ey"}]])});var j2,zft=b(()=>{Ue();j2=me("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]])});var us,Hft=b(()=>{Ue();us=me("ArrowUpRight",[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]])});var nG,Wft=b(()=>{Ue();nG=me("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]])});var rG,Vft=b(()=>{Ue();rG=me("BookOpen",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]])});var gy,qft=b(()=>{Ue();gy=me("Bot",[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]])});var H_,Kft=b(()=>{Ue();H_=me("Brain",[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z",key:"ep3f8r"}],["path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4",key:"1p4c4q"}],["path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375",key:"tmeiqw"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M19.938 10.5a4 4 0 0 1 .585.396",key:"1qfode"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M19.967 17.484A4 4 0 0 1 18 18",key:"159ez6"}]])});var Hr,Gft=b(()=>{Ue();Hr=me("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]])});var Bs,Zft=b(()=>{Ue();Bs=me("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]])});var oG,Yft=b(()=>{Ue();oG=me("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]])});var Vi,Jft=b(()=>{Ue();Vi=me("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]])});var mc,Xft=b(()=>{Ue();mc=me("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]])});var yy,Qft=b(()=>{Ue();yy=me("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]])});var Xf,ept=b(()=>{Ue();Xf=me("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]])});var OC,tpt=b(()=>{Ue();OC=me("CircleDashed",[["path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0",key:"5ilxe3"}],["path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0",key:"11zvb9"}],["path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7",key:"1iw5b2"}],["path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8",key:"c0bmvh"}],["path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69",key:"1ruxm7"}],["path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8",key:"qkgqxc"}],["path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69",key:"1mcia2"}],["path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7",key:"1fvljs"}]])});var xh,npt=b(()=>{Ue();xh=me("CircleHelp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]])});var Sh,rpt=b(()=>{Ue();Sh=me("CirclePlus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]])});var PT,opt=b(()=>{Ue();PT=me("CircleSlash",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"9",x2:"15",y1:"15",y2:"9",key:"1dfufj"}]])});var nm,ipt=b(()=>{Ue();nm=me("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]])});var iG,spt=b(()=>{Ue();iG=me("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]])});var AT,apt=b(()=>{Ue();AT=me("ClipboardList",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]])});var sG,lpt=b(()=>{Ue();sG=me("ClipboardPaste",[["path",{d:"M15 2H9a1 1 0 0 0-1 1v2c0 .6.4 1 1 1h6c.6 0 1-.4 1-1V3c0-.6-.4-1-1-1Z",key:"1pp7kr"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2M16 4h2a2 2 0 0 1 2 2v2M11 14h10",key:"2ik1ml"}],["path",{d:"m17 10 4 4-4 4",key:"vp2hj1"}]])});var aG,cpt=b(()=>{Ue();aG=me("Clipboard",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}]])});var NC,upt=b(()=>{Ue();NC=me("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]])});var lG,dpt=b(()=>{Ue();lG=me("Cog",[["path",{d:"M12 20a8 8 0 1 0 0-16 8 8 0 0 0 0 16Z",key:"sobvz5"}],["path",{d:"M12 14a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z",key:"11i496"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 22v-2",key:"1osdcq"}],["path",{d:"m17 20.66-1-1.73",key:"eq3orb"}],["path",{d:"M11 10.27 7 3.34",key:"16pf9h"}],["path",{d:"m20.66 17-1.73-1",key:"sg0v6f"}],["path",{d:"m3.34 7 1.73 1",key:"1ulond"}],["path",{d:"M14 12h8",key:"4f43i9"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"m20.66 7-1.73 1",key:"1ow05n"}],["path",{d:"m3.34 17 1.73-1",key:"nuk764"}],["path",{d:"m17 3.34-1 1.73",key:"2wel8s"}],["path",{d:"m11 13.73-4 6.93",key:"794ttg"}]])});var cG,fpt=b(()=>{Ue();cG=me("Coins",[["circle",{cx:"8",cy:"8",r:"6",key:"3yglwk"}],["path",{d:"M18.09 10.37A6 6 0 1 1 10.34 18",key:"t5s6rm"}],["path",{d:"M7 6h1v4",key:"1obek4"}],["path",{d:"m16.71 13.88.7.71-2.82 2.82",key:"1rbuyh"}]])});var ET,ppt=b(()=>{Ue();ET=me("Command",[["path",{d:"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",key:"11bfej"}]])});var B2,mpt=b(()=>{Ue();B2=me("CopyPlus",[["line",{x1:"15",x2:"15",y1:"12",y2:"18",key:"1p7wdc"}],["line",{x1:"12",x2:"18",y1:"15",y2:"15",key:"1nscbv"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]])});var rN,hpt=b(()=>{Ue();rN=me("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]])});var W_,gpt=b(()=>{Ue();W_=me("CornerDownLeft",[["polyline",{points:"9 10 4 15 9 20",key:"r3jprv"}],["path",{d:"M20 4v7a4 4 0 0 1-4 4H4",key:"6o5b7l"}]])});var uG,ypt=b(()=>{Ue();uG=me("CornerDownRight",[["polyline",{points:"15 10 20 15 15 20",key:"1q7qjw"}],["path",{d:"M4 4v7a4 4 0 0 0 4 4h12",key:"z08zvw"}]])});var dG,vpt=b(()=>{Ue();dG=me("Cpu",[["rect",{width:"16",height:"16",x:"4",y:"4",rx:"2",key:"14l7u7"}],["rect",{width:"6",height:"6",x:"9",y:"9",rx:"1",key:"5aljv4"}],["path",{d:"M15 2v2",key:"13l42r"}],["path",{d:"M15 20v2",key:"15mkzm"}],["path",{d:"M2 15h2",key:"1gxd5l"}],["path",{d:"M2 9h2",key:"1bbxkp"}],["path",{d:"M20 15h2",key:"19e6y8"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M9 2v2",key:"165o2o"}],["path",{d:"M9 20v2",key:"i2bqo8"}]])});var RC,wpt=b(()=>{Ue();RC=me("Database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]])});var LC,bpt=b(()=>{Ue();LC=me("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]])});var vy,_pt=b(()=>{Ue();vy=me("EllipsisVertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]])});var V_,xpt=b(()=>{Ue();V_=me("Ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]])});var Ch,Spt=b(()=>{Ue();Ch=me("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]])});var $C,Cpt=b(()=>{Ue();$C=me("EyeOff",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]])});var fG,kpt=b(()=>{Ue();fG=me("Eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]])});var pG,Ipt=b(()=>{Ue();pG=me("FileAudio",[["path",{d:"M17.5 22h.5a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"rslqgf"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 19a2 2 0 1 1 4 0v1a2 2 0 1 1-4 0v-4a6 6 0 0 1 12 0v4a2 2 0 1 1-4 0v-1a2 2 0 1 1 4 0",key:"9f7x3i"}]])});var DC,Tpt=b(()=>{Ue();DC=me("FileClock",[["path",{d:"M16 22h2a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"37hlfg"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"8",cy:"16",r:"6",key:"10v15b"}],["path",{d:"M9.5 17.5 8 16.25V14",key:"1o80t2"}]])});var oN,Ppt=b(()=>{Ue();oN=me("FileImage",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]])});var z2,Apt=b(()=>{Ue();z2=me("FileInput",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 15h10",key:"jfw4w8"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]])});var H2,Ept=b(()=>{Ue();H2=me("FileOutput",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 7V4a2 2 0 0 1 2-2 2 2 0 0 0-2 2",key:"1vk7w2"}],["path",{d:"M4.063 20.999a2 2 0 0 0 2 1L18 22a2 2 0 0 0 2-2V7l-5-5H6",key:"1jink5"}],["path",{d:"m5 11-3 3",key:"1dgrs4"}],["path",{d:"m5 17-3-3h10",key:"1mvvaf"}]])});var mG,Mpt=b(()=>{Ue();mG=me("FileSearch",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4.268 21a2 2 0 0 0 1.727 1H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"ms7g94"}],["path",{d:"m9 18-1.5-1.5",key:"1j6qii"}],["circle",{cx:"5",cy:"14",r:"3",key:"ufru5t"}]])});var Jo,Opt=b(()=>{Ue();Jo=me("FileText",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]])});var iN,Npt=b(()=>{Ue();iN=me("FileVideo",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m10 11 5 3-5 3v-6Z",key:"7ntvm4"}]])});var hG,Rpt=b(()=>{Ue();hG=me("Files",[["path",{d:"M20 7h-3a2 2 0 0 1-2-2V2",key:"x099mo"}],["path",{d:"M9 18a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h7l4 4v10a2 2 0 0 1-2 2Z",key:"18t6ie"}],["path",{d:"M3 7.6v12.8A1.6 1.6 0 0 0 4.6 22h9.8",key:"1nja0z"}]])});var gG,Lpt=b(()=>{Ue();gG=me("FolderOpen",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]])});var yG,$pt=b(()=>{Ue();yG=me("FolderPlus",[["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"M9 13h6",key:"1uhe8q"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]])});var kw,Dpt=b(()=>{Ue();kw=me("FolderSearch",[["path",{d:"M10.7 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v4.1",key:"1bw5m7"}],["path",{d:"m21 21-1.9-1.9",key:"1g2n9r"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}]])});var vG,Fpt=b(()=>{Ue();vG=me("FolderSync",[["path",{d:"M9 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v.5",key:"1dkoa9"}],["path",{d:"M12 10v4h4",key:"1czhmt"}],["path",{d:"m12 14 1.535-1.605a5 5 0 0 1 8 1.5",key:"lvuxfi"}],["path",{d:"M22 22v-4h-4",key:"1ewp4q"}],["path",{d:"m22 18-1.535 1.605a5 5 0 0 1-8-1.5",key:"14ync0"}]])});var wG,Upt=b(()=>{Ue();wG=me("FolderTree",[["path",{d:"M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"hod4my"}],["path",{d:"M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"w4yl2u"}],["path",{d:"M3 5a2 2 0 0 0 2 2h3",key:"f2jnh7"}],["path",{d:"M3 3v13a2 2 0 0 0 2 2h3",key:"k8epm1"}]])});var Fl,jpt=b(()=>{Ue();Fl=me("Folder",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]])});var W2,Bpt=b(()=>{Ue();W2=me("GitFork",[["circle",{cx:"12",cy:"18",r:"3",key:"1mpf1b"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["path",{d:"M18 9v2c0 .6-.4 1-1 1H7c-.6 0-1-.4-1-1V9",key:"1uq4wg"}],["path",{d:"M12 12v3",key:"158kv8"}]])});var Xo,zpt=b(()=>{Ue();Xo=me("Globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]])});var FC,Hpt=b(()=>{Ue();FC=me("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]])});var V2,Wpt=b(()=>{Ue();V2=me("Hammer",[["path",{d:"m15 12-8.373 8.373a1 1 0 1 1-3-3L12 9",key:"eefl8a"}],["path",{d:"m18 15 4-4",key:"16gjal"}],["path",{d:"m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172V7l-2.26-2.26a6 6 0 0 0-4.202-1.756L9 2.96l.92.82A6.18 6.18 0 0 1 12 8.4V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5",key:"b7pghm"}]])});var sN,Vpt=b(()=>{Ue();sN=me("Hash",[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]])});var aN,qpt=b(()=>{Ue();aN=me("History",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]])});var bG,Kpt=b(()=>{Ue();bG=me("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]])});var UC,Gpt=b(()=>{Ue();UC=me("Inbox",[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]])});var jC,Zpt=b(()=>{Ue();jC=me("Info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]])});var _G,Ypt=b(()=>{Ue();_G=me("KeyRound",[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]])});var xG,Jpt=b(()=>{Ue();xG=me("Layers",[["path",{d:"m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z",key:"8b97xw"}],["path",{d:"m22 17.65-9.17 4.16a2 2 0 0 1-1.66 0L2 17.65",key:"dd6zsq"}],["path",{d:"m22 12.65-9.17 4.16a2 2 0 0 1-1.66 0L2 12.65",key:"ep9fru"}]])});var SG,Xpt=b(()=>{Ue();SG=me("LayoutGrid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]])});var CG,Qpt=b(()=>{Ue();CG=me("LibraryBig",[["rect",{width:"8",height:"18",x:"3",y:"3",rx:"1",key:"oynpb5"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M20.4 18.9c.2.5-.1 1.1-.6 1.3l-1.9.7c-.5.2-1.1-.1-1.3-.6L11.1 5.1c-.2-.5.1-1.1.6-1.3l1.9-.7c.5-.2 1.1.1 1.3.6Z",key:"1qboyk"}]])});var MT,emt=b(()=>{Ue();MT=me("Link",[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]])});var kG,tmt=b(()=>{Ue();kG=me("ListChecks",[["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}]])});var IG,nmt=b(()=>{Ue();IG=me("List",[["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 18h.01",key:"1tta3j"}],["path",{d:"M3 6h.01",key:"1rqtza"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 18h13",key:"1lx6n3"}],["path",{d:"M8 6h13",key:"ik3vkj"}]])});var Dr,rmt=b(()=>{Ue();Dr=me("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]])});var TG,omt=b(()=>{Ue();TG=me("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]])});var lN,imt=b(()=>{Ue();lN=me("MessageCirclePlus",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]])});var cN,smt=b(()=>{Ue();cN=me("MessageCircleQuestion",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]])});var BC,amt=b(()=>{Ue();BC=me("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]])});var PG,lmt=b(()=>{Ue();PG=me("MessageSquareX",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"m14.5 7.5-5 5",key:"3lb6iw"}],["path",{d:"m9.5 7.5 5 5",key:"ko136h"}]])});var q2,cmt=b(()=>{Ue();q2=me("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]])});var K2,umt=b(()=>{Ue();K2=me("MonitorDown",[["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"m15 10-3 3-3-3",key:"lzhmyn"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]])});var AG,dmt=b(()=>{Ue();AG=me("Move",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]])});var G2,fmt=b(()=>{Ue();G2=me("Pause",[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]])});var Qf,pmt=b(()=>{Ue();Qf=me("PenLine",[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}]])});var rm,mmt=b(()=>{Ue();rm=me("Pen",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]])});var EG,hmt=b(()=>{Ue();EG=me("PencilLine",[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}],["path",{d:"m15 5 3 3",key:"1w25hb"}]])});var wy,gmt=b(()=>{Ue();wy=me("Pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]])});var MG,ymt=b(()=>{Ue();MG=me("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]])});var zs,vmt=b(()=>{Ue();zs=me("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]])});var kh,wmt=b(()=>{Ue();kh=me("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]])});var OG,bmt=b(()=>{Ue();OG=me("Replace",[["path",{d:"M14 4a2 2 0 0 1 2-2",key:"1w2hp7"}],["path",{d:"M16 10a2 2 0 0 1-2-2",key:"shjach"}],["path",{d:"M20 2a2 2 0 0 1 2 2",key:"188mtx"}],["path",{d:"M22 8a2 2 0 0 1-2 2",key:"ddf4tu"}],["path",{d:"m3 7 3 3 3-3",key:"x25e72"}],["path",{d:"M6 10V5a3 3 0 0 1 3-3h1",key:"3y3t5z"}],["rect",{x:"2",y:"14",width:"8",height:"8",rx:"2",key:"4rksxw"}]])});var uN,_mt=b(()=>{Ue();uN=me("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]])});var NG,xmt=b(()=>{Ue();NG=me("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]])});var Iw,Smt=b(()=>{Ue();Iw=me("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]])});var zC,Cmt=b(()=>{Ue();zC=me("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]])});var RG,kmt=b(()=>{Ue();RG=me("Settings2",[["path",{d:"M20 7h-9",key:"3s1dr2"}],["path",{d:"M14 17H5",key:"gfn3mx"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]])});var Ih,Imt=b(()=>{Ue();Ih=me("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]])});var Tw,Tmt=b(()=>{Ue();Tw=me("ShieldCheck",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]])});var LG,Pmt=b(()=>{Ue();LG=me("ShieldQuestion",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}],["path",{d:"M12 17h.01",key:"p32p05"}]])});var $G,Amt=b(()=>{Ue();$G=me("Sigma",[["path",{d:"M18 7V5a1 1 0 0 0-1-1H6.5a.5.5 0 0 0-.4.8l4.5 6a2 2 0 0 1 0 2.4l-4.5 6a.5.5 0 0 0 .4.8H17a1 1 0 0 0 1-1v-2",key:"wuwx1p"}]])});var OT,Emt=b(()=>{Ue();OT=me("SlidersHorizontal",[["line",{x1:"21",x2:"14",y1:"4",y2:"4",key:"obuewd"}],["line",{x1:"10",x2:"3",y1:"4",y2:"4",key:"1q6298"}],["line",{x1:"21",x2:"12",y1:"12",y2:"12",key:"1iu8h1"}],["line",{x1:"8",x2:"3",y1:"12",y2:"12",key:"ntss68"}],["line",{x1:"21",x2:"16",y1:"20",y2:"20",key:"14d8ph"}],["line",{x1:"12",x2:"3",y1:"20",y2:"20",key:"m0wm8r"}],["line",{x1:"14",x2:"14",y1:"2",y2:"6",key:"14e1ph"}],["line",{x1:"8",x2:"8",y1:"10",y2:"14",key:"1i6ji0"}],["line",{x1:"16",x2:"16",y1:"18",y2:"22",key:"1lctlv"}]])});var DG,Mmt=b(()=>{Ue();DG=me("Sparkle",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}]])});var hc,Omt=b(()=>{Ue();hc=me("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]])});var NT,Nmt=b(()=>{Ue();NT=me("SquareArrowOutUpRight",[["path",{d:"M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6",key:"y09zxi"}],["path",{d:"m21 3-9 9",key:"mpx6sq"}],["path",{d:"M15 3h6v6",key:"1q9fwt"}]])});var RT,Rmt=b(()=>{Ue();RT=me("SquareCheckBig",[["path",{d:"M21 10.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.5",key:"1uzm8b"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]])});var ld,Lmt=b(()=>{Ue();ld=me("SquarePen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]])});var q_,$mt=b(()=>{Ue();q_=me("SquarePlay",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m9 8 6 4-6 4Z",key:"f1r3lt"}]])});var HC,Dmt=b(()=>{Ue();HC=me("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]])});var LT,Fmt=b(()=>{Ue();LT=me("Tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]])});var Z2,Umt=b(()=>{Ue();Z2=me("Terminal",[["polyline",{points:"4 17 10 11 4 5",key:"akl6gq"}],["line",{x1:"12",x2:"20",y1:"19",y2:"19",key:"q2wloq"}]])});var dN,jmt=b(()=>{Ue();dN=me("TextCursorInput",[["path",{d:"M5 4h1a3 3 0 0 1 3 3 3 3 0 0 1 3-3h1",key:"18xjzo"}],["path",{d:"M13 20h-1a3 3 0 0 1-3-3 3 3 0 0 1-3 3H5",key:"fj48gi"}],["path",{d:"M5 16H4a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2h1",key:"1n9rhb"}],["path",{d:"M13 8h7a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-7",key:"13ksps"}],["path",{d:"M9 7v10",key:"1vc8ob"}]])});var Ts,Bmt=b(()=>{Ue();Ts=me("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]])});var Wr,zmt=b(()=>{Ue();Wr=me("TriangleAlert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]])});var Pw,Hmt=b(()=>{Ue();Pw=me("Wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z",key:"cbrjhi"}]])});var pn,Wmt=b(()=>{Ue();pn=me("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]])});var Re=b(()=>{Xft();Qft();ept();npt();rpt();ipt();_pt();xpt();rmt();pmt();mmt();Omt();Nmt();Rmt();Lmt();$mt();zmt();jft();Bft();zft();Hft();Wft();Vft();qft();Kft();Gft();Zft();Yft();Jft();tpt();opt();spt();apt();lpt();cpt();upt();dpt();fpt();ppt();mpt();hpt();gpt();ypt();vpt();wpt();bpt();Spt();Cpt();kpt();Ipt();Tpt();Ppt();Apt();Ept();Mpt();Opt();Npt();Rpt();Lpt();$pt();Dpt();Fpt();Upt();jpt();Bpt();zpt();Hpt();Wpt();Vpt();qpt();Kpt();Gpt();Zpt();Ypt();Jpt();Xpt();Qpt();emt();tmt();nmt();omt();imt();smt();amt();lmt();cmt();umt();dmt();fmt();hmt();gmt();ymt();vmt();wmt();bmt();_mt();xmt();Smt();Cmt();kmt();Imt();Tmt();Pmt();Amt();Emt();Mmt();Dmt();Fmt();Umt();jmt();Bmt();Hmt();Wmt();});function vn(){let t=FG.useContext(fN);if(!t)throw new Error("useApp() called outside of an <AppContext.Provider>");return t}var FG,fN,by,Gd,ko=b(()=>{gt();FG=L(B()),fN=FG.createContext(void 0),by=class extends EventTarget{constructor(){super(...arguments);this.pendingInsertText=null;this.visiblePending=!1}queueInsertText(n){this.pendingInsertText=n,this.dispatchEvent(new CustomEvent(cs.INSERT_TEXT_TO_CHAT,{detail:{text:n}}))}consumePendingInsertText(){let n=this.pendingInsertText;return this.pendingInsertText=null,n}queueVisible(){this.visiblePending=!0,this.dispatchEvent(new CustomEvent(cs.CHAT_IS_VISIBLE))}consumePendingVisible(){let n=this.visiblePending;return this.visiblePending=!1,n}},Gd=FG.createContext(void 0)});var eht=wi(Ps=>{"use strict";function JEe(t,e){var n=t.length;t.push(e);e:for(;0<n;){var r=n-1>>>1,o=t[r];if(0<sse(o,e))t[r]=e,t[n]=o,n=r;else break e}}function Aw(t){return t.length===0?null:t[0]}function lse(t){if(t.length===0)return null;var e=t[0],n=t.pop();if(n!==e){t[0]=n;e:for(var r=0,o=t.length,i=o>>>1;r<i;){var s=2*(r+1)-1,a=t[s],l=s+1,c=t[l];if(0>sse(a,n))l<o&&0>sse(c,a)?(t[r]=c,t[l]=n,r=l):(t[r]=a,t[s]=n,r=s);else if(l<o&&0>sse(c,n))t[r]=c,t[l]=n,r=l;else break e}}return e}function sse(t,e){var n=t.sortIndex-e.sortIndex;return n!==0?n:t.id-e.id}typeof performance=="object"&&typeof performance.now=="function"?(Vmt=performance,Ps.unstable_now=function(){return Vmt.now()}):(GEe=Date,qmt=GEe.now(),Ps.unstable_now=function(){return GEe.now()-qmt});var Vmt,GEe,qmt,K_=[],$T=[],XMn=1,_y=null,Zd=3,cse=!1,pN=!1,jG=!1,Zmt=typeof setTimeout=="function"?setTimeout:null,Ymt=typeof clearTimeout=="function"?clearTimeout:null,Kmt=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function XEe(t){for(var e=Aw($T);e!==null;){if(e.callback===null)lse($T);else if(e.startTime<=t)lse($T),e.sortIndex=e.expirationTime,JEe(K_,e);else break;e=Aw($T)}}function QEe(t){if(jG=!1,XEe(t),!pN)if(Aw(K_)!==null)pN=!0,tMe(eMe);else{var e=Aw($T);e!==null&&nMe(QEe,e.startTime-t)}}function eMe(t,e){pN=!1,jG&&(jG=!1,Ymt(BG),BG=-1),cse=!0;var n=Zd;try{for(XEe(e),_y=Aw(K_);_y!==null&&(!(_y.expirationTime>e)||t&&!Qmt());){var r=_y.callback;if(typeof r=="function"){_y.callback=null,Zd=_y.priorityLevel;var o=r(_y.expirationTime<=e);e=Ps.unstable_now(),typeof o=="function"?_y.callback=o:_y===Aw(K_)&&lse(K_),XEe(e)}else lse(K_);_y=Aw(K_)}if(_y!==null)var i=!0;else{var s=Aw($T);s!==null&&nMe(QEe,s.startTime-e),i=!1}return i}finally{_y=null,Zd=n,cse=!1}}var use=!1,ase=null,BG=-1,Jmt=5,Xmt=-1;function Qmt(){return!(Ps.unstable_now()-Xmt<Jmt)}function ZEe(){if(ase!==null){var t=Ps.unstable_now();Xmt=t;var e=!0;try{e=ase(!0,t)}finally{e?UG():(use=!1,ase=null)}}else use=!1}var UG;typeof Kmt=="function"?UG=function(){Kmt(ZEe)}:typeof MessageChannel<"u"?(YEe=new MessageChannel,Gmt=YEe.port2,YEe.port1.onmessage=ZEe,UG=function(){Gmt.postMessage(null)}):UG=function(){Zmt(ZEe,0)};var YEe,Gmt;function tMe(t){ase=t,use||(use=!0,UG())}function nMe(t,e){BG=Zmt(function(){t(Ps.unstable_now())},e)}Ps.unstable_IdlePriority=5;Ps.unstable_ImmediatePriority=1;Ps.unstable_LowPriority=4;Ps.unstable_NormalPriority=3;Ps.unstable_Profiling=null;Ps.unstable_UserBlockingPriority=2;Ps.unstable_cancelCallback=function(t){t.callback=null};Ps.unstable_continueExecution=function(){pN||cse||(pN=!0,tMe(eMe))};Ps.unstable_forceFrameRate=function(t){0>t||125<t?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):Jmt=0<t?Math.floor(1e3/t):5};Ps.unstable_getCurrentPriorityLevel=function(){return Zd};Ps.unstable_getFirstCallbackNode=function(){return Aw(K_)};Ps.unstable_next=function(t){switch(Zd){case 1:case 2:case 3:var e=3;break;default:e=Zd}var n=Zd;Zd=e;try{return t()}finally{Zd=n}};Ps.unstable_pauseExecution=function(){};Ps.unstable_requestPaint=function(){};Ps.unstable_runWithPriority=function(t,e){switch(t){case 1:case 2:case 3:case 4:case 5:break;default:t=3}var n=Zd;Zd=t;try{return e()}finally{Zd=n}};Ps.unstable_scheduleCallback=function(t,e,n){var r=Ps.unstable_now();switch(typeof n=="object"&&n!==null?(n=n.delay,n=typeof n=="number"&&0<n?r+n:r):n=r,t){case 1:var o=-1;break;case 2:o=250;break;case 5:o=1073741823;break;case 4:o=1e4;break;default:o=5e3}return o=n+o,t={id:XMn++,callback:e,priorityLevel:t,startTime:n,expirationTime:o,sortIndex:-1},n>r?(t.sortIndex=n,JEe($T,t),Aw(K_)===null&&t===Aw($T)&&(jG?(Ymt(BG),BG=-1):jG=!0,nMe(QEe,n-r))):(t.sortIndex=o,JEe(K_,t),pN||cse||(pN=!0,tMe(eMe))),t};Ps.unstable_shouldYield=Qmt;Ps.unstable_wrapCallback=function(t){var e=Zd;return function(){var n=Zd;Zd=e;try{return t.apply(this,arguments)}finally{Zd=n}}}});var nht=wi((s7r,tht)=>{"use strict";tht.exports=eht()});var lvt=wi(Oh=>{"use strict";var cgt=B(),Eh=nht();function dt(t){for(var e="https://reactjs.org/docs/error-decoder.html?invariant="+t,n=1;n<arguments.length;n++)e+="&args[]="+encodeURIComponent(arguments[n]);return"Minified React error #"+t+"; visit "+e+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var ugt=new Set,c9={};function IN(t,e){gU(t,e),gU(t+"Capture",e)}function gU(t,e){for(c9[t]=e,t=0;t<e.length;t++)ugt.add(e[t])}var ZC=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),kMe=Object.prototype.hasOwnProperty,QMn=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,rht={},oht={};function eOn(t){return kMe.call(oht,t)?!0:kMe.call(rht,t)?!1:QMn.test(t)?oht[t]=!0:(rht[t]=!0,!1)}function tOn(t,e,n,r){if(n!==null&&n.type===0)return!1;switch(typeof e){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(t=t.toLowerCase().slice(0,5),t!=="data-"&&t!=="aria-");default:return!1}}function nOn(t,e,n,r){if(e===null||typeof e>"u"||tOn(t,e,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!e;case 4:return e===!1;case 5:return isNaN(e);case 6:return isNaN(e)||1>e}return!1}function np(t,e,n,r,o,i,s){this.acceptsBooleans=e===2||e===3||e===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=t,this.type=e,this.sanitizeURL=i,this.removeEmptyString=s}var dd={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(t){dd[t]=new np(t,0,!1,t,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(t){var e=t[0];dd[e]=new np(e,1,!1,t[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(t){dd[t]=new np(t,2,!1,t.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(t){dd[t]=new np(t,2,!1,t,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(t){dd[t]=new np(t,3,!1,t.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(t){dd[t]=new np(t,3,!0,t,null,!1,!1)});["capture","download"].forEach(function(t){dd[t]=new np(t,4,!1,t,null,!1,!1)});["cols","rows","size","span"].forEach(function(t){dd[t]=new np(t,6,!1,t,null,!1,!1)});["rowSpan","start"].forEach(function(t){dd[t]=new np(t,5,!1,t.toLowerCase(),null,!1,!1)});var yOe=/[\-:]([a-z])/g;function vOe(t){return t[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(t){var e=t.replace(yOe,vOe);dd[e]=new np(e,1,!1,t,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(t){var e=t.replace(yOe,vOe);dd[e]=new np(e,1,!1,t,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(t){var e=t.replace(yOe,vOe);dd[e]=new np(e,1,!1,t,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(t){dd[t]=new np(t,1,!1,t.toLowerCase(),null,!1,!1)});dd.xlinkHref=new np("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(t){dd[t]=new np(t,1,!1,t.toLowerCase(),null,!0,!0)});function wOe(t,e,n,r){var o=dd.hasOwnProperty(e)?dd[e]:null;(o!==null?o.type!==0:r||!(2<e.length)||e[0]!=="o"&&e[0]!=="O"||e[1]!=="n"&&e[1]!=="N")&&(nOn(e,n,o,r)&&(n=null),r||o===null?eOn(e)&&(n===null?t.removeAttribute(e):t.setAttribute(e,""+n)):o.mustUseProperty?t[o.propertyName]=n===null?o.type===3?!1:"":n:(e=o.attributeName,r=o.attributeNamespace,n===null?t.removeAttribute(e):(o=o.type,n=o===3||o===4&&n===!0?"":""+n,r?t.setAttributeNS(r,e,n):t.setAttribute(e,n))))}var QC=cgt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,dse=Symbol.for("react.element"),X2=Symbol.for("react.portal"),Q2=Symbol.for("react.fragment"),bOe=Symbol.for("react.strict_mode"),IMe=Symbol.for("react.profiler"),dgt=Symbol.for("react.provider"),fgt=Symbol.for("react.context"),_Oe=Symbol.for("react.forward_ref"),TMe=Symbol.for("react.suspense"),PMe=Symbol.for("react.suspense_list"),xOe=Symbol.for("react.memo"),FT=Symbol.for("react.lazy");Symbol.for("react.scope");Symbol.for("react.debug_trace_mode");var pgt=Symbol.for("react.offscreen");Symbol.for("react.legacy_hidden");Symbol.for("react.cache");Symbol.for("react.tracing_marker");var iht=Symbol.iterator;function zG(t){return t===null||typeof t!="object"?null:(t=iht&&t[iht]||t["@@iterator"],typeof t=="function"?t:null)}var Ta=Object.assign,rMe;function YG(t){if(rMe===void 0)try{throw Error()}catch(n){var e=n.stack.trim().match(/\n( *(at )?)/);rMe=e&&e[1]||""}return`
`+rMe+t}var oMe=!1;function iMe(t,e){if(!t||oMe)return"";oMe=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(e)if(e=function(){throw Error()},Object.defineProperty(e.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(e,[])}catch(c){var r=c}Reflect.construct(t,[],e)}else{try{e.call()}catch(c){r=c}t.call(e.prototype)}else{try{throw Error()}catch(c){r=c}t()}}catch(c){if(c&&r&&typeof c.stack=="string"){for(var o=c.stack.split(`
`),i=r.stack.split(`
`),s=o.length-1,a=i.length-1;1<=s&&0<=a&&o[s]!==i[a];)a--;for(;1<=s&&0<=a;s--,a--)if(o[s]!==i[a]){if(s!==1||a!==1)do if(s--,a--,0>a||o[s]!==i[a]){var l=`
`+o[s].replace(" at new "," at ");return t.displayName&&l.includes("<anonymous>")&&(l=l.replace("<anonymous>",t.displayName)),l}while(1<=s&&0<=a);break}}}finally{oMe=!1,Error.prepareStackTrace=n}return(t=t?t.displayName||t.name:"")?YG(t):""}function rOn(t){switch(t.tag){case 5:return YG(t.type);case 16:return YG("Lazy");case 13:return YG("Suspense");case 19:return YG("SuspenseList");case 0:case 2:case 15:return t=iMe(t.type,!1),t;case 11:return t=iMe(t.type.render,!1),t;case 1:return t=iMe(t.type,!0),t;default:return""}}function AMe(t){if(t==null)return null;if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case Q2:return"Fragment";case X2:return"Portal";case IMe:return"Profiler";case bOe:return"StrictMode";case TMe:return"Suspense";case PMe:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case fgt:return(t.displayName||"Context")+".Consumer";case dgt:return(t._context.displayName||"Context")+".Provider";case _Oe:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case xOe:return e=t.displayName||null,e!==null?e:AMe(t.type)||"Memo";case FT:e=t._payload,t=t._init;try{return AMe(t(e))}catch{}}return null}function oOn(t){var e=t.type;switch(t.tag){case 24:return"Cache";case 9:return(e.displayName||"Context")+".Consumer";case 10:return(e._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return t=e.render,t=t.displayName||t.name||"",e.displayName||(t!==""?"ForwardRef("+t+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return AMe(e);case 8:return e===bOe?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e}return null}function XT(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function mgt(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function iOn(t){var e=mgt(t)?"checked":"value",n=Object.getOwnPropertyDescriptor(t.constructor.prototype,e),r=""+t[e];if(!t.hasOwnProperty(e)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var o=n.get,i=n.set;return Object.defineProperty(t,e,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.call(this,s)}}),Object.defineProperty(t,e,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(s){r=""+s},stopTracking:function(){t._valueTracker=null,delete t[e]}}}}function fse(t){t._valueTracker||(t._valueTracker=iOn(t))}function hgt(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var n=e.getValue(),r="";return t&&(r=mgt(t)?t.checked?"true":"false":t.value),t=r,t!==n?(e.setValue(t),!0):!1}function jse(t){if(t=t||(typeof document<"u"?document:void 0),typeof t>"u")return null;try{return t.activeElement||t.body}catch{return t.body}}function EMe(t,e){var n=e.checked;return Ta({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??t._wrapperState.initialChecked})}function sht(t,e){var n=e.defaultValue==null?"":e.defaultValue,r=e.checked!=null?e.checked:e.defaultChecked;n=XT(e.value!=null?e.value:n),t._wrapperState={initialChecked:r,initialValue:n,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function ggt(t,e){e=e.checked,e!=null&&wOe(t,"checked",e,!1)}function MMe(t,e){ggt(t,e);var n=XT(e.value),r=e.type;if(n!=null)r==="number"?(n===0&&t.value===""||t.value!=n)&&(t.value=""+n):t.value!==""+n&&(t.value=""+n);else if(r==="submit"||r==="reset"){t.removeAttribute("value");return}e.hasOwnProperty("value")?OMe(t,e.type,n):e.hasOwnProperty("defaultValue")&&OMe(t,e.type,XT(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function aht(t,e,n){if(e.hasOwnProperty("value")||e.hasOwnProperty("defaultValue")){var r=e.type;if(!(r!=="submit"&&r!=="reset"||e.value!==void 0&&e.value!==null))return;e=""+t._wrapperState.initialValue,n||e===t.value||(t.value=e),t.defaultValue=e}n=t.name,n!==""&&(t.name=""),t.defaultChecked=!!t._wrapperState.initialChecked,n!==""&&(t.name=n)}function OMe(t,e,n){(e!=="number"||jse(t.ownerDocument)!==t)&&(n==null?t.defaultValue=""+t._wrapperState.initialValue:t.defaultValue!==""+n&&(t.defaultValue=""+n))}var JG=Array.isArray;function uU(t,e,n,r){if(t=t.options,e){e={};for(var o=0;o<n.length;o++)e["$"+n[o]]=!0;for(n=0;n<t.length;n++)o=e.hasOwnProperty("$"+t[n].value),t[n].selected!==o&&(t[n].selected=o),o&&r&&(t[n].defaultSelected=!0)}else{for(n=""+XT(n),e=null,o=0;o<t.length;o++){if(t[o].value===n){t[o].selected=!0,r&&(t[o].defaultSelected=!0);return}e!==null||t[o].disabled||(e=t[o])}e!==null&&(e.selected=!0)}}function NMe(t,e){if(e.dangerouslySetInnerHTML!=null)throw Error(dt(91));return Ta({},e,{value:void 0,defaultValue:void 0,children:""+t._wrapperState.initialValue})}function lht(t,e){var n=e.value;if(n==null){if(n=e.children,e=e.defaultValue,n!=null){if(e!=null)throw Error(dt(92));if(JG(n)){if(1<n.length)throw Error(dt(93));n=n[0]}e=n}e==null&&(e=""),n=e}t._wrapperState={initialValue:XT(n)}}function ygt(t,e){var n=XT(e.value),r=XT(e.defaultValue);n!=null&&(n=""+n,n!==t.value&&(t.value=n),e.defaultValue==null&&t.defaultValue!==n&&(t.defaultValue=n)),r!=null&&(t.defaultValue=""+r)}function cht(t){var e=t.textContent;e===t._wrapperState.initialValue&&e!==""&&e!==null&&(t.value=e)}function vgt(t){switch(t){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function RMe(t,e){return t==null||t==="http://www.w3.org/1999/xhtml"?vgt(e):t==="http://www.w3.org/2000/svg"&&e==="foreignObject"?"http://www.w3.org/1999/xhtml":t}var pse,wgt=function(t){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(e,n,r,o){MSApp.execUnsafeLocalFunction(function(){return t(e,n,r,o)})}:t}(function(t,e){if(t.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in t)t.innerHTML=e;else{for(pse=pse||document.createElement("div"),pse.innerHTML="<svg>"+e.valueOf().toString()+"</svg>",e=pse.firstChild;t.firstChild;)t.removeChild(t.firstChild);for(;e.firstChild;)t.appendChild(e.firstChild)}});function u9(t,e){if(e){var n=t.firstChild;if(n&&n===t.lastChild&&n.nodeType===3){n.nodeValue=e;return}}t.textContent=e}var e9={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},sOn=["Webkit","ms","Moz","O"];Object.keys(e9).forEach(function(t){sOn.forEach(function(e){e=e+t.charAt(0).toUpperCase()+t.substring(1),e9[e]=e9[t]})});function bgt(t,e,n){return e==null||typeof e=="boolean"||e===""?"":n||typeof e!="number"||e===0||e9.hasOwnProperty(t)&&e9[t]?(""+e).trim():e+"px"}function _gt(t,e){t=t.style;for(var n in e)if(e.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=bgt(n,e[n],r);n==="float"&&(n="cssFloat"),r?t.setProperty(n,o):t[n]=o}}var aOn=Ta({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function LMe(t,e){if(e){if(aOn[t]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(dt(137,t));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(dt(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(dt(61))}if(e.style!=null&&typeof e.style!="object")throw Error(dt(62))}}function $Me(t,e){if(t.indexOf("-")===-1)return typeof e.is=="string";switch(t){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var DMe=null;function SOe(t){return t=t.target||t.srcElement||window,t.correspondingUseElement&&(t=t.correspondingUseElement),t.nodeType===3?t.parentNode:t}var FMe=null,dU=null,fU=null;function uht(t){if(t=P9(t)){if(typeof FMe!="function")throw Error(dt(280));var e=t.stateNode;e&&(e=mae(e),FMe(t.stateNode,t.type,e))}}function xgt(t){dU?fU?fU.push(t):fU=[t]:dU=t}function Sgt(){if(dU){var t=dU,e=fU;if(fU=dU=null,uht(t),e)for(t=0;t<e.length;t++)uht(e[t])}}function Cgt(t,e){return t(e)}function kgt(){}var sMe=!1;function Igt(t,e,n){if(sMe)return t(e,n);sMe=!0;try{return Cgt(t,e,n)}finally{sMe=!1,(dU!==null||fU!==null)&&(kgt(),Sgt())}}function d9(t,e){var n=t.stateNode;if(n===null)return null;var r=mae(n);if(r===null)return null;n=r[e];e:switch(e){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(r=!r.disabled)||(t=t.type,r=!(t==="button"||t==="input"||t==="select"||t==="textarea")),t=!r;break e;default:t=!1}if(t)return null;if(n&&typeof n!="function")throw Error(dt(231,e,typeof n));return n}var UMe=!1;if(ZC)try{Y2={},Object.defineProperty(Y2,"passive",{get:function(){UMe=!0}}),window.addEventListener("test",Y2,Y2),window.removeEventListener("test",Y2,Y2)}catch{UMe=!1}var Y2;function lOn(t,e,n,r,o,i,s,a,l){var c=Array.prototype.slice.call(arguments,3);try{e.apply(n,c)}catch(u){this.onError(u)}}var t9=!1,Bse=null,zse=!1,jMe=null,cOn={onError:function(t){t9=!0,Bse=t}};function uOn(t,e,n,r,o,i,s,a,l){t9=!1,Bse=null,lOn.apply(cOn,arguments)}function dOn(t,e,n,r,o,i,s,a,l){if(uOn.apply(this,arguments),t9){if(t9){var c=Bse;t9=!1,Bse=null}else throw Error(dt(198));zse||(zse=!0,jMe=c)}}function TN(t){var e=t,n=t;if(t.alternate)for(;e.return;)e=e.return;else{t=e;do e=t,(e.flags&4098)!==0&&(n=e.return),t=e.return;while(t)}return e.tag===3?n:null}function Tgt(t){if(t.tag===13){var e=t.memoizedState;if(e===null&&(t=t.alternate,t!==null&&(e=t.memoizedState)),e!==null)return e.dehydrated}return null}function dht(t){if(TN(t)!==t)throw Error(dt(188))}function fOn(t){var e=t.alternate;if(!e){if(e=TN(t),e===null)throw Error(dt(188));return e!==t?null:t}for(var n=t,r=e;;){var o=n.return;if(o===null)break;var i=o.alternate;if(i===null){if(r=o.return,r!==null){n=r;continue}break}if(o.child===i.child){for(i=o.child;i;){if(i===n)return dht(o),t;if(i===r)return dht(o),e;i=i.sibling}throw Error(dt(188))}if(n.return!==r.return)n=o,r=i;else{for(var s=!1,a=o.child;a;){if(a===n){s=!0,n=o,r=i;break}if(a===r){s=!0,r=o,n=i;break}a=a.sibling}if(!s){for(a=i.child;a;){if(a===n){s=!0,n=i,r=o;break}if(a===r){s=!0,r=i,n=o;break}a=a.sibling}if(!s)throw Error(dt(189))}}if(n.alternate!==r)throw Error(dt(190))}if(n.tag!==3)throw Error(dt(188));return n.stateNode.current===n?t:e}function Pgt(t){return t=fOn(t),t!==null?Agt(t):null}function Agt(t){if(t.tag===5||t.tag===6)return t;for(t=t.child;t!==null;){var e=Agt(t);if(e!==null)return e;t=t.sibling}return null}var Egt=Eh.unstable_scheduleCallback,fht=Eh.unstable_cancelCallback,pOn=Eh.unstable_shouldYield,mOn=Eh.unstable_requestPaint,ml=Eh.unstable_now,hOn=Eh.unstable_getCurrentPriorityLevel,COe=Eh.unstable_ImmediatePriority,Mgt=Eh.unstable_UserBlockingPriority,Hse=Eh.unstable_NormalPriority,gOn=Eh.unstable_LowPriority,Ogt=Eh.unstable_IdlePriority,uae=null,J_=null;function yOn(t){if(J_&&typeof J_.onCommitFiberRoot=="function")try{J_.onCommitFiberRoot(uae,t,void 0,(t.current.flags&128)===128)}catch{}}var Rw=Math.clz32?Math.clz32:bOn,vOn=Math.log,wOn=Math.LN2;function bOn(t){return t>>>=0,t===0?32:31-(vOn(t)/wOn|0)|0}var mse=64,hse=4194304;function XG(t){switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return t&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return t}}function Wse(t,e){var n=t.pendingLanes;if(n===0)return 0;var r=0,o=t.suspendedLanes,i=t.pingedLanes,s=n&268435455;if(s!==0){var a=s&~o;a!==0?r=XG(a):(i&=s,i!==0&&(r=XG(i)))}else s=n&~o,s!==0?r=XG(s):i!==0&&(r=XG(i));if(r===0)return 0;if(e!==0&&e!==r&&(e&o)===0&&(o=r&-r,i=e&-e,o>=i||o===16&&(i&4194240)!==0))return e;if((r&4)!==0&&(r|=n&16),e=t.entangledLanes,e!==0)for(t=t.entanglements,e&=r;0<e;)n=31-Rw(e),o=1<<n,r|=t[n],e&=~o;return r}function _On(t,e){switch(t){case 1:case 2:case 4:return e+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function xOn(t,e){for(var n=t.suspendedLanes,r=t.pingedLanes,o=t.expirationTimes,i=t.pendingLanes;0<i;){var s=31-Rw(i),a=1<<s,l=o[s];l===-1?((a&n)===0||(a&r)!==0)&&(o[s]=_On(a,e)):l<=e&&(t.expiredLanes|=a),i&=~a}}function BMe(t){return t=t.pendingLanes&-1073741825,t!==0?t:t&1073741824?1073741824:0}function Ngt(){var t=mse;return mse<<=1,(mse&4194240)===0&&(mse=64),t}function aMe(t){for(var e=[],n=0;31>n;n++)e.push(t);return e}function I9(t,e,n){t.pendingLanes|=e,e!==536870912&&(t.suspendedLanes=0,t.pingedLanes=0),t=t.eventTimes,e=31-Rw(e),t[e]=n}function SOn(t,e){var n=t.pendingLanes&~e;t.pendingLanes=e,t.suspendedLanes=0,t.pingedLanes=0,t.expiredLanes&=e,t.mutableReadLanes&=e,t.entangledLanes&=e,e=t.entanglements;var r=t.eventTimes;for(t=t.expirationTimes;0<n;){var o=31-Rw(n),i=1<<o;e[o]=0,r[o]=-1,t[o]=-1,n&=~i}}function kOe(t,e){var n=t.entangledLanes|=e;for(t=t.entanglements;n;){var r=31-Rw(n),o=1<<r;o&e|t[r]&e&&(t[r]|=e),n&=~o}}var qi=0;function Rgt(t){return t&=-t,1<t?4<t?(t&268435455)!==0?16:536870912:4:1}var Lgt,IOe,$gt,Dgt,Fgt,zMe=!1,gse=[],WT=null,VT=null,qT=null,f9=new Map,p9=new Map,jT=[],COn="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function pht(t,e){switch(t){case"focusin":case"focusout":WT=null;break;case"dragenter":case"dragleave":VT=null;break;case"mouseover":case"mouseout":qT=null;break;case"pointerover":case"pointerout":f9.delete(e.pointerId);break;case"gotpointercapture":case"lostpointercapture":p9.delete(e.pointerId)}}function HG(t,e,n,r,o,i){return t===null||t.nativeEvent!==i?(t={blockedOn:e,domEventName:n,eventSystemFlags:r,nativeEvent:i,targetContainers:[o]},e!==null&&(e=P9(e),e!==null&&IOe(e)),t):(t.eventSystemFlags|=r,e=t.targetContainers,o!==null&&e.indexOf(o)===-1&&e.push(o),t)}function kOn(t,e,n,r,o){switch(e){case"focusin":return WT=HG(WT,t,e,n,r,o),!0;case"dragenter":return VT=HG(VT,t,e,n,r,o),!0;case"mouseover":return qT=HG(qT,t,e,n,r,o),!0;case"pointerover":var i=o.pointerId;return f9.set(i,HG(f9.get(i)||null,t,e,n,r,o)),!0;case"gotpointercapture":return i=o.pointerId,p9.set(i,HG(p9.get(i)||null,t,e,n,r,o)),!0}return!1}function Ugt(t){var e=gN(t.target);if(e!==null){var n=TN(e);if(n!==null){if(e=n.tag,e===13){if(e=Tgt(n),e!==null){t.blockedOn=e,Fgt(t.priority,function(){$gt(n)});return}}else if(e===3&&n.stateNode.current.memoizedState.isDehydrated){t.blockedOn=n.tag===3?n.stateNode.containerInfo:null;return}}}t.blockedOn=null}function Ese(t){if(t.blockedOn!==null)return!1;for(var e=t.targetContainers;0<e.length;){var n=HMe(t.domEventName,t.eventSystemFlags,e[0],t.nativeEvent);if(n===null){n=t.nativeEvent;var r=new n.constructor(n.type,n);DMe=r,n.target.dispatchEvent(r),DMe=null}else return e=P9(n),e!==null&&IOe(e),t.blockedOn=n,!1;e.shift()}return!0}function mht(t,e,n){Ese(t)&&n.delete(e)}function IOn(){zMe=!1,WT!==null&&Ese(WT)&&(WT=null),VT!==null&&Ese(VT)&&(VT=null),qT!==null&&Ese(qT)&&(qT=null),f9.forEach(mht),p9.forEach(mht)}function WG(t,e){t.blockedOn===e&&(t.blockedOn=null,zMe||(zMe=!0,Eh.unstable_scheduleCallback(Eh.unstable_NormalPriority,IOn)))}function m9(t){function e(o){return WG(o,t)}if(0<gse.length){WG(gse[0],t);for(var n=1;n<gse.length;n++){var r=gse[n];r.blockedOn===t&&(r.blockedOn=null)}}for(WT!==null&&WG(WT,t),VT!==null&&WG(VT,t),qT!==null&&WG(qT,t),f9.forEach(e),p9.forEach(e),n=0;n<jT.length;n++)r=jT[n],r.blockedOn===t&&(r.blockedOn=null);for(;0<jT.length&&(n=jT[0],n.blockedOn===null);)Ugt(n),n.blockedOn===null&&jT.shift()}var pU=QC.ReactCurrentBatchConfig,Vse=!0;function TOn(t,e,n,r){var o=qi,i=pU.transition;pU.transition=null;try{qi=1,TOe(t,e,n,r)}finally{qi=o,pU.transition=i}}function POn(t,e,n,r){var o=qi,i=pU.transition;pU.transition=null;try{qi=4,TOe(t,e,n,r)}finally{qi=o,pU.transition=i}}function TOe(t,e,n,r){if(Vse){var o=HMe(t,e,n,r);if(o===null)mMe(t,e,r,qse,n),pht(t,r);else if(kOn(o,t,e,n,r))r.stopPropagation();else if(pht(t,r),e&4&&-1<COn.indexOf(t)){for(;o!==null;){var i=P9(o);if(i!==null&&Lgt(i),i=HMe(t,e,n,r),i===null&&mMe(t,e,r,qse,n),i===o)break;o=i}o!==null&&r.stopPropagation()}else mMe(t,e,r,null,n)}}var qse=null;function HMe(t,e,n,r){if(qse=null,t=SOe(r),t=gN(t),t!==null)if(e=TN(t),e===null)t=null;else if(n=e.tag,n===13){if(t=Tgt(e),t!==null)return t;t=null}else if(n===3){if(e.stateNode.current.memoizedState.isDehydrated)return e.tag===3?e.stateNode.containerInfo:null;t=null}else e!==t&&(t=null);return qse=t,null}function jgt(t){switch(t){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(hOn()){case COe:return 1;case Mgt:return 4;case Hse:case gOn:return 16;case Ogt:return 536870912;default:return 16}default:return 16}}var zT=null,POe=null,Mse=null;function Bgt(){if(Mse)return Mse;var t,e=POe,n=e.length,r,o="value"in zT?zT.value:zT.textContent,i=o.length;for(t=0;t<n&&e[t]===o[t];t++);var s=n-t;for(r=1;r<=s&&e[n-r]===o[i-r];r++);return Mse=o.slice(t,1<r?1-r:void 0)}function Ose(t){var e=t.keyCode;return"charCode"in t?(t=t.charCode,t===0&&e===13&&(t=13)):t=e,t===10&&(t=13),32<=t||t===13?t:0}function yse(){return!0}function hht(){return!1}function Mh(t){function e(n,r,o,i,s){this._reactName=n,this._targetInst=o,this.type=r,this.nativeEvent=i,this.target=s,this.currentTarget=null;for(var a in t)t.hasOwnProperty(a)&&(n=t[a],this[a]=n?n(i):i[a]);return this.isDefaultPrevented=(i.defaultPrevented!=null?i.defaultPrevented:i.returnValue===!1)?yse:hht,this.isPropagationStopped=hht,this}return Ta(e.prototype,{preventDefault:function(){this.defaultPrevented=!0;var n=this.nativeEvent;n&&(n.preventDefault?n.preventDefault():typeof n.returnValue!="unknown"&&(n.returnValue=!1),this.isDefaultPrevented=yse)},stopPropagation:function(){var n=this.nativeEvent;n&&(n.stopPropagation?n.stopPropagation():typeof n.cancelBubble!="unknown"&&(n.cancelBubble=!0),this.isPropagationStopped=yse)},persist:function(){},isPersistent:yse}),e}var SU={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(t){return t.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},AOe=Mh(SU),T9=Ta({},SU,{view:0,detail:0}),AOn=Mh(T9),lMe,cMe,VG,dae=Ta({},T9,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:EOe,button:0,buttons:0,relatedTarget:function(t){return t.relatedTarget===void 0?t.fromElement===t.srcElement?t.toElement:t.fromElement:t.relatedTarget},movementX:function(t){return"movementX"in t?t.movementX:(t!==VG&&(VG&&t.type==="mousemove"?(lMe=t.screenX-VG.screenX,cMe=t.screenY-VG.screenY):cMe=lMe=0,VG=t),lMe)},movementY:function(t){return"movementY"in t?t.movementY:cMe}}),ght=Mh(dae),EOn=Ta({},dae,{dataTransfer:0}),MOn=Mh(EOn),OOn=Ta({},T9,{relatedTarget:0}),uMe=Mh(OOn),NOn=Ta({},SU,{animationName:0,elapsedTime:0,pseudoElement:0}),ROn=Mh(NOn),LOn=Ta({},SU,{clipboardData:function(t){return"clipboardData"in t?t.clipboardData:window.clipboardData}}),$On=Mh(LOn),DOn=Ta({},SU,{data:0}),yht=Mh(DOn),FOn={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},UOn={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},jOn={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function BOn(t){var e=this.nativeEvent;return e.getModifierState?e.getModifierState(t):(t=jOn[t])?!!e[t]:!1}function EOe(){return BOn}var zOn=Ta({},T9,{key:function(t){if(t.key){var e=FOn[t.key]||t.key;if(e!=="Unidentified")return e}return t.type==="keypress"?(t=Ose(t),t===13?"Enter":String.fromCharCode(t)):t.type==="keydown"||t.type==="keyup"?UOn[t.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:EOe,charCode:function(t){return t.type==="keypress"?Ose(t):0},keyCode:function(t){return t.type==="keydown"||t.type==="keyup"?t.keyCode:0},which:function(t){return t.type==="keypress"?Ose(t):t.type==="keydown"||t.type==="keyup"?t.keyCode:0}}),HOn=Mh(zOn),WOn=Ta({},dae,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),vht=Mh(WOn),VOn=Ta({},T9,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:EOe}),qOn=Mh(VOn),KOn=Ta({},SU,{propertyName:0,elapsedTime:0,pseudoElement:0}),GOn=Mh(KOn),ZOn=Ta({},dae,{deltaX:function(t){return"deltaX"in t?t.deltaX:"wheelDeltaX"in t?-t.wheelDeltaX:0},deltaY:function(t){return"deltaY"in t?t.deltaY:"wheelDeltaY"in t?-t.wheelDeltaY:"wheelDelta"in t?-t.wheelDelta:0},deltaZ:0,deltaMode:0}),YOn=Mh(ZOn),JOn=[9,13,27,32],MOe=ZC&&"CompositionEvent"in window,n9=null;ZC&&"documentMode"in document&&(n9=document.documentMode);var XOn=ZC&&"TextEvent"in window&&!n9,zgt=ZC&&(!MOe||n9&&8<n9&&11>=n9),wht=" ",bht=!1;function Hgt(t,e){switch(t){case"keyup":return JOn.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Wgt(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var eU=!1;function QOn(t,e){switch(t){case"compositionend":return Wgt(e);case"keypress":return e.which!==32?null:(bht=!0,wht);case"textInput":return t=e.data,t===wht&&bht?null:t;default:return null}}function eNn(t,e){if(eU)return t==="compositionend"||!MOe&&Hgt(t,e)?(t=Bgt(),Mse=POe=zT=null,eU=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1<e.char.length)return e.char;if(e.which)return String.fromCharCode(e.which)}return null;case"compositionend":return zgt&&e.locale!=="ko"?null:e.data;default:return null}}var tNn={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function _ht(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e==="input"?!!tNn[t.type]:e==="textarea"}function Vgt(t,e,n,r){xgt(r),e=Kse(e,"onChange"),0<e.length&&(n=new AOe("onChange","change",null,n,r),t.push({event:n,listeners:e}))}var r9=null,h9=null;function nNn(t){nyt(t,0)}function fae(t){var e=rU(t);if(hgt(e))return t}function rNn(t,e){if(t==="change")return e}var qgt=!1;ZC&&(ZC?(wse="oninput"in document,wse||(dMe=document.createElement("div"),dMe.setAttribute("oninput","return;"),wse=typeof dMe.oninput=="function"),vse=wse):vse=!1,qgt=vse&&(!document.documentMode||9<document.documentMode));var vse,wse,dMe;function xht(){r9&&(r9.detachEvent("onpropertychange",Kgt),h9=r9=null)}function Kgt(t){if(t.propertyName==="value"&&fae(h9)){var e=[];Vgt(e,h9,t,SOe(t)),Igt(nNn,e)}}function oNn(t,e,n){t==="focusin"?(xht(),r9=e,h9=n,r9.attachEvent("onpropertychange",Kgt)):t==="focusout"&&xht()}function iNn(t){if(t==="selectionchange"||t==="keyup"||t==="keydown")return fae(h9)}function sNn(t,e){if(t==="click")return fae(e)}function aNn(t,e){if(t==="input"||t==="change")return fae(e)}function lNn(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var $w=typeof Object.is=="function"?Object.is:lNn;function g9(t,e){if($w(t,e))return!0;if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;var n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(r=0;r<n.length;r++){var o=n[r];if(!kMe.call(e,o)||!$w(t[o],e[o]))return!1}return!0}function Sht(t){for(;t&&t.firstChild;)t=t.firstChild;return t}function Cht(t,e){var n=Sht(t);t=0;for(var r;n;){if(n.nodeType===3){if(r=t+n.textContent.length,t<=e&&r>=e)return{node:n,offset:e-t};t=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Sht(n)}}function Ggt(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?Ggt(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function Zgt(){for(var t=window,e=jse();e instanceof t.HTMLIFrameElement;){try{var n=typeof e.contentWindow.location.href=="string"}catch{n=!1}if(n)t=e.contentWindow;else break;e=jse(t.document)}return e}function OOe(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e&&(e==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||e==="textarea"||t.contentEditable==="true")}function cNn(t){var e=Zgt(),n=t.focusedElem,r=t.selectionRange;if(e!==n&&n&&n.ownerDocument&&Ggt(n.ownerDocument.documentElement,n)){if(r!==null&&OOe(n)){if(e=r.start,t=r.end,t===void 0&&(t=e),"selectionStart"in n)n.selectionStart=e,n.selectionEnd=Math.min(t,n.value.length);else if(t=(e=n.ownerDocument||document)&&e.defaultView||window,t.getSelection){t=t.getSelection();var o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!t.extend&&i>r&&(o=r,r=i,i=o),o=Cht(n,i);var s=Cht(n,r);o&&s&&(t.rangeCount!==1||t.anchorNode!==o.node||t.anchorOffset!==o.offset||t.focusNode!==s.node||t.focusOffset!==s.offset)&&(e=e.createRange(),e.setStart(o.node,o.offset),t.removeAllRanges(),i>r?(t.addRange(e),t.extend(s.node,s.offset)):(e.setEnd(s.node,s.offset),t.addRange(e)))}}for(e=[],t=n;t=t.parentNode;)t.nodeType===1&&e.push({element:t,left:t.scrollLeft,top:t.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n<e.length;n++)t=e[n],t.element.scrollLeft=t.left,t.element.scrollTop=t.top}}var uNn=ZC&&"documentMode"in document&&11>=document.documentMode,tU=null,WMe=null,o9=null,VMe=!1;function kht(t,e,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;VMe||tU==null||tU!==jse(r)||(r=tU,"selectionStart"in r&&OOe(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),o9&&g9(o9,r)||(o9=r,r=Kse(WMe,"onSelect"),0<r.length&&(e=new AOe("onSelect","select",null,e,n),t.push({event:e,listeners:r}),e.target=tU)))}function bse(t,e){var n={};return n[t.toLowerCase()]=e.toLowerCase(),n["Webkit"+t]="webkit"+e,n["Moz"+t]="moz"+e,n}var nU={animationend:bse("Animation","AnimationEnd"),animationiteration:bse("Animation","AnimationIteration"),animationstart:bse("Animation","AnimationStart"),transitionend:bse("Transition","TransitionEnd")},fMe={},Ygt={};ZC&&(Ygt=document.createElement("div").style,"AnimationEvent"in window||(delete nU.animationend.animation,delete nU.animationiteration.animation,delete nU.animationstart.animation),"TransitionEvent"in window||delete nU.transitionend.transition);function pae(t){if(fMe[t])return fMe[t];if(!nU[t])return t;var e=nU[t],n;for(n in e)if(e.hasOwnProperty(n)&&n in Ygt)return fMe[t]=e[n];return t}var Jgt=pae("animationend"),Xgt=pae("animationiteration"),Qgt=pae("animationstart"),eyt=pae("transitionend"),tyt=new Map,Iht="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function eP(t,e){tyt.set(t,e),IN(e,[t])}for(_se=0;_se<Iht.length;_se++)xse=Iht[_se],Tht=xse.toLowerCase(),Pht=xse[0].toUpperCase()+xse.slice(1),eP(Tht,"on"+Pht);var xse,Tht,Pht,_se;eP(Jgt,"onAnimationEnd");eP(Xgt,"onAnimationIteration");eP(Qgt,"onAnimationStart");eP("dblclick","onDoubleClick");eP("focusin","onFocus");eP("focusout","onBlur");eP(eyt,"onTransitionEnd");gU("onMouseEnter",["mouseout","mouseover"]);gU("onMouseLeave",["mouseout","mouseover"]);gU("onPointerEnter",["pointerout","pointerover"]);gU("onPointerLeave",["pointerout","pointerover"]);IN("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));IN("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));IN("onBeforeInput",["compositionend","keypress","textInput","paste"]);IN("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));IN("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));IN("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var QG="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),dNn=new Set("cancel close invalid load scroll toggle".split(" ").concat(QG));function Aht(t,e,n){var r=t.type||"unknown-event";t.currentTarget=n,dOn(r,e,void 0,t),t.currentTarget=null}function nyt(t,e){e=(e&4)!==0;for(var n=0;n<t.length;n++){var r=t[n],o=r.event;r=r.listeners;e:{var i=void 0;if(e)for(var s=r.length-1;0<=s;s--){var a=r[s],l=a.instance,c=a.currentTarget;if(a=a.listener,l!==i&&o.isPropagationStopped())break e;Aht(o,a,c),i=l}else for(s=0;s<r.length;s++){if(a=r[s],l=a.instance,c=a.currentTarget,a=a.listener,l!==i&&o.isPropagationStopped())break e;Aht(o,a,c),i=l}}}if(zse)throw t=jMe,zse=!1,jMe=null,t}function Hs(t,e){var n=e[YMe];n===void 0&&(n=e[YMe]=new Set);var r=t+"__bubble";n.has(r)||(ryt(e,t,2,!1),n.add(r))}function pMe(t,e,n){var r=0;e&&(r|=4),ryt(n,t,r,e)}var Sse="_reactListening"+Math.random().toString(36).slice(2);function y9(t){if(!t[Sse]){t[Sse]=!0,ugt.forEach(function(n){n!=="selectionchange"&&(dNn.has(n)||pMe(n,!1,t),pMe(n,!0,t))});var e=t.nodeType===9?t:t.ownerDocument;e===null||e[Sse]||(e[Sse]=!0,pMe("selectionchange",!1,e))}}function ryt(t,e,n,r){switch(jgt(e)){case 1:var o=TOn;break;case 4:o=POn;break;default:o=TOe}n=o.bind(null,e,n,t),o=void 0,!UMe||e!=="touchstart"&&e!=="touchmove"&&e!=="wheel"||(o=!0),r?o!==void 0?t.addEventListener(e,n,{capture:!0,passive:o}):t.addEventListener(e,n,!0):o!==void 0?t.addEventListener(e,n,{passive:o}):t.addEventListener(e,n,!1)}function mMe(t,e,n,r,o){var i=r;if((e&1)===0&&(e&2)===0&&r!==null)e:for(;;){if(r===null)return;var s=r.tag;if(s===3||s===4){var a=r.stateNode.containerInfo;if(a===o||a.nodeType===8&&a.parentNode===o)break;if(s===4)for(s=r.return;s!==null;){var l=s.tag;if((l===3||l===4)&&(l=s.stateNode.containerInfo,l===o||l.nodeType===8&&l.parentNode===o))return;s=s.return}for(;a!==null;){if(s=gN(a),s===null)return;if(l=s.tag,l===5||l===6){r=i=s;continue e}a=a.parentNode}}r=r.return}Igt(function(){var c=i,u=SOe(n),d=[];e:{var f=tyt.get(t);if(f!==void 0){var p=AOe,m=t;switch(t){case"keypress":if(Ose(n)===0)break e;case"keydown":case"keyup":p=HOn;break;case"focusin":m="focus",p=uMe;break;case"focusout":m="blur",p=uMe;break;case"beforeblur":case"afterblur":p=uMe;break;case"click":if(n.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":p=ght;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":p=MOn;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":p=qOn;break;case Jgt:case Xgt:case Qgt:p=ROn;break;case eyt:p=GOn;break;case"scroll":p=AOn;break;case"wheel":p=YOn;break;case"copy":case"cut":case"paste":p=$On;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":p=vht}var h=(e&4)!==0,g=!h&&t==="scroll",v=h?f!==null?f+"Capture":null:f;h=[];for(var y=c,w;y!==null;){w=y;var _=w.stateNode;if(w.tag===5&&_!==null&&(w=_,v!==null&&(_=d9(y,v),_!=null&&h.push(v9(y,_,w)))),g)break;y=y.return}0<h.length&&(f=new p(f,m,null,n,u),d.push({event:f,listeners:h}))}}if((e&7)===0){e:{if(f=t==="mouseover"||t==="pointerover",p=t==="mouseout"||t==="pointerout",f&&n!==DMe&&(m=n.relatedTarget||n.fromElement)&&(gN(m)||m[YC]))break e;if((p||f)&&(f=u.window===u?u:(f=u.ownerDocument)?f.defaultView||f.parentWindow:window,p?(m=n.relatedTarget||n.toElement,p=c,m=m?gN(m):null,m!==null&&(g=TN(m),m!==g||m.tag!==5&&m.tag!==6)&&(m=null)):(p=null,m=c),p!==m)){if(h=ght,_="onMouseLeave",v="onMouseEnter",y="mouse",(t==="pointerout"||t==="pointerover")&&(h=vht,_="onPointerLeave",v="onPointerEnter",y="pointer"),g=p==null?f:rU(p),w=m==null?f:rU(m),f=new h(_,y+"leave",p,n,u),f.target=g,f.relatedTarget=w,_=null,gN(u)===c&&(h=new h(v,y+"enter",m,n,u),h.target=w,h.relatedTarget=g,_=h),g=_,p&&m)t:{for(h=p,v=m,y=0,w=h;w;w=J2(w))y++;for(w=0,_=v;_;_=J2(_))w++;for(;0<y-w;)h=J2(h),y--;for(;0<w-y;)v=J2(v),w--;for(;y--;){if(h===v||v!==null&&h===v.alternate)break t;h=J2(h),v=J2(v)}h=null}else h=null;p!==null&&Eht(d,f,p,h,!1),m!==null&&g!==null&&Eht(d,g,m,h,!0)}}e:{if(f=c?rU(c):window,p=f.nodeName&&f.nodeName.toLowerCase(),p==="select"||p==="input"&&f.type==="file")var S=rNn;else if(_ht(f))if(qgt)S=aNn;else{S=iNn;var I=oNn}else(p=f.nodeName)&&p.toLowerCase()==="input"&&(f.type==="checkbox"||f.type==="radio")&&(S=sNn);if(S&&(S=S(t,c))){Vgt(d,S,n,u);break e}I&&I(t,f,c),t==="focusout"&&(I=f._wrapperState)&&I.controlled&&f.type==="number"&&OMe(f,"number",f.value)}switch(I=c?rU(c):window,t){case"focusin":(_ht(I)||I.contentEditable==="true")&&(tU=I,WMe=c,o9=null);break;case"focusout":o9=WMe=tU=null;break;case"mousedown":VMe=!0;break;case"contextmenu":case"mouseup":case"dragend":VMe=!1,kht(d,n,u);break;case"selectionchange":if(uNn)break;case"keydown":case"keyup":kht(d,n,u)}var C;if(MOe)e:{switch(t){case"compositionstart":var k="onCompositionStart";break e;case"compositionend":k="onCompositionEnd";break e;case"compositionupdate":k="onCompositionUpdate";break e}k=void 0}else eU?Hgt(t,n)&&(k="onCompositionEnd"):t==="keydown"&&n.keyCode===229&&(k="onCompositionStart");k&&(zgt&&n.locale!=="ko"&&(eU||k!=="onCompositionStart"?k==="onCompositionEnd"&&eU&&(C=Bgt()):(zT=u,POe="value"in zT?zT.value:zT.textContent,eU=!0)),I=Kse(c,k),0<I.length&&(k=new yht(k,t,null,n,u),d.push({event:k,listeners:I}),C?k.data=C:(C=Wgt(n),C!==null&&(k.data=C)))),(C=XOn?QOn(t,n):eNn(t,n))&&(c=Kse(c,"onBeforeInput"),0<c.length&&(u=new yht("onBeforeInput","beforeinput",null,n,u),d.push({event:u,listeners:c}),u.data=C))}nyt(d,e)})}function v9(t,e,n){return{instance:t,listener:e,currentTarget:n}}function Kse(t,e){for(var n=e+"Capture",r=[];t!==null;){var o=t,i=o.stateNode;o.tag===5&&i!==null&&(o=i,i=d9(t,n),i!=null&&r.unshift(v9(t,i,o)),i=d9(t,e),i!=null&&r.push(v9(t,i,o))),t=t.return}return r}function J2(t){if(t===null)return null;do t=t.return;while(t&&t.tag!==5);return t||null}function Eht(t,e,n,r,o){for(var i=e._reactName,s=[];n!==null&&n!==r;){var a=n,l=a.alternate,c=a.stateNode;if(l!==null&&l===r)break;a.tag===5&&c!==null&&(a=c,o?(l=d9(n,i),l!=null&&s.unshift(v9(n,l,a))):o||(l=d9(n,i),l!=null&&s.push(v9(n,l,a)))),n=n.return}s.length!==0&&t.push({event:e,listeners:s})}var fNn=/\r\n?/g,pNn=/\u0000|\uFFFD/g;function Mht(t){return(typeof t=="string"?t:""+t).replace(fNn,`
`).replace(pNn,"")}function Cse(t,e,n){if(e=Mht(e),Mht(t)!==e&&n)throw Error(dt(425))}function Gse(){}var qMe=null,KMe=null;function GMe(t,e){return t==="textarea"||t==="noscript"||typeof e.children=="string"||typeof e.children=="number"||typeof e.dangerouslySetInnerHTML=="object"&&e.dangerouslySetInnerHTML!==null&&e.dangerouslySetInnerHTML.__html!=null}var ZMe=typeof setTimeout=="function"?setTimeout:void 0,mNn=typeof clearTimeout=="function"?clearTimeout:void 0,Oht=typeof Promise=="function"?Promise:void 0,hNn=typeof queueMicrotask=="function"?queueMicrotask:typeof Oht<"u"?function(t){return Oht.resolve(null).then(t).catch(gNn)}:ZMe;function gNn(t){setTimeout(function(){throw t})}function hMe(t,e){var n=e,r=0;do{var o=n.nextSibling;if(t.removeChild(n),o&&o.nodeType===8)if(n=o.data,n==="/$"){if(r===0){t.removeChild(o),m9(e);return}r--}else n!=="$"&&n!=="$?"&&n!=="$!"||r++;n=o}while(n);m9(e)}function KT(t){for(;t!=null;t=t.nextSibling){var e=t.nodeType;if(e===1||e===3)break;if(e===8){if(e=t.data,e==="$"||e==="$!"||e==="$?")break;if(e==="/$")return null}}return t}function Nht(t){t=t.previousSibling;for(var e=0;t;){if(t.nodeType===8){var n=t.data;if(n==="$"||n==="$!"||n==="$?"){if(e===0)return t;e--}else n==="/$"&&e++}t=t.previousSibling}return null}var CU=Math.random().toString(36).slice(2),Y_="__reactFiber$"+CU,w9="__reactProps$"+CU,YC="__reactContainer$"+CU,YMe="__reactEvents$"+CU,yNn="__reactListeners$"+CU,vNn="__reactHandles$"+CU;function gN(t){var e=t[Y_];if(e)return e;for(var n=t.parentNode;n;){if(e=n[YC]||n[Y_]){if(n=e.alternate,e.child!==null||n!==null&&n.child!==null)for(t=Nht(t);t!==null;){if(n=t[Y_])return n;t=Nht(t)}return e}t=n,n=t.parentNode}return null}function P9(t){return t=t[Y_]||t[YC],!t||t.tag!==5&&t.tag!==6&&t.tag!==13&&t.tag!==3?null:t}function rU(t){if(t.tag===5||t.tag===6)return t.stateNode;throw Error(dt(33))}function mae(t){return t[w9]||null}var JMe=[],oU=-1;function tP(t){return{current:t}}function Ws(t){0>oU||(t.current=JMe[oU],JMe[oU]=null,oU--)}function As(t,e){oU++,JMe[oU]=t.current,t.current=e}var QT={},Qd=tP(QT),sm=tP(!1),_N=QT;function yU(t,e){var n=t.type.contextTypes;if(!n)return QT;var r=t.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===e)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=e[i];return r&&(t=t.stateNode,t.__reactInternalMemoizedUnmaskedChildContext=e,t.__reactInternalMemoizedMaskedChildContext=o),o}function am(t){return t=t.childContextTypes,t!=null}function Zse(){Ws(sm),Ws(Qd)}function Rht(t,e,n){if(Qd.current!==QT)throw Error(dt(168));As(Qd,e),As(sm,n)}function oyt(t,e,n){var r=t.stateNode;if(e=e.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in e))throw Error(dt(108,oOn(t)||"Unknown",o));return Ta({},n,r)}function Yse(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||QT,_N=Qd.current,As(Qd,t),As(sm,sm.current),!0}function Lht(t,e,n){var r=t.stateNode;if(!r)throw Error(dt(169));n?(t=oyt(t,e,_N),r.__reactInternalMemoizedMergedChildContext=t,Ws(sm),Ws(Qd),As(Qd,t)):Ws(sm),As(sm,n)}var VC=null,hae=!1,gMe=!1;function iyt(t){VC===null?VC=[t]:VC.push(t)}function wNn(t){hae=!0,iyt(t)}function nP(){if(!gMe&&VC!==null){gMe=!0;var t=0,e=qi;try{var n=VC;for(qi=1;t<n.length;t++){var r=n[t];do r=r(!0);while(r!==null)}VC=null,hae=!1}catch(o){throw VC!==null&&(VC=VC.slice(t+1)),Egt(COe,nP),o}finally{qi=e,gMe=!1}}return null}var iU=[],sU=0,Jse=null,Xse=0,xy=[],Sy=0,xN=null,qC=1,KC="";function mN(t,e){iU[sU++]=Xse,iU[sU++]=Jse,Jse=t,Xse=e}function syt(t,e,n){xy[Sy++]=qC,xy[Sy++]=KC,xy[Sy++]=xN,xN=t;var r=qC;t=KC;var o=32-Rw(r)-1;r&=~(1<<o),n+=1;var i=32-Rw(e)+o;if(30<i){var s=o-o%5;i=(r&(1<<s)-1).toString(32),r>>=s,o-=s,qC=1<<32-Rw(e)+o|n<<o|r,KC=i+t}else qC=1<<i|n<<o|r,KC=t}function NOe(t){t.return!==null&&(mN(t,1),syt(t,1,0))}function ROe(t){for(;t===Jse;)Jse=iU[--sU],iU[sU]=null,Xse=iU[--sU],iU[sU]=null;for(;t===xN;)xN=xy[--Sy],xy[Sy]=null,KC=xy[--Sy],xy[Sy]=null,qC=xy[--Sy],xy[Sy]=null}var Ah=null,Ph=null,ua=!1,Nw=null;function ayt(t,e){var n=Cy(5,null,null,0);n.elementType="DELETED",n.stateNode=e,n.return=t,e=t.deletions,e===null?(t.deletions=[n],t.flags|=16):e.push(n)}function $ht(t,e){switch(t.tag){case 5:var n=t.type;return e=e.nodeType!==1||n.toLowerCase()!==e.nodeName.toLowerCase()?null:e,e!==null?(t.stateNode=e,Ah=t,Ph=KT(e.firstChild),!0):!1;case 6:return e=t.pendingProps===""||e.nodeType!==3?null:e,e!==null?(t.stateNode=e,Ah=t,Ph=null,!0):!1;case 13:return e=e.nodeType!==8?null:e,e!==null?(n=xN!==null?{id:qC,overflow:KC}:null,t.memoizedState={dehydrated:e,treeContext:n,retryLane:1073741824},n=Cy(18,null,null,0),n.stateNode=e,n.return=t,t.child=n,Ah=t,Ph=null,!0):!1;default:return!1}}function XMe(t){return(t.mode&1)!==0&&(t.flags&128)===0}function QMe(t){if(ua){var e=Ph;if(e){var n=e;if(!$ht(t,e)){if(XMe(t))throw Error(dt(418));e=KT(n.nextSibling);var r=Ah;e&&$ht(t,e)?ayt(r,n):(t.flags=t.flags&-4097|2,ua=!1,Ah=t)}}else{if(XMe(t))throw Error(dt(418));t.flags=t.flags&-4097|2,ua=!1,Ah=t}}}function Dht(t){for(t=t.return;t!==null&&t.tag!==5&&t.tag!==3&&t.tag!==13;)t=t.return;Ah=t}function kse(t){if(t!==Ah)return!1;if(!ua)return Dht(t),ua=!0,!1;var e;if((e=t.tag!==3)&&!(e=t.tag!==5)&&(e=t.type,e=e!=="head"&&e!=="body"&&!GMe(t.type,t.memoizedProps)),e&&(e=Ph)){if(XMe(t))throw lyt(),Error(dt(418));for(;e;)ayt(t,e),e=KT(e.nextSibling)}if(Dht(t),t.tag===13){if(t=t.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(dt(317));e:{for(t=t.nextSibling,e=0;t;){if(t.nodeType===8){var n=t.data;if(n==="/$"){if(e===0){Ph=KT(t.nextSibling);break e}e--}else n!=="$"&&n!=="$!"&&n!=="$?"||e++}t=t.nextSibling}Ph=null}}else Ph=Ah?KT(t.stateNode.nextSibling):null;return!0}function lyt(){for(var t=Ph;t;)t=KT(t.nextSibling)}function vU(){Ph=Ah=null,ua=!1}function LOe(t){Nw===null?Nw=[t]:Nw.push(t)}var bNn=QC.ReactCurrentBatchConfig;function Mw(t,e){if(t&&t.defaultProps){e=Ta({},e),t=t.defaultProps;for(var n in t)e[n]===void 0&&(e[n]=t[n]);return e}return e}var Qse=tP(null),eae=null,aU=null,$Oe=null;function DOe(){$Oe=aU=eae=null}function FOe(t){var e=Qse.current;Ws(Qse),t._currentValue=e}function eOe(t,e,n){for(;t!==null;){var r=t.alternate;if((t.childLanes&e)!==e?(t.childLanes|=e,r!==null&&(r.childLanes|=e)):r!==null&&(r.childLanes&e)!==e&&(r.childLanes|=e),t===n)break;t=t.return}}function mU(t,e){eae=t,$Oe=aU=null,t=t.dependencies,t!==null&&t.firstContext!==null&&((t.lanes&e)!==0&&(im=!0),t.firstContext=null)}function Iy(t){var e=t._currentValue;if($Oe!==t)if(t={context:t,memoizedValue:e,next:null},aU===null){if(eae===null)throw Error(dt(308));aU=t,eae.dependencies={lanes:0,firstContext:t}}else aU=aU.next=t;return e}var yN=null;function UOe(t){yN===null?yN=[t]:yN.push(t)}function cyt(t,e,n,r){var o=e.interleaved;return o===null?(n.next=n,UOe(e)):(n.next=o.next,o.next=n),e.interleaved=n,JC(t,r)}function JC(t,e){t.lanes|=e;var n=t.alternate;for(n!==null&&(n.lanes|=e),n=t,t=t.return;t!==null;)t.childLanes|=e,n=t.alternate,n!==null&&(n.childLanes|=e),n=t,t=t.return;return n.tag===3?n.stateNode:null}var UT=!1;function jOe(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function uyt(t,e){t=t.updateQueue,e.updateQueue===t&&(e.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,effects:t.effects})}function GC(t,e){return{eventTime:t,lane:e,tag:0,payload:null,callback:null,next:null}}function GT(t,e,n){var r=t.updateQueue;if(r===null)return null;if(r=r.shared,(Qo&2)!==0){var o=r.pending;return o===null?e.next=e:(e.next=o.next,o.next=e),r.pending=e,JC(t,n)}return o=r.interleaved,o===null?(e.next=e,UOe(r)):(e.next=o.next,o.next=e),r.interleaved=e,JC(t,n)}function Nse(t,e,n){if(e=e.updateQueue,e!==null&&(e=e.shared,(n&4194240)!==0)){var r=e.lanes;r&=t.pendingLanes,n|=r,e.lanes=n,kOe(t,n)}}function Fht(t,e){var n=t.updateQueue,r=t.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var o=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var s={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?o=i=s:i=i.next=s,n=n.next}while(n!==null);i===null?o=i=e:i=i.next=e}else o=i=e;n={baseState:r.baseState,firstBaseUpdate:o,lastBaseUpdate:i,shared:r.shared,effects:r.effects},t.updateQueue=n;return}t=n.lastBaseUpdate,t===null?n.firstBaseUpdate=e:t.next=e,n.lastBaseUpdate=e}function tae(t,e,n,r){var o=t.updateQueue;UT=!1;var i=o.firstBaseUpdate,s=o.lastBaseUpdate,a=o.shared.pending;if(a!==null){o.shared.pending=null;var l=a,c=l.next;l.next=null,s===null?i=c:s.next=c,s=l;var u=t.alternate;u!==null&&(u=u.updateQueue,a=u.lastBaseUpdate,a!==s&&(a===null?u.firstBaseUpdate=c:a.next=c,u.lastBaseUpdate=l))}if(i!==null){var d=o.baseState;s=0,u=c=l=null,a=i;do{var f=a.lane,p=a.eventTime;if((r&f)===f){u!==null&&(u=u.next={eventTime:p,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var m=t,h=a;switch(f=e,p=n,h.tag){case 1:if(m=h.payload,typeof m=="function"){d=m.call(p,d,f);break e}d=m;break e;case 3:m.flags=m.flags&-65537|128;case 0:if(m=h.payload,f=typeof m=="function"?m.call(p,d,f):m,f==null)break e;d=Ta({},d,f);break e;case 2:UT=!0}}a.callback!==null&&a.lane!==0&&(t.flags|=64,f=o.effects,f===null?o.effects=[a]:f.push(a))}else p={eventTime:p,lane:f,tag:a.tag,payload:a.payload,callback:a.callback,next:null},u===null?(c=u=p,l=d):u=u.next=p,s|=f;if(a=a.next,a===null){if(a=o.shared.pending,a===null)break;f=a,a=f.next,f.next=null,o.lastBaseUpdate=f,o.shared.pending=null}}while(!0);if(u===null&&(l=d),o.baseState=l,o.firstBaseUpdate=c,o.lastBaseUpdate=u,e=o.shared.interleaved,e!==null){o=e;do s|=o.lane,o=o.next;while(o!==e)}else i===null&&(o.shared.lanes=0);CN|=s,t.lanes=s,t.memoizedState=d}}function Uht(t,e,n){if(t=e.effects,e.effects=null,t!==null)for(e=0;e<t.length;e++){var r=t[e],o=r.callback;if(o!==null){if(r.callback=null,r=n,typeof o!="function")throw Error(dt(191,o));o.call(r)}}}var dyt=new cgt.Component().refs;function tOe(t,e,n,r){e=t.memoizedState,n=n(r,e),n=n==null?e:Ta({},e,n),t.memoizedState=n,t.lanes===0&&(t.updateQueue.baseState=n)}var gae={isMounted:function(t){return(t=t._reactInternals)?TN(t)===t:!1},enqueueSetState:function(t,e,n){t=t._reactInternals;var r=tp(),o=YT(t),i=GC(r,o);i.payload=e,n!=null&&(i.callback=n),e=GT(t,i,o),e!==null&&(Lw(e,t,o,r),Nse(e,t,o))},enqueueReplaceState:function(t,e,n){t=t._reactInternals;var r=tp(),o=YT(t),i=GC(r,o);i.tag=1,i.payload=e,n!=null&&(i.callback=n),e=GT(t,i,o),e!==null&&(Lw(e,t,o,r),Nse(e,t,o))},enqueueForceUpdate:function(t,e){t=t._reactInternals;var n=tp(),r=YT(t),o=GC(n,r);o.tag=2,e!=null&&(o.callback=e),e=GT(t,o,r),e!==null&&(Lw(e,t,r,n),Nse(e,t,r))}};function jht(t,e,n,r,o,i,s){return t=t.stateNode,typeof t.shouldComponentUpdate=="function"?t.shouldComponentUpdate(r,i,s):e.prototype&&e.prototype.isPureReactComponent?!g9(n,r)||!g9(o,i):!0}function fyt(t,e,n){var r=!1,o=QT,i=e.contextType;return typeof i=="object"&&i!==null?i=Iy(i):(o=am(e)?_N:Qd.current,r=e.contextTypes,i=(r=r!=null)?yU(t,o):QT),e=new e(n,i),t.memoizedState=e.state!==null&&e.state!==void 0?e.state:null,e.updater=gae,t.stateNode=e,e._reactInternals=t,r&&(t=t.stateNode,t.__reactInternalMemoizedUnmaskedChildContext=o,t.__reactInternalMemoizedMaskedChildContext=i),e}function Bht(t,e,n,r){t=e.state,typeof e.componentWillReceiveProps=="function"&&e.componentWillReceiveProps(n,r),typeof e.UNSAFE_componentWillReceiveProps=="function"&&e.UNSAFE_componentWillReceiveProps(n,r),e.state!==t&&gae.enqueueReplaceState(e,e.state,null)}function nOe(t,e,n,r){var o=t.stateNode;o.props=n,o.state=t.memoizedState,o.refs=dyt,jOe(t);var i=e.contextType;typeof i=="object"&&i!==null?o.context=Iy(i):(i=am(e)?_N:Qd.current,o.context=yU(t,i)),o.state=t.memoizedState,i=e.getDerivedStateFromProps,typeof i=="function"&&(tOe(t,e,i,n),o.state=t.memoizedState),typeof e.getDerivedStateFromProps=="function"||typeof o.getSnapshotBeforeUpdate=="function"||typeof o.UNSAFE_componentWillMount!="function"&&typeof o.componentWillMount!="function"||(e=o.state,typeof o.componentWillMount=="function"&&o.componentWillMount(),typeof o.UNSAFE_componentWillMount=="function"&&o.UNSAFE_componentWillMount(),e!==o.state&&gae.enqueueReplaceState(o,o.state,null),tae(t,n,o,r),o.state=t.memoizedState),typeof o.componentDidMount=="function"&&(t.flags|=4194308)}function qG(t,e,n){if(t=n.ref,t!==null&&typeof t!="function"&&typeof t!="object"){if(n._owner){if(n=n._owner,n){if(n.tag!==1)throw Error(dt(309));var r=n.stateNode}if(!r)throw Error(dt(147,t));var o=r,i=""+t;return e!==null&&e.ref!==null&&typeof e.ref=="function"&&e.ref._stringRef===i?e.ref:(e=function(s){var a=o.refs;a===dyt&&(a=o.refs={}),s===null?delete a[i]:a[i]=s},e._stringRef=i,e)}if(typeof t!="string")throw Error(dt(284));if(!n._owner)throw Error(dt(290,t))}return t}function Ise(t,e){throw t=Object.prototype.toString.call(e),Error(dt(31,t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t))}function zht(t){var e=t._init;return e(t._payload)}function pyt(t){function e(v,y){if(t){var w=v.deletions;w===null?(v.deletions=[y],v.flags|=16):w.push(y)}}function n(v,y){if(!t)return null;for(;y!==null;)e(v,y),y=y.sibling;return null}function r(v,y){for(v=new Map;y!==null;)y.key!==null?v.set(y.key,y):v.set(y.index,y),y=y.sibling;return v}function o(v,y){return v=JT(v,y),v.index=0,v.sibling=null,v}function i(v,y,w){return v.index=w,t?(w=v.alternate,w!==null?(w=w.index,w<y?(v.flags|=2,y):w):(v.flags|=2,y)):(v.flags|=1048576,y)}function s(v){return t&&v.alternate===null&&(v.flags|=2),v}function a(v,y,w,_){return y===null||y.tag!==6?(y=SMe(w,v.mode,_),y.return=v,y):(y=o(y,w),y.return=v,y)}function l(v,y,w,_){var S=w.type;return S===Q2?u(v,y,w.props.children,_,w.key):y!==null&&(y.elementType===S||typeof S=="object"&&S!==null&&S.$$typeof===FT&&zht(S)===y.type)?(_=o(y,w.props),_.ref=qG(v,y,w),_.return=v,_):(_=Use(w.type,w.key,w.props,null,v.mode,_),_.ref=qG(v,y,w),_.return=v,_)}function c(v,y,w,_){return y===null||y.tag!==4||y.stateNode.containerInfo!==w.containerInfo||y.stateNode.implementation!==w.implementation?(y=CMe(w,v.mode,_),y.return=v,y):(y=o(y,w.children||[]),y.return=v,y)}function u(v,y,w,_,S){return y===null||y.tag!==7?(y=bN(w,v.mode,_,S),y.return=v,y):(y=o(y,w),y.return=v,y)}function d(v,y,w){if(typeof y=="string"&&y!==""||typeof y=="number")return y=SMe(""+y,v.mode,w),y.return=v,y;if(typeof y=="object"&&y!==null){switch(y.$$typeof){case dse:return w=Use(y.type,y.key,y.props,null,v.mode,w),w.ref=qG(v,null,y),w.return=v,w;case X2:return y=CMe(y,v.mode,w),y.return=v,y;case FT:var _=y._init;return d(v,_(y._payload),w)}if(JG(y)||zG(y))return y=bN(y,v.mode,w,null),y.return=v,y;Ise(v,y)}return null}function f(v,y,w,_){var S=y!==null?y.key:null;if(typeof w=="string"&&w!==""||typeof w=="number")return S!==null?null:a(v,y,""+w,_);if(typeof w=="object"&&w!==null){switch(w.$$typeof){case dse:return w.key===S?l(v,y,w,_):null;case X2:return w.key===S?c(v,y,w,_):null;case FT:return S=w._init,f(v,y,S(w._payload),_)}if(JG(w)||zG(w))return S!==null?null:u(v,y,w,_,null);Ise(v,w)}return null}function p(v,y,w,_,S){if(typeof _=="string"&&_!==""||typeof _=="number")return v=v.get(w)||null,a(y,v,""+_,S);if(typeof _=="object"&&_!==null){switch(_.$$typeof){case dse:return v=v.get(_.key===null?w:_.key)||null,l(y,v,_,S);case X2:return v=v.get(_.key===null?w:_.key)||null,c(y,v,_,S);case FT:var I=_._init;return p(v,y,w,I(_._payload),S)}if(JG(_)||zG(_))return v=v.get(w)||null,u(y,v,_,S,null);Ise(y,_)}return null}function m(v,y,w,_){for(var S=null,I=null,C=y,k=y=0,T=null;C!==null&&k<w.length;k++){C.index>k?(T=C,C=null):T=C.sibling;var P=f(v,C,w[k],_);if(P===null){C===null&&(C=T);break}t&&C&&P.alternate===null&&e(v,C),y=i(P,y,k),I===null?S=P:I.sibling=P,I=P,C=T}if(k===w.length)return n(v,C),ua&&mN(v,k),S;if(C===null){for(;k<w.length;k++)C=d(v,w[k],_),C!==null&&(y=i(C,y,k),I===null?S=C:I.sibling=C,I=C);return ua&&mN(v,k),S}for(C=r(v,C);k<w.length;k++)T=p(C,v,k,w[k],_),T!==null&&(t&&T.alternate!==null&&C.delete(T.key===null?k:T.key),y=i(T,y,k),I===null?S=T:I.sibling=T,I=T);return t&&C.forEach(function(E){return e(v,E)}),ua&&mN(v,k),S}function h(v,y,w,_){var S=zG(w);if(typeof S!="function")throw Error(dt(150));if(w=S.call(w),w==null)throw Error(dt(151));for(var I=S=null,C=y,k=y=0,T=null,P=w.next();C!==null&&!P.done;k++,P=w.next()){C.index>k?(T=C,C=null):T=C.sibling;var E=f(v,C,P.value,_);if(E===null){C===null&&(C=T);break}t&&C&&E.alternate===null&&e(v,C),y=i(E,y,k),I===null?S=E:I.sibling=E,I=E,C=T}if(P.done)return n(v,C),ua&&mN(v,k),S;if(C===null){for(;!P.done;k++,P=w.next())P=d(v,P.value,_),P!==null&&(y=i(P,y,k),I===null?S=P:I.sibling=P,I=P);return ua&&mN(v,k),S}for(C=r(v,C);!P.done;k++,P=w.next())P=p(C,v,k,P.value,_),P!==null&&(t&&P.alternate!==null&&C.delete(P.key===null?k:P.key),y=i(P,y,k),I===null?S=P:I.sibling=P,I=P);return t&&C.forEach(function(O){return e(v,O)}),ua&&mN(v,k),S}function g(v,y,w,_){if(typeof w=="object"&&w!==null&&w.type===Q2&&w.key===null&&(w=w.props.children),typeof w=="object"&&w!==null){switch(w.$$typeof){case dse:e:{for(var S=w.key,I=y;I!==null;){if(I.key===S){if(S=w.type,S===Q2){if(I.tag===7){n(v,I.sibling),y=o(I,w.props.children),y.return=v,v=y;break e}}else if(I.elementType===S||typeof S=="object"&&S!==null&&S.$$typeof===FT&&zht(S)===I.type){n(v,I.sibling),y=o(I,w.props),y.ref=qG(v,I,w),y.return=v,v=y;break e}n(v,I);break}else e(v,I);I=I.sibling}w.type===Q2?(y=bN(w.props.children,v.mode,_,w.key),y.return=v,v=y):(_=Use(w.type,w.key,w.props,null,v.mode,_),_.ref=qG(v,y,w),_.return=v,v=_)}return s(v);case X2:e:{for(I=w.key;y!==null;){if(y.key===I)if(y.tag===4&&y.stateNode.containerInfo===w.containerInfo&&y.stateNode.implementation===w.implementation){n(v,y.sibling),y=o(y,w.children||[]),y.return=v,v=y;break e}else{n(v,y);break}else e(v,y);y=y.sibling}y=CMe(w,v.mode,_),y.return=v,v=y}return s(v);case FT:return I=w._init,g(v,y,I(w._payload),_)}if(JG(w))return m(v,y,w,_);if(zG(w))return h(v,y,w,_);Ise(v,w)}return typeof w=="string"&&w!==""||typeof w=="number"?(w=""+w,y!==null&&y.tag===6?(n(v,y.sibling),y=o(y,w),y.return=v,v=y):(n(v,y),y=SMe(w,v.mode,_),y.return=v,v=y),s(v)):n(v,y)}return g}var wU=pyt(!0),myt=pyt(!1),A9={},X_=tP(A9),b9=tP(A9),_9=tP(A9);function vN(t){if(t===A9)throw Error(dt(174));return t}function BOe(t,e){switch(As(_9,e),As(b9,t),As(X_,A9),t=e.nodeType,t){case 9:case 11:e=(e=e.documentElement)?e.namespaceURI:RMe(null,"");break;default:t=t===8?e.parentNode:e,e=t.namespaceURI||null,t=t.tagName,e=RMe(e,t)}Ws(X_),As(X_,e)}function bU(){Ws(X_),Ws(b9),Ws(_9)}function hyt(t){vN(_9.current);var e=vN(X_.current),n=RMe(e,t.type);e!==n&&(As(b9,t),As(X_,n))}function zOe(t){b9.current===t&&(Ws(X_),Ws(b9))}var ka=tP(0);function nae(t){for(var e=t;e!==null;){if(e.tag===13){var n=e.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||n.data==="$!"))return e}else if(e.tag===19&&e.memoizedProps.revealOrder!==void 0){if((e.flags&128)!==0)return e}else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break;for(;e.sibling===null;){if(e.return===null||e.return===t)return null;e=e.return}e.sibling.return=e.return,e=e.sibling}return null}var yMe=[];function HOe(){for(var t=0;t<yMe.length;t++)yMe[t]._workInProgressVersionPrimary=null;yMe.length=0}var Rse=QC.ReactCurrentDispatcher,vMe=QC.ReactCurrentBatchConfig,SN=0,Ia=null,gc=null,ku=null,rae=!1,i9=!1,x9=0,_Nn=0;function Yd(){throw Error(dt(321))}function WOe(t,e){if(e===null)return!1;for(var n=0;n<e.length&&n<t.length;n++)if(!$w(t[n],e[n]))return!1;return!0}function VOe(t,e,n,r,o,i){if(SN=i,Ia=e,e.memoizedState=null,e.updateQueue=null,e.lanes=0,Rse.current=t===null||t.memoizedState===null?kNn:INn,t=n(r,o),i9){i=0;do{if(i9=!1,x9=0,25<=i)throw Error(dt(301));i+=1,ku=gc=null,e.updateQueue=null,Rse.current=TNn,t=n(r,o)}while(i9)}if(Rse.current=oae,e=gc!==null&&gc.next!==null,SN=0,ku=gc=Ia=null,rae=!1,e)throw Error(dt(300));return t}function qOe(){var t=x9!==0;return x9=0,t}function Z_(){var t={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return ku===null?Ia.memoizedState=ku=t:ku=ku.next=t,ku}function Ty(){if(gc===null){var t=Ia.alternate;t=t!==null?t.memoizedState:null}else t=gc.next;var e=ku===null?Ia.memoizedState:ku.next;if(e!==null)ku=e,gc=t;else{if(t===null)throw Error(dt(310));gc=t,t={memoizedState:gc.memoizedState,baseState:gc.baseState,baseQueue:gc.baseQueue,queue:gc.queue,next:null},ku===null?Ia.memoizedState=ku=t:ku=ku.next=t}return ku}function S9(t,e){return typeof e=="function"?e(t):e}function wMe(t){var e=Ty(),n=e.queue;if(n===null)throw Error(dt(311));n.lastRenderedReducer=t;var r=gc,o=r.baseQueue,i=n.pending;if(i!==null){if(o!==null){var s=o.next;o.next=i.next,i.next=s}r.baseQueue=o=i,n.pending=null}if(o!==null){i=o.next,r=r.baseState;var a=s=null,l=null,c=i;do{var u=c.lane;if((SN&u)===u)l!==null&&(l=l.next={lane:0,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null}),r=c.hasEagerState?c.eagerState:t(r,c.action);else{var d={lane:u,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null};l===null?(a=l=d,s=r):l=l.next=d,Ia.lanes|=u,CN|=u}c=c.next}while(c!==null&&c!==i);l===null?s=r:l.next=a,$w(r,e.memoizedState)||(im=!0),e.memoizedState=r,e.baseState=s,e.baseQueue=l,n.lastRenderedState=r}if(t=n.interleaved,t!==null){o=t;do i=o.lane,Ia.lanes|=i,CN|=i,o=o.next;while(o!==t)}else o===null&&(n.lanes=0);return[e.memoizedState,n.dispatch]}function bMe(t){var e=Ty(),n=e.queue;if(n===null)throw Error(dt(311));n.lastRenderedReducer=t;var r=n.dispatch,o=n.pending,i=e.memoizedState;if(o!==null){n.pending=null;var s=o=o.next;do i=t(i,s.action),s=s.next;while(s!==o);$w(i,e.memoizedState)||(im=!0),e.memoizedState=i,e.baseQueue===null&&(e.baseState=i),n.lastRenderedState=i}return[i,r]}function gyt(){}function yyt(t,e){var n=Ia,r=Ty(),o=e(),i=!$w(r.memoizedState,o);if(i&&(r.memoizedState=o,im=!0),r=r.queue,KOe(byt.bind(null,n,r,t),[t]),r.getSnapshot!==e||i||ku!==null&&ku.memoizedState.tag&1){if(n.flags|=2048,C9(9,wyt.bind(null,n,r,o,e),void 0,null),Iu===null)throw Error(dt(349));(SN&30)!==0||vyt(n,e,o)}return o}function vyt(t,e,n){t.flags|=16384,t={getSnapshot:e,value:n},e=Ia.updateQueue,e===null?(e={lastEffect:null,stores:null},Ia.updateQueue=e,e.stores=[t]):(n=e.stores,n===null?e.stores=[t]:n.push(t))}function wyt(t,e,n,r){e.value=n,e.getSnapshot=r,_yt(e)&&xyt(t)}function byt(t,e,n){return n(function(){_yt(e)&&xyt(t)})}function _yt(t){var e=t.getSnapshot;t=t.value;try{var n=e();return!$w(t,n)}catch{return!0}}function xyt(t){var e=JC(t,1);e!==null&&Lw(e,t,1,-1)}function Hht(t){var e=Z_();return typeof t=="function"&&(t=t()),e.memoizedState=e.baseState=t,t={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:S9,lastRenderedState:t},e.queue=t,t=t.dispatch=CNn.bind(null,Ia,t),[e.memoizedState,t]}function C9(t,e,n,r){return t={tag:t,create:e,destroy:n,deps:r,next:null},e=Ia.updateQueue,e===null?(e={lastEffect:null,stores:null},Ia.updateQueue=e,e.lastEffect=t.next=t):(n=e.lastEffect,n===null?e.lastEffect=t.next=t:(r=n.next,n.next=t,t.next=r,e.lastEffect=t)),t}function Syt(){return Ty().memoizedState}function Lse(t,e,n,r){var o=Z_();Ia.flags|=t,o.memoizedState=C9(1|e,n,void 0,r===void 0?null:r)}function yae(t,e,n,r){var o=Ty();r=r===void 0?null:r;var i=void 0;if(gc!==null){var s=gc.memoizedState;if(i=s.destroy,r!==null&&WOe(r,s.deps)){o.memoizedState=C9(e,n,i,r);return}}Ia.flags|=t,o.memoizedState=C9(1|e,n,i,r)}function Wht(t,e){return Lse(8390656,8,t,e)}function KOe(t,e){return yae(2048,8,t,e)}function Cyt(t,e){return yae(4,2,t,e)}function kyt(t,e){return yae(4,4,t,e)}function Iyt(t,e){if(typeof e=="function")return t=t(),e(t),function(){e(null)};if(e!=null)return t=t(),e.current=t,function(){e.current=null}}function Tyt(t,e,n){return n=n!=null?n.concat([t]):null,yae(4,4,Iyt.bind(null,e,t),n)}function GOe(){}function Pyt(t,e){var n=Ty();e=e===void 0?null:e;var r=n.memoizedState;return r!==null&&e!==null&&WOe(e,r[1])?r[0]:(n.memoizedState=[t,e],t)}function Ayt(t,e){var n=Ty();e=e===void 0?null:e;var r=n.memoizedState;return r!==null&&e!==null&&WOe(e,r[1])?r[0]:(t=t(),n.memoizedState=[t,e],t)}function Eyt(t,e,n){return(SN&21)===0?(t.baseState&&(t.baseState=!1,im=!0),t.memoizedState=n):($w(n,e)||(n=Ngt(),Ia.lanes|=n,CN|=n,t.baseState=!0),e)}function xNn(t,e){var n=qi;qi=n!==0&&4>n?n:4,t(!0);var r=vMe.transition;vMe.transition={};try{t(!1),e()}finally{qi=n,vMe.transition=r}}function Myt(){return Ty().memoizedState}function SNn(t,e,n){var r=YT(t);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Oyt(t))Nyt(e,n);else if(n=cyt(t,e,n,r),n!==null){var o=tp();Lw(n,t,r,o),Ryt(n,e,r)}}function CNn(t,e,n){var r=YT(t),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Oyt(t))Nyt(e,o);else{var i=t.alternate;if(t.lanes===0&&(i===null||i.lanes===0)&&(i=e.lastRenderedReducer,i!==null))try{var s=e.lastRenderedState,a=i(s,n);if(o.hasEagerState=!0,o.eagerState=a,$w(a,s)){var l=e.interleaved;l===null?(o.next=o,UOe(e)):(o.next=l.next,l.next=o),e.interleaved=o;return}}catch{}finally{}n=cyt(t,e,o,r),n!==null&&(o=tp(),Lw(n,t,r,o),Ryt(n,e,r))}}function Oyt(t){var e=t.alternate;return t===Ia||e!==null&&e===Ia}function Nyt(t,e){i9=rae=!0;var n=t.pending;n===null?e.next=e:(e.next=n.next,n.next=e),t.pending=e}function Ryt(t,e,n){if((n&4194240)!==0){var r=e.lanes;r&=t.pendingLanes,n|=r,e.lanes=n,kOe(t,n)}}var oae={readContext:Iy,useCallback:Yd,useContext:Yd,useEffect:Yd,useImperativeHandle:Yd,useInsertionEffect:Yd,useLayoutEffect:Yd,useMemo:Yd,useReducer:Yd,useRef:Yd,useState:Yd,useDebugValue:Yd,useDeferredValue:Yd,useTransition:Yd,useMutableSource:Yd,useSyncExternalStore:Yd,useId:Yd,unstable_isNewReconciler:!1},kNn={readContext:Iy,useCallback:function(t,e){return Z_().memoizedState=[t,e===void 0?null:e],t},useContext:Iy,useEffect:Wht,useImperativeHandle:function(t,e,n){return n=n!=null?n.concat([t]):null,Lse(4194308,4,Iyt.bind(null,e,t),n)},useLayoutEffect:function(t,e){return Lse(4194308,4,t,e)},useInsertionEffect:function(t,e){return Lse(4,2,t,e)},useMemo:function(t,e){var n=Z_();return e=e===void 0?null:e,t=t(),n.memoizedState=[t,e],t},useReducer:function(t,e,n){var r=Z_();return e=n!==void 0?n(e):e,r.memoizedState=r.baseState=e,t={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:e},r.queue=t,t=t.dispatch=SNn.bind(null,Ia,t),[r.memoizedState,t]},useRef:function(t){var e=Z_();return t={current:t},e.memoizedState=t},useState:Hht,useDebugValue:GOe,useDeferredValue:function(t){return Z_().memoizedState=t},useTransition:function(){var t=Hht(!1),e=t[0];return t=xNn.bind(null,t[1]),Z_().memoizedState=t,[e,t]},useMutableSource:function(){},useSyncExternalStore:function(t,e,n){var r=Ia,o=Z_();if(ua){if(n===void 0)throw Error(dt(407));n=n()}else{if(n=e(),Iu===null)throw Error(dt(349));(SN&30)!==0||vyt(r,e,n)}o.memoizedState=n;var i={value:n,getSnapshot:e};return o.queue=i,Wht(byt.bind(null,r,i,t),[t]),r.flags|=2048,C9(9,wyt.bind(null,r,i,n,e),void 0,null),n},useId:function(){var t=Z_(),e=Iu.identifierPrefix;if(ua){var n=KC,r=qC;n=(r&~(1<<32-Rw(r)-1)).toString(32)+n,e=":"+e+"R"+n,n=x9++,0<n&&(e+="H"+n.toString(32)),e+=":"}else n=_Nn++,e=":"+e+"r"+n.toString(32)+":";return t.memoizedState=e},unstable_isNewReconciler:!1},INn={readContext:Iy,useCallback:Pyt,useContext:Iy,useEffect:KOe,useImperativeHandle:Tyt,useInsertionEffect:Cyt,useLayoutEffect:kyt,useMemo:Ayt,useReducer:wMe,useRef:Syt,useState:function(){return wMe(S9)},useDebugValue:GOe,useDeferredValue:function(t){var e=Ty();return Eyt(e,gc.memoizedState,t)},useTransition:function(){var t=wMe(S9)[0],e=Ty().memoizedState;return[t,e]},useMutableSource:gyt,useSyncExternalStore:yyt,useId:Myt,unstable_isNewReconciler:!1},TNn={readContext:Iy,useCallback:Pyt,useContext:Iy,useEffect:KOe,useImperativeHandle:Tyt,useInsertionEffect:Cyt,useLayoutEffect:kyt,useMemo:Ayt,useReducer:bMe,useRef:Syt,useState:function(){return bMe(S9)},useDebugValue:GOe,useDeferredValue:function(t){var e=Ty();return gc===null?e.memoizedState=t:Eyt(e,gc.memoizedState,t)},useTransition:function(){var t=bMe(S9)[0],e=Ty().memoizedState;return[t,e]},useMutableSource:gyt,useSyncExternalStore:yyt,useId:Myt,unstable_isNewReconciler:!1};function _U(t,e){try{var n="",r=e;do n+=rOn(r),r=r.return;while(r);var o=n}catch(i){o=`
Error generating stack: `+i.message+`
`+i.stack}return{value:t,source:e,stack:o,digest:null}}function _Me(t,e,n){return{value:t,source:null,stack:n??null,digest:e??null}}function rOe(t,e){try{console.error(e.value)}catch(n){setTimeout(function(){throw n})}}var PNn=typeof WeakMap=="function"?WeakMap:Map;function Lyt(t,e,n){n=GC(-1,n),n.tag=3,n.payload={element:null};var r=e.value;return n.callback=function(){sae||(sae=!0,pOe=r),rOe(t,e)},n}function $yt(t,e,n){n=GC(-1,n),n.tag=3;var r=t.type.getDerivedStateFromError;if(typeof r=="function"){var o=e.value;n.payload=function(){return r(o)},n.callback=function(){rOe(t,e)}}var i=t.stateNode;return i!==null&&typeof i.componentDidCatch=="function"&&(n.callback=function(){rOe(t,e),typeof r!="function"&&(ZT===null?ZT=new Set([this]):ZT.add(this));var s=e.stack;this.componentDidCatch(e.value,{componentStack:s!==null?s:""})}),n}function Vht(t,e,n){var r=t.pingCache;if(r===null){r=t.pingCache=new PNn;var o=new Set;r.set(e,o)}else o=r.get(e),o===void 0&&(o=new Set,r.set(e,o));o.has(n)||(o.add(n),t=zNn.bind(null,t,e,n),e.then(t,t))}function qht(t){do{var e;if((e=t.tag===13)&&(e=t.memoizedState,e=e!==null?e.dehydrated!==null:!0),e)return t;t=t.return}while(t!==null);return null}function Kht(t,e,n,r,o){return(t.mode&1)===0?(t===e?t.flags|=65536:(t.flags|=128,n.flags|=131072,n.flags&=-52805,n.tag===1&&(n.alternate===null?n.tag=17:(e=GC(-1,1),e.tag=2,GT(n,e,1))),n.lanes|=1),t):(t.flags|=65536,t.lanes=o,t)}var ANn=QC.ReactCurrentOwner,im=!1;function ep(t,e,n,r){e.child=t===null?myt(e,null,n,r):wU(e,t.child,n,r)}function Ght(t,e,n,r,o){n=n.render;var i=e.ref;return mU(e,o),r=VOe(t,e,n,r,i,o),n=qOe(),t!==null&&!im?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,XC(t,e,o)):(ua&&n&&NOe(e),e.flags|=1,ep(t,e,r,o),e.child)}function Zht(t,e,n,r,o){if(t===null){var i=n.type;return typeof i=="function"&&!nNe(i)&&i.defaultProps===void 0&&n.compare===null&&n.defaultProps===void 0?(e.tag=15,e.type=i,Dyt(t,e,i,r,o)):(t=Use(n.type,null,r,e,e.mode,o),t.ref=e.ref,t.return=e,e.child=t)}if(i=t.child,(t.lanes&o)===0){var s=i.memoizedProps;if(n=n.compare,n=n!==null?n:g9,n(s,r)&&t.ref===e.ref)return XC(t,e,o)}return e.flags|=1,t=JT(i,r),t.ref=e.ref,t.return=e,e.child=t}function Dyt(t,e,n,r,o){if(t!==null){var i=t.memoizedProps;if(g9(i,r)&&t.ref===e.ref)if(im=!1,e.pendingProps=r=i,(t.lanes&o)!==0)(t.flags&131072)!==0&&(im=!0);else return e.lanes=t.lanes,XC(t,e,o)}return oOe(t,e,n,r,o)}function Fyt(t,e,n){var r=e.pendingProps,o=r.children,i=t!==null?t.memoizedState:null;if(r.mode==="hidden")if((e.mode&1)===0)e.memoizedState={baseLanes:0,cachePool:null,transitions:null},As(cU,Th),Th|=n;else{if((n&1073741824)===0)return t=i!==null?i.baseLanes|n:n,e.lanes=e.childLanes=1073741824,e.memoizedState={baseLanes:t,cachePool:null,transitions:null},e.updateQueue=null,As(cU,Th),Th|=t,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=i!==null?i.baseLanes:n,As(cU,Th),Th|=r}else i!==null?(r=i.baseLanes|n,e.memoizedState=null):r=n,As(cU,Th),Th|=r;return ep(t,e,o,n),e.child}function Uyt(t,e){var n=e.ref;(t===null&&n!==null||t!==null&&t.ref!==n)&&(e.flags|=512,e.flags|=2097152)}function oOe(t,e,n,r,o){var i=am(n)?_N:Qd.current;return i=yU(e,i),mU(e,o),n=VOe(t,e,n,r,i,o),r=qOe(),t!==null&&!im?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,XC(t,e,o)):(ua&&r&&NOe(e),e.flags|=1,ep(t,e,n,o),e.child)}function Yht(t,e,n,r,o){if(am(n)){var i=!0;Yse(e)}else i=!1;if(mU(e,o),e.stateNode===null)$se(t,e),fyt(e,n,r),nOe(e,n,r,o),r=!0;else if(t===null){var s=e.stateNode,a=e.memoizedProps;s.props=a;var l=s.context,c=n.contextType;typeof c=="object"&&c!==null?c=Iy(c):(c=am(n)?_N:Qd.current,c=yU(e,c));var u=n.getDerivedStateFromProps,d=typeof u=="function"||typeof s.getSnapshotBeforeUpdate=="function";d||typeof s.UNSAFE_componentWillReceiveProps!="function"&&typeof s.componentWillReceiveProps!="function"||(a!==r||l!==c)&&Bht(e,s,r,c),UT=!1;var f=e.memoizedState;s.state=f,tae(e,r,s,o),l=e.memoizedState,a!==r||f!==l||sm.current||UT?(typeof u=="function"&&(tOe(e,n,u,r),l=e.memoizedState),(a=UT||jht(e,n,a,r,f,l,c))?(d||typeof s.UNSAFE_componentWillMount!="function"&&typeof s.componentWillMount!="function"||(typeof s.componentWillMount=="function"&&s.componentWillMount(),typeof s.UNSAFE_componentWillMount=="function"&&s.UNSAFE_componentWillMount()),typeof s.componentDidMount=="function"&&(e.flags|=4194308)):(typeof s.componentDidMount=="function"&&(e.flags|=4194308),e.memoizedProps=r,e.memoizedState=l),s.props=r,s.state=l,s.context=c,r=a):(typeof s.componentDidMount=="function"&&(e.flags|=4194308),r=!1)}else{s=e.stateNode,uyt(t,e),a=e.memoizedProps,c=e.type===e.elementType?a:Mw(e.type,a),s.props=c,d=e.pendingProps,f=s.context,l=n.contextType,typeof l=="object"&&l!==null?l=Iy(l):(l=am(n)?_N:Qd.current,l=yU(e,l));var p=n.getDerivedStateFromProps;(u=typeof p=="function"||typeof s.getSnapshotBeforeUpdate=="function")||typeof s.UNSAFE_componentWillReceiveProps!="function"&&typeof s.componentWillReceiveProps!="function"||(a!==d||f!==l)&&Bht(e,s,r,l),UT=!1,f=e.memoizedState,s.state=f,tae(e,r,s,o);var m=e.memoizedState;a!==d||f!==m||sm.current||UT?(typeof p=="function"&&(tOe(e,n,p,r),m=e.memoizedState),(c=UT||jht(e,n,c,r,f,m,l)||!1)?(u||typeof s.UNSAFE_componentWillUpdate!="function"&&typeof s.componentWillUpdate!="function"||(typeof s.componentWillUpdate=="function"&&s.componentWillUpdate(r,m,l),typeof s.UNSAFE_componentWillUpdate=="function"&&s.UNSAFE_componentWillUpdate(r,m,l)),typeof s.componentDidUpdate=="function"&&(e.flags|=4),typeof s.getSnapshotBeforeUpdate=="function"&&(e.flags|=1024)):(typeof s.componentDidUpdate!="function"||a===t.memoizedProps&&f===t.memoizedState||(e.flags|=4),typeof s.getSnapshotBeforeUpdate!="function"||a===t.memoizedProps&&f===t.memoizedState||(e.flags|=1024),e.memoizedProps=r,e.memoizedState=m),s.props=r,s.state=m,s.context=l,r=c):(typeof s.componentDidUpdate!="function"||a===t.memoizedProps&&f===t.memoizedState||(e.flags|=4),typeof s.getSnapshotBeforeUpdate!="function"||a===t.memoizedProps&&f===t.memoizedState||(e.flags|=1024),r=!1)}return iOe(t,e,n,r,i,o)}function iOe(t,e,n,r,o,i){Uyt(t,e);var s=(e.flags&128)!==0;if(!r&&!s)return o&&Lht(e,n,!1),XC(t,e,i);r=e.stateNode,ANn.current=e;var a=s&&typeof n.getDerivedStateFromError!="function"?null:r.render();return e.flags|=1,t!==null&&s?(e.child=wU(e,t.child,null,i),e.child=wU(e,null,a,i)):ep(t,e,a,i),e.memoizedState=r.state,o&&Lht(e,n,!0),e.child}function jyt(t){var e=t.stateNode;e.pendingContext?Rht(t,e.pendingContext,e.pendingContext!==e.context):e.context&&Rht(t,e.context,!1),BOe(t,e.containerInfo)}function Jht(t,e,n,r,o){return vU(),LOe(o),e.flags|=256,ep(t,e,n,r),e.child}var sOe={dehydrated:null,treeContext:null,retryLane:0};function aOe(t){return{baseLanes:t,cachePool:null,transitions:null}}function Byt(t,e,n){var r=e.pendingProps,o=ka.current,i=!1,s=(e.flags&128)!==0,a;if((a=s)||(a=t!==null&&t.memoizedState===null?!1:(o&2)!==0),a?(i=!0,e.flags&=-129):(t===null||t.memoizedState!==null)&&(o|=1),As(ka,o&1),t===null)return QMe(e),t=e.memoizedState,t!==null&&(t=t.dehydrated,t!==null)?((e.mode&1)===0?e.lanes=1:t.data==="$!"?e.lanes=8:e.lanes=1073741824,null):(s=r.children,t=r.fallback,i?(r=e.mode,i=e.child,s={mode:"hidden",children:s},(r&1)===0&&i!==null?(i.childLanes=0,i.pendingProps=s):i=bae(s,r,0,null),t=bN(t,r,n,null),i.return=e,t.return=e,i.sibling=t,e.child=i,e.child.memoizedState=aOe(n),e.memoizedState=sOe,t):ZOe(e,s));if(o=t.memoizedState,o!==null&&(a=o.dehydrated,a!==null))return ENn(t,e,s,r,a,o,n);if(i){i=r.fallback,s=e.mode,o=t.child,a=o.sibling;var l={mode:"hidden",children:r.children};return(s&1)===0&&e.child!==o?(r=e.child,r.childLanes=0,r.pendingProps=l,e.deletions=null):(r=JT(o,l),r.subtreeFlags=o.subtreeFlags&14680064),a!==null?i=JT(a,i):(i=bN(i,s,n,null),i.flags|=2),i.return=e,r.return=e,r.sibling=i,e.child=r,r=i,i=e.child,s=t.child.memoizedState,s=s===null?aOe(n):{baseLanes:s.baseLanes|n,cachePool:null,transitions:s.transitions},i.memoizedState=s,i.childLanes=t.childLanes&~n,e.memoizedState=sOe,r}return i=t.child,t=i.sibling,r=JT(i,{mode:"visible",children:r.children}),(e.mode&1)===0&&(r.lanes=n),r.return=e,r.sibling=null,t!==null&&(n=e.deletions,n===null?(e.deletions=[t],e.flags|=16):n.push(t)),e.child=r,e.memoizedState=null,r}function ZOe(t,e){return e=bae({mode:"visible",children:e},t.mode,0,null),e.return=t,t.child=e}function Tse(t,e,n,r){return r!==null&&LOe(r),wU(e,t.child,null,n),t=ZOe(e,e.pendingProps.children),t.flags|=2,e.memoizedState=null,t}function ENn(t,e,n,r,o,i,s){if(n)return e.flags&256?(e.flags&=-257,r=_Me(Error(dt(422))),Tse(t,e,s,r)):e.memoizedState!==null?(e.child=t.child,e.flags|=128,null):(i=r.fallback,o=e.mode,r=bae({mode:"visible",children:r.children},o,0,null),i=bN(i,o,s,null),i.flags|=2,r.return=e,i.return=e,r.sibling=i,e.child=r,(e.mode&1)!==0&&wU(e,t.child,null,s),e.child.memoizedState=aOe(s),e.memoizedState=sOe,i);if((e.mode&1)===0)return Tse(t,e,s,null);if(o.data==="$!"){if(r=o.nextSibling&&o.nextSibling.dataset,r)var a=r.dgst;return r=a,i=Error(dt(419)),r=_Me(i,r,void 0),Tse(t,e,s,r)}if(a=(s&t.childLanes)!==0,im||a){if(r=Iu,r!==null){switch(s&-s){case 4:o=2;break;case 16:o=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:o=32;break;case 536870912:o=268435456;break;default:o=0}o=(o&(r.suspendedLanes|s))!==0?0:o,o!==0&&o!==i.retryLane&&(i.retryLane=o,JC(t,o),Lw(r,t,o,-1))}return tNe(),r=_Me(Error(dt(421))),Tse(t,e,s,r)}return o.data==="$?"?(e.flags|=128,e.child=t.child,e=HNn.bind(null,t),o._reactRetry=e,null):(t=i.treeContext,Ph=KT(o.nextSibling),Ah=e,ua=!0,Nw=null,t!==null&&(xy[Sy++]=qC,xy[Sy++]=KC,xy[Sy++]=xN,qC=t.id,KC=t.overflow,xN=e),e=ZOe(e,r.children),e.flags|=4096,e)}function Xht(t,e,n){t.lanes|=e;var r=t.alternate;r!==null&&(r.lanes|=e),eOe(t.return,e,n)}function xMe(t,e,n,r,o){var i=t.memoizedState;i===null?t.memoizedState={isBackwards:e,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:o}:(i.isBackwards=e,i.rendering=null,i.renderingStartTime=0,i.last=r,i.tail=n,i.tailMode=o)}function zyt(t,e,n){var r=e.pendingProps,o=r.revealOrder,i=r.tail;if(ep(t,e,r.children,n),r=ka.current,(r&2)!==0)r=r&1|2,e.flags|=128;else{if(t!==null&&(t.flags&128)!==0)e:for(t=e.child;t!==null;){if(t.tag===13)t.memoizedState!==null&&Xht(t,n,e);else if(t.tag===19)Xht(t,n,e);else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break e;for(;t.sibling===null;){if(t.return===null||t.return===e)break e;t=t.return}t.sibling.return=t.return,t=t.sibling}r&=1}if(As(ka,r),(e.mode&1)===0)e.memoizedState=null;else switch(o){case"forwards":for(n=e.child,o=null;n!==null;)t=n.alternate,t!==null&&nae(t)===null&&(o=n),n=n.sibling;n=o,n===null?(o=e.child,e.child=null):(o=n.sibling,n.sibling=null),xMe(e,!1,o,n,i);break;case"backwards":for(n=null,o=e.child,e.child=null;o!==null;){if(t=o.alternate,t!==null&&nae(t)===null){e.child=o;break}t=o.sibling,o.sibling=n,n=o,o=t}xMe(e,!0,n,null,i);break;case"together":xMe(e,!1,null,null,void 0);break;default:e.memoizedState=null}return e.child}function $se(t,e){(e.mode&1)===0&&t!==null&&(t.alternate=null,e.alternate=null,e.flags|=2)}function XC(t,e,n){if(t!==null&&(e.dependencies=t.dependencies),CN|=e.lanes,(n&e.childLanes)===0)return null;if(t!==null&&e.child!==t.child)throw Error(dt(153));if(e.child!==null){for(t=e.child,n=JT(t,t.pendingProps),e.child=n,n.return=e;t.sibling!==null;)t=t.sibling,n=n.sibling=JT(t,t.pendingProps),n.return=e;n.sibling=null}return e.child}function MNn(t,e,n){switch(e.tag){case 3:jyt(e),vU();break;case 5:hyt(e);break;case 1:am(e.type)&&Yse(e);break;case 4:BOe(e,e.stateNode.containerInfo);break;case 10:var r=e.type._context,o=e.memoizedProps.value;As(Qse,r._currentValue),r._currentValue=o;break;case 13:if(r=e.memoizedState,r!==null)return r.dehydrated!==null?(As(ka,ka.current&1),e.flags|=128,null):(n&e.child.childLanes)!==0?Byt(t,e,n):(As(ka,ka.current&1),t=XC(t,e,n),t!==null?t.sibling:null);As(ka,ka.current&1);break;case 19:if(r=(n&e.childLanes)!==0,(t.flags&128)!==0){if(r)return zyt(t,e,n);e.flags|=128}if(o=e.memoizedState,o!==null&&(o.rendering=null,o.tail=null,o.lastEffect=null),As(ka,ka.current),r)break;return null;case 22:case 23:return e.lanes=0,Fyt(t,e,n)}return XC(t,e,n)}var Hyt,lOe,Wyt,Vyt;Hyt=function(t,e){for(var n=e.child;n!==null;){if(n.tag===5||n.tag===6)t.appendChild(n.stateNode);else if(n.tag!==4&&n.child!==null){n.child.return=n,n=n.child;continue}if(n===e)break;for(;n.sibling===null;){if(n.return===null||n.return===e)return;n=n.return}n.sibling.return=n.return,n=n.sibling}};lOe=function(){};Wyt=function(t,e,n,r){var o=t.memoizedProps;if(o!==r){t=e.stateNode,vN(X_.current);var i=null;switch(n){case"input":o=EMe(t,o),r=EMe(t,r),i=[];break;case"select":o=Ta({},o,{value:void 0}),r=Ta({},r,{value:void 0}),i=[];break;case"textarea":o=NMe(t,o),r=NMe(t,r),i=[];break;default:typeof o.onClick!="function"&&typeof r.onClick=="function"&&(t.onclick=Gse)}LMe(n,r);var s;n=null;for(c in o)if(!r.hasOwnProperty(c)&&o.hasOwnProperty(c)&&o[c]!=null)if(c==="style"){var a=o[c];for(s in a)a.hasOwnProperty(s)&&(n||(n={}),n[s]="")}else c!=="dangerouslySetInnerHTML"&&c!=="children"&&c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&c!=="autoFocus"&&(c9.hasOwnProperty(c)?i||(i=[]):(i=i||[]).push(c,null));for(c in r){var l=r[c];if(a=o?.[c],r.hasOwnProperty(c)&&l!==a&&(l!=null||a!=null))if(c==="style")if(a){for(s in a)!a.hasOwnProperty(s)||l&&l.hasOwnProperty(s)||(n||(n={}),n[s]="");for(s in l)l.hasOwnProperty(s)&&a[s]!==l[s]&&(n||(n={}),n[s]=l[s])}else n||(i||(i=[]),i.push(c,n)),n=l;else c==="dangerouslySetInnerHTML"?(l=l?l.__html:void 0,a=a?a.__html:void 0,l!=null&&a!==l&&(i=i||[]).push(c,l)):c==="children"?typeof l!="string"&&typeof l!="number"||(i=i||[]).push(c,""+l):c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&(c9.hasOwnProperty(c)?(l!=null&&c==="onScroll"&&Hs("scroll",t),i||a===l||(i=[])):(i=i||[]).push(c,l))}n&&(i=i||[]).push("style",n);var c=i;(e.updateQueue=c)&&(e.flags|=4)}};Vyt=function(t,e,n,r){n!==r&&(e.flags|=4)};function KG(t,e){if(!ua)switch(t.tailMode){case"hidden":e=t.tail;for(var n=null;e!==null;)e.alternate!==null&&(n=e),e=e.sibling;n===null?t.tail=null:n.sibling=null;break;case"collapsed":n=t.tail;for(var r=null;n!==null;)n.alternate!==null&&(r=n),n=n.sibling;r===null?e||t.tail===null?t.tail=null:t.tail.sibling=null:r.sibling=null}}function Jd(t){var e=t.alternate!==null&&t.alternate.child===t.child,n=0,r=0;if(e)for(var o=t.child;o!==null;)n|=o.lanes|o.childLanes,r|=o.subtreeFlags&14680064,r|=o.flags&14680064,o.return=t,o=o.sibling;else for(o=t.child;o!==null;)n|=o.lanes|o.childLanes,r|=o.subtreeFlags,r|=o.flags,o.return=t,o=o.sibling;return t.subtreeFlags|=r,t.childLanes=n,e}function ONn(t,e,n){var r=e.pendingProps;switch(ROe(e),e.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Jd(e),null;case 1:return am(e.type)&&Zse(),Jd(e),null;case 3:return r=e.stateNode,bU(),Ws(sm),Ws(Qd),HOe(),r.pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),(t===null||t.child===null)&&(kse(e)?e.flags|=4:t===null||t.memoizedState.isDehydrated&&(e.flags&256)===0||(e.flags|=1024,Nw!==null&&(gOe(Nw),Nw=null))),lOe(t,e),Jd(e),null;case 5:zOe(e);var o=vN(_9.current);if(n=e.type,t!==null&&e.stateNode!=null)Wyt(t,e,n,r,o),t.ref!==e.ref&&(e.flags|=512,e.flags|=2097152);else{if(!r){if(e.stateNode===null)throw Error(dt(166));return Jd(e),null}if(t=vN(X_.current),kse(e)){r=e.stateNode,n=e.type;var i=e.memoizedProps;switch(r[Y_]=e,r[w9]=i,t=(e.mode&1)!==0,n){case"dialog":Hs("cancel",r),Hs("close",r);break;case"iframe":case"object":case"embed":Hs("load",r);break;case"video":case"audio":for(o=0;o<QG.length;o++)Hs(QG[o],r);break;case"source":Hs("error",r);break;case"img":case"image":case"link":Hs("error",r),Hs("load",r);break;case"details":Hs("toggle",r);break;case"input":sht(r,i),Hs("invalid",r);break;case"select":r._wrapperState={wasMultiple:!!i.multiple},Hs("invalid",r);break;case"textarea":lht(r,i),Hs("invalid",r)}LMe(n,i),o=null;for(var s in i)if(i.hasOwnProperty(s)){var a=i[s];s==="children"?typeof a=="string"?r.textContent!==a&&(i.suppressHydrationWarning!==!0&&Cse(r.textContent,a,t),o=["children",a]):typeof a=="number"&&r.textContent!==""+a&&(i.suppressHydrationWarning!==!0&&Cse(r.textContent,a,t),o=["children",""+a]):c9.hasOwnProperty(s)&&a!=null&&s==="onScroll"&&Hs("scroll",r)}switch(n){case"input":fse(r),aht(r,i,!0);break;case"textarea":fse(r),cht(r);break;case"select":case"option":break;default:typeof i.onClick=="function"&&(r.onclick=Gse)}r=o,e.updateQueue=r,r!==null&&(e.flags|=4)}else{s=o.nodeType===9?o:o.ownerDocument,t==="http://www.w3.org/1999/xhtml"&&(t=vgt(n)),t==="http://www.w3.org/1999/xhtml"?n==="script"?(t=s.createElement("div"),t.innerHTML="<script><\/script>",t=t.removeChild(t.firstChild)):typeof r.is=="string"?t=s.createElement(n,{is:r.is}):(t=s.createElement(n),n==="select"&&(s=t,r.multiple?s.multiple=!0:r.size&&(s.size=r.size))):t=s.createElementNS(t,n),t[Y_]=e,t[w9]=r,Hyt(t,e,!1,!1),e.stateNode=t;e:{switch(s=$Me(n,r),n){case"dialog":Hs("cancel",t),Hs("close",t),o=r;break;case"iframe":case"object":case"embed":Hs("load",t),o=r;break;case"video":case"audio":for(o=0;o<QG.length;o++)Hs(QG[o],t);o=r;break;case"source":Hs("error",t),o=r;break;case"img":case"image":case"link":Hs("error",t),Hs("load",t),o=r;break;case"details":Hs("toggle",t),o=r;break;case"input":sht(t,r),o=EMe(t,r),Hs("invalid",t);break;case"option":o=r;break;case"select":t._wrapperState={wasMultiple:!!r.multiple},o=Ta({},r,{value:void 0}),Hs("invalid",t);break;case"textarea":lht(t,r),o=NMe(t,r),Hs("invalid",t);break;default:o=r}LMe(n,o),a=o;for(i in a)if(a.hasOwnProperty(i)){var l=a[i];i==="style"?_gt(t,l):i==="dangerouslySetInnerHTML"?(l=l?l.__html:void 0,l!=null&&wgt(t,l)):i==="children"?typeof l=="string"?(n!=="textarea"||l!=="")&&u9(t,l):typeof l=="number"&&u9(t,""+l):i!=="suppressContentEditableWarning"&&i!=="suppressHydrationWarning"&&i!=="autoFocus"&&(c9.hasOwnProperty(i)?l!=null&&i==="onScroll"&&Hs("scroll",t):l!=null&&wOe(t,i,l,s))}switch(n){case"input":fse(t),aht(t,r,!1);break;case"textarea":fse(t),cht(t);break;case"option":r.value!=null&&t.setAttribute("value",""+XT(r.value));break;case"select":t.multiple=!!r.multiple,i=r.value,i!=null?uU(t,!!r.multiple,i,!1):r.defaultValue!=null&&uU(t,!!r.multiple,r.defaultValue,!0);break;default:typeof o.onClick=="function"&&(t.onclick=Gse)}switch(n){case"button":case"input":case"select":case"textarea":r=!!r.autoFocus;break e;case"img":r=!0;break e;default:r=!1}}r&&(e.flags|=4)}e.ref!==null&&(e.flags|=512,e.flags|=2097152)}return Jd(e),null;case 6:if(t&&e.stateNode!=null)Vyt(t,e,t.memoizedProps,r);else{if(typeof r!="string"&&e.stateNode===null)throw Error(dt(166));if(n=vN(_9.current),vN(X_.current),kse(e)){if(r=e.stateNode,n=e.memoizedProps,r[Y_]=e,(i=r.nodeValue!==n)&&(t=Ah,t!==null))switch(t.tag){case 3:Cse(r.nodeValue,n,(t.mode&1)!==0);break;case 5:t.memoizedProps.suppressHydrationWarning!==!0&&Cse(r.nodeValue,n,(t.mode&1)!==0)}i&&(e.flags|=4)}else r=(n.nodeType===9?n:n.ownerDocument).createTextNode(r),r[Y_]=e,e.stateNode=r}return Jd(e),null;case 13:if(Ws(ka),r=e.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(ua&&Ph!==null&&(e.mode&1)!==0&&(e.flags&128)===0)lyt(),vU(),e.flags|=98560,i=!1;else if(i=kse(e),r!==null&&r.dehydrated!==null){if(t===null){if(!i)throw Error(dt(318));if(i=e.memoizedState,i=i!==null?i.dehydrated:null,!i)throw Error(dt(317));i[Y_]=e}else vU(),(e.flags&128)===0&&(e.memoizedState=null),e.flags|=4;Jd(e),i=!1}else Nw!==null&&(gOe(Nw),Nw=null),i=!0;if(!i)return e.flags&65536?e:null}return(e.flags&128)!==0?(e.lanes=n,e):(r=r!==null,r!==(t!==null&&t.memoizedState!==null)&&r&&(e.child.flags|=8192,(e.mode&1)!==0&&(t===null||(ka.current&1)!==0?yc===0&&(yc=3):tNe())),e.updateQueue!==null&&(e.flags|=4),Jd(e),null);case 4:return bU(),lOe(t,e),t===null&&y9(e.stateNode.containerInfo),Jd(e),null;case 10:return FOe(e.type._context),Jd(e),null;case 17:return am(e.type)&&Zse(),Jd(e),null;case 19:if(Ws(ka),i=e.memoizedState,i===null)return Jd(e),null;if(r=(e.flags&128)!==0,s=i.rendering,s===null)if(r)KG(i,!1);else{if(yc!==0||t!==null&&(t.flags&128)!==0)for(t=e.child;t!==null;){if(s=nae(t),s!==null){for(e.flags|=128,KG(i,!1),r=s.updateQueue,r!==null&&(e.updateQueue=r,e.flags|=4),e.subtreeFlags=0,r=n,n=e.child;n!==null;)i=n,t=r,i.flags&=14680066,s=i.alternate,s===null?(i.childLanes=0,i.lanes=t,i.child=null,i.subtreeFlags=0,i.memoizedProps=null,i.memoizedState=null,i.updateQueue=null,i.dependencies=null,i.stateNode=null):(i.childLanes=s.childLanes,i.lanes=s.lanes,i.child=s.child,i.subtreeFlags=0,i.deletions=null,i.memoizedProps=s.memoizedProps,i.memoizedState=s.memoizedState,i.updateQueue=s.updateQueue,i.type=s.type,t=s.dependencies,i.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext}),n=n.sibling;return As(ka,ka.current&1|2),e.child}t=t.sibling}i.tail!==null&&ml()>xU&&(e.flags|=128,r=!0,KG(i,!1),e.lanes=4194304)}else{if(!r)if(t=nae(s),t!==null){if(e.flags|=128,r=!0,n=t.updateQueue,n!==null&&(e.updateQueue=n,e.flags|=4),KG(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!ua)return Jd(e),null}else 2*ml()-i.renderingStartTime>xU&&n!==1073741824&&(e.flags|=128,r=!0,KG(i,!1),e.lanes=4194304);i.isBackwards?(s.sibling=e.child,e.child=s):(n=i.last,n!==null?n.sibling=s:e.child=s,i.last=s)}return i.tail!==null?(e=i.tail,i.rendering=e,i.tail=e.sibling,i.renderingStartTime=ml(),e.sibling=null,n=ka.current,As(ka,r?n&1|2:n&1),e):(Jd(e),null);case 22:case 23:return eNe(),r=e.memoizedState!==null,t!==null&&t.memoizedState!==null!==r&&(e.flags|=8192),r&&(e.mode&1)!==0?(Th&1073741824)!==0&&(Jd(e),e.subtreeFlags&6&&(e.flags|=8192)):Jd(e),null;case 24:return null;case 25:return null}throw Error(dt(156,e.tag))}function NNn(t,e){switch(ROe(e),e.tag){case 1:return am(e.type)&&Zse(),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return bU(),Ws(sm),Ws(Qd),HOe(),t=e.flags,(t&65536)!==0&&(t&128)===0?(e.flags=t&-65537|128,e):null;case 5:return zOe(e),null;case 13:if(Ws(ka),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(dt(340));vU()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return Ws(ka),null;case 4:return bU(),null;case 10:return FOe(e.type._context),null;case 22:case 23:return eNe(),null;case 24:return null;default:return null}}var Pse=!1,Xd=!1,RNn=typeof WeakSet=="function"?WeakSet:Set,en=null;function lU(t,e){var n=t.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){za(t,e,r)}else n.current=null}function cOe(t,e,n){try{n()}catch(r){za(t,e,r)}}var Qht=!1;function LNn(t,e){if(qMe=Vse,t=Zgt(),OOe(t)){if("selectionStart"in t)var n={start:t.selectionStart,end:t.selectionEnd};else e:{n=(n=t.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var o=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var s=0,a=-1,l=-1,c=0,u=0,d=t,f=null;t:for(;;){for(var p;d!==n||o!==0&&d.nodeType!==3||(a=s+o),d!==i||r!==0&&d.nodeType!==3||(l=s+r),d.nodeType===3&&(s+=d.nodeValue.length),(p=d.firstChild)!==null;)f=d,d=p;for(;;){if(d===t)break t;if(f===n&&++c===o&&(a=s),f===i&&++u===r&&(l=s),(p=d.nextSibling)!==null)break;d=f,f=d.parentNode}d=p}n=a===-1||l===-1?null:{start:a,end:l}}else n=null}n=n||{start:0,end:0}}else n=null;for(KMe={focusedElem:t,selectionRange:n},Vse=!1,en=e;en!==null;)if(e=en,t=e.child,(e.subtreeFlags&1028)!==0&&t!==null)t.return=e,en=t;else for(;en!==null;){e=en;try{var m=e.alternate;if((e.flags&1024)!==0)switch(e.tag){case 0:case 11:case 15:break;case 1:if(m!==null){var h=m.memoizedProps,g=m.memoizedState,v=e.stateNode,y=v.getSnapshotBeforeUpdate(e.elementType===e.type?h:Mw(e.type,h),g);v.__reactInternalSnapshotBeforeUpdate=y}break;case 3:var w=e.stateNode.containerInfo;w.nodeType===1?w.textContent="":w.nodeType===9&&w.documentElement&&w.removeChild(w.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(dt(163))}}catch(_){za(e,e.return,_)}if(t=e.sibling,t!==null){t.return=e.return,en=t;break}en=e.return}return m=Qht,Qht=!1,m}function s9(t,e,n){var r=e.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&t)===t){var i=o.destroy;o.destroy=void 0,i!==void 0&&cOe(e,n,i)}o=o.next}while(o!==r)}}function vae(t,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var n=e=e.next;do{if((n.tag&t)===t){var r=n.create;n.destroy=r()}n=n.next}while(n!==e)}}function uOe(t){var e=t.ref;if(e!==null){var n=t.stateNode;switch(t.tag){case 5:t=n;break;default:t=n}typeof e=="function"?e(t):e.current=t}}function qyt(t){var e=t.alternate;e!==null&&(t.alternate=null,qyt(e)),t.child=null,t.deletions=null,t.sibling=null,t.tag===5&&(e=t.stateNode,e!==null&&(delete e[Y_],delete e[w9],delete e[YMe],delete e[yNn],delete e[vNn])),t.stateNode=null,t.return=null,t.dependencies=null,t.memoizedProps=null,t.memoizedState=null,t.pendingProps=null,t.stateNode=null,t.updateQueue=null}function Kyt(t){return t.tag===5||t.tag===3||t.tag===4}function egt(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||Kyt(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function dOe(t,e,n){var r=t.tag;if(r===5||r===6)t=t.stateNode,e?n.nodeType===8?n.parentNode.insertBefore(t,e):n.insertBefore(t,e):(n.nodeType===8?(e=n.parentNode,e.insertBefore(t,n)):(e=n,e.appendChild(t)),n=n._reactRootContainer,n!=null||e.onclick!==null||(e.onclick=Gse));else if(r!==4&&(t=t.child,t!==null))for(dOe(t,e,n),t=t.sibling;t!==null;)dOe(t,e,n),t=t.sibling}function fOe(t,e,n){var r=t.tag;if(r===5||r===6)t=t.stateNode,e?n.insertBefore(t,e):n.appendChild(t);else if(r!==4&&(t=t.child,t!==null))for(fOe(t,e,n),t=t.sibling;t!==null;)fOe(t,e,n),t=t.sibling}var cd=null,Ow=!1;function DT(t,e,n){for(n=n.child;n!==null;)Gyt(t,e,n),n=n.sibling}function Gyt(t,e,n){if(J_&&typeof J_.onCommitFiberUnmount=="function")try{J_.onCommitFiberUnmount(uae,n)}catch{}switch(n.tag){case 5:Xd||lU(n,e);case 6:var r=cd,o=Ow;cd=null,DT(t,e,n),cd=r,Ow=o,cd!==null&&(Ow?(t=cd,n=n.stateNode,t.nodeType===8?t.parentNode.removeChild(n):t.removeChild(n)):cd.removeChild(n.stateNode));break;case 18:cd!==null&&(Ow?(t=cd,n=n.stateNode,t.nodeType===8?hMe(t.parentNode,n):t.nodeType===1&&hMe(t,n),m9(t)):hMe(cd,n.stateNode));break;case 4:r=cd,o=Ow,cd=n.stateNode.containerInfo,Ow=!0,DT(t,e,n),cd=r,Ow=o;break;case 0:case 11:case 14:case 15:if(!Xd&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){o=r=r.next;do{var i=o,s=i.destroy;i=i.tag,s!==void 0&&((i&2)!==0||(i&4)!==0)&&cOe(n,e,s),o=o.next}while(o!==r)}DT(t,e,n);break;case 1:if(!Xd&&(lU(n,e),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(a){za(n,e,a)}DT(t,e,n);break;case 21:DT(t,e,n);break;case 22:n.mode&1?(Xd=(r=Xd)||n.memoizedState!==null,DT(t,e,n),Xd=r):DT(t,e,n);break;default:DT(t,e,n)}}function tgt(t){var e=t.updateQueue;if(e!==null){t.updateQueue=null;var n=t.stateNode;n===null&&(n=t.stateNode=new RNn),e.forEach(function(r){var o=WNn.bind(null,t,r);n.has(r)||(n.add(r),r.then(o,o))})}}function Ew(t,e){var n=e.deletions;if(n!==null)for(var r=0;r<n.length;r++){var o=n[r];try{var i=t,s=e,a=s;e:for(;a!==null;){switch(a.tag){case 5:cd=a.stateNode,Ow=!1;break e;case 3:cd=a.stateNode.containerInfo,Ow=!0;break e;case 4:cd=a.stateNode.containerInfo,Ow=!0;break e}a=a.return}if(cd===null)throw Error(dt(160));Gyt(i,s,o),cd=null,Ow=!1;var l=o.alternate;l!==null&&(l.return=null),o.return=null}catch(c){za(o,e,c)}}if(e.subtreeFlags&12854)for(e=e.child;e!==null;)Zyt(e,t),e=e.sibling}function Zyt(t,e){var n=t.alternate,r=t.flags;switch(t.tag){case 0:case 11:case 14:case 15:if(Ew(e,t),G_(t),r&4){try{s9(3,t,t.return),vae(3,t)}catch(h){za(t,t.return,h)}try{s9(5,t,t.return)}catch(h){za(t,t.return,h)}}break;case 1:Ew(e,t),G_(t),r&512&&n!==null&&lU(n,n.return);break;case 5:if(Ew(e,t),G_(t),r&512&&n!==null&&lU(n,n.return),t.flags&32){var o=t.stateNode;try{u9(o,"")}catch(h){za(t,t.return,h)}}if(r&4&&(o=t.stateNode,o!=null)){var i=t.memoizedProps,s=n!==null?n.memoizedProps:i,a=t.type,l=t.updateQueue;if(t.updateQueue=null,l!==null)try{a==="input"&&i.type==="radio"&&i.name!=null&&ggt(o,i),$Me(a,s);var c=$Me(a,i);for(s=0;s<l.length;s+=2){var u=l[s],d=l[s+1];u==="style"?_gt(o,d):u==="dangerouslySetInnerHTML"?wgt(o,d):u==="children"?u9(o,d):wOe(o,u,d,c)}switch(a){case"input":MMe(o,i);break;case"textarea":ygt(o,i);break;case"select":var f=o._wrapperState.wasMultiple;o._wrapperState.wasMultiple=!!i.multiple;var p=i.value;p!=null?uU(o,!!i.multiple,p,!1):f!==!!i.multiple&&(i.defaultValue!=null?uU(o,!!i.multiple,i.defaultValue,!0):uU(o,!!i.multiple,i.multiple?[]:"",!1))}o[w9]=i}catch(h){za(t,t.return,h)}}break;case 6:if(Ew(e,t),G_(t),r&4){if(t.stateNode===null)throw Error(dt(162));o=t.stateNode,i=t.memoizedProps;try{o.nodeValue=i}catch(h){za(t,t.return,h)}}break;case 3:if(Ew(e,t),G_(t),r&4&&n!==null&&n.memoizedState.isDehydrated)try{m9(e.containerInfo)}catch(h){za(t,t.return,h)}break;case 4:Ew(e,t),G_(t);break;case 13:Ew(e,t),G_(t),o=t.child,o.flags&8192&&(i=o.memoizedState!==null,o.stateNode.isHidden=i,!i||o.alternate!==null&&o.alternate.memoizedState!==null||(XOe=ml())),r&4&&tgt(t);break;case 22:if(u=n!==null&&n.memoizedState!==null,t.mode&1?(Xd=(c=Xd)||u,Ew(e,t),Xd=c):Ew(e,t),G_(t),r&8192){if(c=t.memoizedState!==null,(t.stateNode.isHidden=c)&&!u&&(t.mode&1)!==0)for(en=t,u=t.child;u!==null;){for(d=en=u;en!==null;){switch(f=en,p=f.child,f.tag){case 0:case 11:case 14:case 15:s9(4,f,f.return);break;case 1:lU(f,f.return);var m=f.stateNode;if(typeof m.componentWillUnmount=="function"){r=f,n=f.return;try{e=r,m.props=e.memoizedProps,m.state=e.memoizedState,m.componentWillUnmount()}catch(h){za(r,n,h)}}break;case 5:lU(f,f.return);break;case 22:if(f.memoizedState!==null){rgt(d);continue}}p!==null?(p.return=f,en=p):rgt(d)}u=u.sibling}e:for(u=null,d=t;;){if(d.tag===5){if(u===null){u=d;try{o=d.stateNode,c?(i=o.style,typeof i.setProperty=="function"?i.setProperty("display","none","important"):i.display="none"):(a=d.stateNode,l=d.memoizedProps.style,s=l!=null&&l.hasOwnProperty("display")?l.display:null,a.style.display=bgt("display",s))}catch(h){za(t,t.return,h)}}}else if(d.tag===6){if(u===null)try{d.stateNode.nodeValue=c?"":d.memoizedProps}catch(h){za(t,t.return,h)}}else if((d.tag!==22&&d.tag!==23||d.memoizedState===null||d===t)&&d.child!==null){d.child.return=d,d=d.child;continue}if(d===t)break e;for(;d.sibling===null;){if(d.return===null||d.return===t)break e;u===d&&(u=null),d=d.return}u===d&&(u=null),d.sibling.return=d.return,d=d.sibling}}break;case 19:Ew(e,t),G_(t),r&4&&tgt(t);break;case 21:break;default:Ew(e,t),G_(t)}}function G_(t){var e=t.flags;if(e&2){try{e:{for(var n=t.return;n!==null;){if(Kyt(n)){var r=n;break e}n=n.return}throw Error(dt(160))}switch(r.tag){case 5:var o=r.stateNode;r.flags&32&&(u9(o,""),r.flags&=-33);var i=egt(t);fOe(t,i,o);break;case 3:case 4:var s=r.stateNode.containerInfo,a=egt(t);dOe(t,a,s);break;default:throw Error(dt(161))}}catch(l){za(t,t.return,l)}t.flags&=-3}e&4096&&(t.flags&=-4097)}function $Nn(t,e,n){en=t,Yyt(t,e,n)}function Yyt(t,e,n){for(var r=(t.mode&1)!==0;en!==null;){var o=en,i=o.child;if(o.tag===22&&r){var s=o.memoizedState!==null||Pse;if(!s){var a=o.alternate,l=a!==null&&a.memoizedState!==null||Xd;a=Pse;var c=Xd;if(Pse=s,(Xd=l)&&!c)for(en=o;en!==null;)s=en,l=s.child,s.tag===22&&s.memoizedState!==null?ogt(o):l!==null?(l.return=s,en=l):ogt(o);for(;i!==null;)en=i,Yyt(i,e,n),i=i.sibling;en=o,Pse=a,Xd=c}ngt(t,e,n)}else(o.subtreeFlags&8772)!==0&&i!==null?(i.return=o,en=i):ngt(t,e,n)}}function ngt(t){for(;en!==null;){var e=en;if((e.flags&8772)!==0){var n=e.alternate;try{if((e.flags&8772)!==0)switch(e.tag){case 0:case 11:case 15:Xd||vae(5,e);break;case 1:var r=e.stateNode;if(e.flags&4&&!Xd)if(n===null)r.componentDidMount();else{var o=e.elementType===e.type?n.memoizedProps:Mw(e.type,n.memoizedProps);r.componentDidUpdate(o,n.memoizedState,r.__reactInternalSnapshotBeforeUpdate)}var i=e.updateQueue;i!==null&&Uht(e,i,r);break;case 3:var s=e.updateQueue;if(s!==null){if(n=null,e.child!==null)switch(e.child.tag){case 5:n=e.child.stateNode;break;case 1:n=e.child.stateNode}Uht(e,s,n)}break;case 5:var a=e.stateNode;if(n===null&&e.flags&4){n=a;var l=e.memoizedProps;switch(e.type){case"button":case"input":case"select":case"textarea":l.autoFocus&&n.focus();break;case"img":l.src&&(n.src=l.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(e.memoizedState===null){var c=e.alternate;if(c!==null){var u=c.memoizedState;if(u!==null){var d=u.dehydrated;d!==null&&m9(d)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(dt(163))}Xd||e.flags&512&&uOe(e)}catch(f){za(e,e.return,f)}}if(e===t){en=null;break}if(n=e.sibling,n!==null){n.return=e.return,en=n;break}en=e.return}}function rgt(t){for(;en!==null;){var e=en;if(e===t){en=null;break}var n=e.sibling;if(n!==null){n.return=e.return,en=n;break}en=e.return}}function ogt(t){for(;en!==null;){var e=en;try{switch(e.tag){case 0:case 11:case 15:var n=e.return;try{vae(4,e)}catch(l){za(e,n,l)}break;case 1:var r=e.stateNode;if(typeof r.componentDidMount=="function"){var o=e.return;try{r.componentDidMount()}catch(l){za(e,o,l)}}var i=e.return;try{uOe(e)}catch(l){za(e,i,l)}break;case 5:var s=e.return;try{uOe(e)}catch(l){za(e,s,l)}}}catch(l){za(e,e.return,l)}if(e===t){en=null;break}var a=e.sibling;if(a!==null){a.return=e.return,en=a;break}en=e.return}}var DNn=Math.ceil,iae=QC.ReactCurrentDispatcher,YOe=QC.ReactCurrentOwner,ky=QC.ReactCurrentBatchConfig,Qo=0,Iu=null,Ul=null,ud=0,Th=0,cU=tP(0),yc=0,k9=null,CN=0,wae=0,JOe=0,a9=null,om=null,XOe=0,xU=1/0,WC=null,sae=!1,pOe=null,ZT=null,Ase=!1,HT=null,aae=0,l9=0,mOe=null,Dse=-1,Fse=0;function tp(){return(Qo&6)!==0?ml():Dse!==-1?Dse:Dse=ml()}function YT(t){return(t.mode&1)===0?1:(Qo&2)!==0&&ud!==0?ud&-ud:bNn.transition!==null?(Fse===0&&(Fse=Ngt()),Fse):(t=qi,t!==0||(t=window.event,t=t===void 0?16:jgt(t.type)),t)}function Lw(t,e,n,r){if(50<l9)throw l9=0,mOe=null,Error(dt(185));I9(t,n,r),((Qo&2)===0||t!==Iu)&&(t===Iu&&((Qo&2)===0&&(wae|=n),yc===4&&BT(t,ud)),lm(t,r),n===1&&Qo===0&&(e.mode&1)===0&&(xU=ml()+500,hae&&nP()))}function lm(t,e){var n=t.callbackNode;xOn(t,e);var r=Wse(t,t===Iu?ud:0);if(r===0)n!==null&&fht(n),t.callbackNode=null,t.callbackPriority=0;else if(e=r&-r,t.callbackPriority!==e){if(n!=null&&fht(n),e===1)t.tag===0?wNn(igt.bind(null,t)):iyt(igt.bind(null,t)),hNn(function(){(Qo&6)===0&&nP()}),n=null;else{switch(Rgt(r)){case 1:n=COe;break;case 4:n=Mgt;break;case 16:n=Hse;break;case 536870912:n=Ogt;break;default:n=Hse}n=ovt(n,Jyt.bind(null,t))}t.callbackPriority=e,t.callbackNode=n}}function Jyt(t,e){if(Dse=-1,Fse=0,(Qo&6)!==0)throw Error(dt(327));var n=t.callbackNode;if(hU()&&t.callbackNode!==n)return null;var r=Wse(t,t===Iu?ud:0);if(r===0)return null;if((r&30)!==0||(r&t.expiredLanes)!==0||e)e=lae(t,r);else{e=r;var o=Qo;Qo|=2;var i=Qyt();(Iu!==t||ud!==e)&&(WC=null,xU=ml()+500,wN(t,e));do try{jNn();break}catch(a){Xyt(t,a)}while(!0);DOe(),iae.current=i,Qo=o,Ul!==null?e=0:(Iu=null,ud=0,e=yc)}if(e!==0){if(e===2&&(o=BMe(t),o!==0&&(r=o,e=hOe(t,o))),e===1)throw n=k9,wN(t,0),BT(t,r),lm(t,ml()),n;if(e===6)BT(t,r);else{if(o=t.current.alternate,(r&30)===0&&!FNn(o)&&(e=lae(t,r),e===2&&(i=BMe(t),i!==0&&(r=i,e=hOe(t,i))),e===1))throw n=k9,wN(t,0),BT(t,r),lm(t,ml()),n;switch(t.finishedWork=o,t.finishedLanes=r,e){case 0:case 1:throw Error(dt(345));case 2:hN(t,om,WC);break;case 3:if(BT(t,r),(r&130023424)===r&&(e=XOe+500-ml(),10<e)){if(Wse(t,0)!==0)break;if(o=t.suspendedLanes,(o&r)!==r){tp(),t.pingedLanes|=t.suspendedLanes&o;break}t.timeoutHandle=ZMe(hN.bind(null,t,om,WC),e);break}hN(t,om,WC);break;case 4:if(BT(t,r),(r&4194240)===r)break;for(e=t.eventTimes,o=-1;0<r;){var s=31-Rw(r);i=1<<s,s=e[s],s>o&&(o=s),r&=~i}if(r=o,r=ml()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*DNn(r/1960))-r,10<r){t.timeoutHandle=ZMe(hN.bind(null,t,om,WC),r);break}hN(t,om,WC);break;case 5:hN(t,om,WC);break;default:throw Error(dt(329))}}}return lm(t,ml()),t.callbackNode===n?Jyt.bind(null,t):null}function hOe(t,e){var n=a9;return t.current.memoizedState.isDehydrated&&(wN(t,e).flags|=256),t=lae(t,e),t!==2&&(e=om,om=n,e!==null&&gOe(e)),t}function gOe(t){om===null?om=t:om.push.apply(om,t)}function FNn(t){for(var e=t;;){if(e.flags&16384){var n=e.updateQueue;if(n!==null&&(n=n.stores,n!==null))for(var r=0;r<n.length;r++){var o=n[r],i=o.getSnapshot;o=o.value;try{if(!$w(i(),o))return!1}catch{return!1}}}if(n=e.child,e.subtreeFlags&16384&&n!==null)n.return=e,e=n;else{if(e===t)break;for(;e.sibling===null;){if(e.return===null||e.return===t)return!0;e=e.return}e.sibling.return=e.return,e=e.sibling}}return!0}function BT(t,e){for(e&=~JOe,e&=~wae,t.suspendedLanes|=e,t.pingedLanes&=~e,t=t.expirationTimes;0<e;){var n=31-Rw(e),r=1<<n;t[n]=-1,e&=~r}}function igt(t){if((Qo&6)!==0)throw Error(dt(327));hU();var e=Wse(t,0);if((e&1)===0)return lm(t,ml()),null;var n=lae(t,e);if(t.tag!==0&&n===2){var r=BMe(t);r!==0&&(e=r,n=hOe(t,r))}if(n===1)throw n=k9,wN(t,0),BT(t,e),lm(t,ml()),n;if(n===6)throw Error(dt(345));return t.finishedWork=t.current.alternate,t.finishedLanes=e,hN(t,om,WC),lm(t,ml()),null}function QOe(t,e){var n=Qo;Qo|=1;try{return t(e)}finally{Qo=n,Qo===0&&(xU=ml()+500,hae&&nP())}}function kN(t){HT!==null&&HT.tag===0&&(Qo&6)===0&&hU();var e=Qo;Qo|=1;var n=ky.transition,r=qi;try{if(ky.transition=null,qi=1,t)return t()}finally{qi=r,ky.transition=n,Qo=e,(Qo&6)===0&&nP()}}function eNe(){Th=cU.current,Ws(cU)}function wN(t,e){t.finishedWork=null,t.finishedLanes=0;var n=t.timeoutHandle;if(n!==-1&&(t.timeoutHandle=-1,mNn(n)),Ul!==null)for(n=Ul.return;n!==null;){var r=n;switch(ROe(r),r.tag){case 1:r=r.type.childContextTypes,r!=null&&Zse();break;case 3:bU(),Ws(sm),Ws(Qd),HOe();break;case 5:zOe(r);break;case 4:bU();break;case 13:Ws(ka);break;case 19:Ws(ka);break;case 10:FOe(r.type._context);break;case 22:case 23:eNe()}n=n.return}if(Iu=t,Ul=t=JT(t.current,null),ud=Th=e,yc=0,k9=null,JOe=wae=CN=0,om=a9=null,yN!==null){for(e=0;e<yN.length;e++)if(n=yN[e],r=n.interleaved,r!==null){n.interleaved=null;var o=r.next,i=n.pending;if(i!==null){var s=i.next;i.next=o,r.next=s}n.pending=r}yN=null}return t}function Xyt(t,e){do{var n=Ul;try{if(DOe(),Rse.current=oae,rae){for(var r=Ia.memoizedState;r!==null;){var o=r.queue;o!==null&&(o.pending=null),r=r.next}rae=!1}if(SN=0,ku=gc=Ia=null,i9=!1,x9=0,YOe.current=null,n===null||n.return===null){yc=1,k9=e,Ul=null;break}e:{var i=t,s=n.return,a=n,l=e;if(e=ud,a.flags|=32768,l!==null&&typeof l=="object"&&typeof l.then=="function"){var c=l,u=a,d=u.tag;if((u.mode&1)===0&&(d===0||d===11||d===15)){var f=u.alternate;f?(u.updateQueue=f.updateQueue,u.memoizedState=f.memoizedState,u.lanes=f.lanes):(u.updateQueue=null,u.memoizedState=null)}var p=qht(s);if(p!==null){p.flags&=-257,Kht(p,s,a,i,e),p.mode&1&&Vht(i,c,e),e=p,l=c;var m=e.updateQueue;if(m===null){var h=new Set;h.add(l),e.updateQueue=h}else m.add(l);break e}else{if((e&1)===0){Vht(i,c,e),tNe();break e}l=Error(dt(426))}}else if(ua&&a.mode&1){var g=qht(s);if(g!==null){(g.flags&65536)===0&&(g.flags|=256),Kht(g,s,a,i,e),LOe(_U(l,a));break e}}i=l=_U(l,a),yc!==4&&(yc=2),a9===null?a9=[i]:a9.push(i),i=s;do{switch(i.tag){case 3:i.flags|=65536,e&=-e,i.lanes|=e;var v=Lyt(i,l,e);Fht(i,v);break e;case 1:a=l;var y=i.type,w=i.stateNode;if((i.flags&128)===0&&(typeof y.getDerivedStateFromError=="function"||w!==null&&typeof w.componentDidCatch=="function"&&(ZT===null||!ZT.has(w)))){i.flags|=65536,e&=-e,i.lanes|=e;var _=$yt(i,a,e);Fht(i,_);break e}}i=i.return}while(i!==null)}tvt(n)}catch(S){e=S,Ul===n&&n!==null&&(Ul=n=n.return);continue}break}while(!0)}function Qyt(){var t=iae.current;return iae.current=oae,t===null?oae:t}function tNe(){(yc===0||yc===3||yc===2)&&(yc=4),Iu===null||(CN&268435455)===0&&(wae&268435455)===0||BT(Iu,ud)}function lae(t,e){var n=Qo;Qo|=2;var r=Qyt();(Iu!==t||ud!==e)&&(WC=null,wN(t,e));do try{UNn();break}catch(o){Xyt(t,o)}while(!0);if(DOe(),Qo=n,iae.current=r,Ul!==null)throw Error(dt(261));return Iu=null,ud=0,yc}function UNn(){for(;Ul!==null;)evt(Ul)}function jNn(){for(;Ul!==null&&!pOn();)evt(Ul)}function evt(t){var e=rvt(t.alternate,t,Th);t.memoizedProps=t.pendingProps,e===null?tvt(t):Ul=e,YOe.current=null}function tvt(t){var e=t;do{var n=e.alternate;if(t=e.return,(e.flags&32768)===0){if(n=ONn(n,e,Th),n!==null){Ul=n;return}}else{if(n=NNn(n,e),n!==null){n.flags&=32767,Ul=n;return}if(t!==null)t.flags|=32768,t.subtreeFlags=0,t.deletions=null;else{yc=6,Ul=null;return}}if(e=e.sibling,e!==null){Ul=e;return}Ul=e=t}while(e!==null);yc===0&&(yc=5)}function hN(t,e,n){var r=qi,o=ky.transition;try{ky.transition=null,qi=1,BNn(t,e,n,r)}finally{ky.transition=o,qi=r}return null}function BNn(t,e,n,r){do hU();while(HT!==null);if((Qo&6)!==0)throw Error(dt(327));n=t.finishedWork;var o=t.finishedLanes;if(n===null)return null;if(t.finishedWork=null,t.finishedLanes=0,n===t.current)throw Error(dt(177));t.callbackNode=null,t.callbackPriority=0;var i=n.lanes|n.childLanes;if(SOn(t,i),t===Iu&&(Ul=Iu=null,ud=0),(n.subtreeFlags&2064)===0&&(n.flags&2064)===0||Ase||(Ase=!0,ovt(Hse,function(){return hU(),null})),i=(n.flags&15990)!==0,(n.subtreeFlags&15990)!==0||i){i=ky.transition,ky.transition=null;var s=qi;qi=1;var a=Qo;Qo|=4,YOe.current=null,LNn(t,n),Zyt(n,t),cNn(KMe),Vse=!!qMe,KMe=qMe=null,t.current=n,$Nn(n,t,o),mOn(),Qo=a,qi=s,ky.transition=i}else t.current=n;if(Ase&&(Ase=!1,HT=t,aae=o),i=t.pendingLanes,i===0&&(ZT=null),yOn(n.stateNode,r),lm(t,ml()),e!==null)for(r=t.onRecoverableError,n=0;n<e.length;n++)o=e[n],r(o.value,{componentStack:o.stack,digest:o.digest});if(sae)throw sae=!1,t=pOe,pOe=null,t;return(aae&1)!==0&&t.tag!==0&&hU(),i=t.pendingLanes,(i&1)!==0?t===mOe?l9++:(l9=0,mOe=t):l9=0,nP(),null}function hU(){if(HT!==null){var t=Rgt(aae),e=ky.transition,n=qi;try{if(ky.transition=null,qi=16>t?16:t,HT===null)var r=!1;else{if(t=HT,HT=null,aae=0,(Qo&6)!==0)throw Error(dt(331));var o=Qo;for(Qo|=4,en=t.current;en!==null;){var i=en,s=i.child;if((en.flags&16)!==0){var a=i.deletions;if(a!==null){for(var l=0;l<a.length;l++){var c=a[l];for(en=c;en!==null;){var u=en;switch(u.tag){case 0:case 11:case 15:s9(8,u,i)}var d=u.child;if(d!==null)d.return=u,en=d;else for(;en!==null;){u=en;var f=u.sibling,p=u.return;if(qyt(u),u===c){en=null;break}if(f!==null){f.return=p,en=f;break}en=p}}}var m=i.alternate;if(m!==null){var h=m.child;if(h!==null){m.child=null;do{var g=h.sibling;h.sibling=null,h=g}while(h!==null)}}en=i}}if((i.subtreeFlags&2064)!==0&&s!==null)s.return=i,en=s;else e:for(;en!==null;){if(i=en,(i.flags&2048)!==0)switch(i.tag){case 0:case 11:case 15:s9(9,i,i.return)}var v=i.sibling;if(v!==null){v.return=i.return,en=v;break e}en=i.return}}var y=t.current;for(en=y;en!==null;){s=en;var w=s.child;if((s.subtreeFlags&2064)!==0&&w!==null)w.return=s,en=w;else e:for(s=y;en!==null;){if(a=en,(a.flags&2048)!==0)try{switch(a.tag){case 0:case 11:case 15:vae(9,a)}}catch(S){za(a,a.return,S)}if(a===s){en=null;break e}var _=a.sibling;if(_!==null){_.return=a.return,en=_;break e}en=a.return}}if(Qo=o,nP(),J_&&typeof J_.onPostCommitFiberRoot=="function")try{J_.onPostCommitFiberRoot(uae,t)}catch{}r=!0}return r}finally{qi=n,ky.transition=e}}return!1}function sgt(t,e,n){e=_U(n,e),e=Lyt(t,e,1),t=GT(t,e,1),e=tp(),t!==null&&(I9(t,1,e),lm(t,e))}function za(t,e,n){if(t.tag===3)sgt(t,t,n);else for(;e!==null;){if(e.tag===3){sgt(e,t,n);break}else if(e.tag===1){var r=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof r.componentDidCatch=="function"&&(ZT===null||!ZT.has(r))){t=_U(n,t),t=$yt(e,t,1),e=GT(e,t,1),t=tp(),e!==null&&(I9(e,1,t),lm(e,t));break}}e=e.return}}function zNn(t,e,n){var r=t.pingCache;r!==null&&r.delete(e),e=tp(),t.pingedLanes|=t.suspendedLanes&n,Iu===t&&(ud&n)===n&&(yc===4||yc===3&&(ud&130023424)===ud&&500>ml()-XOe?wN(t,0):JOe|=n),lm(t,e)}function nvt(t,e){e===0&&((t.mode&1)===0?e=1:(e=hse,hse<<=1,(hse&130023424)===0&&(hse=4194304)));var n=tp();t=JC(t,e),t!==null&&(I9(t,e,n),lm(t,n))}function HNn(t){var e=t.memoizedState,n=0;e!==null&&(n=e.retryLane),nvt(t,n)}function WNn(t,e){var n=0;switch(t.tag){case 13:var r=t.stateNode,o=t.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=t.stateNode;break;default:throw Error(dt(314))}r!==null&&r.delete(e),nvt(t,n)}var rvt;rvt=function(t,e,n){if(t!==null)if(t.memoizedProps!==e.pendingProps||sm.current)im=!0;else{if((t.lanes&n)===0&&(e.flags&128)===0)return im=!1,MNn(t,e,n);im=(t.flags&131072)!==0}else im=!1,ua&&(e.flags&1048576)!==0&&syt(e,Xse,e.index);switch(e.lanes=0,e.tag){case 2:var r=e.type;$se(t,e),t=e.pendingProps;var o=yU(e,Qd.current);mU(e,n),o=VOe(null,e,r,t,o,n);var i=qOe();return e.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(e.tag=1,e.memoizedState=null,e.updateQueue=null,am(r)?(i=!0,Yse(e)):i=!1,e.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,jOe(e),o.updater=gae,e.stateNode=o,o._reactInternals=e,nOe(e,r,t,n),e=iOe(null,e,r,!0,i,n)):(e.tag=0,ua&&i&&NOe(e),ep(null,e,o,n),e=e.child),e;case 16:r=e.elementType;e:{switch($se(t,e),t=e.pendingProps,o=r._init,r=o(r._payload),e.type=r,o=e.tag=qNn(r),t=Mw(r,t),o){case 0:e=oOe(null,e,r,t,n);break e;case 1:e=Yht(null,e,r,t,n);break e;case 11:e=Ght(null,e,r,t,n);break e;case 14:e=Zht(null,e,r,Mw(r.type,t),n);break e}throw Error(dt(306,r,""))}return e;case 0:return r=e.type,o=e.pendingProps,o=e.elementType===r?o:Mw(r,o),oOe(t,e,r,o,n);case 1:return r=e.type,o=e.pendingProps,o=e.elementType===r?o:Mw(r,o),Yht(t,e,r,o,n);case 3:e:{if(jyt(e),t===null)throw Error(dt(387));r=e.pendingProps,i=e.memoizedState,o=i.element,uyt(t,e),tae(e,r,null,n);var s=e.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},e.updateQueue.baseState=i,e.memoizedState=i,e.flags&256){o=_U(Error(dt(423)),e),e=Jht(t,e,r,n,o);break e}else if(r!==o){o=_U(Error(dt(424)),e),e=Jht(t,e,r,n,o);break e}else for(Ph=KT(e.stateNode.containerInfo.firstChild),Ah=e,ua=!0,Nw=null,n=myt(e,null,r,n),e.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(vU(),r===o){e=XC(t,e,n);break e}ep(t,e,r,n)}e=e.child}return e;case 5:return hyt(e),t===null&&QMe(e),r=e.type,o=e.pendingProps,i=t!==null?t.memoizedProps:null,s=o.children,GMe(r,o)?s=null:i!==null&&GMe(r,i)&&(e.flags|=32),Uyt(t,e),ep(t,e,s,n),e.child;case 6:return t===null&&QMe(e),null;case 13:return Byt(t,e,n);case 4:return BOe(e,e.stateNode.containerInfo),r=e.pendingProps,t===null?e.child=wU(e,null,r,n):ep(t,e,r,n),e.child;case 11:return r=e.type,o=e.pendingProps,o=e.elementType===r?o:Mw(r,o),Ght(t,e,r,o,n);case 7:return ep(t,e,e.pendingProps,n),e.child;case 8:return ep(t,e,e.pendingProps.children,n),e.child;case 12:return ep(t,e,e.pendingProps.children,n),e.child;case 10:e:{if(r=e.type._context,o=e.pendingProps,i=e.memoizedProps,s=o.value,As(Qse,r._currentValue),r._currentValue=s,i!==null)if($w(i.value,s)){if(i.children===o.children&&!sm.current){e=XC(t,e,n);break e}}else for(i=e.child,i!==null&&(i.return=e);i!==null;){var a=i.dependencies;if(a!==null){s=i.child;for(var l=a.firstContext;l!==null;){if(l.context===r){if(i.tag===1){l=GC(-1,n&-n),l.tag=2;var c=i.updateQueue;if(c!==null){c=c.shared;var u=c.pending;u===null?l.next=l:(l.next=u.next,u.next=l),c.pending=l}}i.lanes|=n,l=i.alternate,l!==null&&(l.lanes|=n),eOe(i.return,n,e),a.lanes|=n;break}l=l.next}}else if(i.tag===10)s=i.type===e.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(dt(341));s.lanes|=n,a=s.alternate,a!==null&&(a.lanes|=n),eOe(s,n,e),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===e){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}ep(t,e,o.children,n),e=e.child}return e;case 9:return o=e.type,r=e.pendingProps.children,mU(e,n),o=Iy(o),r=r(o),e.flags|=1,ep(t,e,r,n),e.child;case 14:return r=e.type,o=Mw(r,e.pendingProps),o=Mw(r.type,o),Zht(t,e,r,o,n);case 15:return Dyt(t,e,e.type,e.pendingProps,n);case 17:return r=e.type,o=e.pendingProps,o=e.elementType===r?o:Mw(r,o),$se(t,e),e.tag=1,am(r)?(t=!0,Yse(e)):t=!1,mU(e,n),fyt(e,r,o),nOe(e,r,o,n),iOe(null,e,r,!0,t,n);case 19:return zyt(t,e,n);case 22:return Fyt(t,e,n)}throw Error(dt(156,e.tag))};function ovt(t,e){return Egt(t,e)}function VNn(t,e,n,r){this.tag=t,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=e,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Cy(t,e,n,r){return new VNn(t,e,n,r)}function nNe(t){return t=t.prototype,!(!t||!t.isReactComponent)}function qNn(t){if(typeof t=="function")return nNe(t)?1:0;if(t!=null){if(t=t.$$typeof,t===_Oe)return 11;if(t===xOe)return 14}return 2}function JT(t,e){var n=t.alternate;return n===null?(n=Cy(t.tag,e,t.key,t.mode),n.elementType=t.elementType,n.type=t.type,n.stateNode=t.stateNode,n.alternate=t,t.alternate=n):(n.pendingProps=e,n.type=t.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=t.flags&14680064,n.childLanes=t.childLanes,n.lanes=t.lanes,n.child=t.child,n.memoizedProps=t.memoizedProps,n.memoizedState=t.memoizedState,n.updateQueue=t.updateQueue,e=t.dependencies,n.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},n.sibling=t.sibling,n.index=t.index,n.ref=t.ref,n}function Use(t,e,n,r,o,i){var s=2;if(r=t,typeof t=="function")nNe(t)&&(s=1);else if(typeof t=="string")s=5;else e:switch(t){case Q2:return bN(n.children,o,i,e);case bOe:s=8,o|=8;break;case IMe:return t=Cy(12,n,e,o|2),t.elementType=IMe,t.lanes=i,t;case TMe:return t=Cy(13,n,e,o),t.elementType=TMe,t.lanes=i,t;case PMe:return t=Cy(19,n,e,o),t.elementType=PMe,t.lanes=i,t;case pgt:return bae(n,o,i,e);default:if(typeof t=="object"&&t!==null)switch(t.$$typeof){case dgt:s=10;break e;case fgt:s=9;break e;case _Oe:s=11;break e;case xOe:s=14;break e;case FT:s=16,r=null;break e}throw Error(dt(130,t==null?t:typeof t,""))}return e=Cy(s,n,e,o),e.elementType=t,e.type=r,e.lanes=i,e}function bN(t,e,n,r){return t=Cy(7,t,r,e),t.lanes=n,t}function bae(t,e,n,r){return t=Cy(22,t,r,e),t.elementType=pgt,t.lanes=n,t.stateNode={isHidden:!1},t}function SMe(t,e,n){return t=Cy(6,t,null,e),t.lanes=n,t}function CMe(t,e,n){return e=Cy(4,t.children!==null?t.children:[],t.key,e),e.lanes=n,e.stateNode={containerInfo:t.containerInfo,pendingChildren:null,implementation:t.implementation},e}function KNn(t,e,n,r,o){this.tag=e,this.containerInfo=t,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=aMe(0),this.expirationTimes=aMe(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=aMe(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function rNe(t,e,n,r,o,i,s,a,l){return t=new KNn(t,e,n,a,l),e===1?(e=1,i===!0&&(e|=8)):e=0,i=Cy(3,null,null,e),t.current=i,i.stateNode=t,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},jOe(i),t}function GNn(t,e,n){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:X2,key:r==null?null:""+r,children:t,containerInfo:e,implementation:n}}function ivt(t){if(!t)return QT;t=t._reactInternals;e:{if(TN(t)!==t||t.tag!==1)throw Error(dt(170));var e=t;do{switch(e.tag){case 3:e=e.stateNode.context;break e;case 1:if(am(e.type)){e=e.stateNode.__reactInternalMemoizedMergedChildContext;break e}}e=e.return}while(e!==null);throw Error(dt(171))}if(t.tag===1){var n=t.type;if(am(n))return oyt(t,n,e)}return e}function svt(t,e,n,r,o,i,s,a,l){return t=rNe(n,r,!0,t,o,i,s,a,l),t.context=ivt(null),n=t.current,r=tp(),o=YT(n),i=GC(r,o),i.callback=e??null,GT(n,i,o),t.current.lanes=o,I9(t,o,r),lm(t,r),t}function _ae(t,e,n,r){var o=e.current,i=tp(),s=YT(o);return n=ivt(n),e.context===null?e.context=n:e.pendingContext=n,e=GC(i,s),e.payload={element:t},r=r===void 0?null:r,r!==null&&(e.callback=r),t=GT(o,e,s),t!==null&&(Lw(t,o,s,i),Nse(t,o,s)),s}function cae(t){if(t=t.current,!t.child)return null;switch(t.child.tag){case 5:return t.child.stateNode;default:return t.child.stateNode}}function agt(t,e){if(t=t.memoizedState,t!==null&&t.dehydrated!==null){var n=t.retryLane;t.retryLane=n!==0&&n<e?n:e}}function oNe(t,e){agt(t,e),(t=t.alternate)&&agt(t,e)}function ZNn(){return null}var avt=typeof reportError=="function"?reportError:function(t){console.error(t)};function iNe(t){this._internalRoot=t}xae.prototype.render=iNe.prototype.render=function(t){var e=this._internalRoot;if(e===null)throw Error(dt(409));_ae(t,e,null,null)};xae.prototype.unmount=iNe.prototype.unmount=function(){var t=this._internalRoot;if(t!==null){this._internalRoot=null;var e=t.containerInfo;kN(function(){_ae(null,t,null,null)}),e[YC]=null}};function xae(t){this._internalRoot=t}xae.prototype.unstable_scheduleHydration=function(t){if(t){var e=Dgt();t={blockedOn:null,target:t,priority:e};for(var n=0;n<jT.length&&e!==0&&e<jT[n].priority;n++);jT.splice(n,0,t),n===0&&Ugt(t)}};function sNe(t){return!(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11)}function Sae(t){return!(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11&&(t.nodeType!==8||t.nodeValue!==" react-mount-point-unstable "))}function lgt(){}function YNn(t,e,n,r,o){if(o){if(typeof r=="function"){var i=r;r=function(){var c=cae(s);i.call(c)}}var s=svt(e,r,t,0,null,!1,!1,"",lgt);return t._reactRootContainer=s,t[YC]=s.current,y9(t.nodeType===8?t.parentNode:t),kN(),s}for(;o=t.lastChild;)t.removeChild(o);if(typeof r=="function"){var a=r;r=function(){var c=cae(l);a.call(c)}}var l=rNe(t,0,!1,null,null,!1,!1,"",lgt);return t._reactRootContainer=l,t[YC]=l.current,y9(t.nodeType===8?t.parentNode:t),kN(function(){_ae(e,l,n,r)}),l}function Cae(t,e,n,r,o){var i=n._reactRootContainer;if(i){var s=i;if(typeof o=="function"){var a=o;o=function(){var l=cae(s);a.call(l)}}_ae(e,s,t,o)}else s=YNn(n,e,t,o,r);return cae(s)}Lgt=function(t){switch(t.tag){case 3:var e=t.stateNode;if(e.current.memoizedState.isDehydrated){var n=XG(e.pendingLanes);n!==0&&(kOe(e,n|1),lm(e,ml()),(Qo&6)===0&&(xU=ml()+500,nP()))}break;case 13:kN(function(){var r=JC(t,1);if(r!==null){var o=tp();Lw(r,t,1,o)}}),oNe(t,1)}};IOe=function(t){if(t.tag===13){var e=JC(t,134217728);if(e!==null){var n=tp();Lw(e,t,134217728,n)}oNe(t,134217728)}};$gt=function(t){if(t.tag===13){var e=YT(t),n=JC(t,e);if(n!==null){var r=tp();Lw(n,t,e,r)}oNe(t,e)}};Dgt=function(){return qi};Fgt=function(t,e){var n=qi;try{return qi=t,e()}finally{qi=n}};FMe=function(t,e,n){switch(e){case"input":if(MMe(t,n),e=n.name,n.type==="radio"&&e!=null){for(n=t;n.parentNode;)n=n.parentNode;for(n=n.querySelectorAll("input[name="+JSON.stringify(""+e)+'][type="radio"]'),e=0;e<n.length;e++){var r=n[e];if(r!==t&&r.form===t.form){var o=mae(r);if(!o)throw Error(dt(90));hgt(r),MMe(r,o)}}}break;case"textarea":ygt(t,n);break;case"select":e=n.value,e!=null&&uU(t,!!n.multiple,e,!1)}};Cgt=QOe;kgt=kN;var JNn={usingClientEntryPoint:!1,Events:[P9,rU,mae,xgt,Sgt,QOe]},GG={findFiberByHostInstance:gN,bundleType:0,version:"18.2.0",rendererPackageName:"react-dom"},XNn={bundleType:GG.bundleType,version:GG.version,rendererPackageName:GG.rendererPackageName,rendererConfig:GG.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:QC.ReactCurrentDispatcher,findHostInstanceByFiber:function(t){return t=Pgt(t),t===null?null:t.stateNode},findFiberByHostInstance:GG.findFiberByHostInstance||ZNn,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.2.0-next-9e3b772b8-20220608"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&(ZG=__REACT_DEVTOOLS_GLOBAL_HOOK__,!ZG.isDisabled&&ZG.supportsFiber))try{uae=ZG.inject(XNn),J_=ZG}catch{}var ZG;Oh.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=JNn;Oh.createPortal=function(t,e){var n=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!sNe(e))throw Error(dt(200));return GNn(t,e,null,n)};Oh.createRoot=function(t,e){if(!sNe(t))throw Error(dt(299));var n=!1,r="",o=avt;return e!=null&&(e.unstable_strictMode===!0&&(n=!0),e.identifierPrefix!==void 0&&(r=e.identifierPrefix),e.onRecoverableError!==void 0&&(o=e.onRecoverableError)),e=rNe(t,1,!1,null,null,n,!1,r,o),t[YC]=e.current,y9(t.nodeType===8?t.parentNode:t),new iNe(e)};Oh.findDOMNode=function(t){if(t==null)return null;if(t.nodeType===1)return t;var e=t._reactInternals;if(e===void 0)throw typeof t.render=="function"?Error(dt(188)):(t=Object.keys(t).join(","),Error(dt(268,t)));return t=Pgt(e),t=t===null?null:t.stateNode,t};Oh.flushSync=function(t){return kN(t)};Oh.hydrate=function(t,e,n){if(!Sae(e))throw Error(dt(200));return Cae(null,t,e,!0,n)};Oh.hydrateRoot=function(t,e,n){if(!sNe(t))throw Error(dt(405));var r=n!=null&&n.hydratedSources||null,o=!1,i="",s=avt;if(n!=null&&(n.unstable_strictMode===!0&&(o=!0),n.identifierPrefix!==void 0&&(i=n.identifierPrefix),n.onRecoverableError!==void 0&&(s=n.onRecoverableError)),e=svt(e,null,t,1,n??null,o,!1,i,s),t[YC]=e.current,y9(t),r)for(t=0;t<r.length;t++)n=r[t],o=n._getVersion,o=o(n._source),e.mutableSourceEagerHydrationData==null?e.mutableSourceEagerHydrationData=[n,o]:e.mutableSourceEagerHydrationData.push(n,o);return new xae(e)};Oh.render=function(t,e,n){if(!Sae(e))throw Error(dt(200));return Cae(null,t,e,!1,n)};Oh.unmountComponentAtNode=function(t){if(!Sae(t))throw Error(dt(40));return t._reactRootContainer?(kN(function(){Cae(null,null,t,!1,function(){t._reactRootContainer=null,t[YC]=null})}),!0):!1};Oh.unstable_batchedUpdates=QOe;Oh.unstable_renderSubtreeIntoContainer=function(t,e,n,r){if(!Sae(n))throw Error(dt(200));if(t==null||t._reactInternals===void 0)throw Error(dt(38));return Cae(t,e,n,!1,r)};Oh.version="18.2.0-next-9e3b772b8-20220608"});var Es=wi((l7r,uvt)=>{"use strict";function cvt(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(cvt)}catch(t){console.error(t)}}cvt(),uvt.exports=lvt()});var fvt=wi(aNe=>{"use strict";var dvt=Es();aNe.createRoot=dvt.createRoot,aNe.hydrateRoot=dvt.hydrateRoot;var c7r});function Er(t,e){let n=(0,mvt.createRoot)(t);return{render(r){n.render(pvt.default.createElement(fN.Provider,{value:e},r))},unmount(){n.unmount()}}}var pvt,mvt,Pa=b(()=>{ko();pvt=L(B()),mvt=L(fvt())});function QNn({onCancel:t,isUsingPlusModels:e}){return Q_.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Q_.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Q_.default.createElement("div",null,"Your Copilot Plus license key is no longer valid. Please renew your subscription to continue using Copilot Plus."),e&&Q_.default.createElement("div",{className:"tw-text-sm tw-text-warning"},"The Copilot Plus exclusive models will stop working. You can switch to the default models in the Settings.")),Q_.default.createElement("div",{className:"tw-flex tw-w-full tw-justify-end tw-gap-2"},Q_.default.createElement(oe,{variant:"ghost",onClick:t},"Close"),Q_.default.createElement(oe,{variant:"default",onClick:()=>{ek(hw.EXPIRED_MODAL)}},"Renew Now ",Q_.default.createElement(Ch,{className:"tw-size-4"}))))}var Q_,hvt,kae,gvt=b(()=>{Q_=L(B()),hvt=require("obsidian");yt();vc();gt();Re();Se();Pa();kae=class extends hvt.Modal{constructor(e){super(e),this.setTitle("Thanks for being a Copilot Plus user \u{1F44B}")}onOpen(){let{contentEl:e}=this;this.root=Er(e,this.app);let n=()=>{this.close()};this.root.render(Q_.default.createElement(QNn,{onCancel:n,isUsingPlusModels:yvt(Y())}))}onClose(){this.root.unmount()}}});var lNe,cNe=b(()=>{lNe={"ent-2026-06":{kty:"EC",crv:"P-256",x:"9j3HVz0TWJ5VFMTiaNhExKQJAPWjduz2wdZpKAXIkzk",y:"ZA9ARslf7l1XUK5zL5Tgbm-eY-zxWaVLzQD7nTnId6Y"}}});function wvt(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e+"=".repeat((4-e.length%4)%4),r=atob(n),o=new Uint8Array(r.length);for(let i=0;i<r.length;i++)o[i]=r.charCodeAt(i);return o}function vvt(t){try{return JSON.parse(new TextDecoder().decode(wvt(t)))}catch{return null}}async function E9(t,e={}){let{now:n=Date.now(),publicKeys:r=lNe,expectedUserId:o,subtle:i=crypto.subtle}=e;if(!t)return null;let s=t.split(".");if(s.length!==3)return null;let[a,l,c]=s,u=vvt(a);if(!u||u.alg!=="ES256"||!u.kid)return null;let d=r[u.kid];if(!d)return null;let f=!1;try{let m=await i.importKey("jwk",d,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);f=await i.verify({name:"ECDSA",hash:"SHA-256"},m,wvt(c),new TextEncoder().encode(`${a}.${l}`))}catch{return null}if(!f)return null;let p=vvt(l);return!p||typeof p.user_id!="string"||!Array.isArray(p.features)||typeof p.exp!="number"||p.exp*1e3<=n||o&&p.user_id!==o?null:p}var bvt=b(()=>{cNe()});var _vt=b(()=>{cNe();bvt()});function Ln(){return uNe.Platform.isDesktopApp&&!uNe.Platform.isMobile}function Pe(t){if(!Ln())throw new Error(`Node built-in module "${t}" is unavailable outside the desktop runtime.`);return require(t)}var uNe,$n=b(()=>{uNe=require("obsidian")});function Tae(){return Ar(tk,{store:ef})}function xvt(){return zO(Iae,{store:ef})}function kU(){return ef.get(tk)}function PN(){return ef.get(Iae)}function Pae(t){ef.set(tk,t)}function AN(t){let e=ef.get(tk),n=e.findIndex(r=>r.title===t.title);if(n!==-1){let r=[...e];r[n]=t,ef.set(tk,r)}else ef.set(tk,[...e,t])}function IU(t){let e=ef.get(tk);ef.set(tk,e.filter(n=>n.title!==t))}function rP(t){ef.set(Iae,t)}function M9(t){ef.set(dNe,t)}function EN(){return ef.get(dNe)}function Svt(t){let e=[ef.sub(Iae,t),ef.sub(dNe,t),ef.sub(tk,t)];return()=>{for(let n of e)n()}}function oP(t){fNe.add(t)}function iP(t){fNe.delete(t)}function nk(t){return fNe.has(t)}function Aae(){return Y().defaultSystemPromptTitle}function Cvt(){let t=kU(),e=PN();if(e){let r=t.find(o=>o.title===e);if(r)return r.content}let n=Aae();if(n){let r=t.find(o=>o.title===n);if(r)return r.content}return""}function kvt(){let t=Aae();rP(t)}function pNe(){M9(!1),rP("")}var ef,tk,Iae,dNe,fNe,rk=b(()=>{Us();Us();Se();ef=sy(),tk=yo([]),Iae=yo(""),dNe=yo(!1);fNe=new Set});function Tvt(t){let e="";for(let n=0;n<t.length;n++)e+=Ivt[t[n]>>>4]+Ivt[t[n]&15];return e}function nRn(t,e){return t<<e|t>>>32-e}function jl(t){let e=new TextEncoder().encode(t),n=e.length,r=(n+8>>>6)+1<<6,o=new Uint8Array(r);o.set(e),o[n]=128;let i=new DataView(o.buffer),s=n*8>>>0,a=Math.floor(n/536870912);i.setUint32(r-8,s,!0),i.setUint32(r-4,a,!0);let l=1732584193,c=-271733879,u=-1732584194,d=271733878,f=new Int32Array(16);for(let h=0;h<r;h+=64){for(let _=0;_<16;_++)f[_]=i.getInt32(h+_*4,!0);let g=l,v=c,y=u,w=d;for(let _=0;_<64;_++){let S,I;_<16?(S=v&y|~v&w,I=_):_<32?(S=w&v|~w&y,I=5*_+1&15):_<48?(S=v^y^w,I=3*_+5&15):(S=y^(v|~w),I=7*_&15);let C=w;w=y,y=v,v=v+nRn(g+S+eRn[_]+f[I]|0,tRn[_])|0,g=C}l=l+g|0,c=c+v|0,u=u+y|0,d=d+w|0}let p=new Uint8Array(16),m=new DataView(p.buffer);return m.setInt32(0,l,!0),m.setInt32(4,c,!0),m.setInt32(8,u,!0),m.setInt32(12,d,!0),Tvt(p)}function ex(t,e){return t>>>e|t<<32-e}function MN(t){let e=new TextEncoder().encode(t),n=e.length,r=(n+8>>>6)+1<<6,o=new Uint8Array(r);o.set(e),o[n]=128;let i=new DataView(o.buffer),s=n*8>>>0,a=Math.floor(n/536870912);i.setUint32(r-8,a,!1),i.setUint32(r-4,s,!1);let l=1779033703,c=-1150833019,u=1013904242,d=-1521486534,f=1359893119,p=-1694144372,m=528734635,h=1541459225,g=new Int32Array(64);for(let w=0;w<r;w+=64){for(let O=0;O<16;O++)g[O]=i.getInt32(w+O*4,!1);for(let O=16;O<64;O++){let $=g[O-15],U=g[O-2],V=ex($,7)^ex($,18)^$>>>3,K=ex(U,17)^ex(U,19)^U>>>10;g[O]=g[O-16]+V+g[O-7]+K|0}let _=l,S=c,I=u,C=d,k=f,T=p,P=m,E=h;for(let O=0;O<64;O++){let $=ex(k,6)^ex(k,11)^ex(k,25),U=k&T^~k&P,V=E+$+U+rRn[O]+g[O]|0,K=ex(_,2)^ex(_,13)^ex(_,22),se=_&S^_&I^S&I,le=K+se|0;E=P,P=T,T=k,k=C+V|0,C=I,I=S,S=_,_=V+le|0}l=l+_|0,c=c+S|0,u=u+I|0,d=d+C|0,f=f+k|0,p=p+T|0,m=m+P|0,h=h+E|0}let v=new Uint8Array(32),y=new DataView(v.buffer);return y.setInt32(0,l,!1),y.setInt32(4,c,!1),y.setInt32(8,u,!1),y.setInt32(12,d,!1),y.setInt32(16,f,!1),y.setInt32(20,p,!1),y.setInt32(24,m,!1),y.setInt32(28,h,!1),Tvt(v)}var Ivt,eRn,tRn,rRn,Py=b(()=>{Ivt="0123456789abcdef";eRn=new Int32Array([-680876936,-389564586,606105819,-1044525330,-176418897,1200080426,-1473231341,-45705983,1770035416,-1958414417,-42063,-1990404162,1804603682,-40341101,-1502002290,1236535329,-165796510,-1069501632,643717713,-373897302,-701558691,38016083,-660478335,-405537848,568446438,-1019803690,-187363961,1163531501,-1444681467,-51403784,1735328473,-1926607734,-378558,-2022574463,1839030562,-35309556,-1530992060,1272893353,-155497632,-1094730640,681279174,-358537222,-722521979,76029189,-640364487,-421815835,530742520,-995338651,-198630844,1126891415,-1416354905,-57434055,1700485571,-1894986606,-1051523,-2054922799,1873313359,-30611744,-1560198380,1309151649,-145523070,-1120210379,718787259,-343485551]),tRn=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21];rRn=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298])});function TU(t){return Pe("path").join(t,oRn)}function Eae(t){let e=t.vault.adapter,n=e instanceof Pvt.FileSystemAdapter?e.getBasePath():"";return n?jl(n).slice(0,8):"default"}var Pvt,oRn,Mae=b(()=>{Pvt=require("obsidian");$n();Py();oRn=".obsidian-copilot"});function mNe(){return"The user composes messages in a rich editor that supports @-mentions of vault items.\nMentioned items appear inline in your input as the following literal tokens \u2014 treat\nthem as concrete references the user picked, NOT as template placeholders to substitute.\n\n- `[[note_title]]` \u2014 a specific note in the vault. To read or modify it, call `read`\n or `edit` with the resolved path; never infer a note's contents from its title alone.\n When you cite a note in your written reply, use the same `[[title]]` form (no backticks).\n- `{folder_name}` \u2014 a vault folder the user wants you to focus on. To scope work to that\n folder, pass `folder_name/**` to `glob`, or include `folder_name/` as a path prefix\n when calling `read`, `grep`, or other path-aware tools.\n- `{activeNote}` \u2014 the user's currently active note (reserved special token). Resolve it\n the same way as `[[note_title]]`.\n\nAny other `{...}` token in the user's message refers to a folder by that name, not a\nplaceholder to fill in."}var hNe=b(()=>{});var Avt,Evt=b(()=>{Avt=`## Task planning
Use your built-in todo/plan tool for complex work so the user can follow your progress.
**When to plan:** the task takes roughly 3+ meaningful steps, spans multiple notes or files, or the user explicitly asks for a plan or checklist.
**When to skip:** simple questions, single-step tasks, or anything you can answer directly \u2014 an unnecessary plan is just noise.
When you plan:
- Write each item in the user's language.
- Keep exactly one item in progress at a time: mark it in progress before you start that step, and completed as soon as the work is actually done.
- Update the plan as scope changes \u2014 add steps you discover and drop ones that no longer apply.`});function sP(){let t=[];if(!EN()){let e=Y();t.push(dRn),t.push(iRn),t.push(e.docProcessorBackend==="miyo"?aRn:sRn),e.enableMiyoSearchSkill===!0&&t.push(lRn),t.push(Avt)}return t.push(cRn),t.push(uRn),t.push(mNe()),t.join(`
`)}var iRn,sRn,aRn,lRn,cRn,uRn,dRn,O9=b(()=>{hNe();Se();Evt();rk();iRn=`## Copilot Plus tools
For these requests, prefer the bundled Copilot skill over any built-in tool of your own:
- Searching the web \u2192 the \`copilot-web-search\` skill
- Fetching or reading a specific web page \u2192 the \`copilot-web-fetch\` skill
- Getting a YouTube video's transcript \u2192 the \`copilot-youtube-transcript\` skill
- Fetching an X (Twitter) post \u2192 the \`copilot-fetch-x\` skill
Each skill ships a runnable script per OS \u2014 a \`.sh\` for macOS/Linux and a \`.cmd\` for Windows. Follow the skill's own "How to run" instructions for the right command; both runtimes are always present, so nothing needs to be installed.
Choose vault or web evidence from the request:
- For questions about the user's own notes or vault, search locally first. Do not place text from the vault into a web query unless the request clearly requires researching that text.
- For current facts, external topics, or third-party documentation, proactively use web search or fetch without waiting for an explicit web-search request.
- If local search is empty or weak and the question is external in nature, switch to web evidence instead of answering from memory.
Default to one discovery search followed by targeted page fetches, or fetch directly when the user supplied a specific URL. Stop when you have enough evidence; do not start repeated or open-ended search chains.
If a skill is missing, disabled, reports that Copilot Plus is not active, or fails for this particular request (for example a page it can't fetch or any other relay error), silently fall back to your own equivalent tool (or, if you have none for that task, tell the user it's unavailable) and complete the request \u2014 never refuse and never block the user on upgrading. Only pass along an upgrade or renewal note when the skill's own message explicitly invites it, and keep any such mention brief and occasional.`,sRn="## Document processing\nFor reading a PDF file, prefer the bundled `copilot-read-pdf` skill over any built-in tool of your own. The fallback rule above applies to it: if it is missing, disabled, or fails for this file, use your own equivalent tool instead.",aRn="## Document processing (local, Miyo)\nThe user selected Miyo as their Document Processor, so PDFs and EPUBs must stay on their machine. For any PDF or EPUB file, use the `miyo-parse` skill, which parses it locally.\n\nThe fallback rule above does NOT apply here. If `miyo-parse` is missing or fails, report the problem and stop \u2014 never send the document to `copilot-read-pdf`, another cloud parser, or any other web service.",lRn="## Vault semantic search (Miyo)\nThe user has Miyo enabled: local, meaning-based semantic search over their vault. For any vault-search intent, use the `miyo-search` skill when your builtin `grep` search is too slow or doesn't surface enough relevant notes, or whenever the user explicitly asks for Miyo search. Follow the skill's own instructions to run it.",cRn="## Project workspaces\nWhen the conversation includes a `<project_context>` block:\n- Treat the working directory as that project's workspace. Write generated files, drafts, and intermediate artifacts under an `outputs/` folder inside it, creating it if needed, unless the user names a different destination.\n- Read and search inside the working directory by default. The configured context sources in `<project_context>` are also opted in even when they live outside it. When a source shows a `\u2192 <absolute path>` snapshot pointer, read that path directly.\n- Don't reach for unrelated files outside the working directory or configured context sources unless the instructions or user name a specific file or location.",uRn=`## AGENTS.md precedence
The user's own instructions reach you as AGENTS.md files, in whatever order this runtime loads them. Judge them by scope, not by the order they appear in: an AGENTS.md inside the current project folder is more specific than the one at the vault root, so follow the project file wherever the two conflict.`,dRn=`You are Obsidian Copilot, an AI assistant that helps users work with their Obsidian vault \u2014 markdown notes for knowledge management, writing, and research. You are NOT a software-engineering agent or CLI coding tool. The working directory is the user's Obsidian vault, or a project folder within it: a collection of markdown notes, not a code repository. Disregard any framing in environment metadata that suggests otherwise.
## Grounding
- The user's vault contains markdown notes. When the user says "note", they mean an Obsidian note in this vault.
- When the user mentions "tags", they usually mean tags in Obsidian note properties.
- Never claim you do not have access to something. Rely on the user's provided context and the tools available to you.
- If you are unsure, say so and ask for more context \u2014 don't guess.
- Always respond in the language of the user's query.
## Tool Behavior
- Prefer evidence from \`read\`, \`grep\`, and \`glob\` over assumption. Don't infer what a note contains from its title \u2014 read it.
- NEVER search for the same or very similar query twice. If results were insufficient, try substantially different terms.
- After 1-2 searches, synthesize an answer from the results you have. Do not keep searching unless the results are clearly insufficient.
- If you have enough information to answer, respond directly without calling any more tools.
## Response Style
- Respond at length appropriate to note-taking and knowledge work. Do NOT default to 1-3 line CLI cadence \u2014 give the user enough context to understand and act on your answer.
- Be direct and concrete. Don't pad with preamble or postamble.
## Markdown Formatting
- Use \`$...$\` for LaTeX equations, never \`\\[...\\]\` or \`\\(...\\)\`.
- For markdown lists, always use \`- \` (hyphen followed by exactly one space) for bullet points, with no leading spaces. Never use \`*\` for bullets.
- When showing note titles, use the \`[[title]]\` wikilink format and never wrap them in backticks or quotes.
- For Obsidian-internal image links, use the \`![[link]]\` format and never wrap them in backticks.
- For web image links, use the \`![alt](url)\` format and never wrap them in backticks.
- For tables, use valid GitHub-flavored markdown: a header row, then a delimiter row of dashes (e.g. \`| --- | --- |\`), then one row per record \u2014 every row wrapped in leading and trailing \`|\`. Put a blank line before the table. If you label the table, put the label on its own line above that blank line; never append a trailing \`|\` to a caption, heading, or any line that is not itself a table row.`});var da,Oae,gNe,ok=b(()=>{da=class extends Error{constructor(e){super(`Agent does not implement ${e}`),this.name="MethodUnsupportedError"}},Oae=class extends Error{constructor(e="Not signed in. Use the Sign in button above to continue."){super(e),this.name="AuthRequiredError"}},gNe=-32601});function fd(t){return t.replace(/\\/g,"/").replace(/\/+$/,"")}function Fr(t,e){let n=t.replace(/\/+$/,""),r=e.replace(/^\/+/,"");return n.length===0?r:`${n}/${r}`}function PU(t){let e=t.replace(/\/+$/,""),n=e.lastIndexOf("/");return n<=0?"/":e.slice(0,n)}function Nae(t){let e=fd(t),n=e.lastIndexOf("/");return n===-1?e:e.slice(n+1)}function Mvt(t,e){let n=fd(t),r=fd(e);return n===r||n.startsWith(r+"/")}function Ovt(t,e,n=!1){if(!t||!e)return t;let r=e.replace(/[/\\]+$/,"");if(!r)return t;let o=r.replace(/\\/g,"/"),i=t.slice(0,r.length).replace(/\\/g,"/");if(!(n?i.toLowerCase()===o.toLowerCase():i===o))return t;let a=t.slice(r.length);return a===""?"~":a[0]==="/"||a[0]==="\\"?"~"+a:t}var rp=b(()=>{});function tx(t){let e=Pe("path"),n=t.platform==="win32"?pRn(t,e.win32):fRn(t,e.posix),r=new Set,o=[];for(let i of n)!i||r.has(i)||(r.add(i),o.push(i));return o}function Rvt(t){return tx(t).filter(e=>Lvt(t.fs,e))}function Lvt(t,e){try{return t.existsSync(e)}catch{return!1}}function fRn(t,e){let{homeDir:n,env:r,fs:o,platform:i}=t,s=[];s.push(r.NVM_BIN??null);let a=r.NVM_DIR??e.join(n,".nvm"),l=e.join(a,"versions","node"),c=hRn(a,l,o,e);c&&s.push(c),s.push(...Nvt(o,l,["bin"],e)),r.FNM_MULTISHELL_PATH&&s.push(e.join(r.FNM_MULTISHELL_PATH,"bin"));for(let f of mRn(n,r,i,e))s.push(...Nvt(o,e.join(f,"node-versions"),["installation","bin"],e));s.push(r.VOLTA_HOME?e.join(r.VOLTA_HOME,"bin"):e.join(n,".volta","bin"));let u=e.join(n,".asdf"),d=r.ASDF_DATA_DIR??(Lvt(o,e.join(u,"shims"))?u:r.ASDF_DIR??u);return s.push(e.join(d,"shims")),s.push(e.join(d,"bin")),r.N_PREFIX&&s.push(e.join(r.N_PREFIX,"bin")),r.npm_config_prefix&&s.push(e.join(r.npm_config_prefix,"bin")),s.push(e.join(n,".npm-global","bin")),s.push(e.join(n,".local","bin")),s}function pRn(t,e){let{homeDir:n,env:r}=t,o=[];return o.push(r.npm_config_prefix??null),o.push(r.APPDATA?e.join(r.APPDATA,"npm"):null),o.push(e.join(n,"AppData","Roaming","npm")),o.push(r.NVM_SYMLINK??null),o.push(r.NVM_HOME??null),r.FNM_MULTISHELL_PATH&&o.push(r.FNM_MULTISHELL_PATH),o.push(r.VOLTA_HOME?e.join(r.VOLTA_HOME,"bin"):e.join(n,".volta","bin")),o}function mRn(t,e,n,r){return e.FNM_DIR?[e.FNM_DIR]:n==="darwin"?[r.join(t,"Library","Application Support","fnm"),r.join(t,".local","share","fnm")]:[r.join(t,".local","share","fnm")]}function Nvt(t,e,n,r){let o;try{o=t.readdirSync(e)}catch{return[]}return o.filter(i=>/^v?\d/.test(i)).sort((i,s)=>s.localeCompare(i,void 0,{numeric:!0})).map(i=>r.join(e,i,...n))}function hRn(t,e,n,r){let o;try{o=n.readFileSync(r.join(t,"alias","default"),"utf8").trim()}catch{return null}if(!o)return null;let i=Dvt(t,o,n,r,0);if(!i)return null;let s;try{s=n.readdirSync(e).filter(l=>l.startsWith("v")).sort((l,c)=>c.localeCompare(l,void 0,{numeric:!0}))}catch{return null}let a=gRn(s,i);return a?r.join(e,a,"bin"):null}function Dvt(t,e,n,r,o){if(o>5)return null;if(/^\d/.test(e)||e.startsWith("v")||$vt.has(e))return e;try{let i=n.readFileSync(r.join(t,"alias",...e.split("/")),"utf8").trim();return i?Dvt(t,i,n,r,o+1):null}catch{return null}}function gRn(t,e){if($vt.has(e))return t[0];let n=e.replace(/^v/,"");return t.find(r=>{let o=r.slice(1);return o===n||o.startsWith(n+".")})}var $vt,N9=b(()=>{$n();$vt=new Set(["node","stable"])});function yNe(t,e){let n=(e??"").split(Fvt).filter(Boolean),r=new Set,o=[];for(let i of[...t,...n])r.has(i)||(r.add(i),o.push(i));return o.join(Fvt)}function yRn(){let t=Pe("os"),e=Pe("fs");return Rvt({homeDir:t.homedir(),platform:process.platform,env:process.env,fs:{existsSync:n=>e.existsSync(n),readFileSync:(n,r)=>e.readFileSync(n,r),readdirSync:n=>e.readdirSync(n)}})}function L9(){let t=process.platform==="win32"?[]:R9;return[...yRn(),...t]}function Uvt(t){return yNe(L9(),t)}function Rae(t){let e=Pe("os");return Ovt(t,e.homedir(),process.platform==="win32")}var R9,Fvt,aP=b(()=>{$n();rp();N9();R9=["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin"],Fvt=process.platform==="win32"?";":":"});function vNe(t){let{override:e,fs:n}=t;if(e&&n.existsSync(e))return e;let r=t.platform==="win32"?zvt(t):Bvt(t);for(let o of r)if(o&&n.existsSync(o))return o;return null}function jvt(t){let e=t.platform==="win32"?zvt(t):Bvt(t),n=Pe("path"),r=t.platform==="win32"?n.win32:n.posix;return Array.from(new Set(e.filter(o=>!!o).map(o=>r.dirname(o))))}function Bvt(t){let e=Pe("path").posix,{homeDir:n,env:r}=t,o=[...tx(t),...R9];return[e.join(n,".claude","local","claude"),...o.map(i=>e.join(i,"claude")),e.join(n,".npm-global","lib","node_modules","@anthropic-ai","claude-code","cli.js"),r.npm_config_prefix?e.join(r.npm_config_prefix,"lib","node_modules","@anthropic-ai","claude-code","cli.js"):null,"/usr/local/lib/node_modules/@anthropic-ai/claude-code/cli.js","/opt/homebrew/lib/node_modules/@anthropic-ai/claude-code/cli.js"]}function zvt(t){let e=Pe("path").win32,{homeDir:n,env:r}=t,o=r.LOCALAPPDATA??e.join(n,"AppData","Local"),i=r.ProgramFiles??"C:\\Program Files",s=r["ProgramFiles(x86)"]??"C:\\Program Files (x86)",a=[e.join(n,".local","bin","claude.exe"),e.join(n,".claude","local","claude.exe"),e.join(o,"Claude","claude.exe"),e.join(i,"Claude","claude.exe"),e.join(s,"Claude","claude.exe")];for(let l of tx(t))a.push(e.join(l,"claude.exe")),a.push(e.join(l,"node_modules","@anthropic-ai","claude-code","cli-wrapper.cjs")),a.push(e.join(l,"node_modules","@anthropic-ai","claude-code","cli.js"));return a}var Hvt=b(()=>{aP();$n();N9()});var Lae,Wvt,wNe=b(()=>{Lae=process.platform==="win32"?"irm https://gist.githubusercontent.com/logancyang/7a87eb38d91015eac567521f8cc9c729/raw/install-claude-agent-mode-windows.ps1 | iex":"npm install -g @anthropic-ai/claude-code",Wvt="claude auth login --claudeai"});function Vvt(t){let e;try{e=JSON.parse(t)}catch{return{loggedIn:!1}}return e.loggedIn!==!0?{loggedIn:!1}:{loggedIn:!0,label:bRn(e)}}function bRn(t){let e=t.email??t.apiProvider,n=t.subscriptionType??t.authMethod;return e&&n?`${e} (${n})`:e??n}async function $ae(t,e){let{execFile:n}=Pe("child_process"),{promisify:r}=Pe("util"),o=r(n);try{let{stdout:i}=await o(t,["auth","status","--json"],{timeout:vRn,env:e});return Vvt(i)}catch(i){let s=i.stdout;return typeof s=="string"&&s.trim().length>0?Vvt(s):(W("[AgentMode] claude auth status failed",kt(i)),{loggedIn:!1})}}function Kvt(t,e,n={}){let{spawn:r}=Pe("child_process");j("[AgentMode] spawning claude auth login");let o=r(t,["auth","login","--claudeai"],{env:e,stdio:["ignore","pipe","pipe"],windowsHide:!0}),i=!1,s=l=>{if(n.onLine?.(l),i)return;let c=wRn.exec(l);c&&(i=!0,n.onUrl?.(c[0]))};return qvt(o.stdout,s),qvt(o.stderr,s),{done:new Promise(l=>{o.on("error",c=>{W("[AgentMode] claude auth login spawn error",kt(c)),l({loggedIn:!1})}),o.on("close",()=>{$ae(t,e).then(l,()=>l({loggedIn:!1}))})}),cancel:()=>{try{o.kill("SIGTERM")}catch(l){W("[AgentMode] claude auth login kill failed",kt(l))}}}}function qvt(t,e){if(!t)return;t.setEncoding("utf8");let n="";t.on("data",r=>{n+=r;let o=n.indexOf(`
`);for(;o>=0;){let i=n.slice(0,o).replace(/\r$/,"");n=n.slice(o+1),i.length>0&&e(i),o=n.indexOf(`
`)}}),t.on("end",()=>{let r=n.trim();r.length>0&&e(r)})}var vRn,wRn,Gvt=b(()=>{pe();ut();$n();vRn=1e4,wRn=/\bhttps?:\/\/[^\s'"]+/});function Dae(t,e){let n=i=>{let s=i.match(/(\d+)\.(\d+)\.(\d+)/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:[0,0,0]},r=n(t),o=n(e);for(let i=0;i<3;i++)if(r[i]!==o[i])return r[i]-o[i];return 0}var bNe=b(()=>{});async function Zvt(t,e,n){let{execFile:r}=Pe("child_process"),{promisify:o}=Pe("util");return o(r)(t,e,n)}function xRn(t,e){return/\.[cm]?js$/i.test(t)?{command:process.execPath,args:[t,"--version"],env:{...e,ELECTRON_RUN_AS_NODE:"1"}}:{command:t,args:["--version"],env:e}}function SRn(t){return t.match(/\b(\d+\.\d+\.\d+)\b/)?.[1]??null}async function _Ne(t,e,n=Zvt){let r=xRn(t,e),o;try{({stdout:o}=await n(r.command,r.args,{env:r.env,timeout:_Rn}))}catch{throw new Error(`Could not verify the installed Claude Code version. Copilot requires Claude Code ${$9} or newer.`)}let i=SRn(o);if(!i)throw new Error(`Could not read the installed Claude Code version. Copilot requires Claude Code ${$9} or newer.`);return Dae(i,$9)<0?{kind:"incompatible",currentVersion:i,minVersion:$9,message:`Claude Code ${i} is not supported. Copilot requires Claude Code ${$9} or newer.`}:{kind:"supported",version:i}}async function Yvt(t,e,n=Zvt){let r=await _Ne(t,e,n);if(r.kind==="incompatible")throw new Error(r.message)}var _Rn,$9,xNe=b(()=>{bNe();$n();_Rn=1e4,$9="2.1.206"});function nx(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var SNe=b(()=>{});function D9(t){return CRn.test(t)}function IRn(t){if(!nx(t))return!1;let e=t.id;return typeof e=="string"&&kRn.has(e)}function TRn(t){switch(t){case"@ai-sdk/anthropic":return"anthropic";case"@ai-sdk/google":return"google";case"@ai-sdk/azure":return"azure";default:return"openai-compatible"}}function PRn(t){if(typeof t.id!="string")return null;let e={id:t.id,displayName:t.name??t.id},n=Array.isArray(t.modalities?.input)?t.modalities.input:void 0,r=Array.isArray(t.modalities?.output)?t.modalities.output:void 0;if((n||r)&&(e.modalities={...n?{input:n}:{},...r?{output:r}:{}}),t.limit){let{context:o,output:i,input:s}=t.limit,a={};typeof o=="number"&&(a.context=o),typeof i=="number"&&(a.output=i),typeof s=="number"&&(a.input=s),Object.keys(a).length>0&&(e.limits=a)}if(typeof t.reasoning=="boolean"&&(e.reasoning=t.reasoning),typeof t.tool_call=="boolean"&&(e.toolCall=t.tool_call),D9(`${t.id} ${typeof t.family=="string"?t.family:""}`)&&(e.isEmbedding=!0),typeof t.release_date=="string"&&(e.releaseDate=t.release_date),t.cost){let{input:o,output:i,cache_read:s,cache_write:a}=t.cost,l={};typeof o=="number"&&(l.input=o),typeof i=="number"&&(l.output=i),typeof s=="number"&&(l.cacheRead=s),typeof a=="number"&&(l.cacheWrite=a),Object.keys(l).length>0&&(e.cost=l)}return e}function ARn(t,e){if(!nx(e)||typeof e.id!="string")return null;let n=e,r={},o=nx(n.models)?n.models:{};for(let[s,a]of Object.entries(o)){if(!nx(a)){W(`[modelsCatalog] dropping model "${s}" under provider "${t}": not an object`);continue}let l=PRn(a);l?r[l.id]=l:W(`[modelsCatalog] dropping model "${s}" under provider "${t}": invalid id`)}let i={id:n.id,displayName:n.name??n.id,providerType:TRn(n.npm),models:r};return typeof n.api=="string"&&n.api.length>0&&(i.defaultBaseUrl=n.api),i}function Jvt(t){if(!nx(t))return[];let e=[];for(let[n,r]of Object.entries(t)){if(IRn(r))continue;let o=ARn(n,r);o?e.push(o):nx(r)&&"id"in r&&W(`[modelsCatalog] dropping provider "${n}": invalid id`)}return e.sort((n,r)=>n.displayName.localeCompare(r.displayName)),e}var CRn,kRn,Fae=b(()=>{pe();SNe();CRn=/(^|[-_/.\s])embed(ding)?($|[-_/.\s])/i;kRn=new Set(["amazon-bedrock"])});var Uae,CNe,ERn,MRn,Xvt,ORn,kNe,F9,INe=b(()=>{Uae=require("obsidian");pe();Fae();SNe();CNe=".copilot",ERn="model-catalog-cache.json",MRn="https://models.dev/api.json",Xvt=5e3,ORn=24*60*60*1e3,kNe=3,F9=class{constructor(e){this.listeners=new Set;this.providers=[];this.byId=new Map;this.loadPromise=null;this.refreshPromise=null;this.failedAutoAttempts=0;this.app=e.app,this.cachePath=(0,Uae.normalizePath)(`${CNe}/${ERn}`)}ensureLoaded(){return this.loadPromise?this.loadPromise:this.providers.length===0&&this.failedAutoAttempts>=kNe?Promise.resolve():(this.loadPromise=this.doEnsureLoaded().then(({attemptedRefresh:e})=>{this.providers.length===0?(this.loadPromise=null,e&&(this.failedAutoAttempts+=1,this.failedAutoAttempts>=kNe&&W(`[modelsCatalog] giving up auto-refresh after ${kNe} empty attempts; use the manual Refresh button to retry`))):this.failedAutoAttempts=0},e=>{throw this.loadPromise=null,e}),this.loadPromise)}refresh(){return this.refreshPromise||(this.refreshPromise=this.doRefresh().finally(()=>{this.refreshPromise=null})),this.refreshPromise}async doRefresh(){let e;try{e=await this.fetchWithTimeout()}catch(o){let i=o instanceof Error?o.message:String(o);return W(`[modelsCatalog] refresh failed: ${i}`),{ok:!1,providerCount:0,error:i}}if(e.status<200||e.status>=300){let o=`models.dev responded with status ${e.status}`;return W(`[modelsCatalog] refresh failed: ${o}`),{ok:!1,providerCount:0,error:o}}let n;try{n=typeof e.json=="string"?JSON.parse(e.json):e.json}catch(o){let i=o instanceof Error?o.message:String(o);return W(`[modelsCatalog] refresh failed: invalid JSON: ${i}`),{ok:!1,providerCount:0,error:`invalid JSON: ${i}`}}if(!nx(n))return W("[modelsCatalog] refresh failed: payload is not an object"),{ok:!1,providerCount:0,error:"payload is not an object"};let r=Date.now();try{await this.app.vault.adapter.exists(CNe)||await this.app.vault.adapter.mkdir(CNe);let o={fetchedAt:r,data:n};await this.app.vault.adapter.write(this.cachePath,JSON.stringify(o))}catch(o){H("[modelsCatalog] failed to write disk cache",o)}return this.swapMemory(n),this.failedAutoAttempts=0,this.emit(),j(`[modelsCatalog] refreshed: ${this.providers.length} providers`),{ok:!0,providerCount:this.providers.length}}getAllProviders(){return[...this.providers]}getProvider(e){return this.byId.get(e)}onChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async doEnsureLoaded(){let e=await this.readDisk();return this.providers.length>0?{attemptedRefresh:!1}:e&&Date.now()-e.fetchedAt<ORn?(this.swapMemory(e.data),j(`[modelsCatalog] loaded from disk: ${this.providers.length} providers`),{attemptedRefresh:!1}):(!(await this.refresh()).ok&&e&&this.providers.length===0&&(this.swapMemory(e.data),j(`[modelsCatalog] refresh failed; falling back to stale disk cache (${this.providers.length} providers)`)),{attemptedRefresh:!0})}async readDisk(){try{if(!await this.app.vault.adapter.exists(this.cachePath))return null;let e=await this.app.vault.adapter.read(this.cachePath),n=JSON.parse(e);return!n||typeof n.fetchedAt!="number"||!nx(n.data)?(W("[modelsCatalog] disk cache rejected: malformed payload"),null):{fetchedAt:n.fetchedAt,data:n.data}}catch(e){return W(`[modelsCatalog] disk cache read failed: ${e instanceof Error?e.message:String(e)}`),null}}fetchWithTimeout(){return new Promise((e,n)=>{let r=window.setTimeout(()=>{n(new Error(`models.dev fetch timed out after ${Xvt}ms`))},Xvt);(0,Uae.requestUrl)({url:MRn,method:"GET",throw:!1}).then(o=>{window.clearTimeout(r),e(o)},o=>{window.clearTimeout(r),n(o instanceof Error?o:new Error(String(o)))})})}swapMemory(e){this.providers=Jvt(e),this.byId=new Map(this.providers.map(n=>[n.id,n]))}emit(){for(let e of this.listeners)try{e()}catch(n){H("[modelsCatalog] onChange listener threw",n)}}}});function Qvt(t){return HO(t)||NRn.includes(t)}function RRn(t){let e=LRn(t);if(e)return jl(e).slice(0,8);let n=window.crypto;if(typeof n?.getRandomValues=="function"){let r=new Uint8Array(4);return n.getRandomValues(r),Array.from(r,o=>o.toString(16).padStart(2,"0")).join("")}return jl(`${Date.now()}-${Math.random()}`).slice(0,8)}function LRn(t){let e=t.vault.adapter;if(e instanceof ewt.FileSystemAdapter)return e.getBasePath();let n=e;if(typeof n.getBasePath=="function")return n.getBasePath();if(typeof n.basePath=="string")return n.basePath}function $Rn(t,e=Hae){let n=t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),r=jl(t).slice(0,8),o=Math.max(0,e-9);return n.slice(0,o)+"-"+r}function jae(t,e){let n=`copilot-v${t}-`,r=e.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,""),o=n+r;if(o.length<=Hae)return o;let i=jl(e).slice(0,8);return o.slice(0,Hae-9)+"-"+i}function Bae(t,e,n,r){let i=`model-${r.replace(/([A-Z])/g,"-$1").toLowerCase()}`,s=`copilot-v${t}-${i}-${e}-`,a=Hae-s.length,l=$Rn(n,a);return s+l}var ewt,zae,NRn,Hae,lP,Ha,cP=b(()=>{ewt=require("obsidian");Se();WO();zae=require("obsidian");Py();pe();NRn=[];Hae=64;lP=class lP{constructor(e){this.app=e,this.vaultId=RRn(e)}static getInstance(e){if(!lP.instance){if(!e)throw new Error("KeychainService must be initialized with app on first call");lP.instance=new lP(e)}return lP.instance}static resetInstance(){lP.instance=null}isAvailable(){return!!this.app.secretStorage}getVaultId(){return this.vaultId}setVaultId(e){this.vaultId=e}get storage(){if(!this.app.secretStorage)throw new Error("OS keychain (SecretStorage) is not available.");return this.app.secretStorage}removeSecret(e){typeof this.storage.deleteSecret=="function"?this.storage.deleteSecret(e):this.storage.setSecret(e,"")}setSecretById(e,n){this.storage.setSecret(e,n)}getSecretById(e){return this.storage.getSecret(e)}deleteSecretById(e){this.removeSecret(e)}setSecret(e,n){let r=jae(this.vaultId,e);this.storage.setSecret(r,n)}deleteSecret(e){this.removeSecret(jae(this.vaultId,e))}getSecret(e){let n=jae(this.vaultId,e);return this.storage.getSecret(n)}setModelSecret(e,n,r,o){let i=Bae(this.vaultId,e,n,r);this.storage.setSecret(i,o)}getModelSecret(e,n,r){let o=Bae(this.vaultId,e,n,r);return this.storage.getSecret(o)}async hydrateFromKeychain(e){let n={...e},r=!1,o=new Set([...nie,...Object.keys(n).filter(a=>Qvt(a))]);for(let a of o){let l;try{l=this.getSecret(a)}catch(c){W(`Keychain read failed for "${a}".`,c),r=!0;continue}l===""?n[a]="":l!==null&&(n[a]=l)}let i=await this.hydrateModelSecrets("chat",n.activeModels??[]);n.activeModels=i.models,r=r||i.hadFailures;let s=await this.hydrateModelSecrets("embedding",n.activeEmbeddingModels??[]);return n.activeEmbeddingModels=s.models,r=r||s.hadFailures,r&&W("Keychain hydrate: some keychain reads failed \u2014 values left as-is."),{settings:n,hadFailures:r}}persistSecrets(e,n){let r=[],o=[];for(let s of Object.keys(e)){if(!Qvt(s))continue;let a=e[s],l=jae(this.vaultId,s);if(typeof a=="string"&&a.length>0)r.push([l,a]);else if(n){let c=n[s];typeof c=="string"&&c.length>0&&o.push(l)}}this.collectModelSecrets("chat",e.activeModels,r,n?.activeModels,o),this.collectModelSecrets("embedding",e.activeEmbeddingModels,r,n?.activeEmbeddingModels,o);let i=[...this.getDeletedModelKeysForScope("chat",n?.activeModels,e.activeModels),...this.getDeletedModelKeysForScope("embedding",n?.activeEmbeddingModels,e.activeEmbeddingModels),...o];return{secretEntries:r,keychainIdsToDelete:i}}clearAllVaultSecrets(){let e=`copilot-v${this.vaultId}-`;if(typeof this.storage.listSecrets!="function")throw new Error("Obsidian Keychain on this build does not support listing entries; cannot guarantee a complete clear.");let n=this.storage.listSecrets(),r=[];for(let o of n)if(o.startsWith(e))try{this.removeSecret(o)}catch{r.push(o)}if(r.length>0)throw new Error(`Failed to clear ${r.length} keychain entr${r.length===1?"y":"ies"}. Please retry.`)}async forgetAllSecrets(e,n){let r=Y();if(!this.isAvailable())throw new Error("Cannot delete API keys from the Obsidian Keychain because Secure Storage is unavailable in this Obsidian build. Update Obsidian to 1.11.4 or later, or open this vault on a device with Keychain access, then try again.");if(typeof this.app.secretStorage?.listSecrets!="function")throw new Error("Cannot delete all API keys because this Obsidian build does not support enumerating Keychain entries. Update Obsidian to a newer version and retry.");let o=QF(r),i=e2(o);try{await e(i)}catch(a){H("forgetAllSecrets: saveData failed \u2014 aborting keychain clear",a),new zae.Notice("Failed to remove API keys from data.json. Obsidian Keychain was NOT cleared. Please try again.");return}let s;try{this.clearAllVaultSecrets()}catch(a){s=a instanceof Error?a:new Error(String(a))}if(n(o),s)throw new zae.Notice("Some Obsidian Keychain entries could not be removed. Your keys have been cleared from data.json and memory. Please restart and retry."),s;new zae.Notice("All API keys for this vault removed. Please re-enter them.")}async hydrateModelSecrets(e,n){if(!n?.length)return{models:n,hadFailures:!1};let r=!1,o=[];for(let i of n){let s=Jn(i),a={...i};for(let l of lT){let c;try{c=this.getModelSecret(e,s,l)}catch(u){W(`Keychain read failed for model "${s}" field "${l}".`,u),r=!0;continue}c===""?a[l]="":c!==null&&(a[l]=c)}o.push(a)}return{models:o,hadFailures:r}}collectModelSecrets(e,n,r,o,i){if(!n?.length)return;let s=new Map;if(o)for(let a of o)s.set(Jn(a),a);for(let a of n){let l=Jn(a),c=s.get(l);for(let u of lT){let d=a[u],f=Bae(this.vaultId,e,l,u);if(typeof d=="string"&&d.length>0)r.push([f,d]);else if(c&&i){let p=c[u];typeof p=="string"&&p.length>0&&i.push(f)}}}}getDeletedModelKeysForScope(e,n,r){if(!n?.length)return[];let o=new Set((r??[]).map(Jn));return n.filter(i=>!o.has(Jn(i))).flatMap(i=>{let s=Jn(i);return lT.flatMap(a=>{let l=i[a];return typeof l!="string"||l.length===0?[]:[Bae(this.vaultId,e,s,a)]})})}};lP.instance=null;Ha=lP});function twt(t){let e=null;return n=>{if(e&&e.source===n)return e.value;let r=t(n);return e={source:n,value:r},r}}function U9(t){let e=new Map;return(n,r)=>{let o=e.get(r);if(o&&o.source===n)return o.value;let i=t(n,r);return e.set(r,{source:n,value:i}),i}}function AU(t,e){return t.length===0?e:Object.freeze(t.slice())}var TNe=b(()=>{});function DRn(t,e){return`copilot-v${t}-provider-${e}`}var PNe,uP,B9,Wae,Vae,qae,MU,Dw,EU,ANe,j9,ENe=b(()=>{Gf();pe();cP();Se();TNe();PNe=Object.freeze([]);j9=class{constructor(e,n){Rt(this,Dw);Rt(this,uP);Rt(this,B9);Rt(this,Wae,twt(e=>AU(Object.values(e),PNe)));Rt(this,Vae,U9((e,n)=>AU(Object.values(e).filter(r=>r.origin.kind===n),PNe)));Rt(this,qae,U9((e,n)=>AU(Object.values(e).filter(r=>r.providerType===n),PNe)));Rt(this,MU,new Set);Et(this,uP,e),Et(this,B9,n)}subscribe(e){return re(this,MU).add(e),()=>re(this,MU).delete(e)}list(){return re(this,Wae).call(this,Y().providers)}get(e){return Y().providers[e]}listByOrigin(e){return re(this,Vae).call(this,Y().providers,e)}listByProviderType(e){return re(this,qae).call(this,Y().providers,e)}async add(e){let n=Co(),r={...e,providerId:n,addedAt:Date.now(),apiKeyKeychainId:null};return En(o=>({providers:{...o.providers,[n]:r}})),Je(this,Dw,EU).call(this),n}async update(e,n){let r=Y().providers[e];if(!r)throw new Error(`[modelManagement] ProviderRegistry.update: unknown providerId ${e}`);let o={...n};delete o.providerId,delete o.addedAt,delete o.apiKeyKeychainId,delete o.providerType,delete o.origin;for(let a of Object.keys(o))Object.is(r[a],o[a])&&delete o[a];if(Object.keys(o).length===0)return;let i=Object.keys(o).some(a=>a!=="enableCors"),s={...r,...o};En(a=>({providers:{...a.providers,[e]:s}})),i&&Je(this,Dw,EU).call(this)}async remove(e){let n=Y().providers[e];if(n){if(n.apiKeyKeychainId)try{Ha.getInstance(re(this,uP)).deleteSecretById(n.apiKeyKeychainId)}catch(r){H("[modelManagement] ProviderRegistry.remove: failed to clear keychain",r)}En(r=>{let o={...r.providers};return delete o[e],{providers:o}}),Je(this,Dw,EU).call(this)}}async getApiKey(e){let n=Y().providers[e];return!n||!n.apiKeyKeychainId?null:Ha.getInstance(re(this,uP)).getSecretById(n.apiKeyKeychainId)}async setApiKey(e,n){let r=Y().providers[e];if(!r)throw new Error(`[modelManagement] ProviderRegistry.setApiKey: unknown providerId ${e}`);let o=Ha.getInstance(re(this,uP)),i=r.apiKeyKeychainId??DRn(o.getVaultId(),e);r.apiKeyKeychainId!==i&&Je(this,Dw,ANe).call(this,e,i),o.setSecretById(i,n),Je(this,Dw,EU).call(this)}async clearApiKey(e){let n=Y().providers[e];if(n&&n.apiKeyKeychainId){try{Ha.getInstance(re(this,uP)).deleteSecretById(n.apiKeyKeychainId)}catch(r){H("[modelManagement] ProviderRegistry.clearApiKey: failed to delete keychain",r)}Je(this,Dw,ANe).call(this,e,null),Je(this,Dw,EU).call(this)}}async verify(e){let n=this.get(e);if(!n)throw new Error(`[modelManagement] ProviderRegistry.verify: unknown providerId ${e}`);let r=await this.getApiKey(e);return re(this,B9).verifyCredentials(n.providerType,{provider:n,apiKey:r,extras:n.extras??{}})}};uP=new WeakMap,B9=new WeakMap,Wae=new WeakMap,Vae=new WeakMap,qae=new WeakMap,MU=new WeakMap,Dw=new WeakSet,EU=function(){for(let e of[...re(this,MU)])try{e()}catch(n){H("[modelManagement] ProviderRegistry listener threw",n)}},ANe=function(e,n){let r=Y().providers[e];r&&r.apiKeyKeychainId!==n&&En(o=>{let i=o.providers[e];return i?{providers:{...o.providers,[e]:{...i,apiKeyKeychainId:n}}}:{}})}});function z9(t){return rwt(t.baseUrl)}function rwt(t){let e=URn(t);if(!e)return!1;if(e==="localhost"||e==="0.0.0.0"||e==="::"||e==="::1"||e.endsWith(".localhost")||e.endsWith(".local")||e.endsWith(".lan")||e.endsWith(".internal")||MNe(e))return!0;let n=e.match(/^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);if(n)return MNe(n[1]);let r=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);return r?MNe(FRn(r[1],r[2])):!!(/^f[cd][0-9a-f]{2}:/.test(e)||/^fe[89ab][0-9a-f]:/.test(e))}function MNe(t){let e=t.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.\d{1,3}$/);if(!e)return!1;let n=Number(e[1]),r=Number(e[2]);return n===127||n===10||n===192&&r===168||n===172&&r>=16&&r<=31||n===169&&r===254}function FRn(t,e){let n=parseInt(t,16),r=parseInt(e,16);return`${n>>8&255}.${n&255}.${r>>8&255}.${r&255}`}function URn(t){let e=t?.trim();if(!e)return null;let n=nwt(e)??nwt(`http://${e}`);return n?n.replace(/^\[/,"").replace(/\]$/,"").toLowerCase():null}function nwt(t){try{return new URL(t).hostname||null}catch{return null}}var ONe=b(()=>{});function rx(t,e){if(!e.enableSelfHostMode)return!1;switch(t.origin.kind){case"copilot-plus":return!0;case"byok":return!z9(t);case"agent":return!1}}var H9=b(()=>{ONe()});function Fw(t){return t.requiresApiKey??!0}function W9(t){return t.origin.kind==="copilot-plus"||Fw(t)||!!t.apiKeyKeychainId}var V9=b(()=>{});function jRn(t,e){return t===e?!0:JSON.stringify(t)===JSON.stringify(e)}var owt,Kae,q9,NNe=b(()=>{Gf();Se();TNe();owt=Object.freeze([]),q9=class{constructor(){Rt(this,Kae,U9((e,n)=>AU(e.filter(r=>r.providerId===n),owt)))}list(){let e=Y().configuredModels;return e.length===0?owt:e}listByProvider(e){return re(this,Kae).call(this,Y().configuredModels,e)}get(e){return Y().configuredModels.find(n=>n.configuredModelId===e)}getByWireId(e,n){return Y().configuredModels.find(r=>r.providerId===e&&r.info.id===n)}async add(e){if(Y().configuredModels.some(i=>i.providerId===e.providerId&&i.info.id===e.info.id))throw new Error(`[modelManagement] ConfiguredModelRegistry.add: model "${e.info.id}" already configured for providerId ${e.providerId}`);let r=Co(),o={...e,configuredModelId:r,configuredAt:Date.now()};return En(i=>({configuredModels:[...i.configuredModels,o]})),r}async update(e,n){let r=Y().configuredModels.find(i=>i.configuredModelId===e);if(!r)throw new Error(`[modelManagement] ConfiguredModelRegistry.update: unknown configuredModelId ${e}`);if(!n.info)return;let o={...r,info:{...r.info,...n.info}};En(i=>({configuredModels:i.configuredModels.map(s=>s.configuredModelId===e?o:s)}))}async remove(e){En(n=>({configuredModels:n.configuredModels.filter(r=>r.configuredModelId!==e)}))}async bulkSet(e,n){let r=Y().configuredModels,o=new Map;for(let c of r)c.providerId===e&&o.set(c.info.id,c);let i=[],s=[],a=new Set,l=Date.now();for(let c of n){if(a.has(c.id))continue;a.add(c.id);let u=o.get(c.id);if(u)s.push(jRn(u.info,c)?u:{...u,info:c}),i.push(u.configuredModelId);else{let d=Co(),f={configuredModelId:d,providerId:e,info:c,configuredAt:l};s.push(f),i.push(d)}}return En(c=>({configuredModels:[...c.configuredModels.filter(u=>u.providerId!==e),...s]})),i}async removeByProvider(e){En(n=>({configuredModels:n.configuredModels.filter(r=>r.providerId!==e)}))}};Kae=new WeakMap});function HRn(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}var BRn,iwt,zRn,Z9,Y9,OU,ik,swt,K9,G9,RNe=b(()=>{pe();Se();H9();BRn=Object.freeze([]),iwt=Object.freeze({enabledModels:BRn}),zRn=Object.freeze([]);G9=class{constructor(e,n){Rt(this,ik);Rt(this,Z9);Rt(this,Y9);Rt(this,OU,new Set);Et(this,Z9,e),Et(this,Y9,n)}subscribe(e){return re(this,OU).add(e),()=>re(this,OU).delete(e)}get(e){return Y().backends[e]??iwt}resolveEnabled(e){let n=Y(),r=n.backends[e]??iwt;return r.enabledModels.length===0?zRn:r.enabledModels.map(o=>{let i=re(this,Y9).get(o),s=i?re(this,Z9).get(i.providerId):void 0;if(i&&s){let a=n.enableSelfHostMode&&rx(s,n);return{configuredModelId:o,state:"ok",configuredModel:i,provider:s,needsSelfHostWarning:a}}return{configuredModelId:o,state:"broken"}})}async setEnabledModels(e,n){Je(this,ik,K9).call(this,()=>{En(r=>{let o=r.backends[e],i=[...n];if(o&&HRn(o.enabledModels,i))return{};let s={enabledModels:i};return{backends:{...r.backends,[e]:s}}})})}async enableModel(e,n){Y().backends[e]?.enabledModels.includes(n)||Je(this,ik,K9).call(this,()=>{En(o=>{let i=o.backends[e];if(i?.enabledModels.includes(n))return{};let s={enabledModels:[...i?.enabledModels??[],n]};return{backends:{...o.backends,[e]:s}}})})}async disableModel(e,n){let r=Y().backends[e];!r||!r.enabledModels.includes(n)||Je(this,ik,K9).call(this,()=>{En(o=>{let i=o.backends[e];if(!i)return{};let a={enabledModels:i.enabledModels.filter(l=>l!==n)};return{backends:{...o.backends,[e]:a}}})})}async removeRefs(e){if(e.length===0)return;let n=new Set(e);Je(this,ik,K9).call(this,()=>{En(r=>{let o=!1,i={...r.backends};for(let[s,a]of Object.entries(r.backends))a.enabledModels.some(l=>n.has(l))&&(i[s]={enabledModels:a.enabledModels.filter(l=>!n.has(l))},o=!0);return o?{backends:i}:{}})})}};Z9=new WeakMap,Y9=new WeakMap,OU=new WeakMap,ik=new WeakSet,swt=function(){for(let e of[...re(this,OU)])try{e()}catch(n){H("[modelManagement] BackendConfigRegistry listener threw",n)}},K9=function(e){let n=Y().backends;e(),Y().backends!==n&&Je(this,ik,swt).call(this)}});var J9,LNe=b(()=>{J9=class{constructor(e,n,r){}build(e){throw new Error("[modelManagement] ChatModelFactory.build not implemented yet")}buildFor(e,n){throw new Error("[modelManagement] ChatModelFactory.buildFor not implemented yet")}}});function awt(t){return(t??"").trim().replace(/\/+$/,"").toLowerCase()}function NU(t){if(t.origin.kind==="copilot-plus")return"copilot-plus";switch(t.providerType){case"anthropic":return"anthropic";case"google":return"google";case"azure":return"azure openai";case"openai-compatible":{let e=t.origin.kind==="byok"?t.origin.catalogProviderId:void 0;return e==="xai"&&t.baseUrl&&awt(t.baseUrl)!==awt(Qp.xai.host)?"3rd party (openai-format)":(e?$Ne[e]:void 0)??"3rd party (openai-format)"}default:{let e=t.providerType;return W(`[chatBridge] unknown providerType "${String(e)}"; defaulting to OpenAI-format`),"3rd party (openai-format)"}}}function Gae(t,e){let n=t[e];return typeof n=="string"&&n.length>0?n:void 0}function X9(t){let{provider:e,configuredModel:n,apiKey:r}=t,o=n.info,i=e.extras??{},s=r&&r.length>0?r:void 0,a=W9(e)||!!s,l=NU(e),c=l==="anthropic"&&o.limits?.output?_ct:void 0,u=[];return o.reasoning&&u.push("reasoning"),o.modalities?.input?.includes("image")&&u.push("vision"),{configuredModelId:n.configuredModelId,name:o.id,provider:l,displayName:o.displayName,enabled:!0,baseUrl:e.baseUrl,apiKey:s,requiresApiKey:a,enableCors:e.enableCors,capabilities:u,maxTokens:c,openAIOrgId:Gae(i,"openAIOrgId"),azureOpenAIApiInstanceName:Gae(i,"azureInstanceName"),azureOpenAIApiDeploymentName:Gae(i,"azureDeploymentName"),azureOpenAIApiVersion:Gae(i,"azureApiVersion")}}var $Ne,Zae=b(()=>{gt();pe();V9();$Ne={openai:"openai",groq:"groq",mistral:"mistralai",openrouter:"openrouterai",deepseek:"deepseek",xai:"xai",cohere:"cohereai",siliconflow:"siliconflow",anthropic:"anthropic",google:"google"}});function VRn(t){let e=new Set([NU(t.provider)]);if(t.provider.origin.kind==="copilot-plus"&&e.add("copilot-plus"),t.provider.origin.kind==="byok"&&t.provider.origin.catalogProviderId){let r=$Ne[t.provider.origin.catalogProviderId];r&&e.add(r)}let n=WRn[t.provider.displayName.toLowerCase()];return n&&e.add(n),[...e].map(r=>`${t.configuredModel.info.id}|${r}`)}function Yae(t,e){return t.configuredModelId===e||VRn(t).includes(e)}function RU(t,e){let n=t.filter(r=>r.state==="ok");return e?n.find(r=>Yae(r,e))??n[0]:n[0]}function Q9(t,e){return RU(t,e)?.configuredModelId}var WRn,DNe=b(()=>{gt();Zae();WRn={ollama:"ollama","lm studio":"lm-studio","openai format":"3rd party (openai-format)",cohere:"cohereai",siliconflow:"siliconflow"}});async function FNe(t,e){let n=t.backendConfigRegistry.resolveEnabled("chat"),r=RU(n,e);if(!r)return{ok:!1,reason:"empty"};e&&!Yae(r,e)&&W(`[chatBridge] chat model "${e}" is not enabled; falling back to configuredModelId="${r.configuredModelId}"`);let o=await t.providerRegistry.getApiKey(r.provider.providerId),i=X9({provider:r.provider,configuredModel:r.configuredModel,apiKey:o});return{ok:!0,configuredModelId:r.configuredModelId,customModel:i}}var lwt=b(()=>{pe();DNe();Zae()});function cwt(t){let e=!!t.reasoning,n=!!t.modalities?.input?.includes(qRn);if(!e&&!n)return KRn;let r=[];return e&&r.push("reasoning"),n&&r.push("vision"),r}function Uw(t){return t.modalities?cwt(t):void 0}var qRn,KRn,UNe=b(()=>{gt();qRn="image",KRn=Object.freeze([])});function ve(t,e,n){function r(a,l){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,l);let c=s.prototype,u=Object.keys(c);for(let d=0;d<u.length;d++){let f=u[d];f in a||(a[f]=c[f].bind(a))}}let o=n?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:t});function s(a){var l;let c=n?.Parent?new i:this;r(c,a),(l=c._zod).deferred??(l.deferred=[]);for(let u of c._zod.deferred)u();return c}return Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(s,"name",{value:t}),s}function Wa(t){return t&&Object.assign(ON,t),ON}var uwt,jNe,BNe,jw,dP,ON,NN=b(()=>{jNe=Object.freeze({status:"aborted"});BNe=Symbol("zod_brand"),jw=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},dP=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(uwt=globalThis).__zod_globalConfig??(uwt.__zod_globalConfig={});ON=globalThis.__zod_globalConfig});var nt={};sr(nt,{BIGINT_FORMAT_RANGES:()=>JNe,Class:()=>HNe,NUMBER_FORMAT_RANGES:()=>YNe,aborted:()=>hP,allowsEval:()=>qNe,assert:()=>XRn,assertEqual:()=>GRn,assertIs:()=>YRn,assertNever:()=>JRn,assertNotEqual:()=>ZRn,assignProp:()=>pP,base64ToUint8Array:()=>fwt,base64urlToUint8Array:()=>hLn,cached:()=>$U,captureStackTrace:()=>Xae,cleanEnum:()=>mLn,cleanRegex:()=>n8,clone:()=>Va,cloneDef:()=>eLn,createTransparentProxy:()=>sLn,defineLazy:()=>lo,esc:()=>Jae,escapeRegex:()=>Ay,explicitlyAborted:()=>XNe,extend:()=>cLn,finalizeIssue:()=>op,floatSafeRemainder:()=>WNe,getElementAtPath:()=>tLn,getEnumValues:()=>t8,getLengthableOrigin:()=>i8,getParsedType:()=>iLn,getSizableOrigin:()=>o8,hexToUint8Array:()=>yLn,isObject:()=>RN,isPlainObject:()=>mP,issue:()=>DU,joinValues:()=>Ce,jsonStringifyReplacer:()=>LU,merge:()=>dLn,mergeDefs:()=>sk,normalizeParams:()=>ft,nullish:()=>fP,numKeys:()=>oLn,objectClone:()=>QRn,omit:()=>lLn,optionalKeys:()=>ZNe,parsedType:()=>Qe,partial:()=>fLn,pick:()=>aLn,prefixIssues:()=>cm,primitiveTypes:()=>GNe,promiseAllObject:()=>nLn,propertyKeyTypes:()=>r8,randomString:()=>rLn,required:()=>pLn,safeExtend:()=>uLn,shallowClone:()=>KNe,slugify:()=>VNe,stringifyPrimitive:()=>Xe,uint8ArrayToBase64:()=>pwt,uint8ArrayToBase64url:()=>gLn,uint8ArrayToHex:()=>vLn,unwrapMessage:()=>e8});function GRn(t){return t}function ZRn(t){return t}function YRn(t){}function JRn(t){throw new Error("Unexpected value in exhaustive check")}function XRn(t){}function t8(t){let e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,o])=>e.indexOf(+r)===-1).map(([r,o])=>o)}function Ce(t,e="|"){return t.map(n=>Xe(n)).join(e)}function LU(t,e){return typeof e=="bigint"?e.toString():e}function $U(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function fP(t){return t==null}function n8(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function WNe(t,e){let n=t/e,r=Math.round(n),o=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<o?0:n-r}function lo(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==dwt)return r===void 0&&(r=dwt,r=n()),r},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function QRn(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function pP(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function sk(...t){let e={};for(let n of t){let r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}function eLn(t){return sk(t._zod.def)}function tLn(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function nLn(t){let e=Object.keys(t),n=e.map(r=>t[r]);return Promise.all(n).then(r=>{let o={};for(let i=0;i<e.length;i++)o[e[i]]=r[i];return o})}function rLn(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<t;r++)n+=e[Math.floor(Math.random()*e.length)];return n}function Jae(t){return JSON.stringify(t)}function VNe(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function RN(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function mP(t){if(RN(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let n=e.prototype;return!(RN(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function KNe(t){return mP(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function oLn(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}function Ay(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Va(t,e,n){let r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function ft(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function sLn(t){let e;return new Proxy({},{get(n,r,o){return e??(e=t()),Reflect.get(e,r,o)},set(n,r,o,i){return e??(e=t()),Reflect.set(e,r,o,i)},has(n,r){return e??(e=t()),Reflect.has(e,r)},deleteProperty(n,r){return e??(e=t()),Reflect.deleteProperty(e,r)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,r){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,r)},defineProperty(n,r,o){return e??(e=t()),Reflect.defineProperty(e,r,o)}})}function Xe(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function ZNe(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function aLn(t,e){let n=t._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i=sk(t._zod.def,{get shape(){let s={};for(let a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(s[a]=n.shape[a])}return pP(this,"shape",s),s},checks:[]});return Va(t,i)}function lLn(t,e){let n=t._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=sk(t._zod.def,{get shape(){let s={...t._zod.def.shape};for(let a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete s[a]}return pP(this,"shape",s),s},checks:[]});return Va(t,i)}function cLn(t,e){if(!mP(e))throw new Error("Invalid input to extend: expected a plain object");let n=t._zod.def.checks;if(n&&n.length>0){let i=t._zod.def.shape;for(let s in e)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=sk(t._zod.def,{get shape(){let i={...t._zod.def.shape,...e};return pP(this,"shape",i),i}});return Va(t,o)}function uLn(t,e){if(!mP(e))throw new Error("Invalid input to safeExtend: expected a plain object");let n=sk(t._zod.def,{get shape(){let r={...t._zod.def.shape,...e};return pP(this,"shape",r),r}});return Va(t,n)}function dLn(t,e){if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=sk(t._zod.def,{get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return pP(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return Va(t,n)}function fLn(t,e,n){let o=e._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=sk(e._zod.def,{get shape(){let a=e._zod.def.shape,l={...a};if(n)for(let c in n){if(!(c in a))throw new Error(`Unrecognized key: "${c}"`);n[c]&&(l[c]=t?new t({type:"optional",innerType:a[c]}):a[c])}else for(let c in a)l[c]=t?new t({type:"optional",innerType:a[c]}):a[c];return pP(this,"shape",l),l},checks:[]});return Va(e,s)}function pLn(t,e,n){let r=sk(e._zod.def,{get shape(){let o=e._zod.def.shape,i={...o};if(n)for(let s in n){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(i[s]=new t({type:"nonoptional",innerType:o[s]}))}else for(let s in o)i[s]=new t({type:"nonoptional",innerType:o[s]});return pP(this,"shape",i),i}});return Va(e,r)}function hP(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function XNe(t,e=0){if(t.aborted===!0)return!0;for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue===!1)return!0;return!1}function cm(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function e8(t){return typeof t=="string"?t:t?.message}function op(t,e,n){let r=t.message?t.message:e8(t.inst?._zod.def?.error?.(t))??e8(e?.error?.(t))??e8(n.customError?.(t))??e8(n.localeError?.(t))??"Invalid input",{inst:o,continue:i,input:s,...a}=t;return a.path??(a.path=[]),a.message=r,e?.reportInput&&(a.input=s),a}function o8(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function i8(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Qe(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let n=t;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return e}function DU(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function mLn(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function fwt(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function pwt(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e)}function hLn(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-e.length%4)%4);return fwt(e+n)}function gLn(t){return pwt(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function yLn(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let n=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)n[r/2]=Number.parseInt(e.slice(r,r+2),16);return n}function vLn(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var dwt,Xae,qNe,iLn,r8,GNe,YNe,JNe,HNe,wn=b(()=>{NN();dwt=Symbol("evaluating");Xae="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};qNe=$U(()=>{if(ON.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});iLn=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},r8=new Set(["string","number","symbol"]),GNe=new Set(["string","number","bigint","boolean","symbol","undefined"]);YNe={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},JNe={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};HNe=class{constructor(...e){}}});function a8(t,e=n=>n.message){let n={},r=[];for(let o of t.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:n}}function l8(t,e=n=>n.message){let n={_errors:[]},r=(o,i=[])=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>r({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")r({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")r({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)n._errors.push(e(s));else{let l=n,c=0;for(;c<a.length;){let u=a[c];c===a.length-1?(l[u]=l[u]||{_errors:[]},l[u]._errors.push(e(s))):l[u]=l[u]||{_errors:[]},l=l[u],c++}}}};return r(t),n}function QNe(t,e=n=>n.message){let n={errors:[]},r=(o,i=[])=>{var s,a;for(let l of o.issues)if(l.code==="invalid_union"&&l.errors.length)l.errors.map(c=>r({issues:c},[...i,...l.path]));else if(l.code==="invalid_key")r({issues:l.issues},[...i,...l.path]);else if(l.code==="invalid_element")r({issues:l.issues},[...i,...l.path]);else{let c=[...i,...l.path];if(c.length===0){n.errors.push(e(l));continue}let u=n,d=0;for(;d<c.length;){let f=c[d],p=d===c.length-1;typeof f=="string"?(u.properties??(u.properties={}),(s=u.properties)[f]??(s[f]={errors:[]}),u=u.properties[f]):(u.items??(u.items=[]),(a=u.items)[f]??(a[f]={errors:[]}),u=u.items[f]),p&&u.errors.push(e(l)),d++}}};return r(t),n}function hwt(t){let e=[],n=t.map(r=>typeof r=="object"?r.key:r);for(let r of n)typeof r=="number"?e.push(`[${r}]`):typeof r=="symbol"?e.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?e.push(`[${JSON.stringify(r)}]`):(e.length&&e.push("."),e.push(r));return e.join("")}function eRe(t){let e=[],n=[...t.issues].sort((r,o)=>(r.path??[]).length-(o.path??[]).length);for(let r of n)e.push(`\u2716 ${r.message}`),r.path?.length&&e.push(` \u2192 at ${hwt(r.path)}`);return e.join(`
`)}var mwt,s8,um,tRe=b(()=>{NN();wn();mwt=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,LU,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},s8=ve("$ZodError",mwt),um=ve("$ZodError",mwt,{Parent:Error})});var FU,LN,UU,$N,jU,nRe,BU,rRe,Qae,bLn,ele,_Ln,tle,xLn,nle,SLn,rle,CLn,ole,kLn,ile,ILn,sle,TLn,oRe=b(()=>{NN();tRe();wn();FU=t=>(e,n,r,o)=>{let i=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new jw;if(s.issues.length){let a=new(o?.Err??t)(s.issues.map(l=>op(l,i,Wa())));throw Xae(a,o?.callee),a}return s.value},LN=FU(um),UU=t=>async(e,n,r,o)=>{let i=r?{...r,async:!0}:{async:!0},s=e._zod.run({value:n,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??t)(s.issues.map(l=>op(l,i,Wa())));throw Xae(a,o?.callee),a}return s.value},$N=UU(um),jU=t=>(e,n,r)=>{let o=r?{...r,async:!1}:{async:!1},i=e._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new jw;return i.issues.length?{success:!1,error:new(t??s8)(i.issues.map(s=>op(s,o,Wa())))}:{success:!0,data:i.value}},nRe=jU(um),BU=t=>async(e,n,r)=>{let o=r?{...r,async:!0}:{async:!0},i=e._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new t(i.issues.map(s=>op(s,o,Wa())))}:{success:!0,data:i.value}},rRe=BU(um),Qae=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return FU(t)(e,n,o)},bLn=Qae(um),ele=t=>(e,n,r)=>FU(t)(e,n,r),_Ln=ele(um),tle=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return UU(t)(e,n,o)},xLn=tle(um),nle=t=>async(e,n,r)=>UU(t)(e,n,r),SLn=nle(um),rle=t=>(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return jU(t)(e,n,o)},CLn=rle(um),ole=t=>(e,n,r)=>jU(t)(e,n,r),kLn=ole(um),ile=t=>async(e,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return BU(t)(e,n,o)},ILn=ile(um),sle=t=>async(e,n,r)=>BU(t)(e,n,r),TLn=sle(um)});var Nh={};sr(Nh,{base64:()=>bRe,base64url:()=>ale,bigint:()=>TRe,boolean:()=>ARe,browserEmail:()=>LLn,cidrv4:()=>vRe,cidrv6:()=>wRe,cuid:()=>iRe,cuid2:()=>sRe,date:()=>SRe,datetime:()=>kRe,domain:()=>FLn,duration:()=>dRe,e164:()=>xRe,email:()=>pRe,emoji:()=>mRe,extendedDuration:()=>PLn,guid:()=>fRe,hex:()=>ULn,hostname:()=>DLn,html5Email:()=>OLn,httpProtocol:()=>_Re,idnEmail:()=>RLn,integer:()=>PRe,ipv4:()=>hRe,ipv6:()=>gRe,ksuid:()=>cRe,lowercase:()=>ORe,mac:()=>yRe,md5_base64:()=>BLn,md5_base64url:()=>zLn,md5_hex:()=>jLn,nanoid:()=>uRe,null:()=>ERe,number:()=>lle,rfc5322Email:()=>NLn,sha1_base64:()=>WLn,sha1_base64url:()=>VLn,sha1_hex:()=>HLn,sha256_base64:()=>KLn,sha256_base64url:()=>GLn,sha256_hex:()=>qLn,sha384_base64:()=>YLn,sha384_base64url:()=>JLn,sha384_hex:()=>ZLn,sha512_base64:()=>QLn,sha512_base64url:()=>e1n,sha512_hex:()=>XLn,string:()=>IRe,time:()=>CRe,ulid:()=>aRe,undefined:()=>MRe,unicodeEmail:()=>gwt,uppercase:()=>NRe,uuid:()=>DN,uuid4:()=>ALn,uuid6:()=>ELn,uuid7:()=>MLn,xid:()=>lRe});function mRe(){return new RegExp($Ln,"u")}function vwt(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function CRe(t){return new RegExp(`^${vwt(t)}$`)}function kRe(t){let e=vwt({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${e}(?:${n.join("|")})`;return new RegExp(`^${ywt}T(?:${r})$`)}function c8(t,e){return new RegExp(`^[A-Za-z0-9+/]{${t}}${e}$`)}function u8(t){return new RegExp(`^[A-Za-z0-9_-]{${t}}$`)}var iRe,sRe,aRe,lRe,cRe,uRe,dRe,PLn,fRe,DN,ALn,ELn,MLn,pRe,OLn,NLn,gwt,RLn,LLn,$Ln,hRe,gRe,yRe,vRe,wRe,bRe,ale,DLn,FLn,_Re,xRe,ywt,SRe,IRe,TRe,PRe,lle,ARe,ERe,MRe,ORe,NRe,ULn,jLn,BLn,zLn,HLn,WLn,VLn,qLn,KLn,GLn,ZLn,YLn,JLn,XLn,QLn,e1n,cle=b(()=>{wn();iRe=/^[cC][0-9a-z]{6,}$/,sRe=/^[0-9a-z]+$/,aRe=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,lRe=/^[0-9a-vA-V]{20}$/,cRe=/^[A-Za-z0-9]{27}$/,uRe=/^[a-zA-Z0-9_-]{21}$/,dRe=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,PLn=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,fRe=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,DN=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,ALn=DN(4),ELn=DN(6),MLn=DN(7),pRe=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,OLn=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,NLn=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,gwt=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,RLn=gwt,LLn=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,$Ln="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";hRe=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,gRe=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,yRe=t=>{let e=Ay(t??":");return new RegExp(`^(?:[0-9A-F]{2}${e}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${e}){5}[0-9a-f]{2}$`)},vRe=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,wRe=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,bRe=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ale=/^[A-Za-z0-9_-]*$/,DLn=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,FLn=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,_Re=/^https?$/,xRe=/^\+[1-9]\d{6,14}$/,ywt="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",SRe=new RegExp(`^${ywt}$`);IRe=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},TRe=/^-?\d+n?$/,PRe=/^-?\d+$/,lle=/^-?\d+(?:\.\d+)?$/,ARe=/^(?:true|false)$/i,ERe=/^null$/i,MRe=/^undefined$/i,ORe=/^[^A-Z]*$/,NRe=/^[^a-z]*$/,ULn=/^[0-9a-fA-F]*$/;jLn=/^[0-9a-fA-F]{32}$/,BLn=c8(22,"=="),zLn=u8(22),HLn=/^[0-9a-fA-F]{40}$/,WLn=c8(27,"="),VLn=u8(27),qLn=/^[0-9a-fA-F]{64}$/,KLn=c8(43,"="),GLn=u8(43),ZLn=/^[0-9a-fA-F]{96}$/,YLn=c8(64,""),JLn=u8(64),XLn=/^[0-9a-fA-F]{128}$/,QLn=c8(86,"=="),e1n=u8(86)});function wwt(t,e,n){t.issues.length&&e.issues.push(...cm(n,t.issues))}var ds,bwt,ule,dle,RRe,LRe,$Re,DRe,FRe,URe,jRe,BRe,zRe,zU,HRe,WRe,VRe,qRe,KRe,GRe,ZRe,YRe,JRe,fle=b(()=>{NN();cle();wn();ds=ve("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),bwt={number:"number",bigint:"bigint",object:"date"},ule=ve("$ZodCheckLessThan",(t,e)=>{ds.init(t,e);let n=bwt[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,i=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<i&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),dle=ve("$ZodCheckGreaterThan",(t,e)=>{ds.init(t,e);let n=bwt[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,i=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>i&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),RRe=ve("$ZodCheckMultipleOf",(t,e)=>{ds.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):WNe(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),LRe=ve("$ZodCheckNumberFormat",(t,e)=>{ds.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[o,i]=YNe[e.format];t._zod.onattach.push(s=>{let a=s._zod.bag;a.format=e.format,a.minimum=o,a.maximum=i,n&&(a.pattern=PRe)}),t._zod.check=s=>{let a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:r,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,inclusive:!0,continue:!e.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,inclusive:!0,continue:!e.abort});return}}a<o&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:t,continue:!e.abort})}}),$Re=ve("$ZodCheckBigIntFormat",(t,e)=>{ds.init(t,e);let[n,r]=JNe[e.format];t._zod.onattach.push(o=>{let i=o._zod.bag;i.format=e.format,i.minimum=n,i.maximum=r}),t._zod.check=o=>{let i=o.value;i<n&&o.issues.push({origin:"bigint",input:i,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!e.abort}),i>r&&o.issues.push({origin:"bigint",input:i,code:"too_big",maximum:r,inclusive:!0,inst:t,continue:!e.abort})}}),DRe=ve("$ZodCheckMaxSize",(t,e)=>{var n;ds.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!fP(o)&&o.size!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let o=r.value;o.size<=e.maximum||r.issues.push({origin:o8(o),code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),FRe=ve("$ZodCheckMinSize",(t,e)=>{var n;ds.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!fP(o)&&o.size!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let o=r.value;o.size>=e.minimum||r.issues.push({origin:o8(o),code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),URe=ve("$ZodCheckSizeEquals",(t,e)=>{var n;ds.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!fP(o)&&o.size!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag;o.minimum=e.size,o.maximum=e.size,o.size=e.size}),t._zod.check=r=>{let o=r.value,i=o.size;if(i===e.size)return;let s=i>e.size;r.issues.push({origin:o8(o),...s?{code:"too_big",maximum:e.size}:{code:"too_small",minimum:e.size},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),jRe=ve("$ZodCheckMaxLength",(t,e)=>{var n;ds.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!fP(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let o=r.value;if(o.length<=e.maximum)return;let s=i8(o);r.issues.push({origin:s,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),BRe=ve("$ZodCheckMinLength",(t,e)=>{var n;ds.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!fP(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let o=r.value;if(o.length>=e.minimum)return;let s=i8(o);r.issues.push({origin:s,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),zRe=ve("$ZodCheckLengthEquals",(t,e)=>{var n;ds.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!fP(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=r=>{let o=r.value,i=o.length;if(i===e.length)return;let s=i8(o),a=i>e.length;r.issues.push({origin:s,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),zU=ve("$ZodCheckStringFormat",(t,e)=>{var n,r;ds.init(t,e),t._zod.onattach.push(o=>{let i=o._zod.bag;i.format=e.format,e.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),HRe=ve("$ZodCheckRegex",(t,e)=>{zU.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),WRe=ve("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=ORe),zU.init(t,e)}),VRe=ve("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=NRe),zU.init(t,e)}),qRe=ve("$ZodCheckIncludes",(t,e)=>{ds.init(t,e);let n=Ay(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),KRe=ve("$ZodCheckStartsWith",(t,e)=>{ds.init(t,e);let n=new RegExp(`^${Ay(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),GRe=ve("$ZodCheckEndsWith",(t,e)=>{ds.init(t,e);let n=new RegExp(`.*${Ay(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}});ZRe=ve("$ZodCheckProperty",(t,e)=>{ds.init(t,e),t._zod.check=n=>{let r=e.schema._zod.run({value:n.value[e.property],issues:[]},{});if(r instanceof Promise)return r.then(o=>wwt(o,n,e.property));wwt(r,n,e.property)}}),YRe=ve("$ZodCheckMimeType",(t,e)=>{ds.init(t,e);let n=new Set(e.mime);t._zod.onattach.push(r=>{r._zod.bag.mime=e.mime}),t._zod.check=r=>{n.has(r.value.type)||r.issues.push({code:"invalid_value",values:e.mime,input:r.value.type,inst:t,continue:!e.abort})}}),JRe=ve("$ZodCheckOverwrite",(t,e)=>{ds.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}})});var d8,XRe=b(()=>{d8=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
`).filter(s=>s),o=Math.min(...r.map(s=>s.length-s.trimStart().length)),i=r.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let e=Function,n=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new e(...n,o.join(`
`))}}});var QRe,eLe=b(()=>{QRe={major:4,minor:4,patch:3}});function xLe(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function $wt(t){if(!ale.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return xLe(n)}function Dwt(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function xwt(t,e,n){t.issues.length&&e.issues.push(...cm(n,t.issues)),e.value[n]=t.value}function gle(t,e,n,r,o,i){let s=n in r;if(t.issues.length){if(o&&i&&!s)return;e.issues.push(...cm(n,t.issues))}if(!s&&!o){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}t.value===void 0?s&&(e.value[n]=void 0):e.value[n]=t.value}function Fwt(t){let e=Object.keys(t.shape);for(let r of e)if(!t.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);let n=ZNe(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function Uwt(t,e,n,r,o,i){let s=[],a=o.keySet,l=o.catchall._zod,c=l.def.type,u=l.optin==="optional",d=l.optout==="optional";for(let f in e){if(f==="__proto__"||a.has(f))continue;if(c==="never"){s.push(f);continue}let p=l.run({value:e[f],issues:[]},r);p instanceof Promise?t.push(p.then(m=>gle(m,n,f,e,u,d))):gle(p,n,f,e,u,d)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:e,inst:i}),t.length?Promise.all(t).then(()=>n):n}function Swt(t,e,n,r){for(let i of t)if(i.issues.length===0)return e.value=i.value,e;let o=t.filter(i=>!hP(i));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(i=>i.issues.map(s=>op(s,r,Wa())))}),e)}function Cwt(t,e,n,r){let o=t.filter(i=>i.issues.length===0);return o.length===1?(e.value=o[0].value,e):(o.length===0?e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(i=>i.issues.map(s=>op(s,r,Wa())))}):e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:[],inclusive:!1}),e)}function tLe(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(mP(t)&&mP(e)){let n=Object.keys(e),r=Object.keys(t).filter(i=>n.indexOf(i)!==-1),o={...t,...e};for(let i of r){let s=tLe(t[i],e[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<t.length;r++){let o=t[r],i=e[r],s=tLe(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function kwt(t,e,n){let r=new Map,o;for(let a of e.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(let l of a.keys)r.has(l)||r.set(l,{}),r.get(l).l=!0}else t.issues.push(a);for(let a of n.issues)if(a.code==="unrecognized_keys")for(let l of a.keys)r.has(l)||r.set(l,{}),r.get(l).r=!0;else t.issues.push(a);let i=[...r].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&o&&t.issues.push({...o,keys:i}),hP(t))return t;let s=tLe(e.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return t.value=s.data,t}function Iwt(t,e){for(let n=t.length-1;n>=0;n--)if(t[n]._zod[e]!=="optional")return n+1;return 0}function Twt(t,e,n){t.issues.length&&e.issues.push(...cm(n,t.issues)),e.value[n]=t.value}function Pwt(t,e,n,r,o){for(let i=0;i<n.length;i++){let s=t[i],a=i<r.length;if(s.issues.length){if(!a&&i>=o){e.value.length=i;break}e.issues.push(...cm(i,s.issues))}e.value[i]=s.value}for(let i=e.value.length-1;i>=r.length&&(n[i]._zod.optout==="optional"&&e.value[i]===void 0);i--)e.value.length=i;return e}function Awt(t,e,n,r,o,i,s){t.issues.length&&(r8.has(typeof r)?n.issues.push(...cm(r,t.issues)):n.issues.push({code:"invalid_key",origin:"map",input:o,inst:i,issues:t.issues.map(a=>op(a,s,Wa()))})),e.issues.length&&(r8.has(typeof r)?n.issues.push(...cm(r,e.issues)):n.issues.push({origin:"map",code:"invalid_element",input:o,inst:i,key:r,issues:e.issues.map(a=>op(a,s,Wa()))})),n.value.set(t.value,e.value)}function Ewt(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}function Mwt(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}function Owt(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function Nwt(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function ple(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},n)}function mle(t,e,n){if(t.issues.length)return t.aborted=!0,t;if((n.direction||"forward")==="forward"){let o=e.transform(t.value,t);return o instanceof Promise?o.then(i=>hle(t,i,e.out,n)):hle(t,o,e.out,n)}else{let o=e.reverseTransform(t.value,t);return o instanceof Promise?o.then(i=>hle(t,i,e.in,n)):hle(t,o,e.in,n)}}function hle(t,e,n,r){return t.issues.length?(t.aborted=!0,t):n._zod.run({value:e,issues:t.issues},r)}function Rwt(t){return t.value=Object.freeze(t.value),t}function Lwt(t,e,n,r){if(!t){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),e.issues.push(DU(o))}}var kr,FN,ts,nLe,rLe,oLe,iLe,sLe,aLe,lLe,cLe,uLe,dLe,fLe,pLe,mLe,hLe,gLe,yLe,vLe,wLe,bLe,_Le,SLe,CLe,kLe,ILe,TLe,yle,PLe,f8,vle,ALe,ELe,MLe,OLe,NLe,wle,p8,RLe,LLe,$Le,jwt,DLe,m8,FLe,ULe,jLe,ble,BLe,zLe,HLe,WLe,VLe,qLe,KLe,h8,GLe,ZLe,YLe,JLe,XLe,QLe,e1e,t1e,_le,g8,n1e,r1e,o1e,i1e,s1e,a1e,l1e,c1e=b(()=>{fle();NN();XRe();oRe();cle();wn();eLe();wn();kr=ve("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=QRe;let r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(let o of r)for(let i of o._zod.onattach)i(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,a,l)=>{let c=hP(s),u;for(let d of a){if(d._zod.def.when){if(XNe(s)||!d._zod.def.when(s))continue}else if(c)continue;let f=s.issues.length,p=d._zod.check(s);if(p instanceof Promise&&l?.async===!1)throw new jw;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==f&&(c||(c=hP(s,f)))});else{if(s.issues.length===f)continue;c||(c=hP(s,f))}}return u?u.then(()=>s):s},i=(s,a,l)=>{if(hP(s))return s.aborted=!0,s;let c=o(a,r,l);if(c instanceof Promise){if(l.async===!1)throw new jw;return c.then(u=>t._zod.parse(u,l))}return t._zod.parse(c,l)};t._zod.run=(s,a)=>{if(a.skipChecks)return t._zod.parse(s,a);if(a.direction==="backward"){let c=t._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return c instanceof Promise?c.then(u=>i(u,s,a)):i(c,s,a)}let l=t._zod.parse(s,a);if(l instanceof Promise){if(a.async===!1)throw new jw;return l.then(c=>o(c,r,a))}return o(l,r,a)}}lo(t,"~standard",()=>({validate:o=>{try{let i=nRe(t,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return rRe(t,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),FN=ve("$ZodString",(t,e)=>{kr.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??IRe(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),ts=ve("$ZodStringFormat",(t,e)=>{zU.init(t,e),FN.init(t,e)}),nLe=ve("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=fRe),ts.init(t,e)}),rLe=ve("$ZodUUID",(t,e)=>{if(e.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=DN(r))}else e.pattern??(e.pattern=DN());ts.init(t,e)}),oLe=ve("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=pRe),ts.init(t,e)}),iLe=ve("$ZodURL",(t,e)=>{ts.init(t,e),t._zod.check=n=>{try{let r=n.value.trim();if(!e.normalize&&e.protocol?.source===_Re.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:t,continue:!e.abort});return}let o=new URL(r);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),e.normalize?n.value=o.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),sLe=ve("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=mRe()),ts.init(t,e)}),aLe=ve("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=uRe),ts.init(t,e)}),lLe=ve("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=iRe),ts.init(t,e)}),cLe=ve("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=sRe),ts.init(t,e)}),uLe=ve("$ZodULID",(t,e)=>{e.pattern??(e.pattern=aRe),ts.init(t,e)}),dLe=ve("$ZodXID",(t,e)=>{e.pattern??(e.pattern=lRe),ts.init(t,e)}),fLe=ve("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=cRe),ts.init(t,e)}),pLe=ve("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=kRe(e)),ts.init(t,e)}),mLe=ve("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=SRe),ts.init(t,e)}),hLe=ve("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=CRe(e)),ts.init(t,e)}),gLe=ve("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=dRe),ts.init(t,e)}),yLe=ve("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=hRe),ts.init(t,e),t._zod.bag.format="ipv4"}),vLe=ve("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=gRe),ts.init(t,e),t._zod.bag.format="ipv6",t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),wLe=ve("$ZodMAC",(t,e)=>{e.pattern??(e.pattern=yRe(e.delimiter)),ts.init(t,e),t._zod.bag.format="mac"}),bLe=ve("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=vRe),ts.init(t,e)}),_Le=ve("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=wRe),ts.init(t,e),t._zod.check=n=>{let r=n.value.split("/");try{if(r.length!==2)throw new Error;let[o,i]=r;if(!i)throw new Error;let s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${o}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});SLe=ve("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=bRe),ts.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{xLe(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});CLe=ve("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=ale),ts.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{$wt(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),kLe=ve("$ZodE164",(t,e)=>{e.pattern??(e.pattern=xRe),ts.init(t,e)});ILe=ve("$ZodJWT",(t,e)=>{ts.init(t,e),t._zod.check=n=>{Dwt(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),TLe=ve("$ZodCustomStringFormat",(t,e)=>{ts.init(t,e),t._zod.check=n=>{e.fn(n.value)||n.issues.push({code:"invalid_format",format:e.format,input:n.value,inst:t,continue:!e.abort})}}),yle=ve("$ZodNumber",(t,e)=>{kr.init(t,e),t._zod.pattern=t._zod.bag.pattern??lle,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}let o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...i?{received:i}:{}}),n}}),PLe=ve("$ZodNumberFormat",(t,e)=>{LRe.init(t,e),yle.init(t,e)}),f8=ve("$ZodBoolean",(t,e)=>{kr.init(t,e),t._zod.pattern=ARe,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}let o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),n}}),vle=ve("$ZodBigInt",(t,e)=>{kr.init(t,e),t._zod.pattern=TRe,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=BigInt(n.value)}catch{}return typeof n.value=="bigint"||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:t}),n}}),ALe=ve("$ZodBigIntFormat",(t,e)=>{$Re.init(t,e),vle.init(t,e)}),ELe=ve("$ZodSymbol",(t,e)=>{kr.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;return typeof o=="symbol"||n.issues.push({expected:"symbol",code:"invalid_type",input:o,inst:t}),n}}),MLe=ve("$ZodUndefined",(t,e)=>{kr.init(t,e),t._zod.pattern=MRe,t._zod.values=new Set([void 0]),t._zod.parse=(n,r)=>{let o=n.value;return typeof o>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:o,inst:t}),n}}),OLe=ve("$ZodNull",(t,e)=>{kr.init(t,e),t._zod.pattern=ERe,t._zod.values=new Set([null]),t._zod.parse=(n,r)=>{let o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),n}}),NLe=ve("$ZodAny",(t,e)=>{kr.init(t,e),t._zod.parse=n=>n}),wle=ve("$ZodUnknown",(t,e)=>{kr.init(t,e),t._zod.parse=n=>n}),p8=ve("$ZodNever",(t,e)=>{kr.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)}),RLe=ve("$ZodVoid",(t,e)=>{kr.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;return typeof o>"u"||n.issues.push({expected:"void",code:"invalid_type",input:o,inst:t}),n}}),LLe=ve("$ZodDate",(t,e)=>{kr.init(t,e),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=new Date(n.value)}catch{}let o=n.value,i=o instanceof Date;return i&&!Number.isNaN(o.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:t}),n}});$Le=ve("$ZodArray",(t,e)=>{kr.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),n;n.value=Array(o.length);let i=[];for(let s=0;s<o.length;s++){let a=o[s],l=e.element._zod.run({value:a,issues:[]},r);l instanceof Promise?i.push(l.then(c=>xwt(c,n,s))):xwt(l,n,s)}return i.length?Promise.all(i).then(()=>n):n}});jwt=ve("$ZodObject",(t,e)=>{if(kr.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let l={...a};return Object.defineProperty(e,"shape",{value:l}),l}})}let r=$U(()=>Fwt(e));lo(t._zod,"propValues",()=>{let a=e.shape,l={};for(let c in a){let u=a[c]._zod;if(u.values){l[c]??(l[c]=new Set);for(let d of u.values)l[c].add(d)}}return l});let o=RN,i=e.catchall,s;t._zod.parse=(a,l)=>{s??(s=r.value);let c=a.value;if(!o(c))return a.issues.push({expected:"object",code:"invalid_type",input:c,inst:t}),a;a.value={};let u=[],d=s.shape;for(let f of s.keys){let p=d[f],m=p._zod.optin==="optional",h=p._zod.optout==="optional",g=p._zod.run({value:c[f],issues:[]},l);g instanceof Promise?u.push(g.then(v=>gle(v,a,f,c,m,h))):gle(g,a,f,c,m,h)}return i?Uwt(u,c,a,l,r.value,t):u.length?Promise.all(u).then(()=>a):a}}),DLe=ve("$ZodObjectJIT",(t,e)=>{jwt.init(t,e);let n=t._zod.parse,r=$U(()=>Fwt(e)),o=f=>{let p=new d8(["shape","payload","ctx"]),m=r.value,h=w=>{let _=Jae(w);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};p.write("const input = payload.value;");let g=Object.create(null),v=0;for(let w of m.keys)g[w]=`key_${v++}`;p.write("const newResult = {};");for(let w of m.keys){let _=g[w],S=Jae(w),I=f[w],C=I?._zod?.optin==="optional",k=I?._zod?.optout==="optional";p.write(`const ${_} = ${h(w)};`),C&&k?p.write(`
if (${_}.issues.length) {
if (${S} in input) {
payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
...iss,
path: iss.path ? [${S}, ...iss.path] : [${S}]
})));
}
}
if (${_}.value === undefined) {
if (${S} in input) {
newResult[${S}] = undefined;
}
} else {
newResult[${S}] = ${_}.value;
}
`):C?p.write(`
if (${_}.issues.length) {
payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
...iss,
path: iss.path ? [${S}, ...iss.path] : [${S}]
})));
}
if (${_}.value === undefined) {
if (${S} in input) {
newResult[${S}] = undefined;
}
} else {
newResult[${S}] = ${_}.value;
}
`):p.write(`
const ${_}_present = ${S} in input;
if (${_}.issues.length) {
payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
...iss,
path: iss.path ? [${S}, ...iss.path] : [${S}]
})));
}
if (!${_}_present && !${_}.issues.length) {
payload.issues.push({
code: "invalid_type",
expected: "nonoptional",
input: undefined,
path: [${S}]
});
}
if (${_}_present) {
if (${_}.value === undefined) {
newResult[${S}] = undefined;
} else {
newResult[${S}] = ${_}.value;
}
}
`)}p.write("payload.value = newResult;"),p.write("return payload;");let y=p.compile();return(w,_)=>y(f,w,_)},i,s=RN,a=!ON.jitless,c=a&&qNe.value,u=e.catchall,d;t._zod.parse=(f,p)=>{d??(d=r.value);let m=f.value;return s(m)?a&&c&&p?.async===!1&&p.jitless!==!0?(i||(i=o(e.shape)),f=i(f,p),u?Uwt([],m,f,p,d,t):f):n(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),f)}});m8=ve("$ZodUnion",(t,e)=>{kr.init(t,e),lo(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),lo(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),lo(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),lo(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>n8(o.source)).join("|")})$`)}});let n=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(r,o)=>{if(n)return n(r,o);let i=!1,s=[];for(let a of e.options){let l=a._zod.run({value:r.value,issues:[]},o);if(l instanceof Promise)s.push(l),i=!0;else{if(l.issues.length===0)return l;s.push(l)}}return i?Promise.all(s).then(a=>Swt(a,r,t,o)):Swt(s,r,t,o)}});FLe=ve("$ZodXor",(t,e)=>{m8.init(t,e),e.inclusive=!1;let n=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(r,o)=>{if(n)return n(r,o);let i=!1,s=[];for(let a of e.options){let l=a._zod.run({value:r.value,issues:[]},o);l instanceof Promise?(s.push(l),i=!0):s.push(l)}return i?Promise.all(s).then(a=>Cwt(a,r,t,o)):Cwt(s,r,t,o)}}),ULe=ve("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,m8.init(t,e);let n=t._zod.parse;lo(t._zod,"propValues",()=>{let o={};for(let i of e.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let[a,l]of Object.entries(s)){o[a]||(o[a]=new Set);for(let c of l)o[a].add(c)}}return o});let r=$U(()=>{let o=e.options,i=new Map;for(let s of o){let a=s._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let l of a){if(i.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);i.set(l,s)}}return i});t._zod.parse=(o,i)=>{let s=o.value;if(!RN(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:t}),o;let a=r.value.get(s?.[e.discriminator]);return a?a._zod.run(o,i):e.unionFallback||i.direction==="backward"?n(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(r.value.keys()),input:s,path:[e.discriminator],inst:t}),o)}}),jLe=ve("$ZodIntersection",(t,e)=>{kr.init(t,e),t._zod.parse=(n,r)=>{let o=n.value,i=e.left._zod.run({value:o,issues:[]},r),s=e.right._zod.run({value:o,issues:[]},r);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([l,c])=>kwt(n,l,c)):kwt(n,i,s)}});ble=ve("$ZodTuple",(t,e)=>{kr.init(t,e);let n=e.items;t._zod.parse=(r,o)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({input:i,inst:t,expected:"tuple",code:"invalid_type"}),r;r.value=[];let s=[],a=Iwt(n,"optin"),l=Iwt(n,"optout");if(!e.rest){if(i.length<a)return r.issues.push({code:"too_small",minimum:a,inclusive:!0,input:i,inst:t,origin:"array"}),r;i.length>n.length&&r.issues.push({code:"too_big",maximum:n.length,inclusive:!0,input:i,inst:t,origin:"array"})}let c=new Array(n.length);for(let u=0;u<n.length;u++){let d=n[u]._zod.run({value:i[u],issues:[]},o);d instanceof Promise?s.push(d.then(f=>{c[u]=f})):c[u]=d}if(e.rest){let u=n.length-1,d=i.slice(n.length);for(let f of d){u++;let p=e.rest._zod.run({value:f,issues:[]},o);p instanceof Promise?s.push(p.then(m=>Twt(m,r,u))):Twt(p,r,u)}}return s.length?Promise.all(s).then(()=>Pwt(c,r,n,i,l)):Pwt(c,r,n,i,l)}});BLe=ve("$ZodRecord",(t,e)=>{kr.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!mP(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let i=[],s=e.keyType._zod.values;if(s){n.value={};let a=new Set;for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){a.add(typeof c=="number"?c.toString():c);let u=e.keyType._zod.run({value:c,issues:[]},r);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(u.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(p=>op(p,r,Wa())),input:c,path:[c],inst:t});continue}let d=u.value,f=e.valueType._zod.run({value:o[c],issues:[]},r);f instanceof Promise?i.push(f.then(p=>{p.issues.length&&n.issues.push(...cm(c,p.issues)),n.value[d]=p.value})):(f.issues.length&&n.issues.push(...cm(c,f.issues)),n.value[d]=f.value)}let l;for(let c in o)a.has(c)||(l=l??[],l.push(c));l&&l.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:l})}else{n.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let l=e.keyType._zod.run({value:a,issues:[]},r);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&lle.test(a)&&l.issues.length){let d=e.keyType._zod.run({value:Number(a),issues:[]},r);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(l=d)}if(l.issues.length){e.mode==="loose"?n.value[a]=o[a]:n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(d=>op(d,r,Wa())),input:a,path:[a],inst:t});continue}let u=e.valueType._zod.run({value:o[a],issues:[]},r);u instanceof Promise?i.push(u.then(d=>{d.issues.length&&n.issues.push(...cm(a,d.issues)),n.value[l.value]=d.value})):(u.issues.length&&n.issues.push(...cm(a,u.issues)),n.value[l.value]=u.value)}}return i.length?Promise.all(i).then(()=>n):n}}),zLe=ve("$ZodMap",(t,e)=>{kr.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!(o instanceof Map))return n.issues.push({expected:"map",code:"invalid_type",input:o,inst:t}),n;let i=[];n.value=new Map;for(let[s,a]of o){let l=e.keyType._zod.run({value:s,issues:[]},r),c=e.valueType._zod.run({value:a,issues:[]},r);l instanceof Promise||c instanceof Promise?i.push(Promise.all([l,c]).then(([u,d])=>{Awt(u,d,n,s,o,t,r)})):Awt(l,c,n,s,o,t,r)}return i.length?Promise.all(i).then(()=>n):n}});HLe=ve("$ZodSet",(t,e)=>{kr.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!(o instanceof Set))return n.issues.push({input:o,inst:t,expected:"set",code:"invalid_type"}),n;let i=[];n.value=new Set;for(let s of o){let a=e.valueType._zod.run({value:s,issues:[]},r);a instanceof Promise?i.push(a.then(l=>Ewt(l,n))):Ewt(a,n)}return i.length?Promise.all(i).then(()=>n):n}});WLe=ve("$ZodEnum",(t,e)=>{kr.init(t,e);let n=t8(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(o=>r8.has(typeof o)).map(o=>typeof o=="string"?Ay(o):o.toString()).join("|")})$`),t._zod.parse=(o,i)=>{let s=o.value;return r.has(s)||o.issues.push({code:"invalid_value",values:n,input:s,inst:t}),o}}),VLe=ve("$ZodLiteral",(t,e)=>{if(kr.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let n=new Set(e.values);t._zod.values=n,t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Ay(r):r?Ay(r.toString()):String(r)).join("|")})$`),t._zod.parse=(r,o)=>{let i=r.value;return n.has(i)||r.issues.push({code:"invalid_value",values:e.values,input:i,inst:t}),r}}),qLe=ve("$ZodFile",(t,e)=>{kr.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;return o instanceof File||n.issues.push({expected:"file",code:"invalid_type",input:o,inst:t}),n}}),KLe=ve("$ZodTransform",(t,e)=>{kr.init(t,e),t._zod.optin="optional",t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new dP(t.constructor.name);let o=e.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(s=>(n.value=s,n.fallback=!0,n));if(o instanceof Promise)throw new jw;return n.value=o,n.fallback=!0,n}});h8=ve("$ZodOptional",(t,e)=>{kr.init(t,e),t._zod.optin="optional",t._zod.optout="optional",lo(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),lo(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${n8(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>{if(e.innerType._zod.optin==="optional"){let o=n.value,i=e.innerType._zod.run(n,r);return i instanceof Promise?i.then(s=>Mwt(s,o)):Mwt(i,o)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),GLe=ve("$ZodExactOptional",(t,e)=>{h8.init(t,e),lo(t._zod,"values",()=>e.innerType._zod.values),lo(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(n,r)=>e.innerType._zod.run(n,r)}),ZLe=ve("$ZodNullable",(t,e)=>{kr.init(t,e),lo(t._zod,"optin",()=>e.innerType._zod.optin),lo(t._zod,"optout",()=>e.innerType._zod.optout),lo(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${n8(n.source)}|null)$`):void 0}),lo(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),YLe=ve("$ZodDefault",(t,e)=>{kr.init(t,e),t._zod.optin="optional",lo(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);if(n.value===void 0)return n.value=e.defaultValue,n;let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>Owt(i,e)):Owt(o,e)}});JLe=ve("$ZodPrefault",(t,e)=>{kr.init(t,e),t._zod.optin="optional",lo(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),XLe=ve("$ZodNonOptional",(t,e)=>{kr.init(t,e),lo(t._zod,"values",()=>{let n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>Nwt(i,t)):Nwt(o,t)}});QLe=ve("$ZodSuccess",(t,e)=>{kr.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new dP("ZodSuccess");let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>(n.value=i.issues.length===0,n)):(n.value=o.issues.length===0,n)}}),e1e=ve("$ZodCatch",(t,e)=>{kr.init(t,e),t._zod.optin="optional",lo(t._zod,"optout",()=>e.innerType._zod.optout),lo(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>(n.value=i.value,i.issues.length&&(n.value=e.catchValue({...n,error:{issues:i.issues.map(s=>op(s,r,Wa()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(i=>op(i,r,Wa()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),t1e=ve("$ZodNaN",(t,e)=>{kr.init(t,e),t._zod.parse=(n,r)=>((typeof n.value!="number"||!Number.isNaN(n.value))&&n.issues.push({input:n.value,inst:t,expected:"nan",code:"invalid_type"}),n)}),_le=ve("$ZodPipe",(t,e)=>{kr.init(t,e),lo(t._zod,"values",()=>e.in._zod.values),lo(t._zod,"optin",()=>e.in._zod.optin),lo(t._zod,"optout",()=>e.out._zod.optout),lo(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,r)=>{if(r.direction==="backward"){let i=e.out._zod.run(n,r);return i instanceof Promise?i.then(s=>ple(s,e.in,r)):ple(i,e.in,r)}let o=e.in._zod.run(n,r);return o instanceof Promise?o.then(i=>ple(i,e.out,r)):ple(o,e.out,r)}});g8=ve("$ZodCodec",(t,e)=>{kr.init(t,e),lo(t._zod,"values",()=>e.in._zod.values),lo(t._zod,"optin",()=>e.in._zod.optin),lo(t._zod,"optout",()=>e.out._zod.optout),lo(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,r)=>{if((r.direction||"forward")==="forward"){let i=e.in._zod.run(n,r);return i instanceof Promise?i.then(s=>mle(s,e,r)):mle(i,e,r)}else{let i=e.out._zod.run(n,r);return i instanceof Promise?i.then(s=>mle(s,e,r)):mle(i,e,r)}}});n1e=ve("$ZodPreprocess",(t,e)=>{_le.init(t,e)}),r1e=ve("$ZodReadonly",(t,e)=>{kr.init(t,e),lo(t._zod,"propValues",()=>e.innerType._zod.propValues),lo(t._zod,"values",()=>e.innerType._zod.values),lo(t._zod,"optin",()=>e.innerType?._zod?.optin),lo(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(Rwt):Rwt(o)}});o1e=ve("$ZodTemplateLiteral",(t,e)=>{kr.init(t,e);let n=[];for(let r of e.parts)if(typeof r=="object"&&r!==null){if(!r._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...r._zod.traits].shift()}`);let o=r._zod.pattern instanceof RegExp?r._zod.pattern.source:r._zod.pattern;if(!o)throw new Error(`Invalid template literal part: ${r._zod.traits}`);let i=o.startsWith("^")?1:0,s=o.endsWith("$")?o.length-1:o.length;n.push(o.slice(i,s))}else if(r===null||GNe.has(typeof r))n.push(Ay(`${r}`));else throw new Error(`Invalid template literal part: ${r}`);t._zod.pattern=new RegExp(`^${n.join("")}$`),t._zod.parse=(r,o)=>typeof r.value!="string"?(r.issues.push({input:r.value,inst:t,expected:"string",code:"invalid_type"}),r):(t._zod.pattern.lastIndex=0,t._zod.pattern.test(r.value)||r.issues.push({input:r.value,inst:t,code:"invalid_format",format:e.format??"template_literal",pattern:t._zod.pattern.source}),r)}),i1e=ve("$ZodFunction",(t,e)=>(kr.init(t,e),t._def=e,t._zod.def=e,t.implement=n=>{if(typeof n!="function")throw new Error("implement() must be called with a function");return function(...r){let o=t._def.input?LN(t._def.input,r):r,i=Reflect.apply(n,this,o);return t._def.output?LN(t._def.output,i):i}},t.implementAsync=n=>{if(typeof n!="function")throw new Error("implementAsync() must be called with a function");return async function(...r){let o=t._def.input?await $N(t._def.input,r):r,i=await Reflect.apply(n,this,o);return t._def.output?await $N(t._def.output,i):i}},t._zod.parse=(n,r)=>typeof n.value!="function"?(n.issues.push({code:"invalid_type",expected:"function",input:n.value,inst:t}),n):(t._def.output&&t._def.output._zod.def.type==="promise"?n.value=t.implementAsync(n.value):n.value=t.implement(n.value),n),t.input=(...n)=>{let r=t.constructor;return Array.isArray(n[0])?new r({type:"function",input:new ble({type:"tuple",items:n[0],rest:n[1]}),output:t._def.output}):new r({type:"function",input:n[0],output:t._def.output})},t.output=n=>{let r=t.constructor;return new r({type:"function",input:t._def.input,output:n})},t)),s1e=ve("$ZodPromise",(t,e)=>{kr.init(t,e),t._zod.parse=(n,r)=>Promise.resolve(n.value).then(o=>e.innerType._zod.run({value:o,issues:[]},r))}),a1e=ve("$ZodLazy",(t,e)=>{kr.init(t,e),lo(t._zod,"innerType",()=>{let n=e;return n._cachedInner||(n._cachedInner=e.getter()),n._cachedInner}),lo(t._zod,"pattern",()=>t._zod.innerType?._zod?.pattern),lo(t._zod,"propValues",()=>t._zod.innerType?._zod?.propValues),lo(t._zod,"optin",()=>t._zod.innerType?._zod?.optin??void 0),lo(t._zod,"optout",()=>t._zod.innerType?._zod?.optout??void 0),t._zod.parse=(n,r)=>t._zod.innerType._zod.run(n,r)}),l1e=ve("$ZodCustom",(t,e)=>{ds.init(t,e),kr.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{let r=n.value,o=e.fn(r);if(o instanceof Promise)return o.then(i=>Lwt(i,n,r,t));Lwt(o,n,r,t)}})});function Bwt(){return{localeError:n1n()}}var n1n,zwt=b(()=>{wn();n1n=()=>{let t={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function e(o){return t[o]??null}let n={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"},r={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${o.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${a}`:`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${i}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${a}`}case"invalid_value":return o.values.length===1?`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${Xe(o.values[0])}`:`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${o.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${i} ${o.maximum.toString()} ${s.unit??"\u0639\u0646\u0635\u0631"}`:`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${o.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${i} ${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${o.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${i} ${o.minimum.toString()} ${s.unit}`:`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${o.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${i} ${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${o.prefix}"`:i.format==="ends_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${i.suffix}"`:i.format==="includes"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${i.includes}"`:i.format==="regex"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${i.pattern}`:`${n[i.format]??o.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${o.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${o.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${o.keys.length>1?"\u0629":""}: ${Ce(o.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${o.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${o.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}}});function Hwt(){return{localeError:r1n()}}var r1n,Wwt=b(()=>{wn();r1n=()=>{let t={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function e(o){return t[o]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${o.expected}, daxil olan ${a}`:`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${i}, daxil olan ${a}`}case"invalid_value":return o.values.length===1?`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${Xe(o.values[0])}`:`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${o.origin??"d\u0259y\u0259r"} ${i}${o.maximum.toString()} ${s.unit??"element"}`:`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${o.origin??"d\u0259y\u0259r"} ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${o.origin} ${i}${o.minimum.toString()} ${s.unit}`:`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${o.origin} ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Yanl\u0131\u015F m\u0259tn: "${i.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`:i.format==="ends_with"?`Yanl\u0131\u015F m\u0259tn: "${i.suffix}" il\u0259 bitm\u0259lidir`:i.format==="includes"?`Yanl\u0131\u015F m\u0259tn: "${i.includes}" daxil olmal\u0131d\u0131r`:i.format==="regex"?`Yanl\u0131\u015F m\u0259tn: ${i.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`:`Yanl\u0131\u015F ${n[i.format]??o.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${o.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${o.keys.length>1?"lar":""}: ${Ce(o.keys,", ")}`;case"invalid_key":return`${o.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${o.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}}}});function Vwt(t,e,n,r){let o=Math.abs(t),i=o%10,s=o%100;return s>=11&&s<=19?r:i===1?e:i>=2&&i<=4?n:r}function qwt(){return{localeError:o1n()}}var o1n,Kwt=b(()=>{wn();o1n=()=>{let t={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function e(o){return t[o]??null}let n={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"},r={nan:"NaN",number:"\u043B\u0456\u043A",array:"\u043C\u0430\u0441\u0456\u045E"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${o.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${a}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${i}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${a}`}case"invalid_value":return o.values.length===1?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${Xe(o.values[0])}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);if(s){let a=Number(o.maximum),l=Vwt(a,s.unit.one,s.unit.few,s.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${s.verb} ${i}${o.maximum.toString()} ${l}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);if(s){let a=Number(o.minimum),l=Vwt(a,s.unit.one,s.unit.few,s.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${o.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${s.verb} ${i}${o.minimum.toString()} ${l}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${o.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${i.prefix}"`:i.format==="ends_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${i.suffix}"`:i.format==="includes"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${i.includes}"`:i.format==="regex"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${i.pattern}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${n[i.format]??o.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${o.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${o.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${Ce(o.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${o.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${o.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}}}});function Gwt(){return{localeError:i1n()}}var i1n,Zwt=b(()=>{wn();i1n=()=>{let t={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},file:{unit:"\u0431\u0430\u0439\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"}};function e(o){return t[o]??null}let n={regex:"\u0432\u0445\u043E\u0434",email:"\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0436\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",base64url:"base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",json_string:"JSON \u043D\u0438\u0437",e164:"E.164 \u043D\u043E\u043C\u0435\u0440",jwt:"JWT",template_literal:"\u0432\u0445\u043E\u0434"},r={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${o.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${a}`:`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${i}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${a}`}case"invalid_value":return o.values.length===1?`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${Xe(o.values[0])}`:`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${o.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${i}${o.maximum.toString()} ${s.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`:`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${o.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${o.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${i}${o.minimum.toString()} ${s.unit}`:`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${o.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;if(i.format==="starts_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${i.prefix}"`;if(i.format==="ends_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${i.suffix}"`;if(i.format==="includes")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${i.includes}"`;if(i.format==="regex")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${i.pattern}`;let s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D";return i.format==="emoji"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"),i.format==="datetime"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"),i.format==="date"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"),i.format==="time"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"),i.format==="duration"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"),`${s} ${n[i.format]??o.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${o.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${o.keys.length>1?"\u0438":""} \u043A\u043B\u044E\u0447${o.keys.length>1?"\u043E\u0432\u0435":""}: ${Ce(o.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${o.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434";case"invalid_element":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${o.origin}`;default:return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"}}}});function Ywt(){return{localeError:s1n()}}var s1n,Jwt=b(()=>{wn();s1n=()=>{let t={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function e(o){return t[o]??null}let n={regex:"entrada",email:"adre\xE7a electr\xF2nica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adre\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},r={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Tipus inv\xE0lid: s'esperava instanceof ${o.expected}, s'ha rebut ${a}`:`Tipus inv\xE0lid: s'esperava ${i}, s'ha rebut ${a}`}case"invalid_value":return o.values.length===1?`Valor inv\xE0lid: s'esperava ${Xe(o.values[0])}`:`Opci\xF3 inv\xE0lida: s'esperava una de ${Ce(o.values," o ")}`;case"too_big":{let i=o.inclusive?"com a m\xE0xim":"menys de",s=e(o.origin);return s?`Massa gran: s'esperava que ${o.origin??"el valor"} contingu\xE9s ${i} ${o.maximum.toString()} ${s.unit??"elements"}`:`Massa gran: s'esperava que ${o.origin??"el valor"} fos ${i} ${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?"com a m\xEDnim":"m\xE9s de",s=e(o.origin);return s?`Massa petit: s'esperava que ${o.origin} contingu\xE9s ${i} ${o.minimum.toString()} ${s.unit}`:`Massa petit: s'esperava que ${o.origin} fos ${i} ${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Format inv\xE0lid: ha de comen\xE7ar amb "${i.prefix}"`:i.format==="ends_with"?`Format inv\xE0lid: ha d'acabar amb "${i.suffix}"`:i.format==="includes"?`Format inv\xE0lid: ha d'incloure "${i.includes}"`:i.format==="regex"?`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${i.pattern}`:`Format inv\xE0lid per a ${n[i.format]??o.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${o.divisor}`;case"unrecognized_keys":return`Clau${o.keys.length>1?"s":""} no reconeguda${o.keys.length>1?"s":""}: ${Ce(o.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${o.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${o.origin}`;default:return"Entrada inv\xE0lida"}}}});function Xwt(){return{localeError:a1n()}}var a1n,Qwt=b(()=>{wn();a1n=()=>{let t={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function e(o){return t[o]??null}let n={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"},r={nan:"NaN",number:"\u010D\xEDslo",string:"\u0159et\u011Bzec",function:"funkce",array:"pole"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${o.expected}, obdr\u017Eeno ${a}`:`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${i}, obdr\u017Eeno ${a}`}case"invalid_value":return o.values.length===1?`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${Xe(o.values[0])}`:`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${o.origin??"hodnota"} mus\xED m\xEDt ${i}${o.maximum.toString()} ${s.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${o.origin??"hodnota"} mus\xED b\xFDt ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${o.origin??"hodnota"} mus\xED m\xEDt ${i}${o.minimum.toString()} ${s.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${o.origin??"hodnota"} mus\xED b\xFDt ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${i.prefix}"`:i.format==="ends_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${i.suffix}"`:i.format==="includes"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${i.includes}"`:i.format==="regex"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${i.pattern}`:`Neplatn\xFD form\xE1t ${n[i.format]??o.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${o.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${Ce(o.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${o.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${o.origin}`;default:return"Neplatn\xFD vstup"}}}});function ebt(){return{localeError:l1n()}}var l1n,tbt=b(()=>{wn();l1n=()=>{let t={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function e(o){return t[o]??null}let n={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkesl\xE6t",date:"ISO-dato",time:"ISO-klokkesl\xE6t",duration:"ISO-varighed",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},r={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"s\xE6t",file:"fil"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Ugyldigt input: forventede instanceof ${o.expected}, fik ${a}`:`Ugyldigt input: forventede ${i}, fik ${a}`}case"invalid_value":return o.values.length===1?`Ugyldig v\xE6rdi: forventede ${Xe(o.values[0])}`:`Ugyldigt valg: forventede en af f\xF8lgende ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin),a=r[o.origin]??o.origin;return s?`For stor: forventede ${a??"value"} ${s.verb} ${i} ${o.maximum.toString()} ${s.unit??"elementer"}`:`For stor: forventede ${a??"value"} havde ${i} ${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin),a=r[o.origin]??o.origin;return s?`For lille: forventede ${a} ${s.verb} ${i} ${o.minimum.toString()} ${s.unit}`:`For lille: forventede ${a} havde ${i} ${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Ugyldig streng: skal starte med "${i.prefix}"`:i.format==="ends_with"?`Ugyldig streng: skal ende med "${i.suffix}"`:i.format==="includes"?`Ugyldig streng: skal indeholde "${i.includes}"`:i.format==="regex"?`Ugyldig streng: skal matche m\xF8nsteret ${i.pattern}`:`Ugyldig ${n[i.format]??o.format}`}case"not_multiple_of":return`Ugyldigt tal: skal v\xE6re deleligt med ${o.divisor}`;case"unrecognized_keys":return`${o.keys.length>1?"Ukendte n\xF8gler":"Ukendt n\xF8gle"}: ${Ce(o.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8gle i ${o.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig v\xE6rdi i ${o.origin}`;default:return"Ugyldigt input"}}}});function nbt(){return{localeError:c1n()}}var c1n,rbt=b(()=>{wn();c1n=()=>{let t={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function e(o){return t[o]??null}let n={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},r={nan:"NaN",number:"Zahl",array:"Array"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Ung\xFCltige Eingabe: erwartet instanceof ${o.expected}, erhalten ${a}`:`Ung\xFCltige Eingabe: erwartet ${i}, erhalten ${a}`}case"invalid_value":return o.values.length===1?`Ung\xFCltige Eingabe: erwartet ${Xe(o.values[0])}`:`Ung\xFCltige Option: erwartet eine von ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Zu gro\xDF: erwartet, dass ${o.origin??"Wert"} ${i}${o.maximum.toString()} ${s.unit??"Elemente"} hat`:`Zu gro\xDF: erwartet, dass ${o.origin??"Wert"} ${i}${o.maximum.toString()} ist`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Zu klein: erwartet, dass ${o.origin} ${i}${o.minimum.toString()} ${s.unit} hat`:`Zu klein: erwartet, dass ${o.origin} ${i}${o.minimum.toString()} ist`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Ung\xFCltiger String: muss mit "${i.prefix}" beginnen`:i.format==="ends_with"?`Ung\xFCltiger String: muss mit "${i.suffix}" enden`:i.format==="includes"?`Ung\xFCltiger String: muss "${i.includes}" enthalten`:i.format==="regex"?`Ung\xFCltiger String: muss dem Muster ${i.pattern} entsprechen`:`Ung\xFCltig: ${n[i.format]??o.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${o.divisor} sein`;case"unrecognized_keys":return`${o.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${Ce(o.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${o.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${o.origin}`;default:return"Ung\xFCltige Eingabe"}}}});function obt(){return{localeError:u1n()}}var u1n,ibt=b(()=>{wn();u1n=()=>{let t={string:{unit:"\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},file:{unit:"bytes",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},array:{unit:"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},set:{unit:"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},map:{unit:"\u03BA\u03B1\u03C4\u03B1\u03C7\u03C9\u03C1\u03AE\u03C3\u03B5\u03B9\u03C2",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"}};function e(o){return t[o]??null}let n={regex:"\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2",email:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1 \u03BA\u03B1\u03B9 \u03CE\u03C1\u03B1",date:"ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1",time:"ISO \u03CE\u03C1\u03B1",duration:"ISO \u03B4\u03B9\u03AC\u03C1\u03BA\u03B5\u03B9\u03B1",ipv4:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv4",ipv6:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv6",mac:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 MAC",cidrv4:"\u03B5\u03CD\u03C1\u03BF\u03C2 IPv4",cidrv6:"\u03B5\u03CD\u03C1\u03BF\u03C2 IPv6",base64:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64",base64url:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url",json_string:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON",e164:"\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164",jwt:"JWT",template_literal:"\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"},r={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return typeof o.expected=="string"&&/^[A-Z]/.test(o.expected)?`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD instanceof ${o.expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${a}`:`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${i}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${a}`}case"invalid_value":return o.values.length===1?`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${Xe(o.values[0])}`:`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03C0\u03B9\u03BB\u03BF\u03B3\u03AE: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD \u03AD\u03BD\u03B1 \u03B1\u03C0\u03CC ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${o.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${i}${o.maximum.toString()} ${s.unit??"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1"}`:`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${o.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${o.origin} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${i}${o.minimum.toString()} ${s.unit}`:`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${o.origin} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03BE\u03B5\u03BA\u03B9\u03BD\u03AC \u03BC\u03B5 "${i.prefix}"`:i.format==="ends_with"?`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B5\u03BB\u03B5\u03B9\u03CE\u03BD\u03B5\u03B9 \u03BC\u03B5 "${i.suffix}"`:i.format==="includes"?`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C0\u03B5\u03C1\u03B9\u03AD\u03C7\u03B5\u03B9 "${i.includes}"`:i.format==="regex"?`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B1\u03B9\u03C1\u03B9\u03AC\u03B6\u03B5\u03B9 \u03BC\u03B5 \u03C4\u03BF \u03BC\u03BF\u03C4\u03AF\u03B2\u03BF ${i.pattern}`:`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF: ${n[i.format]??o.format}`}case"not_multiple_of":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF\u03C2 \u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 \u03C0\u03BF\u03BB\u03BB\u03B1\u03C0\u03BB\u03AC\u03C3\u03B9\u03BF \u03C4\u03BF\u03C5 ${o.divisor}`;case"unrecognized_keys":return`\u0386\u03B3\u03BD\u03C9\u03C3\u03C4${o.keys.length>1?"\u03B1":"\u03BF"} \u03BA\u03BB\u03B5\u03B9\u03B4${o.keys.length>1?"\u03B9\u03AC":"\u03AF"}: ${Ce(o.keys,", ")}`;case"invalid_key":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF \u03BA\u03BB\u03B5\u03B9\u03B4\u03AF \u03C3\u03C4\u03BF ${o.origin}`;case"invalid_union":return"\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2";case"invalid_element":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C4\u03B9\u03BC\u03AE \u03C3\u03C4\u03BF ${o.origin}`;default:return"\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"}}}});function xle(){return{localeError:d1n()}}var d1n,u1e=b(()=>{wn();d1n=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function e(o){return t[o]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return`Invalid input: expected ${i}, received ${a}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${Xe(o.values[0])}`:`Invalid option: expected one of ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Too big: expected ${o.origin??"value"} to have ${i}${o.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Too small: expected ${o.origin} to have ${i}${o.minimum.toString()} ${s.unit}`:`Too small: expected ${o.origin} to be ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${n[i.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${Ce(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return o.options&&Array.isArray(o.options)&&o.options.length>0?`Invalid discriminator value. Expected ${o.options.map(s=>`'${s}'`).join(" | ")}`:"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}}});function sbt(){return{localeError:f1n()}}var f1n,abt=b(()=>{wn();f1n=()=>{let t={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function e(o){return t[o]??null}let n={regex:"enigo",email:"retadreso",url:"URL",emoji:"emo\u011Dio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-da\u016Dro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},r={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Nevalida enigo: atendi\u011Dis instanceof ${o.expected}, ricevi\u011Dis ${a}`:`Nevalida enigo: atendi\u011Dis ${i}, ricevi\u011Dis ${a}`}case"invalid_value":return o.values.length===1?`Nevalida enigo: atendi\u011Dis ${Xe(o.values[0])}`:`Nevalida opcio: atendi\u011Dis unu el ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Tro granda: atendi\u011Dis ke ${o.origin??"valoro"} havu ${i}${o.maximum.toString()} ${s.unit??"elementojn"}`:`Tro granda: atendi\u011Dis ke ${o.origin??"valoro"} havu ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Tro malgranda: atendi\u011Dis ke ${o.origin} havu ${i}${o.minimum.toString()} ${s.unit}`:`Tro malgranda: atendi\u011Dis ke ${o.origin} estu ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Nevalida karaktraro: devas komenci\u011Di per "${i.prefix}"`:i.format==="ends_with"?`Nevalida karaktraro: devas fini\u011Di per "${i.suffix}"`:i.format==="includes"?`Nevalida karaktraro: devas inkluzivi "${i.includes}"`:i.format==="regex"?`Nevalida karaktraro: devas kongrui kun la modelo ${i.pattern}`:`Nevalida ${n[i.format]??o.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${o.divisor}`;case"unrecognized_keys":return`Nekonata${o.keys.length>1?"j":""} \u015Dlosilo${o.keys.length>1?"j":""}: ${Ce(o.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${o.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${o.origin}`;default:return"Nevalida enigo"}}}});function lbt(){return{localeError:p1n()}}var p1n,cbt=b(()=>{wn();p1n=()=>{let t={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function e(o){return t[o]??null}let n={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duraci\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},r={nan:"NaN",string:"texto",number:"n\xFAmero",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"n\xFAmero grande",symbol:"s\xEDmbolo",undefined:"indefinido",null:"nulo",function:"funci\xF3n",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeraci\xF3n",union:"uni\xF3n",literal:"literal",promise:"promesa",void:"vac\xEDo",never:"nunca",unknown:"desconocido",any:"cualquiera"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Entrada inv\xE1lida: se esperaba instanceof ${o.expected}, recibido ${a}`:`Entrada inv\xE1lida: se esperaba ${i}, recibido ${a}`}case"invalid_value":return o.values.length===1?`Entrada inv\xE1lida: se esperaba ${Xe(o.values[0])}`:`Opci\xF3n inv\xE1lida: se esperaba una de ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin),a=r[o.origin]??o.origin;return s?`Demasiado grande: se esperaba que ${a??"valor"} tuviera ${i}${o.maximum.toString()} ${s.unit??"elementos"}`:`Demasiado grande: se esperaba que ${a??"valor"} fuera ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin),a=r[o.origin]??o.origin;return s?`Demasiado peque\xF1o: se esperaba que ${a} tuviera ${i}${o.minimum.toString()} ${s.unit}`:`Demasiado peque\xF1o: se esperaba que ${a} fuera ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Cadena inv\xE1lida: debe comenzar con "${i.prefix}"`:i.format==="ends_with"?`Cadena inv\xE1lida: debe terminar en "${i.suffix}"`:i.format==="includes"?`Cadena inv\xE1lida: debe incluir "${i.includes}"`:i.format==="regex"?`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${i.pattern}`:`Inv\xE1lido ${n[i.format]??o.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${o.divisor}`;case"unrecognized_keys":return`Llave${o.keys.length>1?"s":""} desconocida${o.keys.length>1?"s":""}: ${Ce(o.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${r[o.origin]??o.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${r[o.origin]??o.origin}`;default:return"Entrada inv\xE1lida"}}}});function ubt(){return{localeError:m1n()}}var m1n,dbt=b(()=>{wn();m1n=()=>{let t={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function e(o){return t[o]??null}let n={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"},r={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0622\u0631\u0627\u06CC\u0647"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${o.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${a} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`:`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${i} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${a} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`}case"invalid_value":return o.values.length===1?`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${Xe(o.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`:`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${Ce(o.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${o.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${i}${o.maximum.toString()} ${s.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${o.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${i}${o.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${o.origin} \u0628\u0627\u06CC\u062F ${i}${o.minimum.toString()} ${s.unit} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${o.origin} \u0628\u0627\u06CC\u062F ${i}${o.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${i.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`:i.format==="ends_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${i.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`:i.format==="includes"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${i.includes}" \u0628\u0627\u0634\u062F`:i.format==="regex"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${i.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`:`${n[i.format]??o.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${o.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${o.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${Ce(o.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${o.origin}`;case"invalid_union":return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${o.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}}}});function fbt(){return{localeError:h1n()}}var h1n,pbt=b(()=>{wn();h1n=()=>{let t={string:{unit:"merkki\xE4",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"p\xE4iv\xE4m\xE4\xE4r\xE4n"}};function e(o){return t[o]??null}let n={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},r={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Virheellinen tyyppi: odotettiin instanceof ${o.expected}, oli ${a}`:`Virheellinen tyyppi: odotettiin ${i}, oli ${a}`}case"invalid_value":return o.values.length===1?`Virheellinen sy\xF6te: t\xE4ytyy olla ${Xe(o.values[0])}`:`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Liian suuri: ${s.subject} t\xE4ytyy olla ${i}${o.maximum.toString()} ${s.unit}`.trim():`Liian suuri: arvon t\xE4ytyy olla ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Liian pieni: ${s.subject} t\xE4ytyy olla ${i}${o.minimum.toString()} ${s.unit}`.trim():`Liian pieni: arvon t\xE4ytyy olla ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${i.prefix}"`:i.format==="ends_with"?`Virheellinen sy\xF6te: t\xE4ytyy loppua "${i.suffix}"`:i.format==="includes"?`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${i.includes}"`:i.format==="regex"?`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${i.pattern}`:`Virheellinen ${n[i.format]??o.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${o.divisor} monikerta`;case"unrecognized_keys":return`${o.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${Ce(o.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen sy\xF6te"}}}});function mbt(){return{localeError:g1n()}}var g1n,hbt=b(()=>{wn();g1n=()=>{let t={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function e(o){return t[o]??null}let n={regex:"entr\xE9e",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},r={string:"cha\xEEne",number:"nombre",int:"entier",boolean:"bool\xE9en",bigint:"grand entier",symbol:"symbole",undefined:"ind\xE9fini",null:"null",never:"jamais",void:"vide",date:"date",array:"tableau",object:"objet",tuple:"tuple",record:"enregistrement",map:"carte",set:"ensemble",file:"fichier",nonoptional:"non-optionnel",nan:"NaN",function:"fonction"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Entr\xE9e invalide : instanceof ${o.expected} attendu, ${a} re\xE7u`:`Entr\xE9e invalide : ${i} attendu, ${a} re\xE7u`}case"invalid_value":return o.values.length===1?`Entr\xE9e invalide : ${Xe(o.values[0])} attendu`:`Option invalide : une valeur parmi ${Ce(o.values,"|")} attendue`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Trop grand : ${r[o.origin]??"valeur"} doit ${s.verb} ${i}${o.maximum.toString()} ${s.unit??"\xE9l\xE9ment(s)"}`:`Trop grand : ${r[o.origin]??"valeur"} doit \xEAtre ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Trop petit : ${r[o.origin]??"valeur"} doit ${s.verb} ${i}${o.minimum.toString()} ${s.unit}`:`Trop petit : ${r[o.origin]??"valeur"} doit \xEAtre ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${i.prefix}"`:i.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${i.suffix}"`:i.format==="includes"?`Cha\xEEne invalide : doit inclure "${i.includes}"`:i.format==="regex"?`Cha\xEEne invalide : doit correspondre au mod\xE8le ${i.pattern}`:`${n[i.format]??o.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${o.divisor}`;case"unrecognized_keys":return`Cl\xE9${o.keys.length>1?"s":""} non reconnue${o.keys.length>1?"s":""} : ${Ce(o.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${o.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${o.origin}`;default:return"Entr\xE9e invalide"}}}});function gbt(){return{localeError:y1n()}}var y1n,ybt=b(()=>{wn();y1n=()=>{let t={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function e(o){return t[o]??null}let n={regex:"entr\xE9e",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},r={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Entr\xE9e invalide : attendu instanceof ${o.expected}, re\xE7u ${a}`:`Entr\xE9e invalide : attendu ${i}, re\xE7u ${a}`}case"invalid_value":return o.values.length===1?`Entr\xE9e invalide : attendu ${Xe(o.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"\u2264":"<",s=e(o.origin);return s?`Trop grand : attendu que ${o.origin??"la valeur"} ait ${i}${o.maximum.toString()} ${s.unit}`:`Trop grand : attendu que ${o.origin??"la valeur"} soit ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?"\u2265":">",s=e(o.origin);return s?`Trop petit : attendu que ${o.origin} ait ${i}${o.minimum.toString()} ${s.unit}`:`Trop petit : attendu que ${o.origin} soit ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${i.prefix}"`:i.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${i.suffix}"`:i.format==="includes"?`Cha\xEEne invalide : doit inclure "${i.includes}"`:i.format==="regex"?`Cha\xEEne invalide : doit correspondre au motif ${i.pattern}`:`${n[i.format]??o.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${o.divisor}`;case"unrecognized_keys":return`Cl\xE9${o.keys.length>1?"s":""} non reconnue${o.keys.length>1?"s":""} : ${Ce(o.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${o.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${o.origin}`;default:return"Entr\xE9e invalide"}}}});function vbt(){return{localeError:v1n()}}var v1n,wbt=b(()=>{wn();v1n=()=>{let t={string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA",gender:"f"},number:{label:"\u05DE\u05E1\u05E4\u05E8",gender:"m"},boolean:{label:"\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA",gender:"m"},array:{label:"\u05DE\u05E2\u05E8\u05DA",gender:"m"},object:{label:"\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8",gender:"m"},null:{label:"\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)",gender:"m"},undefined:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)",gender:"m"},symbol:{label:"\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)",gender:"m"},function:{label:"\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4",gender:"f"},map:{label:"\u05DE\u05E4\u05D4 (Map)",gender:"f"},set:{label:"\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)",gender:"f"},file:{label:"\u05E7\u05D5\u05D1\u05E5",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2",gender:"m"},value:{label:"\u05E2\u05E8\u05DA",gender:"m"}},e={string:{unit:"\u05EA\u05D5\u05D5\u05D9\u05DD",shortLabel:"\u05E7\u05E6\u05E8",longLabel:"\u05D0\u05E8\u05D5\u05DA"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},number:{unit:"",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"}},n=c=>c?t[c]:void 0,r=c=>{let u=n(c);return u?u.label:c??t.unknown.label},o=c=>`\u05D4${r(c)}`,i=c=>(n(c)?.gender??"m")==="f"?"\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA":"\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA",s=c=>c?e[c]??null:null,a={regex:{label:"\u05E7\u05DC\u05D8",gender:"m"},email:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",gender:"f"},url:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",gender:"f"},emoji:{label:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",gender:"m"},time:{label:"\u05D6\u05DE\u05DF ISO",gender:"m"},duration:{label:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",gender:"m"},ipv4:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",gender:"f"},ipv6:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",gender:"f"},cidrv4:{label:"\u05D8\u05D5\u05D5\u05D7 IPv4",gender:"m"},cidrv6:{label:"\u05D8\u05D5\u05D5\u05D7 IPv6",gender:"m"},base64:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",gender:"f"},base64url:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",gender:"f"},json_string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",gender:"f"},e164:{label:"\u05DE\u05E1\u05E4\u05E8 E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},includes:{label:"\u05E7\u05DC\u05D8",gender:"m"},lowercase:{label:"\u05E7\u05DC\u05D8",gender:"m"},starts_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},uppercase:{label:"\u05E7\u05DC\u05D8",gender:"m"}},l={nan:"NaN"};return c=>{switch(c.code){case"invalid_type":{let u=c.expected,d=l[u??""]??r(u),f=Qe(c.input),p=l[f]??t[f]?.label??f;return/^[A-Z]/.test(c.expected)?`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${c.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${p}`:`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${d}, \u05D4\u05EA\u05E7\u05D1\u05DC ${p}`}case"invalid_value":{if(c.values.length===1)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${Xe(c.values[0])}`;let u=c.values.map(p=>Xe(p));if(c.values.length===2)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${u[0]} \u05D0\u05D5 ${u[1]}`;let d=u[u.length-1];return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${u.slice(0,-1).join(", ")} \u05D0\u05D5 ${d}`}case"too_big":{let u=s(c.origin),d=o(c.origin??"value");if(c.origin==="string")return`${u?.longLabel??"\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${d} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${c.maximum.toString()} ${u?.unit??""} ${c.inclusive?"\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA":"\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim();if(c.origin==="number"){let m=c.inclusive?`\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${c.maximum}`:`\u05E7\u05D8\u05DF \u05DE-${c.maximum}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${d} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${m}`}if(c.origin==="array"||c.origin==="set"){let m=c.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA",h=c.inclusive?`${c.maximum} ${u?.unit??""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA`:`\u05E4\u05D7\u05D5\u05EA \u05DE-${c.maximum} ${u?.unit??""}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${d} ${m} \u05DC\u05D4\u05DB\u05D9\u05DC ${h}`.trim()}let f=c.inclusive?"<=":"<",p=i(c.origin??"value");return u?.unit?`${u.longLabel} \u05DE\u05D3\u05D9: ${d} ${p} ${f}${c.maximum.toString()} ${u.unit}`:`${u?.longLabel??"\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${d} ${p} ${f}${c.maximum.toString()}`}case"too_small":{let u=s(c.origin),d=o(c.origin??"value");if(c.origin==="string")return`${u?.shortLabel??"\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${d} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${c.minimum.toString()} ${u?.unit??""} ${c.inclusive?"\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8":"\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim();if(c.origin==="number"){let m=c.inclusive?`\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${c.minimum}`:`\u05D2\u05D3\u05D5\u05DC \u05DE-${c.minimum}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${d} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${m}`}if(c.origin==="array"||c.origin==="set"){let m=c.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA";if(c.minimum===1&&c.inclusive){let g=(c.origin==="set","\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3");return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${d} ${m} \u05DC\u05D4\u05DB\u05D9\u05DC ${g}`}let h=c.inclusive?`${c.minimum} ${u?.unit??""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8`:`\u05D9\u05D5\u05EA\u05E8 \u05DE-${c.minimum} ${u?.unit??""}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${d} ${m} \u05DC\u05D4\u05DB\u05D9\u05DC ${h}`.trim()}let f=c.inclusive?">=":">",p=i(c.origin??"value");return u?.unit?`${u.shortLabel} \u05DE\u05D3\u05D9: ${d} ${p} ${f}${c.minimum.toString()} ${u.unit}`:`${u?.shortLabel??"\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${d} ${p} ${f}${c.minimum.toString()}`}case"invalid_format":{let u=c;if(u.format==="starts_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${u.prefix}"`;if(u.format==="ends_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${u.suffix}"`;if(u.format==="includes")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${u.includes}"`;if(u.format==="regex")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${u.pattern}`;let d=a[u.format],f=d?.label??u.format,m=(d?.gender??"m")==="f"?"\u05EA\u05E7\u05D9\u05E0\u05D4":"\u05EA\u05E7\u05D9\u05DF";return`${f} \u05DC\u05D0 ${m}`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${c.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${c.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${c.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${Ce(c.keys,", ")}`;case"invalid_key":return"\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8";case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${o(c.origin??"array")}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}}}});function bbt(){return{localeError:w1n()}}var w1n,_bt=b(()=>{wn();w1n=()=>{let t={string:{unit:"znakova",verb:"imati"},file:{unit:"bajtova",verb:"imati"},array:{unit:"stavki",verb:"imati"},set:{unit:"stavki",verb:"imati"}};function e(o){return t[o]??null}let n={regex:"unos",email:"email adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum i vrijeme",date:"ISO datum",time:"ISO vrijeme",duration:"ISO trajanje",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"IPv4 raspon",cidrv6:"IPv6 raspon",base64:"base64 kodirani tekst",base64url:"base64url kodirani tekst",json_string:"JSON tekst",e164:"E.164 broj",jwt:"JWT",template_literal:"unos"},r={nan:"NaN",string:"tekst",number:"broj",boolean:"boolean",array:"niz",object:"objekt",set:"skup",file:"datoteka",date:"datum",bigint:"bigint",symbol:"simbol",undefined:"undefined",null:"null",function:"funkcija",map:"mapa"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Neispravan unos: o\u010Dekuje se instanceof ${o.expected}, a primljeno je ${a}`:`Neispravan unos: o\u010Dekuje se ${i}, a primljeno je ${a}`}case"invalid_value":return o.values.length===1?`Neispravna vrijednost: o\u010Dekivano ${Xe(o.values[0])}`:`Neispravna opcija: o\u010Dekivano jedno od ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin),a=r[o.origin]??o.origin;return s?`Preveliko: o\u010Dekivano da ${a??"vrijednost"} ima ${i}${o.maximum.toString()} ${s.unit??"elemenata"}`:`Preveliko: o\u010Dekivano da ${a??"vrijednost"} bude ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin),a=r[o.origin]??o.origin;return s?`Premalo: o\u010Dekivano da ${a} ima ${i}${o.minimum.toString()} ${s.unit}`:`Premalo: o\u010Dekivano da ${a} bude ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Neispravan tekst: mora zapo\u010Dinjati s "${i.prefix}"`:i.format==="ends_with"?`Neispravan tekst: mora zavr\u0161avati s "${i.suffix}"`:i.format==="includes"?`Neispravan tekst: mora sadr\u017Eavati "${i.includes}"`:i.format==="regex"?`Neispravan tekst: mora odgovarati uzorku ${i.pattern}`:`Neispravna ${n[i.format]??o.format}`}case"not_multiple_of":return`Neispravan broj: mora biti vi\u0161ekratnik od ${o.divisor}`;case"unrecognized_keys":return`Neprepoznat${o.keys.length>1?"i klju\u010Devi":" klju\u010D"}: ${Ce(o.keys,", ")}`;case"invalid_key":return`Neispravan klju\u010D u ${r[o.origin]??o.origin}`;case"invalid_union":return"Neispravan unos";case"invalid_element":return`Neispravna vrijednost u ${r[o.origin]??o.origin}`;default:return"Neispravan unos"}}}});function xbt(){return{localeError:b1n()}}var b1n,Sbt=b(()=>{wn();b1n=()=>{let t={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function e(o){return t[o]??null}let n={regex:"bemenet",email:"email c\xEDm",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO id\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"},r={nan:"NaN",number:"sz\xE1m",array:"t\xF6mb"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${o.expected}, a kapott \xE9rt\xE9k ${a}`:`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${i}, a kapott \xE9rt\xE9k ${a}`}case"invalid_value":return o.values.length===1?`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${Xe(o.values[0])}`:`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`T\xFAl nagy: ${o.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${i}${o.maximum.toString()} ${s.unit??"elem"}`:`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${o.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${o.origin} m\xE9rete t\xFAl kicsi ${i}${o.minimum.toString()} ${s.unit}`:`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${o.origin} t\xFAl kicsi ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\xC9rv\xE9nytelen string: "${i.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`:i.format==="ends_with"?`\xC9rv\xE9nytelen string: "${i.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`:i.format==="includes"?`\xC9rv\xE9nytelen string: "${i.includes}" \xE9rt\xE9ket kell tartalmaznia`:i.format==="regex"?`\xC9rv\xE9nytelen string: ${i.pattern} mint\xE1nak kell megfelelnie`:`\xC9rv\xE9nytelen ${n[i.format]??o.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${o.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${o.keys.length>1?"s":""}: ${Ce(o.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${o.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${o.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}}}});function Cbt(t,e,n){return Math.abs(t)===1?e:n}function HU(t){if(!t)return"";let e=["\u0561","\u0565","\u0568","\u056B","\u0578","\u0578\u0582","\u0585"],n=t[t.length-1];return t+(e.includes(n)?"\u0576":"\u0568")}function kbt(){return{localeError:_1n()}}var _1n,Ibt=b(()=>{wn();_1n=()=>{let t={string:{unit:{one:"\u0576\u0577\u0561\u0576",many:"\u0576\u0577\u0561\u0576\u0576\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},file:{unit:{one:"\u0562\u0561\u0575\u0569",many:"\u0562\u0561\u0575\u0569\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},array:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},set:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"}};function e(o){return t[o]??null}let n={regex:"\u0574\u0578\u0582\u057F\u0584",email:"\u0567\u056C. \u0570\u0561\u057D\u0581\u0565",url:"URL",emoji:"\u0567\u0574\u0578\u057B\u056B",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574",date:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E",time:"ISO \u056A\u0561\u0574",duration:"ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576",ipv4:"IPv4 \u0570\u0561\u057D\u0581\u0565",ipv6:"IPv6 \u0570\u0561\u057D\u0581\u0565",cidrv4:"IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",cidrv6:"IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",base64:"base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",base64url:"base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",json_string:"JSON \u057F\u0578\u0572",e164:"E.164 \u0570\u0561\u0574\u0561\u0580",jwt:"JWT",template_literal:"\u0574\u0578\u0582\u057F\u0584"},r={nan:"NaN",number:"\u0569\u056B\u057E",array:"\u0566\u0561\u0576\u0563\u057E\u0561\u056E"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${o.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${a}`:`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${i}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${a}`}case"invalid_value":return o.values.length===1?`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${Xe(o.values[1])}`:`\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);if(s){let a=Number(o.maximum),l=Cbt(a,s.unit.one,s.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${HU(o.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${i}${o.maximum.toString()} ${l}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${HU(o.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);if(s){let a=Number(o.minimum),l=Cbt(a,s.unit.one,s.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${HU(o.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${i}${o.minimum.toString()} ${l}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${HU(o.origin)} \u056C\u056B\u0576\u056B ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${i.prefix}"-\u0578\u057E`:i.format==="ends_with"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${i.suffix}"-\u0578\u057E`:i.format==="includes"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${i.includes}"`:i.format==="regex"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${i.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`:`\u054D\u056D\u0561\u056C ${n[i.format]??o.format}`}case"not_multiple_of":return`\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${o.divisor}-\u056B`;case"unrecognized_keys":return`\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${o.keys.length>1?"\u0576\u0565\u0580":""}. ${Ce(o.keys,", ")}`;case"invalid_key":return`\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${HU(o.origin)}-\u0578\u0582\u0574`;case"invalid_union":return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574";case"invalid_element":return`\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${HU(o.origin)}-\u0578\u0582\u0574`;default:return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"}}}});function Tbt(){return{localeError:x1n()}}var x1n,Pbt=b(()=>{wn();x1n=()=>{let t={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function e(o){return t[o]??null}let n={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Input tidak valid: diharapkan instanceof ${o.expected}, diterima ${a}`:`Input tidak valid: diharapkan ${i}, diterima ${a}`}case"invalid_value":return o.values.length===1?`Input tidak valid: diharapkan ${Xe(o.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Terlalu besar: diharapkan ${o.origin??"value"} memiliki ${i}${o.maximum.toString()} ${s.unit??"elemen"}`:`Terlalu besar: diharapkan ${o.origin??"value"} menjadi ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Terlalu kecil: diharapkan ${o.origin} memiliki ${i}${o.minimum.toString()} ${s.unit}`:`Terlalu kecil: diharapkan ${o.origin} menjadi ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`String tidak valid: harus dimulai dengan "${i.prefix}"`:i.format==="ends_with"?`String tidak valid: harus berakhir dengan "${i.suffix}"`:i.format==="includes"?`String tidak valid: harus menyertakan "${i.includes}"`:i.format==="regex"?`String tidak valid: harus sesuai pola ${i.pattern}`:`${n[i.format]??o.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${o.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${o.keys.length>1?"s":""}: ${Ce(o.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${o.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${o.origin}`;default:return"Input tidak valid"}}}});function Abt(){return{localeError:S1n()}}var S1n,Ebt=b(()=>{wn();S1n=()=>{let t={string:{unit:"stafi",verb:"a\xF0 hafa"},file:{unit:"b\xE6ti",verb:"a\xF0 hafa"},array:{unit:"hluti",verb:"a\xF0 hafa"},set:{unit:"hluti",verb:"a\xF0 hafa"}};function e(o){return t[o]??null}let n={regex:"gildi",email:"netfang",url:"vefsl\xF3\xF0",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og t\xEDmi",date:"ISO dagsetning",time:"ISO t\xEDmi",duration:"ISO t\xEDmalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 t\xF6lugildi",jwt:"JWT",template_literal:"gildi"},r={nan:"NaN",number:"n\xFAmer",array:"fylki"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Rangt gildi: \xDE\xFA sl\xF3st inn ${a} \xFEar sem \xE1 a\xF0 vera instanceof ${o.expected}`:`Rangt gildi: \xDE\xFA sl\xF3st inn ${a} \xFEar sem \xE1 a\xF0 vera ${i}`}case"invalid_value":return o.values.length===1?`Rangt gildi: gert r\xE1\xF0 fyrir ${Xe(o.values[0])}`:`\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${o.origin??"gildi"} hafi ${i}${o.maximum.toString()} ${s.unit??"hluti"}`:`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${o.origin??"gildi"} s\xE9 ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${o.origin} hafi ${i}${o.minimum.toString()} ${s.unit}`:`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${o.origin} s\xE9 ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${i.prefix}"`:i.format==="ends_with"?`\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${i.suffix}"`:i.format==="includes"?`\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${i.includes}"`:i.format==="regex"?`\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${i.pattern}`:`Rangt ${n[i.format]??o.format}`}case"not_multiple_of":return`R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${o.divisor}`;case"unrecognized_keys":return`\xD3\xFEekkt ${o.keys.length>1?"ir lyklar":"ur lykill"}: ${Ce(o.keys,", ")}`;case"invalid_key":return`Rangur lykill \xED ${o.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi \xED ${o.origin}`;default:return"Rangt gildi"}}}});function Mbt(){return{localeError:C1n()}}var C1n,Obt=b(()=>{wn();C1n=()=>{let t={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function e(o){return t[o]??null}let n={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},r={nan:"NaN",number:"numero",array:"vettore"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Input non valido: atteso instanceof ${o.expected}, ricevuto ${a}`:`Input non valido: atteso ${i}, ricevuto ${a}`}case"invalid_value":return o.values.length===1?`Input non valido: atteso ${Xe(o.values[0])}`:`Opzione non valida: atteso uno tra ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Troppo grande: ${o.origin??"valore"} deve avere ${i}${o.maximum.toString()} ${s.unit??"elementi"}`:`Troppo grande: ${o.origin??"valore"} deve essere ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Troppo piccolo: ${o.origin} deve avere ${i}${o.minimum.toString()} ${s.unit}`:`Troppo piccolo: ${o.origin} deve essere ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Stringa non valida: deve iniziare con "${i.prefix}"`:i.format==="ends_with"?`Stringa non valida: deve terminare con "${i.suffix}"`:i.format==="includes"?`Stringa non valida: deve includere "${i.includes}"`:i.format==="regex"?`Stringa non valida: deve corrispondere al pattern ${i.pattern}`:`Input non valido: ${n[i.format]??o.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${o.divisor}`;case"unrecognized_keys":return`Chiav${o.keys.length>1?"i":"e"} non riconosciut${o.keys.length>1?"e":"a"}: ${Ce(o.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${o.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${o.origin}`;default:return"Input non valido"}}}});function Nbt(){return{localeError:k1n()}}var k1n,Rbt=b(()=>{wn();k1n=()=>{let t={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function e(o){return t[o]??null}let n={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"},r={nan:"NaN",number:"\u6570\u5024",array:"\u914D\u5217"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`\u7121\u52B9\u306A\u5165\u529B: instanceof ${o.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${a}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`:`\u7121\u52B9\u306A\u5165\u529B: ${i}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${a}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`}case"invalid_value":return o.values.length===1?`\u7121\u52B9\u306A\u5165\u529B: ${Xe(o.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`:`\u7121\u52B9\u306A\u9078\u629E: ${Ce(o.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let i=o.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",s=e(o.origin);return s?`\u5927\u304D\u3059\u304E\u308B\u5024: ${o.origin??"\u5024"}\u306F${o.maximum.toString()}${s.unit??"\u8981\u7D20"}${i}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5927\u304D\u3059\u304E\u308B\u5024: ${o.origin??"\u5024"}\u306F${o.maximum.toString()}${i}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let i=o.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",s=e(o.origin);return s?`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${o.origin}\u306F${o.minimum.toString()}${s.unit}${i}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${o.origin}\u306F${o.minimum.toString()}${i}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${i.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:i.format==="ends_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${i.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:i.format==="includes"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${i.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:i.format==="regex"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${i.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u7121\u52B9\u306A${n[i.format]??o.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${o.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${o.keys.length>1?"\u7FA4":""}: ${Ce(o.keys,"\u3001")}`;case"invalid_key":return`${o.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${o.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}}}});function Lbt(){return{localeError:I1n()}}var I1n,$bt=b(()=>{wn();I1n=()=>{let t={string:{unit:"\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},file:{unit:"\u10D1\u10D0\u10D8\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},array:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},set:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"}};function e(o){return t[o]??null}let n={regex:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0",email:"\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",url:"URL",emoji:"\u10D4\u10DB\u10DD\u10EF\u10D8",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD",date:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8",time:"\u10D3\u10E0\u10DD",duration:"\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0",ipv4:"IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",ipv6:"IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",cidrv4:"IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",cidrv6:"IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",base64:"base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",base64url:"base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",json_string:"JSON \u10D5\u10D4\u10DA\u10D8",e164:"E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8",jwt:"JWT",template_literal:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"},r={nan:"NaN",number:"\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8",string:"\u10D5\u10D4\u10DA\u10D8",boolean:"\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8",function:"\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0",array:"\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${o.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${a}`:`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${i}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${a}`}case"invalid_value":return o.values.length===1?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${Xe(o.values[0])}`:`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${Ce(o.values,"|")}-\u10D3\u10D0\u10DC`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${o.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${s.verb} ${i}${o.maximum.toString()} ${s.unit}`:`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${o.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${o.origin} ${s.verb} ${i}${o.minimum.toString()} ${s.unit}`:`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${o.origin} \u10D8\u10E7\u10DD\u10E1 ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${i.prefix}"-\u10D8\u10D7`:i.format==="ends_with"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${i.suffix}"-\u10D8\u10D7`:i.format==="includes"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${i.includes}"-\u10E1`:i.format==="regex"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${i.pattern}`:`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${n[i.format]??o.format}`}case"not_multiple_of":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${o.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`;case"unrecognized_keys":return`\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${o.keys.length>1?"\u10D4\u10D1\u10D8":"\u10D8"}: ${Ce(o.keys,", ")}`;case"invalid_key":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${o.origin}-\u10E8\u10D8`;case"invalid_union":return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0";case"invalid_element":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${o.origin}-\u10E8\u10D8`;default:return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"}}}});function Sle(){return{localeError:T1n()}}var T1n,d1e=b(()=>{wn();T1n=()=>{let t={string:{unit:"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},file:{unit:"\u1794\u17C3",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},array:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},set:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"}};function e(o){return t[o]??null}let n={regex:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",email:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",url:"URL",emoji:"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",date:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",time:"\u1798\u17C9\u17C4\u1784 ISO",duration:"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",ipv4:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",ipv6:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",cidrv4:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",cidrv6:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",base64:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",base64url:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",json_string:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",e164:"\u179B\u17C1\u1781 E.164",jwt:"JWT",template_literal:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"},r={nan:"NaN",number:"\u179B\u17C1\u1781",array:"\u17A2\u17B6\u179A\u17C1 (Array)",null:"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${o.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${a}`:`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${i} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${a}`}case"invalid_value":return o.values.length===1?`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${Xe(o.values[0])}`:`\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${i} ${o.maximum.toString()} ${s.unit??"\u1792\u17B6\u178F\u17BB"}`:`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${i} ${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o.origin} ${i} ${o.minimum.toString()} ${s.unit}`:`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o.origin} ${i} ${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${i.prefix}"`:i.format==="ends_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${i.suffix}"`:i.format==="includes"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${i.includes}"`:i.format==="regex"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${i.pattern}`:`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${n[i.format]??o.format}`}case"not_multiple_of":return`\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${o.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${Ce(o.keys,", ")}`;case"invalid_key":return`\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${o.origin}`;case"invalid_union":return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C";case"invalid_element":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${o.origin}`;default:return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C"}}}});function Dbt(){return Sle()}var Fbt=b(()=>{d1e()});function Ubt(){return{localeError:P1n()}}var P1n,jbt=b(()=>{wn();P1n=()=>{let t={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function e(o){return t[o]??null}let n={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"},r={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${o.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${a}\uC785\uB2C8\uB2E4`:`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${i}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${a}\uC785\uB2C8\uB2E4`}case"invalid_value":return o.values.length===1?`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${Xe(o.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C \uC635\uC158: ${Ce(o.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let i=o.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",s=i==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",a=e(o.origin),l=a?.unit??"\uC694\uC18C";return a?`${o.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${o.maximum.toString()}${l} ${i}${s}`:`${o.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${o.maximum.toString()} ${i}${s}`}case"too_small":{let i=o.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",s=i==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",a=e(o.origin),l=a?.unit??"\uC694\uC18C";return a?`${o.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${o.minimum.toString()}${l} ${i}${s}`:`${o.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${o.minimum.toString()} ${i}${s}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${i.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`:i.format==="ends_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${i.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`:i.format==="includes"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${i.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`:i.format==="regex"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${i.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C ${n[i.format]??o.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${o.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${Ce(o.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${o.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${o.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}}}});function Bbt(t){let e=Math.abs(t),n=e%10,r=e%100;return r>=11&&r<=19||n===0?"many":n===1?"one":"few"}function zbt(){return{localeError:A1n()}}var y8,A1n,Hbt=b(()=>{wn();y8=t=>t.charAt(0).toUpperCase()+t.slice(1);A1n=()=>{let t={string:{unit:{one:"simbolis",few:"simboliai",many:"simboli\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne ilgesn\u0117 kaip",notInclusive:"turi b\u016Bti trumpesn\u0117 kaip"},bigger:{inclusive:"turi b\u016Bti ne trumpesn\u0117 kaip",notInclusive:"turi b\u016Bti ilgesn\u0117 kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"bait\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne didesnis kaip",notInclusive:"turi b\u016Bti ma\u017Eesnis kaip"},bigger:{inclusive:"turi b\u016Bti ne ma\u017Eesnis kaip",notInclusive:"turi b\u016Bti didesnis kaip"}}},array:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}},set:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}}};function e(o,i,s,a){let l=t[o]??null;return l===null?l:{unit:l.unit[i],verb:l.verb[a][s?"inclusive":"notInclusive"]}}let n={regex:"\u012Fvestis",email:"el. pa\u0161to adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukm\u0117",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 u\u017Ekoduota eilut\u0117",base64url:"base64url u\u017Ekoduota eilut\u0117",json_string:"JSON eilut\u0117",e164:"E.164 numeris",jwt:"JWT",template_literal:"\u012Fvestis"},r={nan:"NaN",number:"skai\u010Dius",bigint:"sveikasis skai\u010Dius",string:"eilut\u0117",boolean:"login\u0117 reik\u0161m\u0117",undefined:"neapibr\u0117\u017Eta reik\u0161m\u0117",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulin\u0117 reik\u0161m\u0117"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Gautas tipas ${a}, o tik\u0117tasi - instanceof ${o.expected}`:`Gautas tipas ${a}, o tik\u0117tasi - ${i}`}case"invalid_value":return o.values.length===1?`Privalo b\u016Bti ${Xe(o.values[0])}`:`Privalo b\u016Bti vienas i\u0161 ${Ce(o.values,"|")} pasirinkim\u0173`;case"too_big":{let i=r[o.origin]??o.origin,s=e(o.origin,Bbt(Number(o.maximum)),o.inclusive??!1,"smaller");if(s?.verb)return`${y8(i??o.origin??"reik\u0161m\u0117")} ${s.verb} ${o.maximum.toString()} ${s.unit??"element\u0173"}`;let a=o.inclusive?"ne didesnis kaip":"ma\u017Eesnis kaip";return`${y8(i??o.origin??"reik\u0161m\u0117")} turi b\u016Bti ${a} ${o.maximum.toString()} ${s?.unit}`}case"too_small":{let i=r[o.origin]??o.origin,s=e(o.origin,Bbt(Number(o.minimum)),o.inclusive??!1,"bigger");if(s?.verb)return`${y8(i??o.origin??"reik\u0161m\u0117")} ${s.verb} ${o.minimum.toString()} ${s.unit??"element\u0173"}`;let a=o.inclusive?"ne ma\u017Eesnis kaip":"didesnis kaip";return`${y8(i??o.origin??"reik\u0161m\u0117")} turi b\u016Bti ${a} ${o.minimum.toString()} ${s?.unit}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Eilut\u0117 privalo prasid\u0117ti "${i.prefix}"`:i.format==="ends_with"?`Eilut\u0117 privalo pasibaigti "${i.suffix}"`:i.format==="includes"?`Eilut\u0117 privalo \u012Ftraukti "${i.includes}"`:i.format==="regex"?`Eilut\u0117 privalo atitikti ${i.pattern}`:`Neteisingas ${n[i.format]??o.format}`}case"not_multiple_of":return`Skai\u010Dius privalo b\u016Bti ${o.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpa\u017Eint${o.keys.length>1?"i":"as"} rakt${o.keys.length>1?"ai":"as"}: ${Ce(o.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga \u012Fvestis";case"invalid_element":{let i=r[o.origin]??o.origin;return`${y8(i??o.origin??"reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`}default:return"Klaidinga \u012Fvestis"}}}});function Wbt(){return{localeError:E1n()}}var E1n,Vbt=b(()=>{wn();E1n=()=>{let t={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function e(o){return t[o]??null}let n={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"},r={nan:"NaN",number:"\u0431\u0440\u043E\u0458",array:"\u043D\u0438\u0437\u0430"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${o.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${a}`:`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${i}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${a}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${Xe(o.values[0])}`:`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${o.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${i}${o.maximum.toString()} ${s.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${o.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${o.origin} \u0434\u0430 \u0438\u043C\u0430 ${i}${o.minimum.toString()} ${s.unit}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${o.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${i.prefix}"`:i.format==="ends_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${i.suffix}"`:i.format==="includes"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${i.includes}"`:i.format==="regex"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${i.pattern}`:`Invalid ${n[i.format]??o.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${o.divisor}`;case"unrecognized_keys":return`${o.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${Ce(o.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${o.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${o.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}}}});function qbt(){return{localeError:M1n()}}var M1n,Kbt=b(()=>{wn();M1n=()=>{let t={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function e(o){return t[o]??null}let n={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},r={nan:"NaN",number:"nombor"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Input tidak sah: dijangka instanceof ${o.expected}, diterima ${a}`:`Input tidak sah: dijangka ${i}, diterima ${a}`}case"invalid_value":return o.values.length===1?`Input tidak sah: dijangka ${Xe(o.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Terlalu besar: dijangka ${o.origin??"nilai"} ${s.verb} ${i}${o.maximum.toString()} ${s.unit??"elemen"}`:`Terlalu besar: dijangka ${o.origin??"nilai"} adalah ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Terlalu kecil: dijangka ${o.origin} ${s.verb} ${i}${o.minimum.toString()} ${s.unit}`:`Terlalu kecil: dijangka ${o.origin} adalah ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`String tidak sah: mesti bermula dengan "${i.prefix}"`:i.format==="ends_with"?`String tidak sah: mesti berakhir dengan "${i.suffix}"`:i.format==="includes"?`String tidak sah: mesti mengandungi "${i.includes}"`:i.format==="regex"?`String tidak sah: mesti sepadan dengan corak ${i.pattern}`:`${n[i.format]??o.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${o.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${Ce(o.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${o.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${o.origin}`;default:return"Input tidak sah"}}}});function Gbt(){return{localeError:O1n()}}var O1n,Zbt=b(()=>{wn();O1n=()=>{let t={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function e(o){return t[o]??null}let n={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},r={nan:"NaN",number:"getal"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Ongeldige invoer: verwacht instanceof ${o.expected}, ontving ${a}`:`Ongeldige invoer: verwacht ${i}, ontving ${a}`}case"invalid_value":return o.values.length===1?`Ongeldige invoer: verwacht ${Xe(o.values[0])}`:`Ongeldige optie: verwacht \xE9\xE9n van ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin),a=o.origin==="date"?"laat":o.origin==="string"?"lang":"groot";return s?`Te ${a}: verwacht dat ${o.origin??"waarde"} ${i}${o.maximum.toString()} ${s.unit??"elementen"} ${s.verb}`:`Te ${a}: verwacht dat ${o.origin??"waarde"} ${i}${o.maximum.toString()} is`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin),a=o.origin==="date"?"vroeg":o.origin==="string"?"kort":"klein";return s?`Te ${a}: verwacht dat ${o.origin} ${i}${o.minimum.toString()} ${s.unit} ${s.verb}`:`Te ${a}: verwacht dat ${o.origin} ${i}${o.minimum.toString()} is`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Ongeldige tekst: moet met "${i.prefix}" beginnen`:i.format==="ends_with"?`Ongeldige tekst: moet op "${i.suffix}" eindigen`:i.format==="includes"?`Ongeldige tekst: moet "${i.includes}" bevatten`:i.format==="regex"?`Ongeldige tekst: moet overeenkomen met patroon ${i.pattern}`:`Ongeldig: ${n[i.format]??o.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${o.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${o.keys.length>1?"s":""}: ${Ce(o.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${o.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${o.origin}`;default:return"Ongeldige invoer"}}}});function Ybt(){return{localeError:N1n()}}var N1n,Jbt=b(()=>{wn();N1n=()=>{let t={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function e(o){return t[o]??null}let n={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},r={nan:"NaN",number:"tall",array:"liste"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Ugyldig input: forventet instanceof ${o.expected}, fikk ${a}`:`Ugyldig input: forventet ${i}, fikk ${a}`}case"invalid_value":return o.values.length===1?`Ugyldig verdi: forventet ${Xe(o.values[0])}`:`Ugyldig valg: forventet en av ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`For stor(t): forventet ${o.origin??"value"} til \xE5 ha ${i}${o.maximum.toString()} ${s.unit??"elementer"}`:`For stor(t): forventet ${o.origin??"value"} til \xE5 ha ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`For lite(n): forventet ${o.origin} til \xE5 ha ${i}${o.minimum.toString()} ${s.unit}`:`For lite(n): forventet ${o.origin} til \xE5 ha ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Ugyldig streng: m\xE5 starte med "${i.prefix}"`:i.format==="ends_with"?`Ugyldig streng: m\xE5 ende med "${i.suffix}"`:i.format==="includes"?`Ugyldig streng: m\xE5 inneholde "${i.includes}"`:i.format==="regex"?`Ugyldig streng: m\xE5 matche m\xF8nsteret ${i.pattern}`:`Ugyldig ${n[i.format]??o.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${o.divisor}`;case"unrecognized_keys":return`${o.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${Ce(o.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${o.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${o.origin}`;default:return"Ugyldig input"}}}});function Xbt(){return{localeError:R1n()}}var R1n,Qbt=b(()=>{wn();R1n=()=>{let t={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function e(o){return t[o]??null}let n={regex:"giren",email:"epostag\xE2h",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO heng\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"},r={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`F\xE2sit giren: umulan instanceof ${o.expected}, al\u0131nan ${a}`:`F\xE2sit giren: umulan ${i}, al\u0131nan ${a}`}case"invalid_value":return o.values.length===1?`F\xE2sit giren: umulan ${Xe(o.values[0])}`:`F\xE2sit tercih: m\xFBteberler ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Fazla b\xFCy\xFCk: ${o.origin??"value"}, ${i}${o.maximum.toString()} ${s.unit??"elements"} sahip olmal\u0131yd\u0131.`:`Fazla b\xFCy\xFCk: ${o.origin??"value"}, ${i}${o.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Fazla k\xFC\xE7\xFCk: ${o.origin}, ${i}${o.minimum.toString()} ${s.unit} sahip olmal\u0131yd\u0131.`:`Fazla k\xFC\xE7\xFCk: ${o.origin}, ${i}${o.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let i=o;return i.format==="starts_with"?`F\xE2sit metin: "${i.prefix}" ile ba\u015Flamal\u0131.`:i.format==="ends_with"?`F\xE2sit metin: "${i.suffix}" ile bitmeli.`:i.format==="includes"?`F\xE2sit metin: "${i.includes}" ihtiv\xE2 etmeli.`:i.format==="regex"?`F\xE2sit metin: ${i.pattern} nak\u015F\u0131na uymal\u0131.`:`F\xE2sit ${n[i.format]??o.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${o.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${o.keys.length>1?"s":""}: ${Ce(o.keys,", ")}`;case"invalid_key":return`${o.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${o.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}}}});function e_t(){return{localeError:L1n()}}var L1n,t_t=b(()=>{wn();L1n=()=>{let t={string:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},file:{unit:"\u0628\u0627\u06CC\u067C\u0633",verb:"\u0648\u0644\u0631\u064A"},array:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},set:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"}};function e(o){return t[o]??null}let n={regex:"\u0648\u0631\u0648\u062F\u064A",email:"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",url:"\u06CC\u0648 \u0622\u0631 \u0627\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",date:"\u0646\u06D0\u067C\u0647",time:"\u0648\u062E\u062A",duration:"\u0645\u0648\u062F\u0647",ipv4:"\u062F IPv4 \u067E\u062A\u0647",ipv6:"\u062F IPv6 \u067E\u062A\u0647",cidrv4:"\u062F IPv4 \u0633\u0627\u062D\u0647",cidrv6:"\u062F IPv6 \u0633\u0627\u062D\u0647",base64:"base64-encoded \u0645\u062A\u0646",base64url:"base64url-encoded \u0645\u062A\u0646",json_string:"JSON \u0645\u062A\u0646",e164:"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u064A"},r={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0627\u0631\u06D0"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${o.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${a} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`:`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${i} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${a} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`}case"invalid_value":return o.values.length===1?`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${Xe(o.values[0])} \u0648\u0627\u06CC`:`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${Ce(o.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${o.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${i}${o.maximum.toString()} ${s.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${o.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${i}${o.maximum.toString()} \u0648\u064A`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${o.origin} \u0628\u0627\u06CC\u062F ${i}${o.minimum.toString()} ${s.unit} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${o.origin} \u0628\u0627\u06CC\u062F ${i}${o.minimum.toString()} \u0648\u064A`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${i.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`:i.format==="ends_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${i.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`:i.format==="includes"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${i.includes}" \u0648\u0644\u0631\u064A`:i.format==="regex"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${i.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`:`${n[i.format]??o.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${o.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${o.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${Ce(o.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${o.origin} \u06A9\u06D0`;case"invalid_union":return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A";case"invalid_element":return`\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${o.origin} \u06A9\u06D0`;default:return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A"}}}});function n_t(){return{localeError:$1n()}}var $1n,r_t=b(()=>{wn();$1n=()=>{let t={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function e(o){return t[o]??null}let n={regex:"wyra\u017Cenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ci\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"},r={nan:"NaN",number:"liczba",array:"tablica"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${o.expected}, otrzymano ${a}`:`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${i}, otrzymano ${a}`}case"invalid_value":return o.values.length===1?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${Xe(o.values[0])}`:`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${o.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${i}${o.maximum.toString()} ${s.unit??"element\xF3w"}`:`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${o.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${o.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${i}${o.minimum.toString()} ${s.unit??"element\xF3w"}`:`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${o.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${i.prefix}"`:i.format==="ends_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${i.suffix}"`:i.format==="includes"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${i.includes}"`:i.format==="regex"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${i.pattern}`:`Nieprawid\u0142ow(y/a/e) ${n[i.format]??o.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${o.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${o.keys.length>1?"s":""}: ${Ce(o.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${o.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${o.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}}}});function o_t(){return{localeError:D1n()}}var D1n,i_t=b(()=>{wn();D1n=()=>{let t={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function e(o){return t[o]??null}let n={regex:"padr\xE3o",email:"endere\xE7o de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"dura\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},r={nan:"NaN",number:"n\xFAmero",null:"nulo"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Tipo inv\xE1lido: esperado instanceof ${o.expected}, recebido ${a}`:`Tipo inv\xE1lido: esperado ${i}, recebido ${a}`}case"invalid_value":return o.values.length===1?`Entrada inv\xE1lida: esperado ${Xe(o.values[0])}`:`Op\xE7\xE3o inv\xE1lida: esperada uma das ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Muito grande: esperado que ${o.origin??"valor"} tivesse ${i}${o.maximum.toString()} ${s.unit??"elementos"}`:`Muito grande: esperado que ${o.origin??"valor"} fosse ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Muito pequeno: esperado que ${o.origin} tivesse ${i}${o.minimum.toString()} ${s.unit}`:`Muito pequeno: esperado que ${o.origin} fosse ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Texto inv\xE1lido: deve come\xE7ar com "${i.prefix}"`:i.format==="ends_with"?`Texto inv\xE1lido: deve terminar com "${i.suffix}"`:i.format==="includes"?`Texto inv\xE1lido: deve incluir "${i.includes}"`:i.format==="regex"?`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${i.pattern}`:`${n[i.format]??o.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${o.divisor}`;case"unrecognized_keys":return`Chave${o.keys.length>1?"s":""} desconhecida${o.keys.length>1?"s":""}: ${Ce(o.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${o.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${o.origin}`;default:return"Campo inv\xE1lido"}}}});function s_t(){return{localeError:F1n()}}var F1n,a_t=b(()=>{wn();F1n=()=>{let t={string:{unit:"caractere",verb:"s\u0103 aib\u0103"},file:{unit:"octe\u021Bi",verb:"s\u0103 aib\u0103"},array:{unit:"elemente",verb:"s\u0103 aib\u0103"},set:{unit:"elemente",verb:"s\u0103 aib\u0103"},map:{unit:"intr\u0103ri",verb:"s\u0103 aib\u0103"}};function e(o){return t[o]??null}let n={regex:"intrare",email:"adres\u0103 de email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"dat\u0103 \u0219i or\u0103 ISO",date:"dat\u0103 ISO",time:"or\u0103 ISO",duration:"durat\u0103 ISO",ipv4:"adres\u0103 IPv4",ipv6:"adres\u0103 IPv6",mac:"adres\u0103 MAC",cidrv4:"interval IPv4",cidrv6:"interval IPv6",base64:"\u0219ir codat base64",base64url:"\u0219ir codat base64url",json_string:"\u0219ir JSON",e164:"num\u0103r E.164",jwt:"JWT",template_literal:"intrare"},r={nan:"NaN",string:"\u0219ir",number:"num\u0103r",boolean:"boolean",function:"func\u021Bie",array:"matrice",object:"obiect",undefined:"nedefinit",symbol:"simbol",bigint:"num\u0103r mare",void:"void",never:"never",map:"hart\u0103",set:"set"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return`Intrare invalid\u0103: a\u0219teptat ${i}, primit ${a}`}case"invalid_value":return o.values.length===1?`Intrare invalid\u0103: a\u0219teptat ${Xe(o.values[0])}`:`Op\u021Biune invalid\u0103: a\u0219teptat una dintre ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Prea mare: a\u0219teptat ca ${o.origin??"valoarea"} ${s.verb} ${i}${o.maximum.toString()} ${s.unit??"elemente"}`:`Prea mare: a\u0219teptat ca ${o.origin??"valoarea"} s\u0103 fie ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Prea mic: a\u0219teptat ca ${o.origin} ${s.verb} ${i}${o.minimum.toString()} ${s.unit}`:`Prea mic: a\u0219teptat ca ${o.origin} s\u0103 fie ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u0218ir invalid: trebuie s\u0103 \xEEnceap\u0103 cu "${i.prefix}"`:i.format==="ends_with"?`\u0218ir invalid: trebuie s\u0103 se termine cu "${i.suffix}"`:i.format==="includes"?`\u0218ir invalid: trebuie s\u0103 includ\u0103 "${i.includes}"`:i.format==="regex"?`\u0218ir invalid: trebuie s\u0103 se potriveasc\u0103 cu modelul ${i.pattern}`:`Format invalid: ${n[i.format]??o.format}`}case"not_multiple_of":return`Num\u0103r invalid: trebuie s\u0103 fie multiplu de ${o.divisor}`;case"unrecognized_keys":return`Chei nerecunoscute: ${Ce(o.keys,", ")}`;case"invalid_key":return`Cheie invalid\u0103 \xEEn ${o.origin}`;case"invalid_union":return"Intrare invalid\u0103";case"invalid_element":return`Valoare invalid\u0103 \xEEn ${o.origin}`;default:return"Intrare invalid\u0103"}}}});function l_t(t,e,n,r){let o=Math.abs(t),i=o%10,s=o%100;return s>=11&&s<=19?r:i===1?e:i>=2&&i<=4?n:r}function c_t(){return{localeError:U1n()}}var U1n,u_t=b(()=>{wn();U1n=()=>{let t={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function e(o){return t[o]??null}let n={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"},r={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0441\u0438\u0432"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${o.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${a}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${i}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${a}`}case"invalid_value":return o.values.length===1?`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${Xe(o.values[0])}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);if(s){let a=Number(o.maximum),l=l_t(a,s.unit.one,s.unit.few,s.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${i}${o.maximum.toString()} ${l}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);if(s){let a=Number(o.minimum),l=l_t(a,s.unit.one,s.unit.few,s.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${o.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${i}${o.minimum.toString()} ${l}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${o.origin} \u0431\u0443\u0434\u0435\u0442 ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${i.prefix}"`:i.format==="ends_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${i.suffix}"`:i.format==="includes"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${i.includes}"`:i.format==="regex"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${i.pattern}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${n[i.format]??o.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${o.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${o.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${o.keys.length>1?"\u0438":""}: ${Ce(o.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${o.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${o.origin}`;default:return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"}}}});function d_t(){return{localeError:j1n()}}var j1n,f_t=b(()=>{wn();j1n=()=>{let t={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function e(o){return t[o]??null}let n={regex:"vnos",email:"e-po\u0161tni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in \u010Das",date:"ISO datum",time:"ISO \u010Das",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 \u0161tevilka",jwt:"JWT",template_literal:"vnos"},r={nan:"NaN",number:"\u0161tevilo",array:"tabela"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Neveljaven vnos: pri\u010Dakovano instanceof ${o.expected}, prejeto ${a}`:`Neveljaven vnos: pri\u010Dakovano ${i}, prejeto ${a}`}case"invalid_value":return o.values.length===1?`Neveljaven vnos: pri\u010Dakovano ${Xe(o.values[0])}`:`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Preveliko: pri\u010Dakovano, da bo ${o.origin??"vrednost"} imelo ${i}${o.maximum.toString()} ${s.unit??"elementov"}`:`Preveliko: pri\u010Dakovano, da bo ${o.origin??"vrednost"} ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Premajhno: pri\u010Dakovano, da bo ${o.origin} imelo ${i}${o.minimum.toString()} ${s.unit}`:`Premajhno: pri\u010Dakovano, da bo ${o.origin} ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Neveljaven niz: mora se za\u010Deti z "${i.prefix}"`:i.format==="ends_with"?`Neveljaven niz: mora se kon\u010Dati z "${i.suffix}"`:i.format==="includes"?`Neveljaven niz: mora vsebovati "${i.includes}"`:i.format==="regex"?`Neveljaven niz: mora ustrezati vzorcu ${i.pattern}`:`Neveljaven ${n[i.format]??o.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${o.divisor}`;case"unrecognized_keys":return`Neprepoznan${o.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${Ce(o.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${o.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${o.origin}`;default:return"Neveljaven vnos"}}}});function p_t(){return{localeError:B1n()}}var B1n,m_t=b(()=>{wn();B1n=()=>{let t={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att inneh\xE5lla"},set:{unit:"objekt",verb:"att inneh\xE5lla"}};function e(o){return t[o]??null}let n={regex:"regulj\xE4rt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad str\xE4ng",base64url:"base64url-kodad str\xE4ng",json_string:"JSON-str\xE4ng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},r={nan:"NaN",number:"antal",array:"lista"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${o.expected}, fick ${a}`:`Ogiltig inmatning: f\xF6rv\xE4ntat ${i}, fick ${a}`}case"invalid_value":return o.values.length===1?`Ogiltig inmatning: f\xF6rv\xE4ntat ${Xe(o.values[0])}`:`Ogiltigt val: f\xF6rv\xE4ntade en av ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`F\xF6r stor(t): f\xF6rv\xE4ntade ${o.origin??"v\xE4rdet"} att ha ${i}${o.maximum.toString()} ${s.unit??"element"}`:`F\xF6r stor(t): f\xF6rv\xE4ntat ${o.origin??"v\xE4rdet"} att ha ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`F\xF6r lite(t): f\xF6rv\xE4ntade ${o.origin??"v\xE4rdet"} att ha ${i}${o.minimum.toString()} ${s.unit}`:`F\xF6r lite(t): f\xF6rv\xE4ntade ${o.origin??"v\xE4rdet"} att ha ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${i.prefix}"`:i.format==="ends_with"?`Ogiltig str\xE4ng: m\xE5ste sluta med "${i.suffix}"`:i.format==="includes"?`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${i.includes}"`:i.format==="regex"?`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${i.pattern}"`:`Ogiltig(t) ${n[i.format]??o.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${o.divisor}`;case"unrecognized_keys":return`${o.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${Ce(o.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${o.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${o.origin??"v\xE4rdet"}`;default:return"Ogiltig input"}}}});function h_t(){return{localeError:z1n()}}var z1n,g_t=b(()=>{wn();z1n=()=>{let t={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function e(o){return t[o]??null}let n={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"},r={nan:"NaN",number:"\u0B8E\u0BA3\u0BCD",array:"\u0B85\u0BA3\u0BBF",null:"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${o.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${a}`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${i}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${a}`}case"invalid_value":return o.values.length===1?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${Xe(o.values[0])}`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${Ce(o.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${o.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${i}${o.maximum.toString()} ${s.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${o.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${i}${o.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${o.origin} ${i}${o.minimum.toString()} ${s.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${o.origin} ${i}${o.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${i.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:i.format==="ends_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${i.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:i.format==="includes"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${i.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:i.format==="regex"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${i.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${n[i.format]??o.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${o.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${o.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${Ce(o.keys,", ")}`;case"invalid_key":return`${o.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${o.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"}}}});function y_t(){return{localeError:H1n()}}var H1n,v_t=b(()=>{wn();H1n=()=>{let t={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function e(o){return t[o]??null}let n={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"},r={nan:"NaN",number:"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02",array:"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)",null:"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${o.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${a}`:`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${i} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${a}`}case"invalid_value":return o.values.length===1?`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${Xe(o.values[0])}`:`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",s=e(o.origin);return s?`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${o.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${i} ${o.maximum.toString()} ${s.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`:`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${o.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${i} ${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",s=e(o.origin);return s?`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${o.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${i} ${o.minimum.toString()} ${s.unit}`:`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${o.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${i} ${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${i.prefix}"`:i.format==="ends_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${i.suffix}"`:i.format==="includes"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${i.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`:i.format==="regex"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${i.pattern}`:`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${n[i.format]??o.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${o.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${Ce(o.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${o.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${o.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}}}});function w_t(){return{localeError:W1n()}}var W1n,b_t=b(()=>{wn();W1n=()=>{let t={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function e(o){return t[o]??null}let n={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO s\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"},r={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Ge\xE7ersiz de\u011Fer: beklenen instanceof ${o.expected}, al\u0131nan ${a}`:`Ge\xE7ersiz de\u011Fer: beklenen ${i}, al\u0131nan ${a}`}case"invalid_value":return o.values.length===1?`Ge\xE7ersiz de\u011Fer: beklenen ${Xe(o.values[0])}`:`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\xC7ok b\xFCy\xFCk: beklenen ${o.origin??"de\u011Fer"} ${i}${o.maximum.toString()} ${s.unit??"\xF6\u011Fe"}`:`\xC7ok b\xFCy\xFCk: beklenen ${o.origin??"de\u011Fer"} ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\xC7ok k\xFC\xE7\xFCk: beklenen ${o.origin} ${i}${o.minimum.toString()} ${s.unit}`:`\xC7ok k\xFC\xE7\xFCk: beklenen ${o.origin} ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Ge\xE7ersiz metin: "${i.prefix}" ile ba\u015Flamal\u0131`:i.format==="ends_with"?`Ge\xE7ersiz metin: "${i.suffix}" ile bitmeli`:i.format==="includes"?`Ge\xE7ersiz metin: "${i.includes}" i\xE7ermeli`:i.format==="regex"?`Ge\xE7ersiz metin: ${i.pattern} desenine uymal\u0131`:`Ge\xE7ersiz ${n[i.format]??o.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${o.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${o.keys.length>1?"lar":""}: ${Ce(o.keys,", ")}`;case"invalid_key":return`${o.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${o.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}}}});function Cle(){return{localeError:V1n()}}var V1n,f1e=b(()=>{wn();V1n=()=>{let t={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function e(o){return t[o]??null}let n={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"},r={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${o.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${a}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${i}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${a}`}case"invalid_value":return o.values.length===1?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${Xe(o.values[0])}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${s.verb} ${i}${o.maximum.toString()} ${s.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${o.origin} ${s.verb} ${i}${o.minimum.toString()} ${s.unit}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${o.origin} \u0431\u0443\u0434\u0435 ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${i.prefix}"`:i.format==="ends_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${i.suffix}"`:i.format==="includes"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${i.includes}"`:i.format==="regex"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${i.pattern}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${n[i.format]??o.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${o.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${o.keys.length>1?"\u0456":""}: ${Ce(o.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${o.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${o.origin}`;default:return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"}}}});function __t(){return Cle()}var x_t=b(()=>{f1e()});function S_t(){return{localeError:q1n()}}var q1n,C_t=b(()=>{wn();q1n=()=>{let t={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function e(o){return t[o]??null}let n={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"},r={nan:"NaN",number:"\u0646\u0645\u0628\u0631",array:"\u0622\u0631\u06D2",null:"\u0646\u0644"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${o.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${a} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`:`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${i} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${a} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`}case"invalid_value":return o.values.length===1?`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${Xe(o.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`:`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${Ce(o.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u0628\u06C1\u062A \u0628\u0691\u0627: ${o.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${i}${o.maximum.toString()} ${s.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0628\u0691\u0627: ${o.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${i}${o.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${o.origin} \u06A9\u06D2 ${i}${o.minimum.toString()} ${s.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${o.origin} \u06A9\u0627 ${i}${o.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${i.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:i.format==="ends_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${i.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:i.format==="includes"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${i.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:i.format==="regex"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${i.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:`\u063A\u0644\u0637 ${n[i.format]??o.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${o.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${o.keys.length>1?"\u0632":""}: ${Ce(o.keys,"\u060C ")}`;case"invalid_key":return`${o.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${o.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}}}});function k_t(){return{localeError:K1n()}}var K1n,I_t=b(()=>{wn();K1n=()=>{let t={string:{unit:"belgi",verb:"bo\u2018lishi kerak"},file:{unit:"bayt",verb:"bo\u2018lishi kerak"},array:{unit:"element",verb:"bo\u2018lishi kerak"},set:{unit:"element",verb:"bo\u2018lishi kerak"},map:{unit:"yozuv",verb:"bo\u2018lishi kerak"}};function e(o){return t[o]??null}let n={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},r={nan:"NaN",number:"raqam",array:"massiv"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`Noto\u2018g\u2018ri kirish: kutilgan instanceof ${o.expected}, qabul qilingan ${a}`:`Noto\u2018g\u2018ri kirish: kutilgan ${i}, qabul qilingan ${a}`}case"invalid_value":return o.values.length===1?`Noto\u2018g\u2018ri kirish: kutilgan ${Xe(o.values[0])}`:`Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Juda katta: kutilgan ${o.origin??"qiymat"} ${i}${o.maximum.toString()} ${s.unit} ${s.verb}`:`Juda katta: kutilgan ${o.origin??"qiymat"} ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Juda kichik: kutilgan ${o.origin} ${i}${o.minimum.toString()} ${s.unit} ${s.verb}`:`Juda kichik: kutilgan ${o.origin} ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Noto\u2018g\u2018ri satr: "${i.prefix}" bilan boshlanishi kerak`:i.format==="ends_with"?`Noto\u2018g\u2018ri satr: "${i.suffix}" bilan tugashi kerak`:i.format==="includes"?`Noto\u2018g\u2018ri satr: "${i.includes}" ni o\u2018z ichiga olishi kerak`:i.format==="regex"?`Noto\u2018g\u2018ri satr: ${i.pattern} shabloniga mos kelishi kerak`:`Noto\u2018g\u2018ri ${n[i.format]??o.format}`}case"not_multiple_of":return`Noto\u2018g\u2018ri raqam: ${o.divisor} ning karralisi bo\u2018lishi kerak`;case"unrecognized_keys":return`Noma\u2019lum kalit${o.keys.length>1?"lar":""}: ${Ce(o.keys,", ")}`;case"invalid_key":return`${o.origin} dagi kalit noto\u2018g\u2018ri`;case"invalid_union":return"Noto\u2018g\u2018ri kirish";case"invalid_element":return`${o.origin} da noto\u2018g\u2018ri qiymat`;default:return"Noto\u2018g\u2018ri kirish"}}}});function T_t(){return{localeError:G1n()}}var G1n,P_t=b(()=>{wn();G1n=()=>{let t={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function e(o){return t[o]??null}let n={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ng\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"},r={nan:"NaN",number:"s\u1ED1",array:"m\u1EA3ng"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${o.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${a}`:`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${i}, nh\u1EADn \u0111\u01B0\u1EE3c ${a}`}case"invalid_value":return o.values.length===1?`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${Xe(o.values[0])}`:`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${o.origin??"gi\xE1 tr\u1ECB"} ${s.verb} ${i}${o.maximum.toString()} ${s.unit??"ph\u1EA7n t\u1EED"}`:`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${o.origin??"gi\xE1 tr\u1ECB"} ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${o.origin} ${s.verb} ${i}${o.minimum.toString()} ${s.unit}`:`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${o.origin} ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${i.prefix}"`:i.format==="ends_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${i.suffix}"`:i.format==="includes"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${i.includes}"`:i.format==="regex"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${i.pattern}`:`${n[i.format]??o.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${o.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${Ce(o.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${o.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${o.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}}}});function A_t(){return{localeError:Z1n()}}var Z1n,E_t=b(()=>{wn();Z1n=()=>{let t={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function e(o){return t[o]??null}let n={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"},r={nan:"NaN",number:"\u6570\u5B57",array:"\u6570\u7EC4",null:"\u7A7A\u503C(null)"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${o.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${a}`:`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${i}\uFF0C\u5B9E\u9645\u63A5\u6536 ${a}`}case"invalid_value":return o.values.length===1?`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${Xe(o.values[0])}`:`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${o.origin??"\u503C"} ${i}${o.maximum.toString()} ${s.unit??"\u4E2A\u5143\u7D20"}`:`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${o.origin??"\u503C"} ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${o.origin} ${i}${o.minimum.toString()} ${s.unit}`:`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${o.origin} ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${i.prefix}" \u5F00\u5934`:i.format==="ends_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${i.suffix}" \u7ED3\u5C3E`:i.format==="includes"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${i.includes}"`:i.format==="regex"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${i.pattern}`:`\u65E0\u6548${n[i.format]??o.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${o.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${Ce(o.keys,", ")}`;case"invalid_key":return`${o.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${o.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}}}});function M_t(){return{localeError:Y1n()}}var Y1n,O_t=b(()=>{wn();Y1n=()=>{let t={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function e(o){return t[o]??null}let n={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"},r={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${o.expected}\uFF0C\u4F46\u6536\u5230 ${a}`:`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${i}\uFF0C\u4F46\u6536\u5230 ${a}`}case"invalid_value":return o.values.length===1?`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${Xe(o.values[0])}`:`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${o.origin??"\u503C"} \u61C9\u70BA ${i}${o.maximum.toString()} ${s.unit??"\u500B\u5143\u7D20"}`:`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${o.origin??"\u503C"} \u61C9\u70BA ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${o.origin} \u61C9\u70BA ${i}${o.minimum.toString()} ${s.unit}`:`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${o.origin} \u61C9\u70BA ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${i.prefix}" \u958B\u982D`:i.format==="ends_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${i.suffix}" \u7D50\u5C3E`:i.format==="includes"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${i.includes}"`:i.format==="regex"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${i.pattern}`:`\u7121\u6548\u7684 ${n[i.format]??o.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${o.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${o.keys.length>1?"\u5011":""}\uFF1A${Ce(o.keys,"\u3001")}`;case"invalid_key":return`${o.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${o.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}}}});function N_t(){return{localeError:J1n()}}var J1n,R_t=b(()=>{wn();J1n=()=>{let t={string:{unit:"\xE0mi",verb:"n\xED"},file:{unit:"bytes",verb:"n\xED"},array:{unit:"nkan",verb:"n\xED"},set:{unit:"nkan",verb:"n\xED"}};function e(o){return t[o]??null}let n={regex:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9",email:"\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\xE0k\xF3k\xF2 ISO",date:"\u1ECDj\u1ECD\u0301 ISO",time:"\xE0k\xF3k\xF2 ISO",duration:"\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO",ipv4:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv4",ipv6:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv6",cidrv4:"\xE0gb\xE8gb\xE8 IPv4",cidrv6:"\xE0gb\xE8gb\xE8 IPv6",base64:"\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64",base64url:"\u1ECD\u0300r\u1ECD\u0300 base64url",json_string:"\u1ECD\u0300r\u1ECD\u0300 JSON",e164:"n\u1ECD\u0301mb\xE0 E.164",jwt:"JWT",template_literal:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9"},r={nan:"NaN",number:"n\u1ECD\u0301mb\xE0",array:"akop\u1ECD"};return o=>{switch(o.code){case"invalid_type":{let i=r[o.expected]??o.expected,s=Qe(o.input),a=r[s]??s;return/^[A-Z]/.test(o.expected)?`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${o.expected}, \xE0m\u1ECD\u0300 a r\xED ${a}`:`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${i}, \xE0m\u1ECD\u0300 a r\xED ${a}`}case"invalid_value":return o.values.length===1?`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${Xe(o.values[0])}`:`\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${Ce(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${o.origin??"iye"} ${s.verb} ${i}${o.maximum} ${s.unit}`:`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${i}${o.maximum}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${o.origin} ${s.verb} ${i}${o.minimum} ${s.unit}`:`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${i}${o.minimum}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${i.prefix}"`:i.format==="ends_with"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${i.suffix}"`:i.format==="includes"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${i.includes}"`:i.format==="regex"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${i.pattern}`:`A\u1E63\xEC\u1E63e: ${n[i.format]??o.format}`}case"not_multiple_of":return`N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${o.divisor}`;case"unrecognized_keys":return`B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${Ce(o.keys,", ")}`;case"invalid_key":return`B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${o.origin}`;case"invalid_union":return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";case"invalid_element":return`Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${o.origin}`;default:return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"}}}});var v8={};sr(v8,{ar:()=>Bwt,az:()=>Hwt,be:()=>qwt,bg:()=>Gwt,ca:()=>Ywt,cs:()=>Xwt,da:()=>ebt,de:()=>nbt,el:()=>obt,en:()=>xle,eo:()=>sbt,es:()=>lbt,fa:()=>ubt,fi:()=>fbt,fr:()=>mbt,frCA:()=>gbt,he:()=>vbt,hr:()=>bbt,hu:()=>xbt,hy:()=>kbt,id:()=>Tbt,is:()=>Abt,it:()=>Mbt,ja:()=>Nbt,ka:()=>Lbt,kh:()=>Dbt,km:()=>Sle,ko:()=>Ubt,lt:()=>zbt,mk:()=>Wbt,ms:()=>qbt,nl:()=>Gbt,no:()=>Ybt,ota:()=>Xbt,pl:()=>n_t,ps:()=>e_t,pt:()=>o_t,ro:()=>s_t,ru:()=>c_t,sl:()=>d_t,sv:()=>p_t,ta:()=>h_t,th:()=>y_t,tr:()=>w_t,ua:()=>__t,uk:()=>Cle,ur:()=>S_t,uz:()=>k_t,vi:()=>T_t,yo:()=>N_t,zhCN:()=>A_t,zhTW:()=>M_t});var p1e=b(()=>{zwt();Wwt();Kwt();Zwt();Jwt();Qwt();tbt();rbt();ibt();u1e();abt();cbt();dbt();pbt();hbt();ybt();wbt();_bt();Sbt();Ibt();Pbt();Ebt();Obt();Rbt();$bt();Fbt();d1e();jbt();Hbt();Vbt();Kbt();Zbt();Jbt();Qbt();t_t();r_t();i_t();a_t();u_t();f_t();m_t();g_t();v_t();b_t();x_t();f1e();C_t();I_t();P_t();E_t();O_t();R_t()});function WU(){return new kle}var L_t,m1e,h1e,kle,Vs,w8=b(()=>{m1e=Symbol("ZodOutput"),h1e=Symbol("ZodInput"),kle=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...n){let r=n[0];return this._map.set(e,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){let n=e._zod.parent;if(n){let r={...this.get(n)??{}};delete r.id;let o={...r,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};(L_t=globalThis).__zod_globalRegistry??(L_t.__zod_globalRegistry=WU());Vs=globalThis.__zod_globalRegistry});function g1e(t,e){return new t({type:"string",...ft(e)})}function y1e(t,e){return new t({type:"string",coerce:!0,...ft(e)})}function Ile(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ft(e)})}function b8(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ft(e)})}function Tle(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ft(e)})}function Ple(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ft(e)})}function Ale(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ft(e)})}function Ele(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ft(e)})}function _8(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ft(e)})}function Mle(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ft(e)})}function Ole(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ft(e)})}function Nle(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ft(e)})}function Rle(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ft(e)})}function Lle(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ft(e)})}function $le(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ft(e)})}function Dle(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ft(e)})}function Fle(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ft(e)})}function Ule(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ft(e)})}function v1e(t,e){return new t({type:"string",format:"mac",check:"string_format",abort:!1,...ft(e)})}function jle(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ft(e)})}function Ble(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ft(e)})}function zle(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ft(e)})}function Hle(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ft(e)})}function Wle(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ft(e)})}function Vle(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ft(e)})}function b1e(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ft(e)})}function _1e(t,e){return new t({type:"string",format:"date",check:"string_format",...ft(e)})}function x1e(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...ft(e)})}function S1e(t,e){return new t({type:"string",format:"duration",check:"string_format",...ft(e)})}function C1e(t,e){return new t({type:"number",checks:[],...ft(e)})}function k1e(t,e){return new t({type:"number",coerce:!0,checks:[],...ft(e)})}function I1e(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ft(e)})}function T1e(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float32",...ft(e)})}function P1e(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float64",...ft(e)})}function A1e(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"int32",...ft(e)})}function E1e(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"uint32",...ft(e)})}function M1e(t,e){return new t({type:"boolean",...ft(e)})}function O1e(t,e){return new t({type:"boolean",coerce:!0,...ft(e)})}function N1e(t,e){return new t({type:"bigint",...ft(e)})}function R1e(t,e){return new t({type:"bigint",coerce:!0,...ft(e)})}function L1e(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...ft(e)})}function $1e(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...ft(e)})}function D1e(t,e){return new t({type:"symbol",...ft(e)})}function F1e(t,e){return new t({type:"undefined",...ft(e)})}function U1e(t,e){return new t({type:"null",...ft(e)})}function j1e(t){return new t({type:"any"})}function qle(t){return new t({type:"unknown"})}function x8(t,e){return new t({type:"never",...ft(e)})}function B1e(t,e){return new t({type:"void",...ft(e)})}function z1e(t,e){return new t({type:"date",...ft(e)})}function H1e(t,e){return new t({type:"date",coerce:!0,...ft(e)})}function W1e(t,e){return new t({type:"nan",...ft(e)})}function ox(t,e){return new ule({check:"less_than",...ft(e),value:t,inclusive:!1})}function Rh(t,e){return new ule({check:"less_than",...ft(e),value:t,inclusive:!0})}function ix(t,e){return new dle({check:"greater_than",...ft(e),value:t,inclusive:!1})}function ip(t,e){return new dle({check:"greater_than",...ft(e),value:t,inclusive:!0})}function Kle(t){return ix(0,t)}function Gle(t){return ox(0,t)}function Zle(t){return Rh(0,t)}function Yle(t){return ip(0,t)}function gP(t,e){return new RRe({check:"multiple_of",...ft(e),value:t})}function yP(t,e){return new DRe({check:"max_size",...ft(e),maximum:t})}function sx(t,e){return new FRe({check:"min_size",...ft(e),minimum:t})}function UN(t,e){return new URe({check:"size_equals",...ft(e),size:t})}function jN(t,e){return new jRe({check:"max_length",...ft(e),maximum:t})}function ak(t,e){return new BRe({check:"min_length",...ft(e),minimum:t})}function BN(t,e){return new zRe({check:"length_equals",...ft(e),length:t})}function VU(t,e){return new HRe({check:"string_format",format:"regex",...ft(e),pattern:t})}function qU(t){return new WRe({check:"string_format",format:"lowercase",...ft(t)})}function KU(t){return new VRe({check:"string_format",format:"uppercase",...ft(t)})}function GU(t,e){return new qRe({check:"string_format",format:"includes",...ft(e),includes:t})}function ZU(t,e){return new KRe({check:"string_format",format:"starts_with",...ft(e),prefix:t})}function YU(t,e){return new GRe({check:"string_format",format:"ends_with",...ft(e),suffix:t})}function Jle(t,e,n){return new ZRe({check:"property",property:t,schema:e,...ft(n)})}function JU(t,e){return new YRe({check:"mime_type",mime:t,...ft(e)})}function Bw(t){return new JRe({check:"overwrite",tx:t})}function XU(t){return Bw(e=>e.normalize(t))}function QU(){return Bw(t=>t.trim())}function ej(){return Bw(t=>t.toLowerCase())}function tj(){return Bw(t=>t.toUpperCase())}function nj(){return Bw(t=>VNe(t))}function V1e(t,e,n){return new t({type:"array",element:e,...ft(n)})}function Q1n(t,e,n){return new t({type:"union",options:e,...ft(n)})}function e$n(t,e,n){return new t({type:"union",options:e,inclusive:!1,...ft(n)})}function t$n(t,e,n,r){return new t({type:"union",options:n,discriminator:e,...ft(r)})}function n$n(t,e,n){return new t({type:"intersection",left:e,right:n})}function r$n(t,e,n,r){let o=n instanceof kr,i=o?r:n,s=o?n:null;return new t({type:"tuple",items:e,rest:s,...ft(i)})}function o$n(t,e,n,r){return new t({type:"record",keyType:e,valueType:n,...ft(r)})}function i$n(t,e,n,r){return new t({type:"map",keyType:e,valueType:n,...ft(r)})}function s$n(t,e,n){return new t({type:"set",valueType:e,...ft(n)})}function a$n(t,e,n){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new t({type:"enum",entries:r,...ft(n)})}function l$n(t,e,n){return new t({type:"enum",entries:e,...ft(n)})}function c$n(t,e,n){return new t({type:"literal",values:Array.isArray(e)?e:[e],...ft(n)})}function q1e(t,e){return new t({type:"file",...ft(e)})}function u$n(t,e){return new t({type:"transform",transform:e})}function d$n(t,e){return new t({type:"optional",innerType:e})}function f$n(t,e){return new t({type:"nullable",innerType:e})}function p$n(t,e,n){return new t({type:"default",innerType:e,get defaultValue(){return typeof n=="function"?n():KNe(n)}})}function m$n(t,e,n){return new t({type:"nonoptional",innerType:e,...ft(n)})}function h$n(t,e){return new t({type:"success",innerType:e})}function g$n(t,e,n){return new t({type:"catch",innerType:e,catchValue:typeof n=="function"?n:()=>n})}function y$n(t,e,n){return new t({type:"pipe",in:e,out:n})}function v$n(t,e){return new t({type:"readonly",innerType:e})}function w$n(t,e,n){return new t({type:"template_literal",parts:e,...ft(n)})}function b$n(t,e){return new t({type:"lazy",getter:e})}function _$n(t,e){return new t({type:"promise",innerType:e})}function K1e(t,e,n){let r=ft(n);return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}function G1e(t,e,n){return new t({type:"custom",check:"custom",fn:e,...ft(n)})}function Z1e(t,e){let n=$_t(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(DU(o,r.value,n._zod.def));else{let i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=n),i.continue??(i.continue=!n._zod.def.abort),r.issues.push(DU(i))}},t(r.value,r)),e);return n}function $_t(t,e){let n=new ds({check:"custom",...ft(e)});return n._zod.check=t,n}function Y1e(t){let e=new ds({check:"describe"});return e._zod.onattach=[n=>{let r=Vs.get(n)??{};Vs.add(n,{...r,description:t})}],e._zod.check=()=>{},e}function J1e(t){let e=new ds({check:"meta"});return e._zod.onattach=[n=>{let r=Vs.get(n)??{};Vs.add(n,{...r,...t})}],e._zod.check=()=>{},e}function X1e(t,e){let n=ft(e),r=n.truthy??["true","1","yes","on","y","enabled"],o=n.falsy??["false","0","no","off","n","disabled"];n.case!=="sensitive"&&(r=r.map(p=>typeof p=="string"?p.toLowerCase():p),o=o.map(p=>typeof p=="string"?p.toLowerCase():p));let i=new Set(r),s=new Set(o),a=t.Codec??g8,l=t.Boolean??f8,c=t.String??FN,u=new c({type:"string",error:n.error}),d=new l({type:"boolean",error:n.error}),f=new a({type:"pipe",in:u,out:d,transform:(p,m)=>{let h=p;return n.case!=="sensitive"&&(h=h.toLowerCase()),i.has(h)?!0:s.has(h)?!1:(m.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...s],input:m.value,inst:f,continue:!1}),{})},reverseTransform:(p,m)=>p===!0?r[0]||"true":o[0]||"false",error:n.error});return f}function rj(t,e,n,r={}){let o=ft(r),i={...ft(r),check:"string_format",type:"string",format:e,fn:typeof n=="function"?n:a=>n.test(a),...o};return n instanceof RegExp&&(i.pattern=n),new t(i)}var w1e,D_t=b(()=>{fle();w8();c1e();wn();w1e={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}});function vP(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??Vs,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function Li(t,e,n={path:[],schemaPath:[]}){var r;let o=t._zod.def,i=e.seen.get(t);if(i)return i.count++,n.schemaPath.includes(t)&&(i.cycle=n.path),i.schema;let s={schema:{},count:1,cycle:void 0,path:n.path};e.seen.set(t,s);let a=t._zod.toJSONSchema?.();if(a)s.schema=a;else{let u={...n,schemaPath:[...n.schemaPath,t],path:n.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,s.schema,u);else{let f=s.schema,p=e.processors[o.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);p(t,e,f,u)}let d=t._zod.parent;d&&(s.ref||(s.ref=d),Li(d,e,u),e.seen.get(d).isParent=!0)}let l=e.metadataRegistry.get(t);return l&&Object.assign(s.schema,l),e.io==="input"&&sp(t)&&(delete s.schema.examples,delete s.schema.default),e.io==="input"&&"_prefault"in s.schema&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.schema._prefault,e.seen.get(t).schema}function wP(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=new Map;for(let s of t.seen.entries()){let a=t.metadataRegistry.get(s[0])?.id;if(a){let l=r.get(a);if(l&&l!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,s[0])}}let o=s=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let d=t.external.registry.get(s[0])?.id,f=t.external.uri??(m=>m);if(d)return{ref:f(d)};let p=s[1].defId??s[1].schema.id??`schema${t.counter++}`;return s[1].defId=p,{defId:p,ref:`${f("__shared")}#/${a}/${p}`}}if(s[1]===n)return{ref:"#"};let c=`#/${a}/`,u=s[1].schema.id??`__schema${t.counter++}`;return{defId:u,ref:c+u}},i=s=>{if(s[1].schema.$ref)return;let a=s[1],{ref:l,defId:c}=o(s);a.def={...a.schema},c&&(a.defId=c);let u=a.schema;for(let d in u)delete u[d];u.$ref=l};if(t.cycles==="throw")for(let s of t.seen.entries()){let a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let a=s[1];if(e===s[0]){i(s);continue}if(t.external){let c=t.external.registry.get(s[0])?.id;if(e!==s[0]&&c){i(s);continue}}if(t.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1&&t.reused==="ref"){i(s);continue}}}function bP(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=a=>{let l=t.seen.get(a);if(l.ref===null)return;let c=l.def??l.schema,u={...c},d=l.ref;if(l.ref=null,d){r(d);let p=t.seen.get(d),m=p.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(m)):Object.assign(c,m),Object.assign(c,u),a._zod.parent===d)for(let g in c)g==="$ref"||g==="allOf"||g in u||delete c[g];if(m.$ref&&p.def)for(let g in c)g==="$ref"||g==="allOf"||g in p.def&&JSON.stringify(c[g])===JSON.stringify(p.def[g])&&delete c[g]}let f=a._zod.parent;if(f&&f!==d){r(f);let p=t.seen.get(f);if(p?.schema.$ref&&(c.$ref=p.schema.$ref,p.def))for(let m in c)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(c[m])===JSON.stringify(p.def[m])&&delete c[m]}t.override({zodSchema:a,jsonSchema:c,path:l.path??[]})};for(let a of[...t.seen.entries()].reverse())r(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,n.def??n.schema);let i=t.metadataRegistry.get(e)?.id;i!==void 0&&o.id===i&&delete o.id;let s=t.external?.defs??{};for(let a of t.seen.entries()){let l=a[1];l.def&&l.defId&&(l.def.id===l.defId&&delete l.def.id,s[l.defId]=l.def)}t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?o.$defs=s:o.definitions=s);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:oj(e,"input",t.processors),output:oj(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function sp(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let r=t._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return sp(r.element,n);if(r.type==="set")return sp(r.valueType,n);if(r.type==="lazy")return sp(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return sp(r.innerType,n);if(r.type==="intersection")return sp(r.left,n)||sp(r.right,n);if(r.type==="record"||r.type==="map")return sp(r.keyType,n)||sp(r.valueType,n);if(r.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:sp(r.in,n)||sp(r.out,n);if(r.type==="object"){for(let o in r.shape)if(sp(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(sp(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(sp(o,n))return!0;return!!(r.rest&&sp(r.rest,n))}return!1}var Q1e,oj,S8=b(()=>{w8();Q1e=(t,e={})=>n=>{let r=vP({...n,processors:e});return Li(t,r),wP(r,t),bP(r,t)},oj=(t,e,n={})=>r=>{let{libraryOptions:o,target:i}=r??{},s=vP({...o??{},target:i,io:e,processors:n});return Li(t,s),wP(s,t),bP(s,t)}});function lk(t,e){if("_idmap"in t){let r=t,o=vP({...e,processors:Xle}),i={};for(let l of r._idmap.entries()){let[c,u]=l;Li(u,o)}let s={},a={registry:r,uri:e?.uri,defs:i};o.external=a;for(let l of r._idmap.entries()){let[c,u]=l;wP(o,u),s[c]=bP(o,u)}if(Object.keys(i).length>0){let l=o.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[l]:i}}return{schemas:s}}let n=vP({...e,processors:Xle});return Li(t,n),wP(n,t),bP(n,t)}var x$n,e$e,t$e,n$e,r$e,o$e,i$e,s$e,a$e,l$e,c$e,u$e,d$e,f$e,p$e,m$e,h$e,g$e,y$e,v$e,w$e,b$e,_$e,x$e,S$e,C$e,Qle,k$e,I$e,T$e,P$e,A$e,E$e,M$e,O$e,N$e,R$e,L$e,ece,$$e,Xle,C8=b(()=>{S8();wn();x$n={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},e$e=(t,e,n,r)=>{let o=n;o.type="string";let{minimum:i,maximum:s,format:a,patterns:l,contentEncoding:c}=t._zod.bag;if(typeof i=="number"&&(o.minLength=i),typeof s=="number"&&(o.maxLength=s),a&&(o.format=x$n[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),c&&(o.contentEncoding=c),l&&l.size>0){let u=[...l];u.length===1?o.pattern=u[0].source:u.length>1&&(o.allOf=[...u.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},t$e=(t,e,n,r)=>{let o=n,{minimum:i,maximum:s,format:a,multipleOf:l,exclusiveMaximum:c,exclusiveMinimum:u}=t._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),f=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),p=e.target==="draft-04"||e.target==="openapi-3.0";d?p?(o.minimum=u,o.exclusiveMinimum=!0):o.exclusiveMinimum=u:typeof i=="number"&&(o.minimum=i),f?p?(o.maximum=c,o.exclusiveMaximum=!0):o.exclusiveMaximum=c:typeof s=="number"&&(o.maximum=s),typeof l=="number"&&(o.multipleOf=l)},n$e=(t,e,n,r)=>{n.type="boolean"},r$e=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},o$e=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},i$e=(t,e,n,r)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},s$e=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},a$e=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},l$e=(t,e,n,r)=>{n.not={}},c$e=(t,e,n,r)=>{},u$e=(t,e,n,r)=>{},d$e=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},f$e=(t,e,n,r)=>{let o=t._zod.def,i=t8(o.entries);i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),n.enum=i},p$e=(t,e,n,r)=>{let o=t._zod.def,i=[];for(let s of o.values)if(s===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){let s=i[0];n.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?n.enum=[s]:n.const=s}else i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),i.every(s=>typeof s=="boolean")&&(n.type="boolean"),i.every(s=>s===null)&&(n.type="null"),n.enum=i},m$e=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},h$e=(t,e,n,r)=>{let o=n,i=t._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");o.type="string",o.pattern=i.source},g$e=(t,e,n,r)=>{let o=n,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:l}=t._zod.bag;s!==void 0&&(i.minLength=s),a!==void 0&&(i.maxLength=a),l?l.length===1?(i.contentMediaType=l[0],Object.assign(o,i)):(Object.assign(o,i),o.anyOf=l.map(c=>({contentMediaType:c}))):Object.assign(o,i)},y$e=(t,e,n,r)=>{n.type="boolean"},v$e=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},w$e=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},b$e=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},_$e=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},x$e=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},S$e=(t,e,n,r)=>{let o=n,i=t._zod.def,{minimum:s,maximum:a}=t._zod.bag;typeof s=="number"&&(o.minItems=s),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=Li(i.element,e,{...r,path:[...r.path,"items"]})},C$e=(t,e,n,r)=>{let o=n,i=t._zod.def;o.type="object",o.properties={};let s=i.shape;for(let c in s)o.properties[c]=Li(s[c],e,{...r,path:[...r.path,"properties",c]});let a=new Set(Object.keys(s)),l=new Set([...a].filter(c=>{let u=i.shape[c]._zod;return e.io==="input"?u.optin===void 0:u.optout===void 0}));l.size>0&&(o.required=Array.from(l)),i.catchall?._zod.def.type==="never"?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=Li(i.catchall,e,{...r,path:[...r.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},Qle=(t,e,n,r)=>{let o=t._zod.def,i=o.inclusive===!1,s=o.options.map((a,l)=>Li(a,e,{...r,path:[...r.path,i?"oneOf":"anyOf",l]}));i?n.oneOf=s:n.anyOf=s},k$e=(t,e,n,r)=>{let o=t._zod.def,i=Li(o.left,e,{...r,path:[...r.path,"allOf",0]}),s=Li(o.right,e,{...r,path:[...r.path,"allOf",1]}),a=c=>"allOf"in c&&Object.keys(c).length===1,l=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];n.allOf=l},I$e=(t,e,n,r)=>{let o=n,i=t._zod.def;o.type="array";let s=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",l=i.items.map((f,p)=>Li(f,e,{...r,path:[...r.path,s,p]})),c=i.rest?Li(i.rest,e,{...r,path:[...r.path,a,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null;e.target==="draft-2020-12"?(o.prefixItems=l,c&&(o.items=c)):e.target==="openapi-3.0"?(o.items={anyOf:l},c&&o.items.anyOf.push(c),o.minItems=l.length,c||(o.maxItems=l.length)):(o.items=l,c&&(o.additionalItems=c));let{minimum:u,maximum:d}=t._zod.bag;typeof u=="number"&&(o.minItems=u),typeof d=="number"&&(o.maxItems=d)},T$e=(t,e,n,r)=>{let o=n,i=t._zod.def;o.type="object";let s=i.keyType,l=s._zod.bag?.patterns;if(i.mode==="loose"&&l&&l.size>0){let u=Li(i.valueType,e,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(let d of l)o.patternProperties[d.source]=u}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(o.propertyNames=Li(i.keyType,e,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=Li(i.valueType,e,{...r,path:[...r.path,"additionalProperties"]});let c=s._zod.values;if(c){let u=[...c].filter(d=>typeof d=="string"||typeof d=="number");u.length>0&&(o.required=u)}},P$e=(t,e,n,r)=>{let o=t._zod.def,i=Li(o.innerType,e,r),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=o.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},A$e=(t,e,n,r)=>{let o=t._zod.def;Li(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType},E$e=(t,e,n,r)=>{let o=t._zod.def;Li(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},M$e=(t,e,n,r)=>{let o=t._zod.def;Li(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},O$e=(t,e,n,r)=>{let o=t._zod.def;Li(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},N$e=(t,e,n,r)=>{let o=t._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?o.out:o.in:o.out;Li(s,e,r);let a=e.seen.get(t);a.ref=s},R$e=(t,e,n,r)=>{let o=t._zod.def;Li(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType,n.readOnly=!0},L$e=(t,e,n,r)=>{let o=t._zod.def;Li(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType},ece=(t,e,n,r)=>{let o=t._zod.def;Li(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType},$$e=(t,e,n,r)=>{let o=t._zod.innerType;Li(o,e,r);let i=e.seen.get(t);i.ref=o},Xle={string:e$e,number:t$e,boolean:n$e,bigint:r$e,symbol:o$e,null:i$e,undefined:s$e,void:a$e,never:l$e,any:c$e,unknown:u$e,date:d$e,enum:f$e,literal:p$e,nan:m$e,template_literal:h$e,file:g$e,success:y$e,custom:v$e,function:w$e,transform:b$e,map:_$e,set:x$e,array:S$e,object:C$e,union:Qle,intersection:k$e,tuple:I$e,record:T$e,nullable:P$e,nonoptional:A$e,default:E$e,prefault:M$e,catch:O$e,pipe:N$e,readonly:R$e,promise:L$e,optional:ece,lazy:$$e}});var tce,F_t=b(()=>{C8();S8();tce=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let n=e?.target??"draft-2020-12";n==="draft-4"&&(n="draft-04"),n==="draft-7"&&(n="draft-07"),this.ctx=vP({processors:Xle,target:n,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,n={path:[],schemaPath:[]}){return Li(e,this.ctx,n)}emit(e,n){n&&(n.cycles&&(this.ctx.cycles=n.cycles),n.reused&&(this.ctx.reused=n.reused),n.external&&(this.ctx.external=n.external)),wP(this.ctx,e);let r=bP(this.ctx,e),{"~standard":o,...i}=r;return i}}});var U_t={};var j_t=b(()=>{});var ck={};sr(ck,{$ZodAny:()=>NLe,$ZodArray:()=>$Le,$ZodAsyncError:()=>jw,$ZodBase64:()=>SLe,$ZodBase64URL:()=>CLe,$ZodBigInt:()=>vle,$ZodBigIntFormat:()=>ALe,$ZodBoolean:()=>f8,$ZodCIDRv4:()=>bLe,$ZodCIDRv6:()=>_Le,$ZodCUID:()=>lLe,$ZodCUID2:()=>cLe,$ZodCatch:()=>e1e,$ZodCheck:()=>ds,$ZodCheckBigIntFormat:()=>$Re,$ZodCheckEndsWith:()=>GRe,$ZodCheckGreaterThan:()=>dle,$ZodCheckIncludes:()=>qRe,$ZodCheckLengthEquals:()=>zRe,$ZodCheckLessThan:()=>ule,$ZodCheckLowerCase:()=>WRe,$ZodCheckMaxLength:()=>jRe,$ZodCheckMaxSize:()=>DRe,$ZodCheckMimeType:()=>YRe,$ZodCheckMinLength:()=>BRe,$ZodCheckMinSize:()=>FRe,$ZodCheckMultipleOf:()=>RRe,$ZodCheckNumberFormat:()=>LRe,$ZodCheckOverwrite:()=>JRe,$ZodCheckProperty:()=>ZRe,$ZodCheckRegex:()=>HRe,$ZodCheckSizeEquals:()=>URe,$ZodCheckStartsWith:()=>KRe,$ZodCheckStringFormat:()=>zU,$ZodCheckUpperCase:()=>VRe,$ZodCodec:()=>g8,$ZodCustom:()=>l1e,$ZodCustomStringFormat:()=>TLe,$ZodDate:()=>LLe,$ZodDefault:()=>YLe,$ZodDiscriminatedUnion:()=>ULe,$ZodE164:()=>kLe,$ZodEmail:()=>oLe,$ZodEmoji:()=>sLe,$ZodEncodeError:()=>dP,$ZodEnum:()=>WLe,$ZodError:()=>s8,$ZodExactOptional:()=>GLe,$ZodFile:()=>qLe,$ZodFunction:()=>i1e,$ZodGUID:()=>nLe,$ZodIPv4:()=>yLe,$ZodIPv6:()=>vLe,$ZodISODate:()=>mLe,$ZodISODateTime:()=>pLe,$ZodISODuration:()=>gLe,$ZodISOTime:()=>hLe,$ZodIntersection:()=>jLe,$ZodJWT:()=>ILe,$ZodKSUID:()=>fLe,$ZodLazy:()=>a1e,$ZodLiteral:()=>VLe,$ZodMAC:()=>wLe,$ZodMap:()=>zLe,$ZodNaN:()=>t1e,$ZodNanoID:()=>aLe,$ZodNever:()=>p8,$ZodNonOptional:()=>XLe,$ZodNull:()=>OLe,$ZodNullable:()=>ZLe,$ZodNumber:()=>yle,$ZodNumberFormat:()=>PLe,$ZodObject:()=>jwt,$ZodObjectJIT:()=>DLe,$ZodOptional:()=>h8,$ZodPipe:()=>_le,$ZodPrefault:()=>JLe,$ZodPreprocess:()=>n1e,$ZodPromise:()=>s1e,$ZodReadonly:()=>r1e,$ZodRealError:()=>um,$ZodRecord:()=>BLe,$ZodRegistry:()=>kle,$ZodSet:()=>HLe,$ZodString:()=>FN,$ZodStringFormat:()=>ts,$ZodSuccess:()=>QLe,$ZodSymbol:()=>ELe,$ZodTemplateLiteral:()=>o1e,$ZodTransform:()=>KLe,$ZodTuple:()=>ble,$ZodType:()=>kr,$ZodULID:()=>uLe,$ZodURL:()=>iLe,$ZodUUID:()=>rLe,$ZodUndefined:()=>MLe,$ZodUnion:()=>m8,$ZodUnknown:()=>wle,$ZodVoid:()=>RLe,$ZodXID:()=>dLe,$ZodXor:()=>FLe,$brand:()=>BNe,$constructor:()=>ve,$input:()=>h1e,$output:()=>m1e,Doc:()=>d8,JSONSchema:()=>U_t,JSONSchemaGenerator:()=>tce,NEVER:()=>jNe,TimePrecision:()=>w1e,_any:()=>j1e,_array:()=>V1e,_base64:()=>zle,_base64url:()=>Hle,_bigint:()=>N1e,_boolean:()=>M1e,_catch:()=>g$n,_check:()=>$_t,_cidrv4:()=>jle,_cidrv6:()=>Ble,_coercedBigint:()=>R1e,_coercedBoolean:()=>O1e,_coercedDate:()=>H1e,_coercedNumber:()=>k1e,_coercedString:()=>y1e,_cuid:()=>Nle,_cuid2:()=>Rle,_custom:()=>K1e,_date:()=>z1e,_decode:()=>ele,_decodeAsync:()=>nle,_default:()=>p$n,_discriminatedUnion:()=>t$n,_e164:()=>Wle,_email:()=>Ile,_emoji:()=>Mle,_encode:()=>Qae,_encodeAsync:()=>tle,_endsWith:()=>YU,_enum:()=>a$n,_file:()=>q1e,_float32:()=>T1e,_float64:()=>P1e,_gt:()=>ix,_gte:()=>ip,_guid:()=>b8,_includes:()=>GU,_int:()=>I1e,_int32:()=>A1e,_int64:()=>L1e,_intersection:()=>n$n,_ipv4:()=>Fle,_ipv6:()=>Ule,_isoDate:()=>_1e,_isoDateTime:()=>b1e,_isoDuration:()=>S1e,_isoTime:()=>x1e,_jwt:()=>Vle,_ksuid:()=>Dle,_lazy:()=>b$n,_length:()=>BN,_literal:()=>c$n,_lowercase:()=>qU,_lt:()=>ox,_lte:()=>Rh,_mac:()=>v1e,_map:()=>i$n,_max:()=>Rh,_maxLength:()=>jN,_maxSize:()=>yP,_mime:()=>JU,_min:()=>ip,_minLength:()=>ak,_minSize:()=>sx,_multipleOf:()=>gP,_nan:()=>W1e,_nanoid:()=>Ole,_nativeEnum:()=>l$n,_negative:()=>Gle,_never:()=>x8,_nonnegative:()=>Yle,_nonoptional:()=>m$n,_nonpositive:()=>Zle,_normalize:()=>XU,_null:()=>U1e,_nullable:()=>f$n,_number:()=>C1e,_optional:()=>d$n,_overwrite:()=>Bw,_parse:()=>FU,_parseAsync:()=>UU,_pipe:()=>y$n,_positive:()=>Kle,_promise:()=>_$n,_property:()=>Jle,_readonly:()=>v$n,_record:()=>o$n,_refine:()=>G1e,_regex:()=>VU,_safeDecode:()=>ole,_safeDecodeAsync:()=>sle,_safeEncode:()=>rle,_safeEncodeAsync:()=>ile,_safeParse:()=>jU,_safeParseAsync:()=>BU,_set:()=>s$n,_size:()=>UN,_slugify:()=>nj,_startsWith:()=>ZU,_string:()=>g1e,_stringFormat:()=>rj,_stringbool:()=>X1e,_success:()=>h$n,_superRefine:()=>Z1e,_symbol:()=>D1e,_templateLiteral:()=>w$n,_toLowerCase:()=>ej,_toUpperCase:()=>tj,_transform:()=>u$n,_trim:()=>QU,_tuple:()=>r$n,_uint32:()=>E1e,_uint64:()=>$1e,_ulid:()=>Lle,_undefined:()=>F1e,_union:()=>Q1n,_unknown:()=>qle,_uppercase:()=>KU,_url:()=>_8,_uuid:()=>Tle,_uuidv4:()=>Ple,_uuidv6:()=>Ale,_uuidv7:()=>Ele,_void:()=>B1e,_xid:()=>$le,_xor:()=>e$n,clone:()=>Va,config:()=>Wa,createStandardJSONSchemaMethod:()=>oj,createToJSONSchemaMethod:()=>Q1e,decode:()=>_Ln,decodeAsync:()=>SLn,describe:()=>Y1e,encode:()=>bLn,encodeAsync:()=>xLn,extractDefs:()=>wP,finalize:()=>bP,flattenError:()=>a8,formatError:()=>l8,globalConfig:()=>ON,globalRegistry:()=>Vs,initializeContext:()=>vP,isValidBase64:()=>xLe,isValidBase64URL:()=>$wt,isValidJWT:()=>Dwt,locales:()=>v8,meta:()=>J1e,parse:()=>LN,parseAsync:()=>$N,prettifyError:()=>eRe,process:()=>Li,regexes:()=>Nh,registry:()=>WU,safeDecode:()=>kLn,safeDecodeAsync:()=>TLn,safeEncode:()=>CLn,safeEncodeAsync:()=>ILn,safeParse:()=>nRe,safeParseAsync:()=>rRe,toDotPath:()=>hwt,toJSONSchema:()=>lk,treeifyError:()=>QNe,util:()=>nt,version:()=>QRe});var tf=b(()=>{NN();oRe();tRe();c1e();fle();eLe();wn();cle();p1e();w8();XRe();D_t();S8();C8();F_t();j_t()});var nce={};sr(nce,{endsWith:()=>YU,gt:()=>ix,gte:()=>ip,includes:()=>GU,length:()=>BN,lowercase:()=>qU,lt:()=>ox,lte:()=>Rh,maxLength:()=>jN,maxSize:()=>yP,mime:()=>JU,minLength:()=>ak,minSize:()=>sx,multipleOf:()=>gP,negative:()=>Gle,nonnegative:()=>Yle,nonpositive:()=>Zle,normalize:()=>XU,overwrite:()=>Bw,positive:()=>Kle,property:()=>Jle,regex:()=>VU,size:()=>UN,slugify:()=>nj,startsWith:()=>ZU,toLowerCase:()=>ej,toUpperCase:()=>tj,trim:()=>QU,uppercase:()=>KU});var rce=b(()=>{tf()});var ij={};sr(ij,{ZodISODate:()=>ice,ZodISODateTime:()=>oce,ZodISODuration:()=>ace,ZodISOTime:()=>sce,date:()=>F$e,datetime:()=>D$e,duration:()=>j$e,time:()=>U$e});function D$e(t){return b1e(oce,t)}function F$e(t){return _1e(ice,t)}function U$e(t){return x1e(sce,t)}function j$e(t){return S1e(ace,t)}var oce,ice,sce,ace,k8=b(()=>{tf();T8();oce=ve("ZodISODateTime",(t,e)=>{pLe.init(t,e),ns.init(t,e)});ice=ve("ZodISODate",(t,e)=>{mLe.init(t,e),ns.init(t,e)});sce=ve("ZodISOTime",(t,e)=>{hLe.init(t,e),ns.init(t,e)});ace=ve("ZodISODuration",(t,e)=>{gLe.init(t,e),ns.init(t,e)})});var B_t,C$n,dm,B$e=b(()=>{tf();tf();wn();B_t=(t,e)=>{s8.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>l8(t,n)},flatten:{value:n=>a8(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,LU,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,LU,2)}},isEmpty:{get(){return t.issues.length===0}}})},C$n=ve("ZodError",B_t),dm=ve("ZodError",B_t,{Parent:Error})});var P8,z$e,H$e,W$e,V$e,q$e,K$e,G$e,Z$e,Y$e,J$e,X$e,Q$e=b(()=>{tf();B$e();P8=FU(dm),z$e=UU(dm),H$e=jU(dm),W$e=BU(dm),V$e=Qae(dm),q$e=ele(dm),K$e=tle(dm),G$e=nle(dm),Z$e=rle(dm),Y$e=ole(dm),J$e=ile(dm),X$e=sle(dm)});var I8={};sr(I8,{ZodAny:()=>sDe,ZodArray:()=>uDe,ZodBase64:()=>Sce,ZodBase64URL:()=>Cce,ZodBigInt:()=>pj,ZodBigIntFormat:()=>Tce,ZodBoolean:()=>dj,ZodCIDRv4:()=>_ce,ZodCIDRv6:()=>xce,ZodCUID:()=>mce,ZodCUID2:()=>hce,ZodCatch:()=>ODe,ZodCodec:()=>U8,ZodCustom:()=>j8,ZodCustomStringFormat:()=>cj,ZodDate:()=>L8,ZodDefault:()=>IDe,ZodDiscriminatedUnion:()=>fDe,ZodE164:()=>kce,ZodEmail:()=>dce,ZodEmoji:()=>fce,ZodEnum:()=>aj,ZodExactOptional:()=>SDe,ZodFile:()=>_De,ZodFunction:()=>zDe,ZodGUID:()=>E8,ZodIPv4:()=>wce,ZodIPv6:()=>bce,ZodIntersection:()=>pDe,ZodJWT:()=>Ice,ZodKSUID:()=>vce,ZodLazy:()=>UDe,ZodLiteral:()=>bDe,ZodMAC:()=>eDe,ZodMap:()=>vDe,ZodNaN:()=>RDe,ZodNanoID:()=>pce,ZodNever:()=>lDe,ZodNonOptional:()=>Rce,ZodNull:()=>oDe,ZodNullable:()=>kDe,ZodNumber:()=>uj,ZodNumberFormat:()=>zN,ZodObject:()=>$8,ZodOptional:()=>Nce,ZodPipe:()=>F8,ZodPrefault:()=>PDe,ZodPreprocess:()=>LDe,ZodPromise:()=>BDe,ZodReadonly:()=>$De,ZodRecord:()=>sj,ZodSet:()=>wDe,ZodString:()=>lj,ZodStringFormat:()=>ns,ZodSuccess:()=>MDe,ZodSymbol:()=>nDe,ZodTemplateLiteral:()=>FDe,ZodTransform:()=>xDe,ZodTuple:()=>hDe,ZodType:()=>Vr,ZodULID:()=>gce,ZodURL:()=>R8,ZodUUID:()=>ax,ZodUndefined:()=>rDe,ZodUnion:()=>D8,ZodUnknown:()=>aDe,ZodVoid:()=>cDe,ZodXID:()=>yce,ZodXor:()=>dDe,_ZodString:()=>uce,_default:()=>TDe,_function:()=>Gxt,any:()=>Ixt,array:()=>_P,base64:()=>cxt,base64url:()=>uxt,bigint:()=>_xt,boolean:()=>fj,catch:()=>NDe,check:()=>Zxt,cidrv4:()=>axt,cidrv6:()=>lxt,codec:()=>Wxt,cuid:()=>Q_t,cuid2:()=>ext,custom:()=>Lce,date:()=>Pxt,describe:()=>Yxt,discriminatedUnion:()=>Nxt,e164:()=>dxt,email:()=>H_t,emoji:()=>J_t,enum:()=>Mce,exactOptional:()=>CDe,file:()=>jxt,float32:()=>yxt,float64:()=>vxt,function:()=>Gxt,guid:()=>W_t,hash:()=>gxt,hex:()=>hxt,hostname:()=>mxt,httpUrl:()=>Y_t,instanceof:()=>Xxt,int:()=>lce,int32:()=>wxt,int64:()=>xxt,intersection:()=>mDe,invertCodec:()=>Vxt,ipv4:()=>oxt,ipv6:()=>sxt,json:()=>eSt,jwt:()=>fxt,keyof:()=>Axt,ksuid:()=>rxt,lazy:()=>jDe,literal:()=>Uxt,looseObject:()=>Mxt,looseRecord:()=>Lxt,mac:()=>ixt,map:()=>$xt,meta:()=>Jxt,nan:()=>Hxt,nanoid:()=>X_t,nativeEnum:()=>Fxt,never:()=>Pce,nonoptional:()=>EDe,null:()=>iDe,nullable:()=>O8,nullish:()=>Bxt,number:()=>tDe,object:()=>Ace,optional:()=>M8,partialRecord:()=>Rxt,pipe:()=>cce,prefault:()=>ADe,preprocess:()=>tSt,promise:()=>Kxt,readonly:()=>DDe,record:()=>yDe,refine:()=>HDe,set:()=>Dxt,strictObject:()=>Ext,string:()=>A8,stringFormat:()=>pxt,stringbool:()=>Qxt,success:()=>zxt,superRefine:()=>WDe,symbol:()=>Cxt,templateLiteral:()=>qxt,transform:()=>Oce,tuple:()=>gDe,uint32:()=>bxt,uint64:()=>Sxt,ulid:()=>txt,undefined:()=>kxt,union:()=>Ece,unknown:()=>lx,url:()=>Z_t,uuid:()=>V_t,uuidv4:()=>q_t,uuidv6:()=>K_t,uuidv7:()=>G_t,void:()=>Txt,xid:()=>nxt,xor:()=>Oxt});function N8(t,e,n){let r=Object.getPrototypeOf(t),o=z_t.get(r);if(o||(o=new Set,z_t.set(r,o)),!o.has(e)){o.add(e);for(let i in n){let s=n[i];Object.defineProperty(r,i,{configurable:!0,enumerable:!1,get(){let a=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}function A8(t){return g1e(lj,t)}function H_t(t){return Ile(dce,t)}function W_t(t){return b8(E8,t)}function V_t(t){return Tle(ax,t)}function q_t(t){return Ple(ax,t)}function K_t(t){return Ale(ax,t)}function G_t(t){return Ele(ax,t)}function Z_t(t){return _8(R8,t)}function Y_t(t){return _8(R8,{protocol:Nh.httpProtocol,hostname:Nh.domain,...nt.normalizeParams(t)})}function J_t(t){return Mle(fce,t)}function X_t(t){return Ole(pce,t)}function Q_t(t){return Nle(mce,t)}function ext(t){return Rle(hce,t)}function txt(t){return Lle(gce,t)}function nxt(t){return $le(yce,t)}function rxt(t){return Dle(vce,t)}function oxt(t){return Fle(wce,t)}function ixt(t){return v1e(eDe,t)}function sxt(t){return Ule(bce,t)}function axt(t){return jle(_ce,t)}function lxt(t){return Ble(xce,t)}function cxt(t){return zle(Sce,t)}function uxt(t){return Hle(Cce,t)}function dxt(t){return Wle(kce,t)}function fxt(t){return Vle(Ice,t)}function pxt(t,e,n={}){return rj(cj,t,e,n)}function mxt(t){return rj(cj,"hostname",Nh.hostname,t)}function hxt(t){return rj(cj,"hex",Nh.hex,t)}function gxt(t,e){let n=e?.enc??"hex",r=`${t}_${n}`,o=Nh[r];if(!o)throw new Error(`Unrecognized hash format: ${r}`);return rj(cj,r,o,e)}function tDe(t){return C1e(uj,t)}function lce(t){return I1e(zN,t)}function yxt(t){return T1e(zN,t)}function vxt(t){return P1e(zN,t)}function wxt(t){return A1e(zN,t)}function bxt(t){return E1e(zN,t)}function fj(t){return M1e(dj,t)}function _xt(t){return N1e(pj,t)}function xxt(t){return L1e(Tce,t)}function Sxt(t){return $1e(Tce,t)}function Cxt(t){return D1e(nDe,t)}function kxt(t){return F1e(rDe,t)}function iDe(t){return U1e(oDe,t)}function Ixt(){return j1e(sDe)}function lx(){return qle(aDe)}function Pce(t){return x8(lDe,t)}function Txt(t){return B1e(cDe,t)}function Pxt(t){return z1e(L8,t)}function _P(t,e){return V1e(uDe,t,e)}function Axt(t){let e=t._zod.def.shape;return Mce(Object.keys(e))}function Ace(t,e){let n={type:"object",shape:t??{},...nt.normalizeParams(e)};return new $8(n)}function Ext(t,e){return new $8({type:"object",shape:t,catchall:Pce(),...nt.normalizeParams(e)})}function Mxt(t,e){return new $8({type:"object",shape:t,catchall:lx(),...nt.normalizeParams(e)})}function Ece(t,e){return new D8({type:"union",options:t,...nt.normalizeParams(e)})}function Oxt(t,e){return new dDe({type:"union",options:t,inclusive:!1,...nt.normalizeParams(e)})}function Nxt(t,e,n){return new fDe({type:"union",options:e,discriminator:t,...nt.normalizeParams(n)})}function mDe(t,e){return new pDe({type:"intersection",left:t,right:e})}function gDe(t,e,n){let r=e instanceof kr,o=r?n:e,i=r?e:null;return new hDe({type:"tuple",items:t,rest:i,...nt.normalizeParams(o)})}function yDe(t,e,n){return!e||!e._zod?new sj({type:"record",keyType:A8(),valueType:t,...nt.normalizeParams(e)}):new sj({type:"record",keyType:t,valueType:e,...nt.normalizeParams(n)})}function Rxt(t,e,n){let r=Va(t);return r._zod.values=void 0,new sj({type:"record",keyType:r,valueType:e,...nt.normalizeParams(n)})}function Lxt(t,e,n){return new sj({type:"record",keyType:t,valueType:e,mode:"loose",...nt.normalizeParams(n)})}function $xt(t,e,n){return new vDe({type:"map",keyType:t,valueType:e,...nt.normalizeParams(n)})}function Dxt(t,e){return new wDe({type:"set",valueType:t,...nt.normalizeParams(e)})}function Mce(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new aj({type:"enum",entries:n,...nt.normalizeParams(e)})}function Fxt(t,e){return new aj({type:"enum",entries:t,...nt.normalizeParams(e)})}function Uxt(t,e){return new bDe({type:"literal",values:Array.isArray(t)?t:[t],...nt.normalizeParams(e)})}function jxt(t){return q1e(_De,t)}function Oce(t){return new xDe({type:"transform",transform:t})}function M8(t){return new Nce({type:"optional",innerType:t})}function CDe(t){return new SDe({type:"optional",innerType:t})}function O8(t){return new kDe({type:"nullable",innerType:t})}function Bxt(t){return M8(O8(t))}function TDe(t,e){return new IDe({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():nt.shallowClone(e)}})}function ADe(t,e){return new PDe({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():nt.shallowClone(e)}})}function EDe(t,e){return new Rce({type:"nonoptional",innerType:t,...nt.normalizeParams(e)})}function zxt(t){return new MDe({type:"success",innerType:t})}function NDe(t,e){return new ODe({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Hxt(t){return W1e(RDe,t)}function cce(t,e){return new F8({type:"pipe",in:t,out:e})}function Wxt(t,e,n){return new U8({type:"pipe",in:t,out:e,transform:n.decode,reverseTransform:n.encode})}function Vxt(t){let e=t._zod.def;return new U8({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}function DDe(t){return new $De({type:"readonly",innerType:t})}function qxt(t,e){return new FDe({type:"template_literal",parts:t,...nt.normalizeParams(e)})}function jDe(t){return new UDe({type:"lazy",getter:t})}function Kxt(t){return new BDe({type:"promise",innerType:t})}function Gxt(t){return new zDe({type:"function",input:Array.isArray(t?.input)?gDe(t?.input):t?.input??_P(lx()),output:t?.output??lx()})}function Zxt(t){let e=new ds({check:"custom"});return e._zod.check=t,e}function Lce(t,e){return K1e(j8,t??(()=>!0),e)}function HDe(t,e={}){return G1e(j8,t,e)}function WDe(t,e){return Z1e(t,e)}function Xxt(t,e={}){let n=new j8({type:"custom",check:"custom",fn:r=>r instanceof t,abort:!0,...nt.normalizeParams(e)});return n._zod.bag.Class=t,n._zod.check=r=>{r.value instanceof t||r.issues.push({code:"invalid_type",expected:t.name,input:r.value,inst:n,path:[...n._zod.def.path??[]]})},n}function eSt(t){let e=jDe(()=>Ece([A8(t),tDe(),fj(),iDe(),_P(e),yDe(A8(),e)]));return e}function tSt(t,e){return new LDe({type:"pipe",in:Oce(t),out:e})}var z_t,Vr,uce,lj,ns,dce,E8,ax,R8,fce,pce,mce,hce,gce,yce,vce,wce,eDe,bce,_ce,xce,Sce,Cce,kce,Ice,cj,uj,zN,dj,pj,Tce,nDe,rDe,oDe,sDe,aDe,lDe,cDe,L8,uDe,$8,D8,dDe,fDe,pDe,hDe,sj,vDe,wDe,aj,bDe,_De,xDe,Nce,SDe,kDe,IDe,PDe,Rce,MDe,ODe,RDe,F8,U8,LDe,$De,FDe,UDe,BDe,zDe,j8,Yxt,Jxt,Qxt,T8=b(()=>{tf();tf();C8();S8();rce();k8();Q$e();z_t=new WeakMap;Vr=ve("ZodType",(t,e)=>(kr.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:oj(t,"input"),output:oj(t,"output")}}),t.toJSONSchema=Q1e(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(n,r)=>P8(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>H$e(t,n,r),t.parseAsync=async(n,r)=>z$e(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>W$e(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>V$e(t,n,r),t.decode=(n,r)=>q$e(t,n,r),t.encodeAsync=async(n,r)=>K$e(t,n,r),t.decodeAsync=async(n,r)=>G$e(t,n,r),t.safeEncode=(n,r)=>Z$e(t,n,r),t.safeDecode=(n,r)=>Y$e(t,n,r),t.safeEncodeAsync=async(n,r)=>J$e(t,n,r),t.safeDecodeAsync=async(n,r)=>X$e(t,n,r),N8(t,"ZodType",{check(...n){let r=this.def;return this.clone(nt.mergeDefs(r,{checks:[...r.checks??[],...n.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return Va(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(HDe(n,r))},superRefine(n,r){return this.check(WDe(n,r))},overwrite(n){return this.check(Bw(n))},optional(){return M8(this)},exactOptional(){return CDe(this)},nullable(){return O8(this)},nullish(){return M8(O8(this))},nonoptional(n){return EDe(this,n)},array(){return _P(this)},or(n){return Ece([this,n])},and(n){return mDe(this,n)},transform(n){return cce(this,Oce(n))},default(n){return TDe(this,n)},prefault(n){return ADe(this,n)},catch(n){return NDe(this,n)},pipe(n){return cce(this,n)},readonly(){return DDe(this)},describe(n){let r=this.clone();return Vs.add(r,{description:n}),r},meta(...n){if(n.length===0)return Vs.get(this);let r=this.clone();return Vs.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(t,"description",{get(){return Vs.get(t)?.description},configurable:!0}),t)),uce=ve("_ZodString",(t,e)=>{FN.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(r,o,i)=>e$e(t,r,o,i);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,N8(t,"_ZodString",{regex(...r){return this.check(VU(...r))},includes(...r){return this.check(GU(...r))},startsWith(...r){return this.check(ZU(...r))},endsWith(...r){return this.check(YU(...r))},min(...r){return this.check(ak(...r))},max(...r){return this.check(jN(...r))},length(...r){return this.check(BN(...r))},nonempty(...r){return this.check(ak(1,...r))},lowercase(r){return this.check(qU(r))},uppercase(r){return this.check(KU(r))},trim(){return this.check(QU())},normalize(...r){return this.check(XU(...r))},toLowerCase(){return this.check(ej())},toUpperCase(){return this.check(tj())},slugify(){return this.check(nj())}})}),lj=ve("ZodString",(t,e)=>{FN.init(t,e),uce.init(t,e),t.email=n=>t.check(Ile(dce,n)),t.url=n=>t.check(_8(R8,n)),t.jwt=n=>t.check(Vle(Ice,n)),t.emoji=n=>t.check(Mle(fce,n)),t.guid=n=>t.check(b8(E8,n)),t.uuid=n=>t.check(Tle(ax,n)),t.uuidv4=n=>t.check(Ple(ax,n)),t.uuidv6=n=>t.check(Ale(ax,n)),t.uuidv7=n=>t.check(Ele(ax,n)),t.nanoid=n=>t.check(Ole(pce,n)),t.guid=n=>t.check(b8(E8,n)),t.cuid=n=>t.check(Nle(mce,n)),t.cuid2=n=>t.check(Rle(hce,n)),t.ulid=n=>t.check(Lle(gce,n)),t.base64=n=>t.check(zle(Sce,n)),t.base64url=n=>t.check(Hle(Cce,n)),t.xid=n=>t.check($le(yce,n)),t.ksuid=n=>t.check(Dle(vce,n)),t.ipv4=n=>t.check(Fle(wce,n)),t.ipv6=n=>t.check(Ule(bce,n)),t.cidrv4=n=>t.check(jle(_ce,n)),t.cidrv6=n=>t.check(Ble(xce,n)),t.e164=n=>t.check(Wle(kce,n)),t.datetime=n=>t.check(D$e(n)),t.date=n=>t.check(F$e(n)),t.time=n=>t.check(U$e(n)),t.duration=n=>t.check(j$e(n))});ns=ve("ZodStringFormat",(t,e)=>{ts.init(t,e),uce.init(t,e)}),dce=ve("ZodEmail",(t,e)=>{oLe.init(t,e),ns.init(t,e)});E8=ve("ZodGUID",(t,e)=>{nLe.init(t,e),ns.init(t,e)});ax=ve("ZodUUID",(t,e)=>{rLe.init(t,e),ns.init(t,e)});R8=ve("ZodURL",(t,e)=>{iLe.init(t,e),ns.init(t,e)});fce=ve("ZodEmoji",(t,e)=>{sLe.init(t,e),ns.init(t,e)});pce=ve("ZodNanoID",(t,e)=>{aLe.init(t,e),ns.init(t,e)});mce=ve("ZodCUID",(t,e)=>{lLe.init(t,e),ns.init(t,e)});hce=ve("ZodCUID2",(t,e)=>{cLe.init(t,e),ns.init(t,e)});gce=ve("ZodULID",(t,e)=>{uLe.init(t,e),ns.init(t,e)});yce=ve("ZodXID",(t,e)=>{dLe.init(t,e),ns.init(t,e)});vce=ve("ZodKSUID",(t,e)=>{fLe.init(t,e),ns.init(t,e)});wce=ve("ZodIPv4",(t,e)=>{yLe.init(t,e),ns.init(t,e)});eDe=ve("ZodMAC",(t,e)=>{wLe.init(t,e),ns.init(t,e)});bce=ve("ZodIPv6",(t,e)=>{vLe.init(t,e),ns.init(t,e)});_ce=ve("ZodCIDRv4",(t,e)=>{bLe.init(t,e),ns.init(t,e)});xce=ve("ZodCIDRv6",(t,e)=>{_Le.init(t,e),ns.init(t,e)});Sce=ve("ZodBase64",(t,e)=>{SLe.init(t,e),ns.init(t,e)});Cce=ve("ZodBase64URL",(t,e)=>{CLe.init(t,e),ns.init(t,e)});kce=ve("ZodE164",(t,e)=>{kLe.init(t,e),ns.init(t,e)});Ice=ve("ZodJWT",(t,e)=>{ILe.init(t,e),ns.init(t,e)});cj=ve("ZodCustomStringFormat",(t,e)=>{TLe.init(t,e),ns.init(t,e)});uj=ve("ZodNumber",(t,e)=>{yle.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(r,o,i)=>t$e(t,r,o,i),N8(t,"ZodNumber",{gt(r,o){return this.check(ix(r,o))},gte(r,o){return this.check(ip(r,o))},min(r,o){return this.check(ip(r,o))},lt(r,o){return this.check(ox(r,o))},lte(r,o){return this.check(Rh(r,o))},max(r,o){return this.check(Rh(r,o))},int(r){return this.check(lce(r))},safe(r){return this.check(lce(r))},positive(r){return this.check(ix(0,r))},nonnegative(r){return this.check(ip(0,r))},negative(r){return this.check(ox(0,r))},nonpositive(r){return this.check(Rh(0,r))},multipleOf(r,o){return this.check(gP(r,o))},step(r,o){return this.check(gP(r,o))},finite(){return this}});let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});zN=ve("ZodNumberFormat",(t,e)=>{PLe.init(t,e),uj.init(t,e)});dj=ve("ZodBoolean",(t,e)=>{f8.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>n$e(t,n,r,o)});pj=ve("ZodBigInt",(t,e)=>{vle.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(r,o,i)=>r$e(t,r,o,i),t.gte=(r,o)=>t.check(ip(r,o)),t.min=(r,o)=>t.check(ip(r,o)),t.gt=(r,o)=>t.check(ix(r,o)),t.gte=(r,o)=>t.check(ip(r,o)),t.min=(r,o)=>t.check(ip(r,o)),t.lt=(r,o)=>t.check(ox(r,o)),t.lte=(r,o)=>t.check(Rh(r,o)),t.max=(r,o)=>t.check(Rh(r,o)),t.positive=r=>t.check(ix(BigInt(0),r)),t.negative=r=>t.check(ox(BigInt(0),r)),t.nonpositive=r=>t.check(Rh(BigInt(0),r)),t.nonnegative=r=>t.check(ip(BigInt(0),r)),t.multipleOf=(r,o)=>t.check(gP(r,o));let n=t._zod.bag;t.minValue=n.minimum??null,t.maxValue=n.maximum??null,t.format=n.format??null});Tce=ve("ZodBigIntFormat",(t,e)=>{ALe.init(t,e),pj.init(t,e)});nDe=ve("ZodSymbol",(t,e)=>{ELe.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>o$e(t,n,r,o)});rDe=ve("ZodUndefined",(t,e)=>{MLe.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>s$e(t,n,r,o)});oDe=ve("ZodNull",(t,e)=>{OLe.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>i$e(t,n,r,o)});sDe=ve("ZodAny",(t,e)=>{NLe.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>c$e(t,n,r,o)});aDe=ve("ZodUnknown",(t,e)=>{wle.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>u$e(t,n,r,o)});lDe=ve("ZodNever",(t,e)=>{p8.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>l$e(t,n,r,o)});cDe=ve("ZodVoid",(t,e)=>{RLe.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>a$e(t,n,r,o)});L8=ve("ZodDate",(t,e)=>{LLe.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(r,o,i)=>d$e(t,r,o,i),t.min=(r,o)=>t.check(ip(r,o)),t.max=(r,o)=>t.check(Rh(r,o));let n=t._zod.bag;t.minDate=n.minimum?new Date(n.minimum):null,t.maxDate=n.maximum?new Date(n.maximum):null});uDe=ve("ZodArray",(t,e)=>{$Le.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>S$e(t,n,r,o),t.element=e.element,N8(t,"ZodArray",{min(n,r){return this.check(ak(n,r))},nonempty(n){return this.check(ak(1,n))},max(n,r){return this.check(jN(n,r))},length(n,r){return this.check(BN(n,r))},unwrap(){return this.element}})});$8=ve("ZodObject",(t,e)=>{DLe.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>C$e(t,n,r,o),nt.defineLazy(t,"shape",()=>e.shape),N8(t,"ZodObject",{keyof(){return Mce(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:lx()})},loose(){return this.clone({...this._zod.def,catchall:lx()})},strict(){return this.clone({...this._zod.def,catchall:Pce()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return nt.extend(this,n)},safeExtend(n){return nt.safeExtend(this,n)},merge(n){return nt.merge(this,n)},pick(n){return nt.pick(this,n)},omit(n){return nt.omit(this,n)},partial(...n){return nt.partial(Nce,this,n[0])},required(...n){return nt.required(Rce,this,n[0])}})});D8=ve("ZodUnion",(t,e)=>{m8.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Qle(t,n,r,o),t.options=e.options});dDe=ve("ZodXor",(t,e)=>{D8.init(t,e),FLe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Qle(t,n,r,o),t.options=e.options});fDe=ve("ZodDiscriminatedUnion",(t,e)=>{D8.init(t,e),ULe.init(t,e)});pDe=ve("ZodIntersection",(t,e)=>{jLe.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>k$e(t,n,r,o)});hDe=ve("ZodTuple",(t,e)=>{ble.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>I$e(t,n,r,o),t.rest=n=>t.clone({...t._zod.def,rest:n})});sj=ve("ZodRecord",(t,e)=>{BLe.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>T$e(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType});vDe=ve("ZodMap",(t,e)=>{zLe.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>_$e(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...n)=>t.check(sx(...n)),t.nonempty=n=>t.check(sx(1,n)),t.max=(...n)=>t.check(yP(...n)),t.size=(...n)=>t.check(UN(...n))});wDe=ve("ZodSet",(t,e)=>{HLe.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>x$e(t,n,r,o),t.min=(...n)=>t.check(sx(...n)),t.nonempty=n=>t.check(sx(1,n)),t.max=(...n)=>t.check(yP(...n)),t.size=(...n)=>t.check(UN(...n))});aj=ve("ZodEnum",(t,e)=>{WLe.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(r,o,i)=>f$e(t,r,o,i),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{let i={};for(let s of r)if(n.has(s))i[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new aj({...e,checks:[],...nt.normalizeParams(o),entries:i})},t.exclude=(r,o)=>{let i={...e.entries};for(let s of r)if(n.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new aj({...e,checks:[],...nt.normalizeParams(o),entries:i})}});bDe=ve("ZodLiteral",(t,e)=>{VLe.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>p$e(t,n,r,o),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});_De=ve("ZodFile",(t,e)=>{qLe.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>g$e(t,n,r,o),t.min=(n,r)=>t.check(sx(n,r)),t.max=(n,r)=>t.check(yP(n,r)),t.mime=(n,r)=>t.check(JU(Array.isArray(n)?n:[n],r))});xDe=ve("ZodTransform",(t,e)=>{KLe.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>b$e(t,n,r,o),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new dP(t.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(nt.issue(i,n.value,e));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=t),n.issues.push(nt.issue(s))}};let o=e.transform(n.value,n);return o instanceof Promise?o.then(i=>(n.value=i,n.fallback=!0,n)):(n.value=o,n.fallback=!0,n)}});Nce=ve("ZodOptional",(t,e)=>{h8.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ece(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});SDe=ve("ZodExactOptional",(t,e)=>{GLe.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ece(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});kDe=ve("ZodNullable",(t,e)=>{ZLe.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>P$e(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});IDe=ve("ZodDefault",(t,e)=>{YLe.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>E$e(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});PDe=ve("ZodPrefault",(t,e)=>{JLe.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>M$e(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});Rce=ve("ZodNonOptional",(t,e)=>{XLe.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>A$e(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});MDe=ve("ZodSuccess",(t,e)=>{QLe.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>y$e(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});ODe=ve("ZodCatch",(t,e)=>{e1e.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>O$e(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});RDe=ve("ZodNaN",(t,e)=>{t1e.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>m$e(t,n,r,o)});F8=ve("ZodPipe",(t,e)=>{_le.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>N$e(t,n,r,o),t.in=e.in,t.out=e.out});U8=ve("ZodCodec",(t,e)=>{F8.init(t,e),g8.init(t,e)});LDe=ve("ZodPreprocess",(t,e)=>{F8.init(t,e),n1e.init(t,e)}),$De=ve("ZodReadonly",(t,e)=>{r1e.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>R$e(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});FDe=ve("ZodTemplateLiteral",(t,e)=>{o1e.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>h$e(t,n,r,o)});UDe=ve("ZodLazy",(t,e)=>{a1e.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>$$e(t,n,r,o),t.unwrap=()=>t._zod.def.getter()});BDe=ve("ZodPromise",(t,e)=>{s1e.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>L$e(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});zDe=ve("ZodFunction",(t,e)=>{i1e.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>w$e(t,n,r,o)});j8=ve("ZodCustom",(t,e)=>{l1e.init(t,e),Vr.init(t,e),t._zod.processJSONSchema=(n,r,o)=>v$e(t,n,r,o)});Yxt=Y1e,Jxt=J1e;Qxt=(...t)=>X1e({Codec:U8,Boolean:dj,String:lj},...t)});function T$n(t){Wa({customError:t})}function P$n(){return Wa().customError}var I$n,VDe,nSt=b(()=>{tf();I$n={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};VDe||(VDe={})});function E$n(t,e){let n=t.$schema;return n==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":n==="http://json-schema.org/draft-07/schema#"?"draft-7":n==="http://json-schema.org/draft-04/schema#"?"draft-4":e??"draft-2020-12"}function M$n(t,e){if(!t.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let n=t.slice(1).split("/").filter(Boolean);if(n.length===0)return e.rootSchema;let r=e.version==="draft-2020-12"?"$defs":"definitions";if(n[0]===r){let o=n[1];if(!o||!e.defs[o])throw new Error(`Reference not found: ${t}`);return e.defs[o]}throw new Error(`Reference not found: ${t}`)}function rSt(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return Dt.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(t.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(t.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(t.if!==void 0||t.then!==void 0||t.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(t.dependentSchemas!==void 0||t.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(t.$ref){let o=t.$ref;if(e.refs.has(o))return e.refs.get(o);if(e.processing.has(o))return Dt.lazy(()=>{if(!e.refs.has(o))throw new Error(`Circular reference not resolved: ${o}`);return e.refs.get(o)});e.processing.add(o);let i=M$n(o,e),s=nf(i,e);return e.refs.set(o,s),e.processing.delete(o),s}if(t.enum!==void 0){let o=t.enum;if(e.version==="openapi-3.0"&&t.nullable===!0&&o.length===1&&o[0]===null)return Dt.null();if(o.length===0)return Dt.never();if(o.length===1)return Dt.literal(o[0]);if(o.every(s=>typeof s=="string"))return Dt.enum(o);let i=o.map(s=>Dt.literal(s));return i.length<2?i[0]:Dt.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return Dt.literal(t.const);let n=t.type;if(Array.isArray(n)){let o=n.map(i=>{let s={...t,type:i};return rSt(s,e)});return o.length===0?Dt.never():o.length===1?o[0]:Dt.union(o)}if(!n)return Dt.any();let r;switch(n){case"string":{let o=Dt.string();if(t.format){let i=t.format;i==="email"?o=o.check(Dt.email()):i==="uri"||i==="uri-reference"?o=o.check(Dt.url()):i==="uuid"||i==="guid"?o=o.check(Dt.uuid()):i==="date-time"?o=o.check(Dt.iso.datetime()):i==="date"?o=o.check(Dt.iso.date()):i==="time"?o=o.check(Dt.iso.time()):i==="duration"?o=o.check(Dt.iso.duration()):i==="ipv4"?o=o.check(Dt.ipv4()):i==="ipv6"?o=o.check(Dt.ipv6()):i==="mac"?o=o.check(Dt.mac()):i==="cidr"?o=o.check(Dt.cidrv4()):i==="cidr-v6"?o=o.check(Dt.cidrv6()):i==="base64"?o=o.check(Dt.base64()):i==="base64url"?o=o.check(Dt.base64url()):i==="e164"?o=o.check(Dt.e164()):i==="jwt"?o=o.check(Dt.jwt()):i==="emoji"?o=o.check(Dt.emoji()):i==="nanoid"?o=o.check(Dt.nanoid()):i==="cuid"?o=o.check(Dt.cuid()):i==="cuid2"?o=o.check(Dt.cuid2()):i==="ulid"?o=o.check(Dt.ulid()):i==="xid"?o=o.check(Dt.xid()):i==="ksuid"&&(o=o.check(Dt.ksuid()))}typeof t.minLength=="number"&&(o=o.min(t.minLength)),typeof t.maxLength=="number"&&(o=o.max(t.maxLength)),t.pattern&&(o=o.regex(new RegExp(t.pattern))),r=o;break}case"number":case"integer":{let o=n==="integer"?Dt.number().int():Dt.number();typeof t.minimum=="number"&&(o=o.min(t.minimum)),typeof t.maximum=="number"&&(o=o.max(t.maximum)),typeof t.exclusiveMinimum=="number"?o=o.gt(t.exclusiveMinimum):t.exclusiveMinimum===!0&&typeof t.minimum=="number"&&(o=o.gt(t.minimum)),typeof t.exclusiveMaximum=="number"?o=o.lt(t.exclusiveMaximum):t.exclusiveMaximum===!0&&typeof t.maximum=="number"&&(o=o.lt(t.maximum)),typeof t.multipleOf=="number"&&(o=o.multipleOf(t.multipleOf)),r=o;break}case"boolean":{r=Dt.boolean();break}case"null":{r=Dt.null();break}case"object":{let o={},i=t.properties||{},s=new Set(t.required||[]);for(let[l,c]of Object.entries(i)){let u=nf(c,e);o[l]=s.has(l)?u:u.optional()}if(t.propertyNames){let l=nf(t.propertyNames,e),c=t.additionalProperties&&typeof t.additionalProperties=="object"?nf(t.additionalProperties,e):Dt.any();if(Object.keys(o).length===0){r=Dt.record(l,c);break}let u=Dt.object(o).passthrough(),d=Dt.looseRecord(l,c);r=Dt.intersection(u,d);break}if(t.patternProperties){let l=t.patternProperties,c=Object.keys(l),u=[];for(let f of c){let p=nf(l[f],e),m=Dt.string().regex(new RegExp(f));u.push(Dt.looseRecord(m,p))}let d=[];if(Object.keys(o).length>0&&d.push(Dt.object(o).passthrough()),d.push(...u),d.length===0)r=Dt.object({}).passthrough();else if(d.length===1)r=d[0];else{let f=Dt.intersection(d[0],d[1]);for(let p=2;p<d.length;p++)f=Dt.intersection(f,d[p]);r=f}break}let a=Dt.object(o);t.additionalProperties===!1?r=a.strict():typeof t.additionalProperties=="object"?r=a.catchall(nf(t.additionalProperties,e)):r=a.passthrough();break}case"array":{let o=t.prefixItems,i=t.items;if(o&&Array.isArray(o)){let s=o.map(l=>nf(l,e)),a=i&&typeof i=="object"&&!Array.isArray(i)?nf(i,e):void 0;a?r=Dt.tuple(s).rest(a):r=Dt.tuple(s),typeof t.minItems=="number"&&(r=r.check(Dt.minLength(t.minItems))),typeof t.maxItems=="number"&&(r=r.check(Dt.maxLength(t.maxItems)))}else if(Array.isArray(i)){let s=i.map(l=>nf(l,e)),a=t.additionalItems&&typeof t.additionalItems=="object"?nf(t.additionalItems,e):void 0;a?r=Dt.tuple(s).rest(a):r=Dt.tuple(s),typeof t.minItems=="number"&&(r=r.check(Dt.minLength(t.minItems))),typeof t.maxItems=="number"&&(r=r.check(Dt.maxLength(t.maxItems)))}else if(i!==void 0){let s=nf(i,e),a=Dt.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),r=a}else r=Dt.array(Dt.any());break}default:throw new Error(`Unsupported type: ${n}`)}return r}function nf(t,e){if(typeof t=="boolean")return t?Dt.any():Dt.never();let n=rSt(t,e),r=t.type||t.enum!==void 0||t.const!==void 0;if(t.anyOf&&Array.isArray(t.anyOf)){let a=t.anyOf.map(c=>nf(c,e)),l=Dt.union(a);n=r?Dt.intersection(n,l):l}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(c=>nf(c,e)),l=Dt.xor(a);n=r?Dt.intersection(n,l):l}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)n=r?n:Dt.any();else{let a=r?n:nf(t.allOf[0],e),l=r?0:1;for(let c=l;c<t.allOf.length;c++)a=Dt.intersection(a,nf(t.allOf[c],e));n=a}t.nullable===!0&&e.version==="openapi-3.0"&&(n=Dt.nullable(n)),t.readOnly===!0&&(n=Dt.readonly(n)),t.default!==void 0&&(n=n.default(t.default));let o={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of i)a in t&&(o[a]=t[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in t&&(o[a]=t[a]);for(let a of Object.keys(t))A$n.has(a)||(o[a]=t[a]);return Object.keys(o).length>0&&e.registry.add(n,o),t.description&&(n=n.describe(t.description)),n}function oSt(t,e){if(typeof t=="boolean")return t?Dt.any():Dt.never();let n;try{n=JSON.parse(JSON.stringify(t))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let r=E$n(n,e?.defaultTarget),o=n.$defs||n.definitions||{},i={version:r,defs:o,refs:new Map,processing:new Set,rootSchema:n,registry:e?.registry??Vs};return nf(n,i)}var Dt,A$n,iSt=b(()=>{w8();rce();k8();T8();Dt={...I8,...nce,iso:ij},A$n=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"])});var qDe={};sr(qDe,{bigint:()=>L$n,boolean:()=>R$n,date:()=>$$n,number:()=>N$n,string:()=>O$n});function O$n(t){return y1e(lj,t)}function N$n(t){return k1e(uj,t)}function R$n(t){return O1e(dj,t)}function L$n(t){return R1e(pj,t)}function $$n(t){return H1e(L8,t)}var sSt=b(()=>{tf();T8()});var x={};sr(x,{$brand:()=>BNe,$input:()=>h1e,$output:()=>m1e,NEVER:()=>jNe,TimePrecision:()=>w1e,ZodAny:()=>sDe,ZodArray:()=>uDe,ZodBase64:()=>Sce,ZodBase64URL:()=>Cce,ZodBigInt:()=>pj,ZodBigIntFormat:()=>Tce,ZodBoolean:()=>dj,ZodCIDRv4:()=>_ce,ZodCIDRv6:()=>xce,ZodCUID:()=>mce,ZodCUID2:()=>hce,ZodCatch:()=>ODe,ZodCodec:()=>U8,ZodCustom:()=>j8,ZodCustomStringFormat:()=>cj,ZodDate:()=>L8,ZodDefault:()=>IDe,ZodDiscriminatedUnion:()=>fDe,ZodE164:()=>kce,ZodEmail:()=>dce,ZodEmoji:()=>fce,ZodEnum:()=>aj,ZodError:()=>C$n,ZodExactOptional:()=>SDe,ZodFile:()=>_De,ZodFirstPartyTypeKind:()=>VDe,ZodFunction:()=>zDe,ZodGUID:()=>E8,ZodIPv4:()=>wce,ZodIPv6:()=>bce,ZodISODate:()=>ice,ZodISODateTime:()=>oce,ZodISODuration:()=>ace,ZodISOTime:()=>sce,ZodIntersection:()=>pDe,ZodIssueCode:()=>I$n,ZodJWT:()=>Ice,ZodKSUID:()=>vce,ZodLazy:()=>UDe,ZodLiteral:()=>bDe,ZodMAC:()=>eDe,ZodMap:()=>vDe,ZodNaN:()=>RDe,ZodNanoID:()=>pce,ZodNever:()=>lDe,ZodNonOptional:()=>Rce,ZodNull:()=>oDe,ZodNullable:()=>kDe,ZodNumber:()=>uj,ZodNumberFormat:()=>zN,ZodObject:()=>$8,ZodOptional:()=>Nce,ZodPipe:()=>F8,ZodPrefault:()=>PDe,ZodPreprocess:()=>LDe,ZodPromise:()=>BDe,ZodReadonly:()=>$De,ZodRealError:()=>dm,ZodRecord:()=>sj,ZodSet:()=>wDe,ZodString:()=>lj,ZodStringFormat:()=>ns,ZodSuccess:()=>MDe,ZodSymbol:()=>nDe,ZodTemplateLiteral:()=>FDe,ZodTransform:()=>xDe,ZodTuple:()=>hDe,ZodType:()=>Vr,ZodULID:()=>gce,ZodURL:()=>R8,ZodUUID:()=>ax,ZodUndefined:()=>rDe,ZodUnion:()=>D8,ZodUnknown:()=>aDe,ZodVoid:()=>cDe,ZodXID:()=>yce,ZodXor:()=>dDe,_ZodString:()=>uce,_default:()=>TDe,_function:()=>Gxt,any:()=>Ixt,array:()=>_P,base64:()=>cxt,base64url:()=>uxt,bigint:()=>_xt,boolean:()=>fj,catch:()=>NDe,check:()=>Zxt,cidrv4:()=>axt,cidrv6:()=>lxt,clone:()=>Va,codec:()=>Wxt,coerce:()=>qDe,config:()=>Wa,core:()=>ck,cuid:()=>Q_t,cuid2:()=>ext,custom:()=>Lce,date:()=>Pxt,decode:()=>q$e,decodeAsync:()=>G$e,describe:()=>Yxt,discriminatedUnion:()=>Nxt,e164:()=>dxt,email:()=>H_t,emoji:()=>J_t,encode:()=>V$e,encodeAsync:()=>K$e,endsWith:()=>YU,enum:()=>Mce,exactOptional:()=>CDe,file:()=>jxt,flattenError:()=>a8,float32:()=>yxt,float64:()=>vxt,formatError:()=>l8,fromJSONSchema:()=>oSt,function:()=>Gxt,getErrorMap:()=>P$n,globalRegistry:()=>Vs,gt:()=>ix,gte:()=>ip,guid:()=>W_t,hash:()=>gxt,hex:()=>hxt,hostname:()=>mxt,httpUrl:()=>Y_t,includes:()=>GU,instanceof:()=>Xxt,int:()=>lce,int32:()=>wxt,int64:()=>xxt,intersection:()=>mDe,invertCodec:()=>Vxt,ipv4:()=>oxt,ipv6:()=>sxt,iso:()=>ij,json:()=>eSt,jwt:()=>fxt,keyof:()=>Axt,ksuid:()=>rxt,lazy:()=>jDe,length:()=>BN,literal:()=>Uxt,locales:()=>v8,looseObject:()=>Mxt,looseRecord:()=>Lxt,lowercase:()=>qU,lt:()=>ox,lte:()=>Rh,mac:()=>ixt,map:()=>$xt,maxLength:()=>jN,maxSize:()=>yP,meta:()=>Jxt,mime:()=>JU,minLength:()=>ak,minSize:()=>sx,multipleOf:()=>gP,nan:()=>Hxt,nanoid:()=>X_t,nativeEnum:()=>Fxt,negative:()=>Gle,never:()=>Pce,nonnegative:()=>Yle,nonoptional:()=>EDe,nonpositive:()=>Zle,normalize:()=>XU,null:()=>iDe,nullable:()=>O8,nullish:()=>Bxt,number:()=>tDe,object:()=>Ace,optional:()=>M8,overwrite:()=>Bw,parse:()=>P8,parseAsync:()=>z$e,partialRecord:()=>Rxt,pipe:()=>cce,positive:()=>Kle,prefault:()=>ADe,preprocess:()=>tSt,prettifyError:()=>eRe,promise:()=>Kxt,property:()=>Jle,readonly:()=>DDe,record:()=>yDe,refine:()=>HDe,regex:()=>VU,regexes:()=>Nh,registry:()=>WU,safeDecode:()=>Y$e,safeDecodeAsync:()=>X$e,safeEncode:()=>Z$e,safeEncodeAsync:()=>J$e,safeParse:()=>H$e,safeParseAsync:()=>W$e,set:()=>Dxt,setErrorMap:()=>T$n,size:()=>UN,slugify:()=>nj,startsWith:()=>ZU,strictObject:()=>Ext,string:()=>A8,stringFormat:()=>pxt,stringbool:()=>Qxt,success:()=>zxt,superRefine:()=>WDe,symbol:()=>Cxt,templateLiteral:()=>qxt,toJSONSchema:()=>lk,toLowerCase:()=>ej,toUpperCase:()=>tj,transform:()=>Oce,treeifyError:()=>QNe,trim:()=>QU,tuple:()=>gDe,uint32:()=>bxt,uint64:()=>Sxt,ulid:()=>txt,undefined:()=>kxt,union:()=>Ece,unknown:()=>lx,uppercase:()=>KU,url:()=>Z_t,util:()=>nt,uuid:()=>V_t,uuidv4:()=>q_t,uuidv6:()=>K_t,uuidv7:()=>G_t,void:()=>Txt,xid:()=>nxt,xor:()=>Oxt});var B8=b(()=>{tf();T8();rce();B$e();Q$e();nSt();tf();u1e();tf();C8();iSt();p1e();k8();k8();sSt();Wa(xle())});var ap=b(()=>{B8();B8()});async function xP(t,e,n={}){let r=n.timeoutMs??D$n,o,i=new Promise((s,a)=>{o=window.setTimeout(()=>a(new $ce(`Timed out after ${r}ms`)),r)});try{let s=await Promise.race([bh(t,{method:"GET",headers:e}),i]);return await F$n(s)}catch(s){return{ok:!1,code:s instanceof $ce?"timeout":"network",message:s instanceof Error?s.message:String(s),checkedAt:Date.now()}}finally{o!==void 0&&window.clearTimeout(o)}}async function F$n(t){let{status:e}=t,n=Date.now();if(e>=200&&e<300)return{ok:!0,checkedAt:n};if(e===401||e===403)return{ok:!1,code:"invalid_api_key",message:"Authentication failed \u2014 check your API key.",checkedAt:n};if(e===429)return{ok:!1,code:"rate_limited",message:"Rate limited \u2014 try again in a moment.",checkedAt:n};let r=await U$n(t);return{ok:!1,code:"http_error",message:r?`HTTP ${e}: ${r}`:`HTTP ${e}`,checkedAt:n}}async function U$n(t){try{let e=(await t.text()).trim();return e.length>aSt?`${e.slice(0,aSt)}\u2026`:e}catch{return""}}var D$n,aSt,$ce,z8=b(()=>{ut();D$n=8e3,aSt=200,$ce=class extends Error{}});var j$n,B$n,z$n,lSt,cSt=b(()=>{ap();z8();j$n="https://api.anthropic.com",B$n="2023-06-01",z$n=x.object({}).strict(),lSt={providerType:"anthropic",extrasSchema:z$n,buildLangChainClient(t){throw new Error("[modelManagement] anthropicAdapter.buildLangChainClient not implemented yet")},verifyCredentials(t){if(!t.apiKey)return Promise.resolve({ok:!1,code:"missing_api_key",message:"An API key is required to verify this Anthropic provider.",checkedAt:Date.now()});let n=(t.provider.baseUrl?.trim()||j$n).replace(/\/$/,"");return xP(`${n}/v1/models`,{"x-api-key":t.apiKey,"anthropic-version":B$n,"anthropic-dangerous-direct-browser-access":"true"})}}});var H$n,W$n,uSt,dSt=b(()=>{ap();z8();H$n=/^[a-zA-Z0-9-]+$/,W$n=x.object({azureInstanceName:x.string().min(1).regex(H$n,"must contain only letters, digits, and hyphens"),azureDeploymentName:x.string().min(1),azureApiVersion:x.string().min(1)}).strict(),uSt={providerType:"azure",extrasSchema:W$n,buildLangChainClient(t){throw new Error("[modelManagement] azureAdapter.buildLangChainClient not implemented yet")},verifyCredentials(t){if(!t.apiKey)return Promise.resolve({ok:!1,code:"missing_api_key",message:"An API key is required to verify this Azure provider.",checkedAt:Date.now()});let{azureInstanceName:e,azureApiVersion:n}=t.extras,r=`https://${e}.openai.azure.com/openai/deployments?api-version=${encodeURIComponent(n)}`;return xP(r,{"api-key":t.apiKey})}}});var V$n,q$n,fSt,pSt=b(()=>{ap();z8();V$n="https://generativelanguage.googleapis.com",q$n=x.object({}).strict(),fSt={providerType:"google",extrasSchema:q$n,buildLangChainClient(t){throw new Error("[modelManagement] googleAdapter.buildLangChainClient not implemented yet")},verifyCredentials(t){if(!t.apiKey)return Promise.resolve({ok:!1,code:"missing_api_key",message:"An API key is required to verify this Google provider.",checkedAt:Date.now()});let n=(t.provider.baseUrl?.trim()||V$n).replace(/\/$/,"");return xP(`${n}/v1beta/models?key=${encodeURIComponent(t.apiKey)}`,{})}}});function hSt(t){return t?K$n[t]??mSt:mSt}var mSt,K$n,gSt=b(()=>{mSt="models",K$n={openrouter:"key"}});var G$n,ySt,vSt=b(()=>{ap();gSt();z8();G$n=x.object({openAIOrgId:x.string().optional()}).strict(),ySt={providerType:"openai-compatible",extrasSchema:G$n,buildLangChainClient(t){throw new Error("[modelManagement] openaiCompatibleAdapter.buildLangChainClient not implemented yet")},verifyCredentials(t){let e=t.provider.baseUrl?.trim();if(!e)return Promise.resolve({ok:!1,code:"missing_base_url",message:"A base URL is required to verify this OpenAI-compatible provider.",checkedAt:Date.now()});let n=e.replace(/\/$/,""),r={};t.apiKey&&(r.Authorization=`Bearer ${t.apiKey}`),t.extras.openAIOrgId&&(r["OpenAI-Organization"]=t.extras.openAIOrgId);let o=t.provider.origin.kind==="byok"?t.provider.origin.catalogProviderId:void 0,i=hSt(o);return xP(`${n}/${i}`,r)}}});function KDe(){let t=new Dce;return t.register(lSt),t.register(ySt),t.register(fSt),t.register(uSt),t}var Dce,GDe=b(()=>{cSt();dSt();pSt();vSt();Dce=class{constructor(){this.adapters=new Map}register(e){this.adapters.set(e.providerType,e)}get(e){let n=this.adapters.get(e);if(!n)throw new Error(`[modelManagement] No adapter registered for providerType "${e}"`);return n}list(){return[...this.adapters.values()]}buildLangChainClient(e,n){let r=this.get(e),o=r.extrasSchema.parse(n.extras);return r.buildLangChainClient({...n,extras:o})}verifyCredentials(e,n){let r=this.get(e),o=r.extrasSchema.parse(n.extras);return r.verifyCredentials({...n,extras:o})}}});var VN,HN,uk,WN,qN,ZDe,wSt,H8,W8=b(()=>{pe();Fae();VN=["chat","opencode"],H8=class{constructor(e,n,r){Rt(this,qN);Rt(this,HN);Rt(this,uk);Rt(this,WN);Et(this,HN,e),Et(this,uk,n),Et(this,WN,r)}async setupProvider(e){let n=await re(this,HN).add({providerType:e.providerType,displayName:e.displayName,baseUrl:e.baseUrl,enableCors:e.enableCors,requiresApiKey:e.requiresApiKey??!0,origin:{kind:"byok",...e.catalogProviderId?{catalogProviderId:e.catalogProviderId}:{}},extras:e.extras});try{e.apiKey&&await re(this,HN).setApiKey(n,e.apiKey);let r=await re(this,uk).bulkSet(n,e.models),o=r.filter((i,s)=>!e.models[s]?.isEmbedding);return await Je(this,qN,ZDe).call(this,e.autoEnrollIn??VN,o),{providerId:n,configuredModelIds:r}}catch(r){throw await Je(this,qN,wSt).call(this,n),r}}async addModels(e){let n=[],r=[];for(let o of e.models){let i=re(this,uk).getByWireId(e.providerId,o.id);if(i){n.push(i.configuredModelId);continue}let s=await re(this,uk).add({providerId:e.providerId,info:o});n.push(s),(o.isEmbedding??D9(o.id))||r.push(s)}return await Je(this,qN,ZDe).call(this,e.autoEnrollIn??VN,r),n}};HN=new WeakMap,uk=new WeakMap,WN=new WeakMap,qN=new WeakSet,ZDe=async function(e,n){if(n.length!==0)for(let r of e){let i=[...re(this,WN).get(r).enabledModels];for(let s of n)i.includes(s)||i.push(s);await re(this,WN).setEnabledModels(r,i)}},wSt=async function(e){try{let n=re(this,uk).listByProvider(e).map(r=>r.configuredModelId);n.length>0&&(await re(this,WN).removeRefs(n),await re(this,uk).removeByProvider(e)),await re(this,HN).remove(e)}catch(n){H(`[modelManagement] ByokSetupApi rollback failed for ${e}`,n)}}});var bSt,dk,cx,q8,mj,K8,Aa,_St,xSt,SSt,YDe,CSt,JDe,XDe,Fce,V8,QDe=b(()=>{pe();bSt=Object.freeze([]),V8=class{constructor(e,n,r,o,i){Rt(this,Aa);Rt(this,dk);Rt(this,cx);Rt(this,q8);Rt(this,mj);Rt(this,K8);Et(this,dk,e),Et(this,cx,n),Et(this,q8,r),Et(this,mj,o),Et(this,K8,i)}async registerAgentProvider(e){let n=Je(this,Aa,_St).call(this,e.agentType,e.providerType),r;n?(r=n.providerId,await re(this,dk).update(r,{displayName:e.displayName,baseUrl:e.baseUrl,extras:e.extras})):r=await re(this,dk).add({providerType:e.providerType,displayName:e.displayName,baseUrl:e.baseUrl,origin:{kind:"agent",agentType:e.agentType},extras:e.extras,requiresApiKey:!1}),e.apiKey!=null&&await re(this,dk).setApiKey(r,e.apiKey);let o=await Je(this,Aa,SSt).call(this,e.providerType,e.wireModelIds,e.fallbackDisplayNames,e.fallbackDescriptions),{added:i,removed:s}=await Je(this,Aa,Fce).call(this,e.agentType,r,o,{autoEnrollModelIds:e.autoEnrollModelIds}),a=new Map(i.map(c=>[c.wireId,c.configuredModelId])),l=[];for(let c of o){let u=a.get(c.id);if(u){l.push(u);continue}let d=re(this,cx).getByWireId(r,c.id);d&&l.push(d.configuredModelId)}return{providerId:r,configuredModelIds:l}}async syncAgentModels(e){let n=Je(this,Aa,xSt).call(this,e.agentType);if(n.length===0)return{added:[],removed:[]};if(n.length===1){let s=n[0],a=await Je(this,Aa,YDe).call(this,s,e.wireModelIds,e.fallbackDisplayNames,e.fallbackDescriptions),{added:l,removed:c}=await Je(this,Aa,Fce).call(this,e.agentType,s.providerId,a,{autoEnrollModelIds:bSt});return{added:l.map(u=>u.configuredModelId),removed:c.map(u=>u.configuredModelId)}}let r=[],o=[],i=new Set(e.wireModelIds);for(let s of n){let a=[];for(let d of i)re(this,cx).getByWireId(s.providerId,d)&&a.push(d);let l=await Je(this,Aa,YDe).call(this,s,a,e.fallbackDisplayNames,e.fallbackDescriptions),{added:c,removed:u}=await Je(this,Aa,Fce).call(this,e.agentType,s.providerId,l,{autoEnrollModelIds:bSt});for(let d of c)r.push(d.configuredModelId);for(let d of u)o.push(d.configuredModelId)}return{added:r,removed:o}}};dk=new WeakMap,cx=new WeakMap,q8=new WeakMap,mj=new WeakMap,K8=new WeakMap,Aa=new WeakSet,_St=function(e,n){let r=re(this,dk).listByOrigin("agent").filter(o=>o.origin.kind==="agent"&&o.origin.agentType===e&&o.providerType===n);if(r.length>1)throw new Error(`[modelManagement] AgentSetupApi: ${r.length} providers found for (${e}, ${n}); the (agentType, providerType) idempotency invariant is violated`);return r[0]},xSt=function(e){return re(this,dk).listByOrigin("agent").filter(n=>n.origin.kind==="agent"&&n.origin.agentType===e)},SSt=async function(e,n,r,o){let i=await Je(this,Aa,XDe).call(this,e);return Je(this,Aa,CSt).call(this,n,i,r,o)},YDe=async function(e,n,r,o){let i=await Je(this,Aa,XDe).call(this,e.providerType);return n.map(s=>{let a=i.get(s)??re(this,cx).getByWireId(e.providerId,s)?.info??{id:s,displayName:s};return Je(this,Aa,JDe).call(this,a,s,r,o)})},CSt=function(e,n,r,o){return e.map(i=>{let s=n.get(i)??{id:i,displayName:i};return Je(this,Aa,JDe).call(this,s,i,r,o)})},JDe=function(e,n,r,o){let i=r?.[n],s=o?.[n];return i===void 0&&s===void 0?e:{...e,displayName:i??e.displayName,description:s??e.description}},XDe=async function(e){try{await re(this,mj).ensureLoaded()}catch(r){W("[modelManagement] AgentSetupApi: catalog ensureLoaded failed; falling back to wire-id metadata",r)}let n=new Map;for(let r of re(this,mj).getAllProviders())if(r.providerType===e)for(let[o,i]of Object.entries(r.models))n.has(o)||n.set(o,i);return n},Fce=async function(e,n,r,o){let i=re(this,cx).listByProvider(n),s=new Map(i.map(d=>[d.info.id,d])),a=new Set(r.map(d=>d.id)),l=o.autoEnrollModelIds?new Set(o.autoEnrollModelIds):null,c=[];for(let d of r){let f=s.get(d.id);if(!f){let p=await re(this,cx).add({providerId:n,info:d});(!l||l.has(d.id))&&await re(this,q8).enableModel(e,p),c.push({wireId:d.id,configuredModelId:p});continue}(f.info.displayName!==d.displayName||f.info.description!==d.description)&&await re(this,cx).update(f.configuredModelId,{info:{displayName:d.displayName,description:d.description}})}let u=[];for(let d of i)a.has(d.info.id)||(await re(this,K8).removeConfiguredModel(d.configuredModelId),u.push({wireId:d.info.id,configuredModelId:d.configuredModelId}));return{added:c,removed:u}}});var SP,CP,Z8,hj,KN,eFe,kSt,G8,tFe=b(()=>{W8();G8=class{constructor(e,n,r,o){Rt(this,KN);Rt(this,SP);Rt(this,CP);Rt(this,Z8);Rt(this,hj);Et(this,SP,e),Et(this,CP,n),Et(this,Z8,r),Et(this,hj,o)}async registerPlusProvider(e){let n=Je(this,KN,eFe).call(this),r;n?(r=n.providerId,await re(this,SP).update(r,{displayName:e.displayName,baseUrl:e.baseUrl})):r=await re(this,SP).add({providerType:e.providerType,displayName:e.displayName,baseUrl:e.baseUrl,origin:{kind:"copilot-plus"},requiresApiKey:!1}),e.apiKey!=null&&await re(this,SP).setApiKey(r,e.apiKey);let o=await Je(this,KN,kSt).call(this,r,e.models,e.autoEnrollIn??VN,e.autoEnrollModelIds);return{providerId:r,configuredModelIds:o}}async unregisterPlusProvider(){let e=Je(this,KN,eFe).call(this);e&&await re(this,hj).removeProvider(e.providerId)}};SP=new WeakMap,CP=new WeakMap,Z8=new WeakMap,hj=new WeakMap,KN=new WeakSet,eFe=function(){let e=re(this,SP).listByOrigin("copilot-plus");if(e.length>1)throw new Error(`[modelManagement] CopilotPlusSetupApi: ${e.length} copilot-plus providers found; the singleton invariant is violated`);return e[0]},kSt=async function(e,n,r,o){let i=re(this,CP).listByProvider(e),s=new Map(i.map(u=>[u.info.id,u])),a=new Set(n.map(u=>u.id)),l=o?new Set(o):null;for(let u of n){let d=s.get(u.id);if(!d){let f=await re(this,CP).add({providerId:e,info:u});if(!u.isEmbedding&&(!l||l.has(u.id)))for(let p of r)await re(this,Z8).enableModel(p,f);continue}(d.info.displayName!==u.displayName||d.info.description!==u.description||d.info.toolCall!==u.toolCall||d.info.reasoning!==u.reasoning||JSON.stringify(d.info.modalities)!==JSON.stringify(u.modalities))&&await re(this,CP).update(d.configuredModelId,{info:{displayName:u.displayName,description:u.description,toolCall:u.toolCall,reasoning:u.reasoning,modalities:u.modalities}})}for(let u of i)a.has(u.info.id)||await re(this,hj).removeConfiguredModel(u.configuredModelId);let c=[];for(let u of n){let d=re(this,CP).getByWireId(e,u.id);d&&c.push(d.configuredModelId)}return c}});function nFe(t,e){return t.isPaidUser!==e.isPaidUser||!!e.isPaidUser&&t.plusLicenseKey!==e.plusLicenseKey}async function rFe(t,e,n){try{e&&n?await t.setup.copilotPlus.registerPlusProvider({providerType:"openai-compatible",displayName:"Copilot",baseUrl:Jp,apiKey:n,models:gj,autoEnrollModelIds:Uce}):await t.setup.copilotPlus.unregisterPlusProvider()}catch(r){H("[modelManagement] Copilot Plus provider sync failed",r)}}var gj,Uce,ISt=b(()=>{gt();pe();gj=Object.freeze([{id:"copilot-plus-flash",displayName:"Copilot Plus Flash",description:"The default model: fastest responses and the most quota.",toolCall:!0,reasoning:!0,modalities:{input:["text","image"],output:["text"]}},{id:"kimi-k2.6",displayName:"Kimi K2.6",description:"Good for long-running reasoning tasks.",toolCall:!0,modalities:{input:["text"],output:["text"]}},{id:"glm-5.2",displayName:"GLM-5.2",description:"A long-horizon frontier open model that beats some of the best closed models.",toolCall:!0,reasoning:!0,modalities:{input:["text"],output:["text"]}},{id:"kimi-k2.7-code",displayName:"Kimi K2.7 Code",description:"Optimized for coding tasks.",toolCall:!0,reasoning:!0,modalities:{input:["text","image"],output:["text"]}},{id:"deepseek-v4-pro",displayName:"DeepSeek V4 Pro",description:"A top-tier model for the hardest reasoning and agentic tasks.",toolCall:!0,reasoning:!0,modalities:{input:["text"],output:["text"]}},{id:"deepseek-v4-flash-0731",displayName:"DeepSeek V4 Flash 0731",description:"The newest DeepSeek V4 Flash snapshot: fast, cheap, and broadly capable.",toolCall:!0,reasoning:!0,modalities:{input:["text"],output:["text"]}},{id:"mimo-v2.5",displayName:"MiMo V2.5",description:"Cost-effective and capable for everyday use.",toolCall:!0,reasoning:!0,modalities:{input:["text"],output:["text"]}},{id:"minimax-m2.7",displayName:"MiniMax M2.7",description:"A compact, efficient model for lightweight tasks.",toolCall:!0,reasoning:!0,modalities:{input:["text"],output:["text"]}}]),Uce=Object.freeze(["copilot-plus-flash","deepseek-v4-pro","glm-5.2"])});function oFe(t){let{app:e}=t,n=KDe(),r=new F9({app:e}),o=new j9(e,n),i=new q9,s=new G9(o,i),a=new J9(o,i,n),l=new jce(o,i,s),c={byok:new H8(o,i,s),agent:new V8(o,i,s,r,l),copilotPlus:new G8(o,i,s,l)};return{catalogService:r,providerRegistry:o,configuredModelRegistry:i,backendConfigRegistry:s,chatModelFactory:a,adapters:n,setup:c,coordinator:l,dispose:()=>{}}}var Y8,GN,yj,jce,TSt=b(()=>{RNe();INe();LNe();NNe();GDe();ENe();QDe();W8();tFe();jce=class{constructor(e,n,r){Rt(this,Y8);Rt(this,GN);Rt(this,yj);Et(this,Y8,e),Et(this,GN,n),Et(this,yj,r)}async removeProvider(e){let n=re(this,GN).listByProvider(e).map(r=>r.configuredModelId);await re(this,yj).removeRefs(n),await re(this,GN).removeByProvider(e),await re(this,Y8).remove(e)}async removeConfiguredModel(e){await re(this,yj).removeRefs([e]),await re(this,GN).remove(e)}};Y8=new WeakMap,GN=new WeakMap,yj=new WeakMap});function PSt(t,e){let n=null,r=new Map,o=new Set,i=a=>{let l;if(e===void 0)l=r.get(a);else for(let[u,d]of r)if(e(u,a)){l=d;break}if(l!==void 0)if(n?.(l[1],a))i.remove(a);else return l[0];let c=t(a);return r.set(a,[c,Date.now()]),s("CREATE",a,c),c};function s(a,l,c){for(let u of o)u({type:a,param:l,atom:c})}return i.unstable_listen=a=>(o.add(a),()=>{o.delete(a)}),i.getParams=()=>r.keys(),i.remove=a=>{if(e===void 0){if(!r.has(a))return;let[l]=r.get(a);r.delete(a),s("REMOVE",a,l)}else for(let[l,[c]]of r)if(e(l,a)){r.delete(l),s("REMOVE",l,c);break}},i.setShouldRemove=a=>{if(n=a,!!n)for(let[l,[c,u]]of r)n(u,l)&&(r.delete(l),s("REMOVE",l,c))},i}function J$n(t=()=>{try{return window.localStorage}catch(n){(Bce.env?Bce.env.MODE:void 0)!=="production"&&typeof window<"u"&&console.warn(n);return}},e){var n;let r,o,i={getItem:(l,c)=>{var u,d;let f=m=>{if(m=m||"",r!==m){try{o=JSON.parse(m,e?.reviver)}catch{return c}r=m}return o},p=(d=(u=t())==null?void 0:u.getItem(l))!=null?d:null;return Y$n(p)?p.then(f):f(p)},setItem:(l,c)=>{var u;return(u=t())==null?void 0:u.setItem(l,JSON.stringify(c,e?.replacer))},removeItem:l=>{var c;return(c=t())==null?void 0:c.removeItem(l)}},s=l=>(c,u,d)=>l(c,f=>{let p;try{p=JSON.parse(f||"")}catch{p=d}u(p)}),a;try{a=(n=t())==null?void 0:n.subscribe}catch{}return!a&&typeof window<"u"&&typeof window.addEventListener=="function"&&window.Storage&&(a=(l,c)=>{if(!(t()instanceof window.Storage))return()=>{};let u=d=>{d.storageArea===t()&&d.key===l&&c(d.newValue)};return window.addEventListener("storage",u),()=>{window.removeEventListener("storage",u)}}),a&&(i.subscribe=s(a)),i}var Bce,Keo,Y$n,Geo,ASt=b(()=>{Bce={},Keo=Symbol((Bce.env?Bce.env.MODE:void 0)!=="production"?"RESET":"");Y$n=t=>typeof t?.then=="function";Geo=J$n()});var ESt,MSt=b(()=>{"use client";ESt=L(B(),1)});var OSt=b(()=>{ASt();MSt()});function sFe(t,e){return Object.values(t).filter(n=>n.origin.kind===e)}var X$n,fk,ux,vj,iFe,zce,Q$n,aFe,eDn,tDn,ZN,Hce=b(()=>{Us();OSt();Se();H9();X$n=Object.freeze([]),fk=yo(t=>t(yh).providers),ux=yo(t=>t(yh).configuredModels),vj=yo(t=>t(yh).backends),iFe=yo(t=>t(yh).enableSelfHostMode);zce=yo(t=>sFe(t(fk),"byok")),Q$n=Object.freeze([]),aFe=yo(t=>{let e=t(zce),n=t(iFe);if(!n||e.length===0)return e.length===0?Q$n:e;let r=[],o=[];for(let i of e)(rx(i,{enableSelfHostMode:n})?o:r).push(i);return o.length===0?e:[...r,...o]}),eDn=yo(t=>sFe(t(fk),"agent")),tDn=yo(t=>sFe(t(fk),"copilot-plus")),ZN=PSt(t=>yo(e=>{let n=e(vj)[t]??{enabledModels:[]},r=e(ux),o=e(fk),i=e(iFe);return n.enabledModels.length===0?X$n:n.enabledModels.map(s=>{let a=r.find(c=>c.configuredModelId===s),l=a?o[a.providerId]:void 0;if(a&&l){let c=i&&rx(l,{enableSelfHostMode:i});return{configuredModelId:s,state:"ok",configuredModel:a,provider:l,needsSelfHostWarning:c}}return{configuredModelId:s,state:"broken"}})}))});function J8({api:t,children:e}){return wj.default.createElement(NSt.Provider,{value:t},e)}function Ey(){let t=(0,wj.useContext)(NSt);if(t===void 0)throw new Error("useModelManagement must be used inside <ModelManagementProvider>");return t}var wj,NSt,X8=b(()=>{wj=L(B()),NSt=(0,wj.createContext)(void 0)});function nDn({content:t,onConfirm:e,onCancel:n,confirmButtonText:r,cancelButtonText:o}){return YN.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-5"},YN.default.createElement("div",{className:"tw-whitespace-pre-wrap"},t),YN.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},o&&YN.default.createElement(oe,{variant:"secondary",onClick:n},o),r&&YN.default.createElement(oe,{variant:"default",onClick:e},r)))}var RSt,YN,_i,fm=b(()=>{yt();pe();Pa();RSt=require("obsidian"),YN=L(B());_i=class extends RSt.Modal{constructor(n,r,o,i,s="Continue",a="Cancel",l){super(n);this.onConfirm=r;this.content=o;this.confirmButtonText=s;this.cancelButtonText=a;this.onCancel=l;this.confirmed=!1;this.setTitle(i)}onOpen(){let{contentEl:n}=this;this.root=Er(n,this.app);let r=()=>{this.confirmed=!0;let i=this.onConfirm();i instanceof Promise&&i.catch(s=>H("ConfirmModal onConfirm failed",s)),this.close()},o=()=>{this.close()};this.root.render(YN.default.createElement(nDn,{content:this.content,onConfirm:r,onCancel:o,confirmButtonText:this.confirmButtonText,cancelButtonText:this.cancelButtonText}))}onClose(){if(!this.confirmed){let n=this.onCancel?.();n instanceof Promise&&n.catch(r=>H("ConfirmModal onCancel failed",r))}this.root.unmount()}}});var Wce,Ir,hl=b(()=>{Wce=L(B());De();Ir=Wce.forwardRef(({className:t,type:e,...n},r)=>Wce.createElement("input",{type:e,className:J("!tw-h-9 !tw-min-w-[50px] !tw-rounded-md !tw-border tw-border-solid tw-border-border !tw-bg-transparent !tw-px-3 !tw-py-1 !tw-text-sm !tw-transition-colors md:!tw-text-base","focus-visible:!tw-shadow-sm focus-visible:!tw-outline-none focus-visible:!tw-ring-1 focus-visible:!tw-ring-ring","placeholder:tw-text-sm","tw-flex tw-w-full tw-shadow-sm placeholder:tw-text-muted disabled:tw-cursor-not-allowed disabled:tw-opacity-50",t),ref:r,...n}));Ir.displayName="Input"});var bj,rf,pk=b(()=>{bj=L(B());hl();yt();De();Re();rf=({value:t,onChange:e,placeholder:n="Search...",inputClassName:r})=>bj.default.createElement("div",{className:"tw-relative"},bj.default.createElement(Ir,{type:"text",placeholder:n,value:t,onChange:o=>e(o.target.value),className:J("tw-pr-10",r)}),t&&bj.default.createElement(oe,{variant:"secondary",onClick:()=>e(""),className:"tw-absolute tw-right-8 tw-top-1/2 tw-size-4 -tw-translate-y-1/2 tw-transform tw-rounded-full tw-p-0 tw-transition-colors","aria-label":"Clear search"},bj.default.createElement(nm,{className:"tw-size-4 tw-text-muted/60 hover:tw-text-accent-hover"})),bj.default.createElement(Iw,{className:"tw-absolute tw-right-3 tw-top-1/2 tw-size-4 -tw-translate-y-1/2 tw-transform tw-text-muted"}))});var lFe,cFe,vto,LSt=b(()=>{lFe=[{id:"ollama",displayName:"Ollama",providerType:"openai-compatible",defaultBaseUrl:"http://localhost:11434/v1",requiresApiKey:!1,modelInputHint:"e.g. llama3.2, qwen2.5-coder:7b"},{id:"lmstudio",displayName:"LM Studio",providerType:"openai-compatible",defaultBaseUrl:"http://localhost:1234/v1",requiresApiKey:!1,modelInputHint:"e.g. lmstudio-community/Qwen2.5-7B-Instruct-GGUF"}],cFe={id:"custom-openai-compatible",displayName:"Custom OpenAI-compatible",providerType:"openai-compatible",requiresApiKey:!1,modelInputHint:"e.g. gpt-5.5"},vto=[...lFe,cFe,{id:"azure-openai",displayName:"Azure OpenAI",providerType:"azure",requiresApiKey:!0,modelInputHint:"matches your Azure deployment name"}]});var Vce,rDn,ei,pm=b(()=>{Vce=L(B());nse();De();rDn=$2("tw-inline-flex tw-items-center tw-rounded-md tw-px-2.5 tw-py-0.5 tw-text-ui-smaller tw-text-normal tw-transition-colors focus:tw-outline-none",{variants:{variant:{default:"tw-bg-primary-alt tw-shadow",secondary:"tw-bg-secondary-alt",destructive:"tw-bg-modifier-error tw-text-on-accent tw-shadow",outline:"tw-border tw-border-solid tw-border-border",success:"tw-bg-success",accent:"tw-bg-interactive-accent tw-text-on-accent"}},defaultVariants:{variant:"default"}}),ei=Vce.forwardRef(({className:t,variant:e,...n},r)=>Vce.createElement("div",{ref:r,className:J(rDn({variant:e}),t),...n}));ei.displayName="Badge"});function $St(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var DSt=b(()=>{});function USt(t,e=[]){let n=[];function r(i,s){let a=mk.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=mk.useMemo(()=>m,Object.values(m));return(0,FSt.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=mk.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>mk.createContext(s));return function(a){let l=a?.[t]||i;return mk.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,oDn(o,...e)]}function oDn(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return mk.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var mk,FSt,jSt=b(()=>{mk=L(B(),1),FSt=L(Mt(),1)});function uFe(t){let e=_j.useRef(t);return _j.useEffect(()=>{e.current=t}),_j.useMemo(()=>(...n)=>e.current?.(...n),[])}var _j,BSt=b(()=>{_j=L(B(),1)});function zSt({prop:t,defaultProp:e,onChange:n=()=>{}}){let[r,o]=iDn({defaultProp:e,onChange:n}),i=t!==void 0,s=i?t:r,a=uFe(n),l=kP.useCallback(c=>{if(i){let d=typeof c=="function"?c(t):c;d!==t&&a(d)}else o(c)},[i,t,o,a]);return[s,l]}function iDn({defaultProp:t,onChange:e}){let n=kP.useState(t),[r]=n,o=kP.useRef(r),i=uFe(e);return kP.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}var kP,HSt=b(()=>{kP=L(B(),1);BSt()});var WSt,JN,qce=b(()=>{WSt=L(B(),1),JN=globalThis?.document?WSt.useLayoutEffect:()=>{}});function VSt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function dFe(...t){return e=>{let n=!1,r=t.map(o=>{let i=VSt(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():VSt(t[o],null)}}}}function KSt(...t){return qSt.useCallback(dFe(...t),t)}var qSt,fFe=b(()=>{qSt=L(B(),1)});function aDn(t){return pd.isValidElement(t)&&t.type===sDn}function lDn(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{i(...a),o(...a)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function cDn(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var pd,xj,mFe,pFe,sDn,GSt=b(()=>{pd=L(B(),1);fFe();xj=L(Mt(),1),mFe=pd.forwardRef((t,e)=>{let{children:n,...r}=t,o=pd.Children.toArray(n),i=o.find(aDn);if(i){let s=i.props.children,a=o.map(l=>l===i?pd.Children.count(s)>1?pd.Children.only(null):pd.isValidElement(s)?s.props.children:null:l);return(0,xj.jsx)(pFe,{...r,ref:e,children:pd.isValidElement(s)?pd.cloneElement(s,void 0,a):null})}return(0,xj.jsx)(pFe,{...r,ref:e,children:n})});mFe.displayName="Slot";pFe=pd.forwardRef((t,e)=>{let{children:n,...r}=t;if(pd.isValidElement(n)){let o=cDn(n);return pd.cloneElement(n,{...lDn(r,n.props),ref:e?dFe(e,o):o})}return pd.Children.count(n)>1?pd.Children.only(null):null});pFe.displayName="SlotClone";sDn=({children:t})=>(0,xj.jsx)(xj.Fragment,{children:t})});var ZSt,uDn,YSt,dDn,Kce,JSt=b(()=>{ZSt=L(B(),1),uDn=L(Es(),1);GSt();YSt=L(Mt(),1),dDn=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Kce=dDn.reduce((t,e)=>{let n=ZSt.forwardRef((r,o)=>{let{asChild:i,...s}=r,a=i?mFe:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,YSt.jsx)(a,{...s,ref:o})});return n.displayName=`Primitive.${e}`,{...t,[e]:n}},{})});function XSt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function fDn(...t){return e=>{let n=!1,r=t.map(o=>{let i=XSt(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():XSt(t[o],null)}}}}function eCt(...t){return QSt.useCallback(fDn(...t),t)}var QSt,tCt=b(()=>{QSt=L(B(),1)});function pDn(t,e){return nCt.useReducer((n,r)=>e[n][r]??n,t)}function mDn(t){let[e,n]=mm.useState(),r=mm.useRef({}),o=mm.useRef(t),i=mm.useRef("none"),s=t?"mounted":"unmounted",[a,l]=pDn(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return mm.useEffect(()=>{let c=Gce(r.current);i.current=a==="mounted"?c:"none"},[a]),JN(()=>{let c=r.current,u=o.current;if(u!==t){let f=i.current,p=Gce(c);t?l("MOUNT"):p==="none"||c?.display==="none"?l("UNMOUNT"):l(u&&f!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,l]),JN(()=>{if(e){let c,u=e.ownerDocument.defaultView??window,d=p=>{let h=Gce(r.current).includes(p.animationName);if(p.target===e&&h&&(l("ANIMATION_END"),!o.current)){let g=e.style.animationFillMode;e.style.animationFillMode="forwards",c=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=g)})}},f=p=>{p.target===e&&(i.current=Gce(r.current))};return e.addEventListener("animationstart",f),e.addEventListener("animationcancel",d),e.addEventListener("animationend",d),()=>{u.clearTimeout(c),e.removeEventListener("animationstart",f),e.removeEventListener("animationcancel",d),e.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:mm.useCallback(c=>{c&&(r.current=getComputedStyle(c)),n(c)},[])}}function Gce(t){return t?.animationName||"none"}function hDn(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var mm,nCt,hFe,rCt=b(()=>{"use client";mm=L(B(),1);tCt();qce();nCt=L(B(),1);hFe=t=>{let{present:e,children:n}=t,r=mDn(e),o=typeof n=="function"?n({present:r.isPresent}):mm.Children.only(n),i=eCt(r.ref,hDn(o));return typeof n=="function"||r.isPresent?mm.cloneElement(o,{ref:i}):null};hFe.displayName="Presence"});function oCt(t){let[e,n]=Zce.useState(gDn());return JN(()=>{t||n(r=>r??String(yDn++))},[t]),t||(e?`radix-${e}`:"")}var Zce,gDn,yDn,iCt=b(()=>{Zce=L(B(),1);qce();gDn=Zce.useId||(()=>{}),yDn=0});function _Fe(t){return t?"open":"closed"}var md,XN,gFe,vDn,Gto,wDn,yFe,sCt,aCt,vFe,wFe,bFe,bDn,lCt,cCt=b(()=>{"use client";md=L(B(),1);DSt();jSt();HSt();qce();fFe();JSt();rCt();iCt();XN=L(Mt(),1),gFe="Collapsible",[vDn,Gto]=USt(gFe),[wDn,yFe]=vDn(gFe),sCt=md.forwardRef((t,e)=>{let{__scopeCollapsible:n,open:r,defaultOpen:o,disabled:i,onOpenChange:s,...a}=t,[l=!1,c]=zSt({prop:r,defaultProp:o,onChange:s});return(0,XN.jsx)(wDn,{scope:n,disabled:i,contentId:oCt(),open:l,onOpenToggle:md.useCallback(()=>c(u=>!u),[c]),children:(0,XN.jsx)(Kce.div,{"data-state":_Fe(l),"data-disabled":i?"":void 0,...a,ref:e})})});sCt.displayName=gFe;aCt="CollapsibleTrigger",vFe=md.forwardRef((t,e)=>{let{__scopeCollapsible:n,...r}=t,o=yFe(aCt,n);return(0,XN.jsx)(Kce.button,{type:"button","aria-controls":o.contentId,"aria-expanded":o.open||!1,"data-state":_Fe(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...r,ref:e,onClick:$St(t.onClick,o.onOpenToggle)})});vFe.displayName=aCt;wFe="CollapsibleContent",bFe=md.forwardRef((t,e)=>{let{forceMount:n,...r}=t,o=yFe(wFe,t.__scopeCollapsible);return(0,XN.jsx)(hFe,{present:n||o.open,children:({present:i})=>(0,XN.jsx)(bDn,{...r,ref:e,present:i})})});bFe.displayName=wFe;bDn=md.forwardRef((t,e)=>{let{__scopeCollapsible:n,present:r,children:o,...i}=t,s=yFe(wFe,n),[a,l]=md.useState(r),c=md.useRef(null),u=KSt(e,c),d=md.useRef(0),f=d.current,p=md.useRef(0),m=p.current,h=s.open||a,g=md.useRef(h),v=md.useRef(void 0);return md.useEffect(()=>{let y=requestAnimationFrame(()=>g.current=!1);return()=>cancelAnimationFrame(y)},[]),JN(()=>{let y=c.current;if(y){v.current=v.current||{transitionDuration:y.style.transitionDuration,animationName:y.style.animationName},y.style.transitionDuration="0s",y.style.animationName="none";let w=y.getBoundingClientRect();d.current=w.height,p.current=w.width,g.current||(y.style.transitionDuration=v.current.transitionDuration,y.style.animationName=v.current.animationName),l(r)}},[s.open,r]),(0,XN.jsx)(Kce.div,{"data-state":_Fe(s.open),"data-disabled":s.disabled?"":void 0,id:s.contentId,hidden:!h,...i,ref:u,style:{"--radix-collapsible-content-height":f?`${f}px`:void 0,"--radix-collapsible-content-width":m?`${m}px`:void 0,...t.style},children:h&&o})});lCt=sCt});var dx,fx,px,Sj=b(()=>{cCt();dx=lCt,fx=vFe,px=bFe});function Q8(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var Yto,uCt=b(()=>{Yto=!!(typeof window<"u"&&window.document&&window.document.createElement)});function dCt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Yce(...t){return e=>{let n=!1,r=t.map(o=>{let i=dCt(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():dCt(t[o],null)}}}}var xDn,xFe=b(()=>{xDn=L(B(),1)});function pCt(t,e=[]){let n=[];function r(i,s){let a=hk.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=hk.useMemo(()=>m,Object.values(m));return(0,fCt.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=hk.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>hk.createContext(s));return function(a){let l=a?.[t]||i;return hk.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,SDn(o,...e)]}function SDn(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return hk.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var hk,fCt,mCt=b(()=>{hk=L(B(),1),fCt=L(Mt(),1)});var hCt,Jce,SFe=b(()=>{hCt=L(B(),1),Jce=globalThis?.document?hCt.useLayoutEffect:()=>{}});function gCt({prop:t,defaultProp:e,onChange:n=()=>{},caller:r}){let[o,i,s]=kDn({defaultProp:e,onChange:n}),a=t!==void 0,l=a?t:o;{let u=My.useRef(t!==void 0);My.useEffect(()=>{let d=u.current;d!==a&&console.warn(`${r} is changing from ${d?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=a},[a,r])}let c=My.useCallback(u=>{if(a){let d=IDn(u)?u(t):u;d!==t&&s.current?.(d)}else i(u)},[a,t,i,s]);return[l,c]}function kDn({defaultProp:t,onChange:e}){let[n,r]=My.useState(t),o=My.useRef(n),i=My.useRef(e);return CDn(()=>{i.current=e},[e]),My.useEffect(()=>{o.current!==n&&(i.current?.(n),o.current=n)},[n,o]),[n,r,i]}function IDn(t){return typeof t=="function"}var My,Xce,CDn,nno,yCt=b(()=>{My=L(B(),1);SFe();Xce=L(B(),1),CDn=My[" useInsertionEffect ".trim().toString()]||Jce;nno=Symbol("RADIX:SYNC_STATE")});function vCt(t){let e=TDn(t),n=wc.forwardRef((r,o)=>{let{children:i,...s}=r,a=wc.Children.toArray(i),l=a.find(ADn);if(l){let c=l.props.children,u=a.map(d=>d===l?wc.Children.count(c)>1?wc.Children.only(null):wc.isValidElement(c)?c.props.children:null:d);return(0,Qce.jsx)(e,{...s,ref:o,children:wc.isValidElement(c)?wc.cloneElement(c,void 0,u):null})}return(0,Qce.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function TDn(t){let e=wc.forwardRef((n,r)=>{let{children:o,...i}=n;if(wc.isValidElement(o)){let s=MDn(o),a=EDn(i,o.props);return o.type!==wc.Fragment&&(a.ref=r?Yce(r,s):s),wc.cloneElement(o,a)}return wc.Children.count(o)>1?wc.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}function ADn(t){return wc.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===PDn}function EDn(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function MDn(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var wc,Qce,PDn,wCt=b(()=>{wc=L(B(),1);xFe();Qce=L(Mt(),1);PDn=Symbol("radix.slottable")});var bCt,ODn,_Ct,NDn,xCt,SCt=b(()=>{bCt=L(B(),1),ODn=L(Es(),1);wCt();_Ct=L(Mt(),1),NDn=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],xCt=NDn.reduce((t,e)=>{let n=vCt(`Primitive.${e}`),r=bCt.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,_Ct.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{})});function qa(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var lno,CCt=b(()=>{lno=!!(typeof window<"u"&&window.document&&window.document.createElement)});function ICt(t,e=[]){let n=[];function r(i,s){let a=gk.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=gk.useMemo(()=>m,Object.values(m));return(0,kCt.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=gk.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>gk.createContext(s));return function(a){let l=a?.[t]||i;return gk.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,RDn(o,...e)]}function RDn(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return gk.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var gk,kCt,TCt=b(()=>{gk=L(B(),1),kCt=L(Mt(),1)});function PCt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function CFe(...t){return e=>{let n=!1,r=t.map(o=>{let i=PCt(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():PCt(t[o],null)}}}}function kFe(...t){return ACt.useCallback(CFe(...t),t)}var ACt,IFe=b(()=>{ACt=L(B(),1)});function TFe(t){let e=LDn(t),n=bc.forwardRef((r,o)=>{let{children:i,...s}=r,a=bc.Children.toArray(i),l=a.find(DDn);if(l){let c=l.props.children,u=a.map(d=>d===l?bc.Children.count(c)>1?bc.Children.only(null):bc.isValidElement(c)?c.props.children:null:d);return(0,eue.jsx)(e,{...s,ref:o,children:bc.isValidElement(c)?bc.cloneElement(c,void 0,u):null})}return(0,eue.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function LDn(t){let e=bc.forwardRef((n,r)=>{let{children:o,...i}=n;if(bc.isValidElement(o)){let s=UDn(o),a=FDn(i,o.props);return o.type!==bc.Fragment&&(a.ref=r?CFe(r,s):s),bc.cloneElement(o,a)}return bc.Children.count(o)>1?bc.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}function DDn(t){return bc.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===$Dn}function FDn(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function UDn(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var bc,eue,$Dn,ECt=b(()=>{bc=L(B(),1);IFe();eue=L(Mt(),1);$Dn=Symbol("radix.slottable")});function Cj(t){let e=t+"CollectionProvider",[n,r]=ICt(e),[o,i]=n(e,{collectionRef:{current:null},itemMap:new Map}),s=h=>{let{scope:g,children:v}=h,y=IP.default.useRef(null),w=IP.default.useRef(new Map).current;return(0,tue.jsx)(o,{scope:g,itemMap:w,collectionRef:y,children:v})};s.displayName=e;let a=t+"CollectionSlot",l=TFe(a),c=IP.default.forwardRef((h,g)=>{let{scope:v,children:y}=h,w=i(a,v),_=kFe(g,w.collectionRef);return(0,tue.jsx)(l,{ref:_,children:y})});c.displayName=a;let u=t+"CollectionItemSlot",d="data-radix-collection-item",f=TFe(u),p=IP.default.forwardRef((h,g)=>{let{scope:v,children:y,...w}=h,_=IP.default.useRef(null),S=kFe(g,_),I=i(u,v);return IP.default.useEffect(()=>(I.itemMap.set(_,{ref:_,...w}),()=>void I.itemMap.delete(_))),(0,tue.jsx)(f,{[d]:"",ref:S,children:y})});p.displayName=u;function m(h){let g=i(t+"CollectionConsumer",h);return IP.default.useCallback(()=>{let y=g.collectionRef.current;if(!y)return[];let w=Array.from(y.querySelectorAll(`[${d}]`));return Array.from(g.itemMap.values()).sort((I,C)=>w.indexOf(I.ref.current)-w.indexOf(C.ref.current))},[g.collectionRef,g.itemMap])}return[{Provider:s,Slot:c,ItemSlot:p},m,r]}var IP,tue,jDn,BDn,nue=b(()=>{"use client";IP=L(B(),1);TCt();IFe();ECt();tue=L(Mt(),1),jDn=L(B(),1),BDn=L(Mt(),1)});function MCt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function eZ(...t){return e=>{let n=!1,r=t.map(o=>{let i=MCt(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():MCt(t[o],null)}}}}function TP(...t){return OCt.useCallback(eZ(...t),t)}var OCt,rue=b(()=>{OCt=L(B(),1)});function RCt(t,e=[]){let n=[];function r(i,s){let a=yk.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=yk.useMemo(()=>m,Object.values(m));return(0,NCt.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=yk.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>yk.createContext(s));return function(a){let l=a?.[t]||i;return yk.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,zDn(o,...e)]}function zDn(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return yk.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var yk,NCt,LCt=b(()=>{yk=L(B(),1),NCt=L(Mt(),1)});function $Ct(t){let e=oue.useContext(WDn);return t||e||"ltr"}var oue,HDn,WDn,DCt=b(()=>{oue=L(B(),1),HDn=L(Mt(),1),WDn=oue.createContext(void 0)});function iue(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var xno,FCt=b(()=>{xno=!!(typeof window<"u"&&window.document&&window.document.createElement)});function UCt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function PFe(...t){return e=>{let n=!1,r=t.map(o=>{let i=UCt(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():UCt(t[o],null)}}}}function AFe(...t){return jCt.useCallback(PFe(...t),t)}var jCt,EFe=b(()=>{jCt=L(B(),1)});function BCt(t){let e=VDn(t),n=_c.forwardRef((r,o)=>{let{children:i,...s}=r,a=_c.Children.toArray(i),l=a.find(KDn);if(l){let c=l.props.children,u=a.map(d=>d===l?_c.Children.count(c)>1?_c.Children.only(null):_c.isValidElement(c)?c.props.children:null:d);return(0,sue.jsx)(e,{...s,ref:o,children:_c.isValidElement(c)?_c.cloneElement(c,void 0,u):null})}return(0,sue.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function VDn(t){let e=_c.forwardRef((n,r)=>{let{children:o,...i}=n;if(_c.isValidElement(o)){let s=ZDn(o),a=GDn(i,o.props);return o.type!==_c.Fragment&&(a.ref=r?PFe(r,s):s),_c.cloneElement(o,a)}return _c.Children.count(o)>1?_c.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}function KDn(t){return _c.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===qDn}function GDn(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function ZDn(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var _c,sue,qDn,zCt=b(()=>{_c=L(B(),1);EFe();sue=L(Mt(),1);qDn=Symbol("radix.slottable")});function qCt(t,e){t&&WCt.flushSync(()=>t.dispatchEvent(e))}var HCt,WCt,VCt,YDn,MFe,KCt=b(()=>{HCt=L(B(),1),WCt=L(Es(),1);zCt();VCt=L(Mt(),1),YDn=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],MFe=YDn.reduce((t,e)=>{let n=BCt(`Primitive.${e}`),r=HCt.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,VCt.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{})});function OFe(t){let e=kj.useRef(t);return kj.useEffect(()=>{e.current=t}),kj.useMemo(()=>(...n)=>e.current?.(...n),[])}var kj,GCt=b(()=>{kj=L(B(),1)});function ZCt(t){let e=Ij.useRef(t);return Ij.useEffect(()=>{e.current=t}),Ij.useMemo(()=>(...n)=>e.current?.(...n),[])}var Ij,YCt=b(()=>{Ij=L(B(),1)});function XCt(t,e=globalThis?.document){let n=ZCt(t);JCt.useEffect(()=>{let r=o=>{o.key==="Escape"&&n(o)};return e.addEventListener("keydown",r,{capture:!0}),()=>e.removeEventListener("keydown",r,{capture:!0})},[n,e])}var JCt,QCt=b(()=>{JCt=L(B(),1);YCt()});function nFn(t,e=globalThis?.document){let n=OFe(t),r=Ea.useRef(!1),o=Ea.useRef(()=>{});return Ea.useEffect(()=>{let i=a=>{if(a.target&&!r.current){let c=function(){rkt(XDn,n,u,{discrete:!0})};var l=c;let u={originalEvent:a};a.pointerType==="touch"?(e.removeEventListener("click",o.current),o.current=c,e.addEventListener("click",o.current,{once:!0})):c()}else e.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{e.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),e.removeEventListener("pointerdown",i),e.removeEventListener("click",o.current)}},[e,n]),{onPointerDownCapture:()=>r.current=!0}}function rFn(t,e=globalThis?.document){let n=OFe(t),r=Ea.useRef(!1);return Ea.useEffect(()=>{let o=i=>{i.target&&!r.current&&rkt(QDn,n,{originalEvent:i},{discrete:!1})};return e.addEventListener("focusin",o),()=>e.removeEventListener("focusin",o)},[e,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function tkt(){let t=new CustomEvent(NFe);document.dispatchEvent(t)}function rkt(t,e,n,{discrete:r}){let o=n.originalEvent.target,i=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:n});e&&o.addEventListener(t,e,{once:!0}),r?qCt(o,i):o.dispatchEvent(i)}var Ea,RFe,JDn,NFe,XDn,QDn,ekt,nkt,QN,eFn,tFn,aue=b(()=>{"use client";Ea=L(B(),1);FCt();KCt();EFe();GCt();QCt();RFe=L(Mt(),1),JDn="DismissableLayer",NFe="dismissableLayer.update",XDn="dismissableLayer.pointerDownOutside",QDn="dismissableLayer.focusOutside",nkt=Ea.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),QN=Ea.forwardRef((t,e)=>{let{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:i,onInteractOutside:s,onDismiss:a,...l}=t,c=Ea.useContext(nkt),[u,d]=Ea.useState(null),f=u?.ownerDocument??globalThis?.document,[,p]=Ea.useState({}),m=AFe(e,C=>d(C)),h=Array.from(c.layers),[g]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),v=h.indexOf(g),y=u?h.indexOf(u):-1,w=c.layersWithOutsidePointerEventsDisabled.size>0,_=y>=v,S=nFn(C=>{let k=C.target,T=[...c.branches].some(P=>P.contains(k));!_||T||(o?.(C),s?.(C),C.defaultPrevented||a?.())},f),I=rFn(C=>{let k=C.target;[...c.branches].some(P=>P.contains(k))||(i?.(C),s?.(C),C.defaultPrevented||a?.())},f);return XCt(C=>{y===c.layers.size-1&&(r?.(C),!C.defaultPrevented&&a&&(C.preventDefault(),a()))},f),Ea.useEffect(()=>{if(u)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(ekt=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(u)),c.layers.add(u),tkt(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=ekt)}},[u,f,n,c]),Ea.useEffect(()=>()=>{u&&(c.layers.delete(u),c.layersWithOutsidePointerEventsDisabled.delete(u),tkt())},[u,c]),Ea.useEffect(()=>{let C=()=>p({});return document.addEventListener(NFe,C),()=>document.removeEventListener(NFe,C)},[]),(0,RFe.jsx)(MFe.div,{...l,ref:m,style:{pointerEvents:w?_?"auto":"none":void 0,...t.style},onFocusCapture:iue(t.onFocusCapture,I.onFocusCapture),onBlurCapture:iue(t.onBlurCapture,I.onBlurCapture),onPointerDownCapture:iue(t.onPointerDownCapture,S.onPointerDownCapture)})});QN.displayName=JDn;eFn="DismissableLayerBranch",tFn=Ea.forwardRef((t,e)=>{let n=Ea.useContext(nkt),r=Ea.useRef(null),o=AFe(e,r);return Ea.useEffect(()=>{let i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),(0,RFe.jsx)(MFe.div,{...t,ref:o})});tFn.displayName=eFn});function lue(){ikt.useEffect(()=>{let t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??okt()),document.body.insertAdjacentElement("beforeend",t[1]??okt()),LFe++,()=>{LFe===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),LFe--}},[])}function okt(){let t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}var ikt,LFe,$Fe=b(()=>{"use client";ikt=L(B(),1),LFe=0});function skt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function DFe(...t){return e=>{let n=!1,r=t.map(o=>{let i=skt(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():skt(t[o],null)}}}}function lkt(...t){return akt.useCallback(DFe(...t),t)}var akt,FFe=b(()=>{akt=L(B(),1)});function ckt(t){let e=oFn(t),n=xc.forwardRef((r,o)=>{let{children:i,...s}=r,a=xc.Children.toArray(i),l=a.find(sFn);if(l){let c=l.props.children,u=a.map(d=>d===l?xc.Children.count(c)>1?xc.Children.only(null):xc.isValidElement(c)?c.props.children:null:d);return(0,cue.jsx)(e,{...s,ref:o,children:xc.isValidElement(c)?xc.cloneElement(c,void 0,u):null})}return(0,cue.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function oFn(t){let e=xc.forwardRef((n,r)=>{let{children:o,...i}=n;if(xc.isValidElement(o)){let s=lFn(o),a=aFn(i,o.props);return o.type!==xc.Fragment&&(a.ref=r?DFe(r,s):s),xc.cloneElement(o,a)}return xc.Children.count(o)>1?xc.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}function sFn(t){return xc.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===iFn}function aFn(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function lFn(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var xc,cue,iFn,ukt=b(()=>{xc=L(B(),1);FFe();cue=L(Mt(),1);iFn=Symbol("radix.slottable")});var dkt,cFn,fkt,uFn,pkt,mkt=b(()=>{dkt=L(B(),1),cFn=L(Es(),1);ukt();fkt=L(Mt(),1),uFn=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],pkt=uFn.reduce((t,e)=>{let n=ckt(`Primitive.${e}`),r=dkt.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,fkt.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{})});function UFe(t){let e=Tj.useRef(t);return Tj.useEffect(()=>{e.current=t}),Tj.useMemo(()=>(...n)=>e.current?.(...n),[])}var Tj,hkt=b(()=>{Tj=L(B(),1)});function fFn(t,{select:e=!1}={}){let n=document.activeElement;for(let r of t)if(PP(r,{select:e}),document.activeElement!==n)return}function pFn(t){let e=_kt(t),n=ykt(e,t),r=ykt(e.reverse(),t);return[n,r]}function _kt(t){let e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{let o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)e.push(n.currentNode);return e}function ykt(t,e){for(let n of t)if(!mFn(n,{upTo:e}))return n}function mFn(t,{upTo:e}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(e!==void 0&&t===e)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}function hFn(t){return t instanceof HTMLInputElement&&"select"in t}function PP(t,{select:e=!1}={}){if(t&&t.focus){let n=document.activeElement;t.focus({preventScroll:!0}),t!==n&&hFn(t)&&e&&t.select()}}function gFn(){let t=[];return{add(e){let n=t[0];e!==n&&n?.pause(),t=wkt(t,e),t.unshift(e)},remove(e){t=wkt(t,e),t[0]?.resume()}}}function wkt(t,e){let n=[...t],r=n.indexOf(e);return r!==-1&&n.splice(r,1),n}function yFn(t){return t.filter(e=>e.tagName!=="A")}var Oy,bkt,jFe,BFe,gkt,dFn,tZ,vkt,zFe=b(()=>{"use client";Oy=L(B(),1);FFe();mkt();hkt();bkt=L(Mt(),1),jFe="focusScope.autoFocusOnMount",BFe="focusScope.autoFocusOnUnmount",gkt={bubbles:!1,cancelable:!0},dFn="FocusScope",tZ=Oy.forwardRef((t,e)=>{let{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=t,[a,l]=Oy.useState(null),c=UFe(o),u=UFe(i),d=Oy.useRef(null),f=lkt(e,h=>l(h)),p=Oy.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;Oy.useEffect(()=>{if(r){let y=function(I){if(p.paused||!a)return;let C=I.target;a.contains(C)?d.current=C:PP(d.current,{select:!0})},w=function(I){if(p.paused||!a)return;let C=I.relatedTarget;C!==null&&(a.contains(C)||PP(d.current,{select:!0}))},_=function(I){if(document.activeElement===document.body)for(let k of I)k.removedNodes.length>0&&PP(a)};var h=y,g=w,v=_;document.addEventListener("focusin",y),document.addEventListener("focusout",w);let S=new MutationObserver(_);return a&&S.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",y),document.removeEventListener("focusout",w),S.disconnect()}}},[r,a,p.paused]),Oy.useEffect(()=>{if(a){vkt.add(p);let h=document.activeElement;if(!a.contains(h)){let v=new CustomEvent(jFe,gkt);a.addEventListener(jFe,c),a.dispatchEvent(v),v.defaultPrevented||(fFn(yFn(_kt(a)),{select:!0}),document.activeElement===h&&PP(a))}return()=>{a.removeEventListener(jFe,c),setTimeout(()=>{let v=new CustomEvent(BFe,gkt);a.addEventListener(BFe,u),a.dispatchEvent(v),v.defaultPrevented||PP(h??document.body,{select:!0}),a.removeEventListener(BFe,u),vkt.remove(p)},0)}}},[a,c,u,p]);let m=Oy.useCallback(h=>{if(!n&&!r||p.paused)return;let g=h.key==="Tab"&&!h.altKey&&!h.ctrlKey&&!h.metaKey,v=document.activeElement;if(g&&v){let y=h.currentTarget,[w,_]=pFn(y);w&&_?!h.shiftKey&&v===_?(h.preventDefault(),n&&PP(w,{select:!0})):h.shiftKey&&v===w&&(h.preventDefault(),n&&PP(_,{select:!0})):v===y&&h.preventDefault()}},[n,r,p.paused]);return(0,bkt.jsx)(pkt.div,{tabIndex:-1,...s,ref:f,onKeyDown:m})});tZ.displayName=dFn;vkt=gFn()});var xkt,nZ,HFe=b(()=>{xkt=L(B(),1),nZ=globalThis?.document?xkt.useLayoutEffect:()=>{}});function VFe(t){let[e,n]=WFe.useState(vFn());return nZ(()=>{t||n(r=>r??String(wFn++))},[t]),t||(e?`radix-${e}`:"")}var WFe,vFn,wFn,Skt=b(()=>{WFe=L(B(),1);HFe();vFn=WFe[" useId ".trim().toString()]||(()=>{}),wFn=0});function due(t,e,n){return lp(t,mx(e,n))}function hx(t,e){return typeof t=="function"?t(e):t}function gx(t){return t.split("-")[0]}function eR(t){return t.split("-")[1]}function fue(t){return t==="x"?"y":"x"}function pue(t){return t==="y"?"height":"width"}function Hw(t){return xFn.has(gx(t))?"y":"x"}function mue(t){return fue(Hw(t))}function Tkt(t,e,n){n===void 0&&(n=!1);let r=eR(t),o=mue(t),i=pue(o),s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return e.reference[i]>e.floating[i]&&(s=rZ(s)),[s,rZ(s)]}function Pkt(t){let e=rZ(t);return[uue(t),e,uue(e)]}function uue(t){return t.replace(/start|end/g,e=>_Fn[e])}function kFn(t,e,n){switch(t){case"top":case"bottom":return n?e?kkt:Ckt:e?Ckt:kkt;case"left":case"right":return e?SFn:CFn;default:return[]}}function Akt(t,e,n,r){let o=eR(t),i=kFn(gx(t),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),e&&(i=i.concat(i.map(uue)))),i}function rZ(t){return t.replace(/left|right|bottom|top/g,e=>bFn[e])}function IFn(t){return{top:0,right:0,bottom:0,left:0,...t}}function qFe(t){return typeof t!="number"?IFn(t):{top:t,right:t,bottom:t,left:t}}function tR(t){let{x:e,y:n,width:r,height:o}=t;return{width:r,height:o,top:n,left:e,right:e+r,bottom:n+o,x:e,y:n}}var Ikt,mx,lp,oZ,iZ,zw,bFn,_Fn,xFn,Ckt,kkt,SFn,CFn,hue=b(()=>{Ikt=["top","right","bottom","left"],mx=Math.min,lp=Math.max,oZ=Math.round,iZ=Math.floor,zw=t=>({x:t,y:t}),bFn={left:"right",right:"left",bottom:"top",top:"bottom"},_Fn={start:"end",end:"start"};xFn=new Set(["top","bottom"]);Ckt=["left","right"],kkt=["right","left"],SFn=["top","bottom"],CFn=["bottom","top"]});function Ekt(t,e,n){let{reference:r,floating:o}=t,i=Hw(e),s=mue(e),a=pue(s),l=gx(e),c=i==="y",u=r.x+r.width/2-o.width/2,d=r.y+r.height/2-o.height/2,f=r[a]/2-o[a]/2,p;switch(l){case"top":p={x:u,y:r.y-o.height};break;case"bottom":p={x:u,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:d};break;case"left":p={x:r.x-o.width,y:d};break;default:p={x:r.x,y:r.y}}switch(eR(e)){case"start":p[s]-=f*(n&&c?-1:1);break;case"end":p[s]+=f*(n&&c?-1:1);break}return p}async function Pj(t,e){var n;e===void 0&&(e={});let{x:r,y:o,platform:i,rects:s,elements:a,strategy:l}=t,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:d="floating",altBoundary:f=!1,padding:p=0}=hx(e,t),m=qFe(p),g=a[f?d==="floating"?"reference":"floating":d],v=tR(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(g)))==null||n?g:g.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(a.floating)),boundary:c,rootBoundary:u,strategy:l})),y=d==="floating"?{x:r,y:o,width:s.floating.width,height:s.floating.height}:s.reference,w=await(i.getOffsetParent==null?void 0:i.getOffsetParent(a.floating)),_=await(i.isElement==null?void 0:i.isElement(w))?await(i.getScale==null?void 0:i.getScale(w))||{x:1,y:1}:{x:1,y:1},S=tR(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:y,offsetParent:w,strategy:l}):y);return{top:(v.top-S.top+m.top)/_.y,bottom:(S.bottom-v.bottom+m.bottom)/_.y,left:(v.left-S.left+m.left)/_.x,right:(S.right-v.right+m.right)/_.x}}function Mkt(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function Okt(t){return Ikt.some(e=>t[e]>=0)}async function TFn(t,e){let{placement:n,platform:r,elements:o}=t,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=gx(n),a=eR(n),l=Hw(n)==="y",c=Dkt.has(s)?-1:1,u=i&&l?-1:1,d=hx(e,t),{mainAxis:f,crossAxis:p,alignmentAxis:m}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return a&&typeof m=="number"&&(p=a==="end"?m*-1:m),l?{x:p*u,y:f*c}:{x:f*c,y:p*u}}var Nkt,Rkt,Lkt,$kt,Dkt,Fkt,Ukt,jkt,Bkt,zkt=b(()=>{hue();hue();Nkt=async(t,e,n)=>{let{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,a=i.filter(Boolean),l=await(s.isRTL==null?void 0:s.isRTL(e)),c=await s.getElementRects({reference:t,floating:e,strategy:o}),{x:u,y:d}=Ekt(c,r,l),f=r,p={},m=0;for(let h=0;h<a.length;h++){let{name:g,fn:v}=a[h],{x:y,y:w,data:_,reset:S}=await v({x:u,y:d,initialPlacement:r,placement:f,strategy:o,middlewareData:p,rects:c,platform:s,elements:{reference:t,floating:e}});u=y??u,d=w??d,p={...p,[g]:{...p[g],..._}},S&&m<=50&&(m++,typeof S=="object"&&(S.placement&&(f=S.placement),S.rects&&(c=S.rects===!0?await s.getElementRects({reference:t,floating:e,strategy:o}):S.rects),{x:u,y:d}=Ekt(c,f,l)),h=-1)}return{x:u,y:d,placement:f,strategy:o,middlewareData:p}};Rkt=t=>({name:"arrow",options:t,async fn(e){let{x:n,y:r,placement:o,rects:i,platform:s,elements:a,middlewareData:l}=e,{element:c,padding:u=0}=hx(t,e)||{};if(c==null)return{};let d=qFe(u),f={x:n,y:r},p=mue(o),m=pue(p),h=await s.getDimensions(c),g=p==="y",v=g?"top":"left",y=g?"bottom":"right",w=g?"clientHeight":"clientWidth",_=i.reference[m]+i.reference[p]-f[p]-i.floating[m],S=f[p]-i.reference[p],I=await(s.getOffsetParent==null?void 0:s.getOffsetParent(c)),C=I?I[w]:0;(!C||!await(s.isElement==null?void 0:s.isElement(I)))&&(C=a.floating[w]||i.floating[m]);let k=_/2-S/2,T=C/2-h[m]/2-1,P=mx(d[v],T),E=mx(d[y],T),O=P,$=C-h[m]-E,U=C/2-h[m]/2+k,V=due(O,U,$),K=!l.arrow&&eR(o)!=null&&U!==V&&i.reference[m]/2-(U<O?P:E)-h[m]/2<0,se=K?U<O?U-O:U-$:0;return{[p]:f[p]+se,data:{[p]:V,centerOffset:U-V-se,...K&&{alignmentOffset:se}},reset:K}}}),Lkt=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(e){var n,r;let{placement:o,middlewareData:i,rects:s,initialPlacement:a,platform:l,elements:c}=e,{mainAxis:u=!0,crossAxis:d=!0,fallbackPlacements:f,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:m="none",flipAlignment:h=!0,...g}=hx(t,e);if((n=i.arrow)!=null&&n.alignmentOffset)return{};let v=gx(o),y=Hw(a),w=gx(a)===a,_=await(l.isRTL==null?void 0:l.isRTL(c.floating)),S=f||(w||!h?[rZ(a)]:Pkt(a)),I=m!=="none";!f&&I&&S.push(...Akt(a,h,m,_));let C=[a,...S],k=await Pj(e,g),T=[],P=((r=i.flip)==null?void 0:r.overflows)||[];if(u&&T.push(k[v]),d){let U=Tkt(o,s,_);T.push(k[U[0]],k[U[1]])}if(P=[...P,{placement:o,overflows:T}],!T.every(U=>U<=0)){var E,O;let U=(((E=i.flip)==null?void 0:E.index)||0)+1,V=C[U];if(V&&(!(d==="alignment"?y!==Hw(V):!1)||P.every(le=>Hw(le.placement)===y?le.overflows[0]>0:!0)))return{data:{index:U,overflows:P},reset:{placement:V}};let K=(O=P.filter(se=>se.overflows[0]<=0).sort((se,le)=>se.overflows[1]-le.overflows[1])[0])==null?void 0:O.placement;if(!K)switch(p){case"bestFit":{var $;let se=($=P.filter(le=>{if(I){let Q=Hw(le.placement);return Q===y||Q==="y"}return!0}).map(le=>[le.placement,le.overflows.filter(Q=>Q>0).reduce((Q,ne)=>Q+ne,0)]).sort((le,Q)=>le[1]-Q[1])[0])==null?void 0:$[0];se&&(K=se);break}case"initialPlacement":K=a;break}if(o!==K)return{reset:{placement:K}}}return{}}}};$kt=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(e){let{rects:n}=e,{strategy:r="referenceHidden",...o}=hx(t,e);switch(r){case"referenceHidden":{let i=await Pj(e,{...o,elementContext:"reference"}),s=Mkt(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:Okt(s)}}}case"escaped":{let i=await Pj(e,{...o,altBoundary:!0}),s=Mkt(i,n.floating);return{data:{escapedOffsets:s,escaped:Okt(s)}}}default:return{}}}}},Dkt=new Set(["left","top"]);Fkt=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(e){var n,r;let{x:o,y:i,placement:s,middlewareData:a}=e,l=await TFn(e,t);return s===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:i+l.y,data:{...l,placement:s}}}}},Ukt=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(e){let{x:n,y:r,placement:o}=e,{mainAxis:i=!0,crossAxis:s=!1,limiter:a={fn:g=>{let{x:v,y}=g;return{x:v,y}}},...l}=hx(t,e),c={x:n,y:r},u=await Pj(e,l),d=Hw(gx(o)),f=fue(d),p=c[f],m=c[d];if(i){let g=f==="y"?"top":"left",v=f==="y"?"bottom":"right",y=p+u[g],w=p-u[v];p=due(y,p,w)}if(s){let g=d==="y"?"top":"left",v=d==="y"?"bottom":"right",y=m+u[g],w=m-u[v];m=due(y,m,w)}let h=a.fn({...e,[f]:p,[d]:m});return{...h,data:{x:h.x-n,y:h.y-r,enabled:{[f]:i,[d]:s}}}}}},jkt=function(t){return t===void 0&&(t={}),{options:t,fn(e){let{x:n,y:r,placement:o,rects:i,middlewareData:s}=e,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=hx(t,e),u={x:n,y:r},d=Hw(o),f=fue(d),p=u[f],m=u[d],h=hx(a,e),g=typeof h=="number"?{mainAxis:h,crossAxis:0}:{mainAxis:0,crossAxis:0,...h};if(l){let w=f==="y"?"height":"width",_=i.reference[f]-i.floating[w]+g.mainAxis,S=i.reference[f]+i.reference[w]-g.mainAxis;p<_?p=_:p>S&&(p=S)}if(c){var v,y;let w=f==="y"?"width":"height",_=Dkt.has(gx(o)),S=i.reference[d]-i.floating[w]+(_&&((v=s.offset)==null?void 0:v[d])||0)+(_?0:g.crossAxis),I=i.reference[d]+i.reference[w]+(_?0:((y=s.offset)==null?void 0:y[d])||0)-(_?g.crossAxis:0);m<S?m=S:m>I&&(m=I)}return{[f]:p,[d]:m}}}},Bkt=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(e){var n,r;let{placement:o,rects:i,platform:s,elements:a}=e,{apply:l=()=>{},...c}=hx(t,e),u=await Pj(e,c),d=gx(o),f=eR(o),p=Hw(o)==="y",{width:m,height:h}=i.floating,g,v;d==="top"||d==="bottom"?(g=d,v=f===(await(s.isRTL==null?void 0:s.isRTL(a.floating))?"start":"end")?"left":"right"):(v=d,g=f==="end"?"top":"bottom");let y=h-u.top-u.bottom,w=m-u.left-u.right,_=mx(h-u[g],y),S=mx(m-u[v],w),I=!e.middlewareData.shift,C=_,k=S;if((n=e.middlewareData.shift)!=null&&n.enabled.x&&(k=w),(r=e.middlewareData.shift)!=null&&r.enabled.y&&(C=y),I&&!f){let P=lp(u.left,0),E=lp(u.right,0),O=lp(u.top,0),$=lp(u.bottom,0);p?k=m-2*(P!==0||E!==0?P+E:lp(u.left,u.right)):C=h-2*(O!==0||$!==0?O+$:lp(u.top,u.bottom))}await l({...e,availableWidth:k,availableHeight:C});let T=await s.getDimensions(a.floating);return m!==T.width||h!==T.height?{reset:{rects:!0}}:{}}}}});function gue(){return typeof window<"u"}function rR(t){return Wkt(t)?(t.nodeName||"").toLowerCase():"#document"}function hm(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function Ww(t){var e;return(e=(Wkt(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function Wkt(t){return gue()?t instanceof Node||t instanceof hm(t).Node:!1}function Ny(t){return gue()?t instanceof Element||t instanceof hm(t).Element:!1}function Vw(t){return gue()?t instanceof HTMLElement||t instanceof hm(t).HTMLElement:!1}function Hkt(t){return!gue()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof hm(t).ShadowRoot}function Aj(t){let{overflow:e,overflowX:n,overflowY:r,display:o}=Ry(t);return/auto|scroll|overlay|hidden|clip/.test(e+r+n)&&!PFn.has(o)}function Vkt(t){return AFn.has(rR(t))}function sZ(t){return EFn.some(e=>{try{return t.matches(e)}catch{return!1}})}function yue(t){let e=vue(),n=Ny(t)?Ry(t):t;return MFn.some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!e&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!e&&(n.filter?n.filter!=="none":!1)||OFn.some(r=>(n.willChange||"").includes(r))||NFn.some(r=>(n.contain||"").includes(r))}function qkt(t){let e=vk(t);for(;Vw(e)&&!oR(e);){if(yue(e))return e;if(sZ(e))return null;e=vk(e)}return null}function vue(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function oR(t){return RFn.has(rR(t))}function Ry(t){return hm(t).getComputedStyle(t)}function aZ(t){return Ny(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function vk(t){if(rR(t)==="html")return t;let e=t.assignedSlot||t.parentNode||Hkt(t)&&t.host||Ww(t);return Hkt(e)?e.host:e}function Kkt(t){let e=vk(t);return oR(e)?t.ownerDocument?t.ownerDocument.body:t.body:Vw(e)&&Aj(e)?e:Kkt(e)}function nR(t,e,n){var r;e===void 0&&(e=[]),n===void 0&&(n=!0);let o=Kkt(t),i=o===((r=t.ownerDocument)==null?void 0:r.body),s=hm(o);if(i){let a=wue(s);return e.concat(s,s.visualViewport||[],Aj(o)?o:[],a&&n?nR(a):[])}return e.concat(o,nR(o,[],n))}function wue(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}var PFn,AFn,EFn,MFn,OFn,NFn,RFn,Gkt=b(()=>{PFn=new Set(["inline","contents"]);AFn=new Set(["table","td","th"]);EFn=[":popover-open",":modal"];MFn=["transform","translate","scale","rotate","perspective"],OFn=["transform","translate","scale","rotate","perspective","filter"],NFn=["paint","layout","strict","content"];RFn=new Set(["html","body","#document"])});function Xkt(t){let e=Ry(t),n=parseFloat(e.width)||0,r=parseFloat(e.height)||0,o=Vw(t),i=o?t.offsetWidth:n,s=o?t.offsetHeight:r,a=oZ(n)!==i||oZ(r)!==s;return a&&(n=i,r=s),{width:n,height:r,$:a}}function GFe(t){return Ny(t)?t:t.contextElement}function Ej(t){let e=GFe(t);if(!Vw(e))return zw(1);let n=e.getBoundingClientRect(),{width:r,height:o,$:i}=Xkt(e),s=(i?oZ(n.width):n.width)/r,a=(i?oZ(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!a||!Number.isFinite(a))&&(a=1),{x:s,y:a}}function Qkt(t){let e=hm(t);return!vue()||!e.visualViewport?LFn:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function $Fn(t,e,n){return e===void 0&&(e=!1),!n||e&&n!==hm(t)?!1:e}function iR(t,e,n,r){e===void 0&&(e=!1),n===void 0&&(n=!1);let o=t.getBoundingClientRect(),i=GFe(t),s=zw(1);e&&(r?Ny(r)&&(s=Ej(r)):s=Ej(t));let a=$Fn(i,n,r)?Qkt(i):zw(0),l=(o.left+a.x)/s.x,c=(o.top+a.y)/s.y,u=o.width/s.x,d=o.height/s.y;if(i){let f=hm(i),p=r&&Ny(r)?hm(r):r,m=f,h=wue(m);for(;h&&r&&p!==m;){let g=Ej(h),v=h.getBoundingClientRect(),y=Ry(h),w=v.left+(h.clientLeft+parseFloat(y.paddingLeft))*g.x,_=v.top+(h.clientTop+parseFloat(y.paddingTop))*g.y;l*=g.x,c*=g.y,u*=g.x,d*=g.y,l+=w,c+=_,m=hm(h),h=wue(m)}}return tR({width:u,height:d,x:l,y:c})}function bue(t,e){let n=aZ(t).scrollLeft;return e?e.left+n:iR(Ww(t)).left+n}function eIt(t,e){let n=t.getBoundingClientRect(),r=n.left+e.scrollLeft-bue(t,n),o=n.top+e.scrollTop;return{x:r,y:o}}function DFn(t){let{elements:e,rect:n,offsetParent:r,strategy:o}=t,i=o==="fixed",s=Ww(r),a=e?sZ(e.floating):!1;if(r===s||a&&i)return n;let l={scrollLeft:0,scrollTop:0},c=zw(1),u=zw(0),d=Vw(r);if((d||!d&&!i)&&((rR(r)!=="body"||Aj(s))&&(l=aZ(r)),Vw(r))){let p=iR(r);c=Ej(r),u.x=p.x+r.clientLeft,u.y=p.y+r.clientTop}let f=s&&!d&&!i?eIt(s,l):zw(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+u.x+f.x,y:n.y*c.y-l.scrollTop*c.y+u.y+f.y}}function FFn(t){return Array.from(t.getClientRects())}function UFn(t){let e=Ww(t),n=aZ(t),r=t.ownerDocument.body,o=lp(e.scrollWidth,e.clientWidth,r.scrollWidth,r.clientWidth),i=lp(e.scrollHeight,e.clientHeight,r.scrollHeight,r.clientHeight),s=-n.scrollLeft+bue(t),a=-n.scrollTop;return Ry(r).direction==="rtl"&&(s+=lp(e.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:a}}function jFn(t,e){let n=hm(t),r=Ww(t),o=n.visualViewport,i=r.clientWidth,s=r.clientHeight,a=0,l=0;if(o){i=o.width,s=o.height;let u=vue();(!u||u&&e==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}let c=bue(r);if(c<=0){let u=r.ownerDocument,d=u.body,f=getComputedStyle(d),p=u.compatMode==="CSS1Compat"&&parseFloat(f.marginLeft)+parseFloat(f.marginRight)||0,m=Math.abs(r.clientWidth-d.clientWidth-p);m<=Zkt&&(i-=m)}else c<=Zkt&&(i+=c);return{width:i,height:s,x:a,y:l}}function zFn(t,e){let n=iR(t,!0,e==="fixed"),r=n.top+t.clientTop,o=n.left+t.clientLeft,i=Vw(t)?Ej(t):zw(1),s=t.clientWidth*i.x,a=t.clientHeight*i.y,l=o*i.x,c=r*i.y;return{width:s,height:a,x:l,y:c}}function Ykt(t,e,n){let r;if(e==="viewport")r=jFn(t,n);else if(e==="document")r=UFn(Ww(t));else if(Ny(e))r=zFn(e,n);else{let o=Qkt(t);r={x:e.x-o.x,y:e.y-o.y,width:e.width,height:e.height}}return tR(r)}function tIt(t,e){let n=vk(t);return n===e||!Ny(n)||oR(n)?!1:Ry(n).position==="fixed"||tIt(n,e)}function HFn(t,e){let n=e.get(t);if(n)return n;let r=nR(t,[],!1).filter(a=>Ny(a)&&rR(a)!=="body"),o=null,i=Ry(t).position==="fixed",s=i?vk(t):t;for(;Ny(s)&&!oR(s);){let a=Ry(s),l=yue(s);!l&&a.position==="fixed"&&(o=null),(i?!l&&!o:!l&&a.position==="static"&&!!o&&BFn.has(o.position)||Aj(s)&&!l&&tIt(t,s))?r=r.filter(u=>u!==s):o=a,s=vk(s)}return e.set(t,r),r}function WFn(t){let{element:e,boundary:n,rootBoundary:r,strategy:o}=t,s=[...n==="clippingAncestors"?sZ(e)?[]:HFn(e,this._c):[].concat(n),r],a=s[0],l=s.reduce((c,u)=>{let d=Ykt(e,u,o);return c.top=lp(d.top,c.top),c.right=mx(d.right,c.right),c.bottom=mx(d.bottom,c.bottom),c.left=lp(d.left,c.left),c},Ykt(e,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function VFn(t){let{width:e,height:n}=Xkt(t);return{width:e,height:n}}function qFn(t,e,n){let r=Vw(e),o=Ww(e),i=n==="fixed",s=iR(t,!0,i,e),a={scrollLeft:0,scrollTop:0},l=zw(0);function c(){l.x=bue(o)}if(r||!r&&!i)if((rR(e)!=="body"||Aj(o))&&(a=aZ(e)),r){let p=iR(e,!0,i,e);l.x=p.x+e.clientLeft,l.y=p.y+e.clientTop}else o&&c();i&&!r&&o&&c();let u=o&&!r&&!i?eIt(o,a):zw(0),d=s.left+a.scrollLeft-l.x-u.x,f=s.top+a.scrollTop-l.y-u.y;return{x:d,y:f,width:s.width,height:s.height}}function KFe(t){return Ry(t).position==="static"}function Jkt(t,e){if(!Vw(t)||Ry(t).position==="fixed")return null;if(e)return e(t);let n=t.offsetParent;return Ww(t)===n&&(n=n.ownerDocument.body),n}function nIt(t,e){let n=hm(t);if(sZ(t))return n;if(!Vw(t)){let o=vk(t);for(;o&&!oR(o);){if(Ny(o)&&!KFe(o))return o;o=vk(o)}return n}let r=Jkt(t,e);for(;r&&Vkt(r)&&KFe(r);)r=Jkt(r,e);return r&&oR(r)&&KFe(r)&&!yue(r)?n:r||qkt(t)||n}function GFn(t){return Ry(t).direction==="rtl"}function oIt(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}function ZFn(t,e){let n=null,r,o=Ww(t);function i(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function s(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),i();let c=t.getBoundingClientRect(),{left:u,top:d,width:f,height:p}=c;if(a||e(),!f||!p)return;let m=iZ(d),h=iZ(o.clientWidth-(u+f)),g=iZ(o.clientHeight-(d+p)),v=iZ(u),w={rootMargin:-m+"px "+-h+"px "+-g+"px "+-v+"px",threshold:lp(0,mx(1,l))||1},_=!0;function S(I){let C=I[0].intersectionRatio;if(C!==l){if(!_)return s();C?s(!1,C):r=setTimeout(()=>{s(!1,1e-7)},1e3)}C===1&&!oIt(c,t.getBoundingClientRect())&&s(),_=!1}try{n=new IntersectionObserver(S,{...w,root:o.ownerDocument})}catch{n=new IntersectionObserver(S,w)}n.observe(t)}return s(!0),i}function ZFe(t,e,n,r){r===void 0&&(r={});let{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,c=GFe(t),u=o||i?[...c?nR(c):[],...nR(e)]:[];u.forEach(v=>{o&&v.addEventListener("scroll",n,{passive:!0}),i&&v.addEventListener("resize",n)});let d=c&&a?ZFn(c,n):null,f=-1,p=null;s&&(p=new ResizeObserver(v=>{let[y]=v;y&&y.target===c&&p&&(p.unobserve(e),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var w;(w=p)==null||w.observe(e)})),n()}),c&&!l&&p.observe(c),p.observe(e));let m,h=l?iR(t):null;l&&g();function g(){let v=iR(t);h&&!oIt(h,v)&&n(),h=v,m=requestAnimationFrame(g)}return n(),()=>{var v;u.forEach(y=>{o&&y.removeEventListener("scroll",n),i&&y.removeEventListener("resize",n)}),d?.(),(v=p)==null||v.disconnect(),p=null,l&&cancelAnimationFrame(m)}}var LFn,Zkt,BFn,KFn,rIt,iIt,sIt,aIt,lIt,cIt,YFe,uIt,JFe,XFe=b(()=>{zkt();hue();Gkt();LFn=zw(0);Zkt=25;BFn=new Set(["absolute","fixed"]);KFn=async function(t){let e=this.getOffsetParent||nIt,n=this.getDimensions,r=await n(t.floating);return{reference:qFn(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};rIt={convertOffsetParentRelativeRectToViewportRelativeRect:DFn,getDocumentElement:Ww,getClippingRect:WFn,getOffsetParent:nIt,getElementRects:KFn,getClientRects:FFn,getDimensions:VFn,getScale:Ej,isElement:Ny,isRTL:GFn};iIt=Fkt,sIt=Ukt,aIt=Lkt,lIt=Bkt,cIt=$kt,YFe=Rkt,uIt=jkt,JFe=(t,e,n)=>{let r=new Map,o={platform:rIt,...n},i={...o.platform,_c:r};return Nkt(t,e,{...o,platform:i})}});function xue(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(typeof t=="function"&&t.toString()===e.toString())return!0;let n,r,o;if(t&&e&&typeof t=="object"){if(Array.isArray(t)){if(n=t.length,n!==e.length)return!1;for(r=n;r--!==0;)if(!xue(t[r],e[r]))return!1;return!0}if(o=Object.keys(t),n=o.length,n!==Object.keys(e).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(e,o[r]))return!1;for(r=n;r--!==0;){let i=o[r];if(!(i==="_owner"&&t.$$typeof)&&!xue(t[i],e[i]))return!1}return!0}return t!==t&&e!==e}function mIt(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function dIt(t,e){let n=mIt(t);return Math.round(e*n)/n}function QFe(t){let e=Bl.useRef(t);return _ue(()=>{e.current=t}),e}function hIt(t){t===void 0&&(t={});let{placement:e="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:a=!0,whileElementsMounted:l,open:c}=t,[u,d]=Bl.useState({x:0,y:0,strategy:n,placement:e,middlewareData:{},isPositioned:!1}),[f,p]=Bl.useState(r);xue(f,r)||p(r);let[m,h]=Bl.useState(null),[g,v]=Bl.useState(null),y=Bl.useCallback(le=>{le!==I.current&&(I.current=le,h(le))},[]),w=Bl.useCallback(le=>{le!==C.current&&(C.current=le,v(le))},[]),_=i||m,S=s||g,I=Bl.useRef(null),C=Bl.useRef(null),k=Bl.useRef(u),T=l!=null,P=QFe(l),E=QFe(o),O=QFe(c),$=Bl.useCallback(()=>{if(!I.current||!C.current)return;let le={placement:e,strategy:n,middleware:f};E.current&&(le.platform=E.current),JFe(I.current,C.current,le).then(Q=>{let ne={...Q,isPositioned:O.current!==!1};U.current&&!xue(k.current,ne)&&(k.current=ne,pIt.flushSync(()=>{d(ne)}))})},[f,e,n,E,O]);_ue(()=>{c===!1&&k.current.isPositioned&&(k.current.isPositioned=!1,d(le=>({...le,isPositioned:!1})))},[c]);let U=Bl.useRef(!1);_ue(()=>(U.current=!0,()=>{U.current=!1}),[]),_ue(()=>{if(_&&(I.current=_),S&&(C.current=S),_&&S){if(P.current)return P.current(_,S,$);$()}},[_,S,$,P,T]);let V=Bl.useMemo(()=>({reference:I,floating:C,setReference:y,setFloating:w}),[y,w]),K=Bl.useMemo(()=>({reference:_,floating:S}),[_,S]),se=Bl.useMemo(()=>{let le={position:n,left:0,top:0};if(!K.floating)return le;let Q=dIt(K.floating,u.x),ne=dIt(K.floating,u.y);return a?{...le,transform:"translate("+Q+"px, "+ne+"px)",...mIt(K.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:Q,top:ne}},[n,a,K.floating,u.x,u.y]);return Bl.useMemo(()=>({...u,update:$,refs:V,elements:K,floatingStyles:se}),[u,$,V,K,se])}var Bl,fIt,pIt,YFn,JFn,_ue,XFn,gIt,yIt,vIt,wIt,bIt,_It,xIt,SIt=b(()=>{XFe();XFe();Bl=L(B(),1),fIt=L(B(),1),pIt=L(Es(),1),YFn=typeof document<"u",JFn=function(){},_ue=YFn?fIt.useLayoutEffect:JFn;XFn=t=>{function e(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:t,fn(n){let{element:r,padding:o}=typeof t=="function"?t(n):t;return r&&e(r)?r.current!=null?YFe({element:r.current,padding:o}).fn(n):{}:r?YFe({element:r,padding:o}).fn(n):{}}}},gIt=(t,e)=>({...iIt(t),options:[t,e]}),yIt=(t,e)=>({...sIt(t),options:[t,e]}),vIt=(t,e)=>({...uIt(t),options:[t,e]}),wIt=(t,e)=>({...aIt(t),options:[t,e]}),bIt=(t,e)=>({...lIt(t),options:[t,e]}),_It=(t,e)=>({...cIt(t),options:[t,e]}),xIt=(t,e)=>({...XFn(t),options:[t,e]})});function CIt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function kIt(...t){return e=>{let n=!1,r=t.map(o=>{let i=CIt(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():CIt(t[o],null)}}}}var QFn,IIt=b(()=>{QFn=L(B(),1)});function TIt(t){let e=e2n(t),n=Sc.forwardRef((r,o)=>{let{children:i,...s}=r,a=Sc.Children.toArray(i),l=a.find(n2n);if(l){let c=l.props.children,u=a.map(d=>d===l?Sc.Children.count(c)>1?Sc.Children.only(null):Sc.isValidElement(c)?c.props.children:null:d);return(0,Sue.jsx)(e,{...s,ref:o,children:Sc.isValidElement(c)?Sc.cloneElement(c,void 0,u):null})}return(0,Sue.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function e2n(t){let e=Sc.forwardRef((n,r)=>{let{children:o,...i}=n;if(Sc.isValidElement(o)){let s=o2n(o),a=r2n(i,o.props);return o.type!==Sc.Fragment&&(a.ref=r?kIt(r,s):s),Sc.cloneElement(o,a)}return Sc.Children.count(o)>1?Sc.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}function n2n(t){return Sc.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===t2n}function r2n(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function o2n(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Sc,Sue,t2n,PIt=b(()=>{Sc=L(B(),1);IIt();Sue=L(Mt(),1);t2n=Symbol("radix.slottable")});var AIt,i2n,EIt,s2n,MIt,OIt=b(()=>{AIt=L(B(),1),i2n=L(Es(),1);PIt();EIt=L(Mt(),1),s2n=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],MIt=s2n.reduce((t,e)=>{let n=TIt(`Primitive.${e}`),r=AIt.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,EIt.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{})});var NIt,e2e,a2n,RIt,LIt,$It=b(()=>{NIt=L(B(),1);OIt();e2e=L(Mt(),1),a2n="Arrow",RIt=NIt.forwardRef((t,e)=>{let{children:n,width:r=10,height:o=5,...i}=t;return(0,e2e.jsx)(MIt.svg,{...i,ref:e,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?n:(0,e2e.jsx)("polygon",{points:"0,0 30,0 15,10"})})});RIt.displayName=a2n;LIt=RIt});function DIt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function t2e(...t){return e=>{let n=!1,r=t.map(o=>{let i=DIt(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():DIt(t[o],null)}}}}function n2e(...t){return FIt.useCallback(t2e(...t),t)}var FIt,r2e=b(()=>{FIt=L(B(),1)});function jIt(t,e=[]){let n=[];function r(i,s){let a=wk.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=wk.useMemo(()=>m,Object.values(m));return(0,UIt.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=wk.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>wk.createContext(s));return function(a){let l=a?.[t]||i;return wk.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,c2n(o,...e)]}function c2n(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return wk.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var wk,UIt,BIt=b(()=>{wk=L(B(),1),UIt=L(Mt(),1)});function zIt(t){let e=u2n(t),n=Cc.forwardRef((r,o)=>{let{children:i,...s}=r,a=Cc.Children.toArray(i),l=a.find(f2n);if(l){let c=l.props.children,u=a.map(d=>d===l?Cc.Children.count(c)>1?Cc.Children.only(null):Cc.isValidElement(c)?c.props.children:null:d);return(0,Cue.jsx)(e,{...s,ref:o,children:Cc.isValidElement(c)?Cc.cloneElement(c,void 0,u):null})}return(0,Cue.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function u2n(t){let e=Cc.forwardRef((n,r)=>{let{children:o,...i}=n;if(Cc.isValidElement(o)){let s=m2n(o),a=p2n(i,o.props);return o.type!==Cc.Fragment&&(a.ref=r?t2e(r,s):s),Cc.cloneElement(o,a)}return Cc.Children.count(o)>1?Cc.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}function f2n(t){return Cc.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===d2n}function p2n(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function m2n(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Cc,Cue,d2n,HIt=b(()=>{Cc=L(B(),1);r2e();Cue=L(Mt(),1);d2n=Symbol("radix.slottable")});var WIt,h2n,VIt,g2n,o2e,qIt=b(()=>{WIt=L(B(),1),h2n=L(Es(),1);HIt();VIt=L(Mt(),1),g2n=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],o2e=g2n.reduce((t,e)=>{let n=zIt(`Primitive.${e}`),r=WIt.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,VIt.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{})});function KIt(t){let e=Mj.useRef(t);return Mj.useEffect(()=>{e.current=t}),Mj.useMemo(()=>(...n)=>e.current?.(...n),[])}var Mj,GIt=b(()=>{Mj=L(B(),1)});var ZIt,lZ,i2e=b(()=>{ZIt=L(B(),1),lZ=globalThis?.document?ZIt.useLayoutEffect:()=>{}});function JIt(t){let[e,n]=YIt.useState(void 0);return lZ(()=>{if(t){n({width:t.offsetWidth,height:t.offsetHeight});let r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;let i=o[0],s,a;if("borderBoxSize"in i){let l=i.borderBoxSize,c=Array.isArray(l)?l[0]:l;s=c.inlineSize,a=c.blockSize}else s=t.offsetWidth,a=t.offsetHeight;n({width:s,height:a})});return r.observe(t,{box:"border-box"}),()=>r.unobserve(t)}else n(void 0)},[t]),e}var YIt,XIt=b(()=>{YIt=L(B(),1);i2e()});function _2n(t){return t!==null}function a0t(t){let[e,n="center"]=t.split("-");return[e,n]}var gm,AP,s2e,QIt,bk,y2n,e0t,t0t,n0t,r0t,a2e,v2n,w2n,o0t,i0t,b2n,s0t,x2n,sR,aR,Oj,Nj,lR=b(()=>{"use client";gm=L(B(),1);SIt();$It();r2e();BIt();qIt();GIt();i2e();XIt();AP=L(Mt(),1),s2e="Popper",[QIt,bk]=jIt(s2e),[y2n,e0t]=QIt(s2e),t0t=t=>{let{__scopePopper:e,children:n}=t,[r,o]=gm.useState(null);return(0,AP.jsx)(y2n,{scope:e,anchor:r,onAnchorChange:o,children:n})};t0t.displayName=s2e;n0t="PopperAnchor",r0t=gm.forwardRef((t,e)=>{let{__scopePopper:n,virtualRef:r,...o}=t,i=e0t(n0t,n),s=gm.useRef(null),a=n2e(e,s),l=gm.useRef(null);return gm.useEffect(()=>{let c=l.current;l.current=r?.current||s.current,c!==l.current&&i.onAnchorChange(l.current)}),r?null:(0,AP.jsx)(o2e.div,{...o,ref:a})});r0t.displayName=n0t;a2e="PopperContent",[v2n,w2n]=QIt(a2e),o0t=gm.forwardRef((t,e)=>{let{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:i="center",alignOffset:s=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:u=0,sticky:d="partial",hideWhenDetached:f=!1,updatePositionStrategy:p="optimized",onPlaced:m,...h}=t,g=e0t(a2e,n),[v,y]=gm.useState(null),w=n2e(e,R=>y(R)),[_,S]=gm.useState(null),I=JIt(_),C=I?.width??0,k=I?.height??0,T=r+(i!=="center"?"-"+i:""),P=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},E=Array.isArray(c)?c:[c],O=E.length>0,$={padding:P,boundary:E.filter(_2n),altBoundary:O},{refs:U,floatingStyles:V,placement:K,isPositioned:se,middlewareData:le}=hIt({strategy:"fixed",placement:T,whileElementsMounted:(...R)=>ZFe(...R,{animationFrame:p==="always"}),elements:{reference:g.anchor},middleware:[gIt({mainAxis:o+k,alignmentAxis:s}),l&&yIt({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?vIt():void 0,...$}),l&&wIt({...$}),bIt({...$,apply:({elements:R,rects:X,availableWidth:D,availableHeight:G})=>{let{width:ce,height:Z}=X.reference,te=R.floating.style;te.setProperty("--radix-popper-available-width",`${D}px`),te.setProperty("--radix-popper-available-height",`${G}px`),te.setProperty("--radix-popper-anchor-width",`${ce}px`),te.setProperty("--radix-popper-anchor-height",`${Z}px`)}}),_&&xIt({element:_,padding:a}),x2n({arrowWidth:C,arrowHeight:k}),f&&_It({strategy:"referenceHidden",...$})]}),[Q,ne]=a0t(K),ee=KIt(m);lZ(()=>{se&&ee?.()},[se,ee]);let ae=le.arrow?.x,q=le.arrow?.y,F=le.arrow?.centerOffset!==0,[z,N]=gm.useState();return lZ(()=>{v&&N(window.getComputedStyle(v).zIndex)},[v]),(0,AP.jsx)("div",{ref:U.setFloating,"data-radix-popper-content-wrapper":"",style:{...V,transform:se?V.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:z,"--radix-popper-transform-origin":[le.transformOrigin?.x,le.transformOrigin?.y].join(" "),...le.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:(0,AP.jsx)(v2n,{scope:n,placedSide:Q,onArrowChange:S,arrowX:ae,arrowY:q,shouldHideArrow:F,children:(0,AP.jsx)(o2e.div,{"data-side":Q,"data-align":ne,...h,ref:w,style:{...h.style,animation:se?void 0:"none"}})})})});o0t.displayName=a2e;i0t="PopperArrow",b2n={top:"bottom",right:"left",bottom:"top",left:"right"},s0t=gm.forwardRef(function(e,n){let{__scopePopper:r,...o}=e,i=w2n(i0t,r),s=b2n[i.placedSide];return(0,AP.jsx)("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[s]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:(0,AP.jsx)(LIt,{...o,ref:n,style:{...o.style,display:"block"}})})});s0t.displayName=i0t;x2n=t=>({name:"transformOrigin",options:t,fn(e){let{placement:n,rects:r,middlewareData:o}=e,s=o.arrow?.centerOffset!==0,a=s?0:t.arrowWidth,l=s?0:t.arrowHeight,[c,u]=a0t(n),d={start:"0%",center:"50%",end:"100%"}[u],f=(o.arrow?.x??0)+a/2,p=(o.arrow?.y??0)+l/2,m="",h="";return c==="bottom"?(m=s?d:`${f}px`,h=`${-l}px`):c==="top"?(m=s?d:`${f}px`,h=`${r.floating.height+l}px`):c==="right"?(m=`${-l}px`,h=s?d:`${p}px`):c==="left"&&(m=`${r.floating.width+l}px`,h=s?d:`${p}px`),{data:{x:m,y:h}}}});sR=t0t,aR=r0t,Oj=o0t,Nj=s0t});function l0t(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function c0t(...t){return e=>{let n=!1,r=t.map(o=>{let i=l0t(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():l0t(t[o],null)}}}}var S2n,u0t=b(()=>{S2n=L(B(),1)});function d0t(t){let e=C2n(t),n=kc.forwardRef((r,o)=>{let{children:i,...s}=r,a=kc.Children.toArray(i),l=a.find(I2n);if(l){let c=l.props.children,u=a.map(d=>d===l?kc.Children.count(c)>1?kc.Children.only(null):kc.isValidElement(c)?c.props.children:null:d);return(0,kue.jsx)(e,{...s,ref:o,children:kc.isValidElement(c)?kc.cloneElement(c,void 0,u):null})}return(0,kue.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function C2n(t){let e=kc.forwardRef((n,r)=>{let{children:o,...i}=n;if(kc.isValidElement(o)){let s=P2n(o),a=T2n(i,o.props);return o.type!==kc.Fragment&&(a.ref=r?c0t(r,s):s),kc.cloneElement(o,a)}return kc.Children.count(o)>1?kc.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}function I2n(t){return kc.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===k2n}function T2n(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function P2n(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var kc,kue,k2n,f0t=b(()=>{kc=L(B(),1);u0t();kue=L(Mt(),1);k2n=Symbol("radix.slottable")});var p0t,A2n,m0t,E2n,h0t,g0t=b(()=>{p0t=L(B(),1),A2n=L(Es(),1);f0t();m0t=L(Mt(),1),E2n=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],h0t=E2n.reduce((t,e)=>{let n=d0t(`Primitive.${e}`),r=p0t.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,m0t.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{})});var y0t,v0t,w0t=b(()=>{y0t=L(B(),1),v0t=globalThis?.document?y0t.useLayoutEffect:()=>{}});var Iue,b0t,_0t,M2n,cR,Tue=b(()=>{"use client";Iue=L(B(),1),b0t=L(Es(),1);g0t();w0t();_0t=L(Mt(),1),M2n="Portal",cR=Iue.forwardRef((t,e)=>{let{container:n,...r}=t,[o,i]=Iue.useState(!1);v0t(()=>i(!0),[]);let s=n||o&&globalThis?.document?.body;return s?b0t.default.createPortal((0,_0t.jsx)(h0t.div,{...r,ref:e}),s):null});cR.displayName=M2n});function O2n(t,e){return x0t.useReducer((n,r)=>e[n][r]??n,t)}function N2n(t){let[e,n]=ym.useState(),r=ym.useRef(null),o=ym.useRef(t),i=ym.useRef("none"),s=t?"mounted":"unmounted",[a,l]=O2n(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return ym.useEffect(()=>{let c=Pue(r.current);i.current=a==="mounted"?c:"none"},[a]),nZ(()=>{let c=r.current,u=o.current;if(u!==t){let f=i.current,p=Pue(c);t?l("MOUNT"):p==="none"||c?.display==="none"?l("UNMOUNT"):l(u&&f!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,l]),nZ(()=>{if(e){let c,u=e.ownerDocument.defaultView??window,d=p=>{let h=Pue(r.current).includes(CSS.escape(p.animationName));if(p.target===e&&h&&(l("ANIMATION_END"),!o.current)){let g=e.style.animationFillMode;e.style.animationFillMode="forwards",c=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=g)})}},f=p=>{p.target===e&&(i.current=Pue(r.current))};return e.addEventListener("animationstart",f),e.addEventListener("animationcancel",d),e.addEventListener("animationend",d),()=>{u.clearTimeout(c),e.removeEventListener("animationstart",f),e.removeEventListener("animationcancel",d),e.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:ym.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function Pue(t){return t?.animationName||"none"}function R2n(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var ym,x0t,Rj,S0t=b(()=>{"use client";ym=L(B(),1);rue();HFe();x0t=L(B(),1);Rj=t=>{let{present:e,children:n}=t,r=N2n(e),o=typeof n=="function"?n({present:r.isPresent}):ym.Children.only(n),i=TP(r.ref,R2n(o));return typeof n=="function"||r.isPresent?ym.cloneElement(o,{ref:i}):null};Rj.displayName="Presence"});function Eue(t){let e=L2n(t),n=Ic.forwardRef((r,o)=>{let{children:i,...s}=r,a=Ic.Children.toArray(i),l=a.find(D2n);if(l){let c=l.props.children,u=a.map(d=>d===l?Ic.Children.count(c)>1?Ic.Children.only(null):Ic.isValidElement(c)?c.props.children:null:d);return(0,Aue.jsx)(e,{...s,ref:o,children:Ic.isValidElement(c)?Ic.cloneElement(c,void 0,u):null})}return(0,Aue.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function L2n(t){let e=Ic.forwardRef((n,r)=>{let{children:o,...i}=n;if(Ic.isValidElement(o)){let s=U2n(o),a=F2n(i,o.props);return o.type!==Ic.Fragment&&(a.ref=r?eZ(r,s):s),Ic.cloneElement(o,a)}return Ic.Children.count(o)>1?Ic.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}function D2n(t){return Ic.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===$2n}function F2n(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function U2n(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Ic,Aue,$2n,c2e=b(()=>{Ic=L(B(),1);rue();Aue=L(Mt(),1);$2n=Symbol("radix.slottable")});function T0t(t,e){t&&k0t.flushSync(()=>t.dispatchEvent(e))}var C0t,k0t,I0t,j2n,Lj,P0t=b(()=>{C0t=L(B(),1),k0t=L(Es(),1);c2e();I0t=L(Mt(),1),j2n=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Lj=j2n.reduce((t,e)=>{let n=Eue(`Primitive.${e}`),r=C0t.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,I0t.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{})});function uR(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var noo,A0t=b(()=>{noo=!!(typeof window<"u"&&window.document&&window.document.createElement)});function E0t(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function u2e(...t){return e=>{let n=!1,r=t.map(o=>{let i=E0t(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():E0t(t[o],null)}}}}function O0t(...t){return M0t.useCallback(u2e(...t),t)}var M0t,d2e=b(()=>{M0t=L(B(),1)});function R0t(t,e=[]){let n=[];function r(i,s){let a=_k.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=_k.useMemo(()=>m,Object.values(m));return(0,N0t.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=_k.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>_k.createContext(s));return function(a){let l=a?.[t]||i;return _k.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,B2n(o,...e)]}function B2n(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return _k.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var _k,N0t,L0t=b(()=>{_k=L(B(),1),N0t=L(Mt(),1)});var $0t,Mue,f2e=b(()=>{$0t=L(B(),1),Mue=globalThis?.document?$0t.useLayoutEffect:()=>{}});function D0t(t){let[e,n]=p2e.useState(z2n());return Mue(()=>{t||n(r=>r??String(H2n++))},[t]),t||(e?`radix-${e}`:"")}var p2e,z2n,H2n,F0t=b(()=>{p2e=L(B(),1);f2e();z2n=p2e[" useId ".trim().toString()]||(()=>{}),H2n=0});function U0t(t){let e=W2n(t),n=Tc.forwardRef((r,o)=>{let{children:i,...s}=r,a=Tc.Children.toArray(i),l=a.find(q2n);if(l){let c=l.props.children,u=a.map(d=>d===l?Tc.Children.count(c)>1?Tc.Children.only(null):Tc.isValidElement(c)?c.props.children:null:d);return(0,Oue.jsx)(e,{...s,ref:o,children:Tc.isValidElement(c)?Tc.cloneElement(c,void 0,u):null})}return(0,Oue.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function W2n(t){let e=Tc.forwardRef((n,r)=>{let{children:o,...i}=n;if(Tc.isValidElement(o)){let s=G2n(o),a=K2n(i,o.props);return o.type!==Tc.Fragment&&(a.ref=r?u2e(r,s):s),Tc.cloneElement(o,a)}return Tc.Children.count(o)>1?Tc.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}function q2n(t){return Tc.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===V2n}function K2n(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function G2n(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Tc,Oue,V2n,j0t=b(()=>{Tc=L(B(),1);d2e();Oue=L(Mt(),1);V2n=Symbol("radix.slottable")});var B0t,Z2n,z0t,Y2n,m2e,H0t=b(()=>{B0t=L(B(),1),Z2n=L(Es(),1);j0t();z0t=L(Mt(),1),Y2n=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],m2e=Y2n.reduce((t,e)=>{let n=U0t(`Primitive.${e}`),r=B0t.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,z0t.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{})});function W0t(t){let e=$j.useRef(t);return $j.useEffect(()=>{e.current=t}),$j.useMemo(()=>(...n)=>e.current?.(...n),[])}var $j,V0t=b(()=>{$j=L(B(),1)});function q0t({prop:t,defaultProp:e,onChange:n=()=>{},caller:r}){let[o,i,s]=X2n({defaultProp:e,onChange:n}),a=t!==void 0,l=a?t:o;{let u=Ly.useRef(t!==void 0);Ly.useEffect(()=>{let d=u.current;d!==a&&console.warn(`${r} is changing from ${d?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=a},[a,r])}let c=Ly.useCallback(u=>{if(a){let d=Q2n(u)?u(t):u;d!==t&&s.current?.(d)}else i(u)},[a,t,i,s]);return[l,c]}function X2n({defaultProp:t,onChange:e}){let[n,r]=Ly.useState(t),o=Ly.useRef(n),i=Ly.useRef(e);return J2n(()=>{i.current=e},[e]),Ly.useEffect(()=>{o.current!==n&&(i.current?.(n),o.current=n)},[n,o]),[n,r,i]}function Q2n(t){return typeof t=="function"}var Ly,Nue,J2n,hoo,K0t=b(()=>{Ly=L(B(),1);f2e();Nue=L(B(),1),J2n=Ly[" useInsertionEffect ".trim().toString()]||Mue;hoo=Symbol("RADIX:SYNC_STATE")});function G0t(t){let e=Rue.useContext(tUn);return t||e||"ltr"}var Rue,eUn,tUn,Z0t=b(()=>{Rue=L(B(),1),eUn=L(Mt(),1),tUn=Rue.createContext(void 0)});function cUn(t,e){return e!=="rtl"?t:t==="ArrowLeft"?"ArrowRight":t==="ArrowRight"?"ArrowLeft":t}function uUn(t,e,n){let r=cUn(t.key,n);if(!(e==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(e==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return lUn[r]}function eTt(t,e=!1){let n=document.activeElement;for(let r of t)if(r===n||(r.focus({preventScroll:e}),document.activeElement!==n))return}function dUn(t,e){return t.map((n,r)=>t[(e+r)%t.length])}var Tu,EP,h2e,nUn,cZ,g2e,Y0t,rUn,oUn,y2e,iUn,sUn,J0t,aUn,X0t,Q0t,lUn,tTt,nTt,v2e=b(()=>{"use client";Tu=L(B(),1);A0t();nue();d2e();L0t();F0t();H0t();V0t();K0t();Z0t();EP=L(Mt(),1),h2e="rovingFocusGroup.onEntryFocus",nUn={bubbles:!1,cancelable:!0},cZ="RovingFocusGroup",[g2e,Y0t,rUn]=Cj(cZ),[oUn,y2e]=R0t(cZ,[rUn]),[iUn,sUn]=oUn(cZ),J0t=Tu.forwardRef((t,e)=>(0,EP.jsx)(g2e.Provider,{scope:t.__scopeRovingFocusGroup,children:(0,EP.jsx)(g2e.Slot,{scope:t.__scopeRovingFocusGroup,children:(0,EP.jsx)(aUn,{...t,ref:e})})}));J0t.displayName=cZ;aUn=Tu.forwardRef((t,e)=>{let{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:u=!1,...d}=t,f=Tu.useRef(null),p=O0t(e,f),m=G0t(i),[h,g]=q0t({prop:s,defaultProp:a??null,onChange:l,caller:cZ}),[v,y]=Tu.useState(!1),w=W0t(c),_=Y0t(n),S=Tu.useRef(!1),[I,C]=Tu.useState(0);return Tu.useEffect(()=>{let k=f.current;if(k)return k.addEventListener(h2e,w),()=>k.removeEventListener(h2e,w)},[w]),(0,EP.jsx)(iUn,{scope:n,orientation:r,dir:m,loop:o,currentTabStopId:h,onItemFocus:Tu.useCallback(k=>g(k),[g]),onItemShiftTab:Tu.useCallback(()=>y(!0),[]),onFocusableItemAdd:Tu.useCallback(()=>C(k=>k+1),[]),onFocusableItemRemove:Tu.useCallback(()=>C(k=>k-1),[]),children:(0,EP.jsx)(m2e.div,{tabIndex:v||I===0?-1:0,"data-orientation":r,...d,ref:p,style:{outline:"none",...t.style},onMouseDown:uR(t.onMouseDown,()=>{S.current=!0}),onFocus:uR(t.onFocus,k=>{let T=!S.current;if(k.target===k.currentTarget&&T&&!v){let P=new CustomEvent(h2e,nUn);if(k.currentTarget.dispatchEvent(P),!P.defaultPrevented){let E=_().filter(K=>K.focusable),O=E.find(K=>K.active),$=E.find(K=>K.id===h),V=[O,$,...E].filter(Boolean).map(K=>K.ref.current);eTt(V,u)}}S.current=!1}),onBlur:uR(t.onBlur,()=>y(!1))})})}),X0t="RovingFocusGroupItem",Q0t=Tu.forwardRef((t,e)=>{let{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,children:s,...a}=t,l=D0t(),c=i||l,u=sUn(X0t,n),d=u.currentTabStopId===c,f=Y0t(n),{onFocusableItemAdd:p,onFocusableItemRemove:m,currentTabStopId:h}=u;return Tu.useEffect(()=>{if(r)return p(),()=>m()},[r,p,m]),(0,EP.jsx)(g2e.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:(0,EP.jsx)(m2e.span,{tabIndex:d?0:-1,"data-orientation":u.orientation,...a,ref:e,onMouseDown:uR(t.onMouseDown,g=>{r?u.onItemFocus(c):g.preventDefault()}),onFocus:uR(t.onFocus,()=>u.onItemFocus(c)),onKeyDown:uR(t.onKeyDown,g=>{if(g.key==="Tab"&&g.shiftKey){u.onItemShiftTab();return}if(g.target!==g.currentTarget)return;let v=uUn(g,u.orientation,u.dir);if(v!==void 0){if(g.metaKey||g.ctrlKey||g.altKey||g.shiftKey)return;g.preventDefault();let w=f().filter(_=>_.focusable).map(_=>_.ref.current);if(v==="last")w.reverse();else if(v==="prev"||v==="next"){v==="prev"&&w.reverse();let _=w.indexOf(g.currentTarget);w=u.loop?dUn(w,_+1):w.slice(_+1)}setTimeout(()=>eTt(w))}}),children:typeof s=="function"?s({isCurrentTabStop:d,hasTabStop:h!=null}):s})})});Q0t.displayName=X0t;lUn={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};tTt=J0t,nTt=Q0t});function Lue(t){let e=Dj.useRef(t);return Dj.useEffect(()=>{e.current=t}),Dj.useMemo(()=>(...n)=>e.current?.(...n),[])}var Dj,rTt=b(()=>{Dj=L(B(),1)});var pUn,Fj,$ue,Due,w2e,oTt,mUn,hUn,Fue,b2e=b(()=>{pUn=function(t){if(typeof document>"u")return null;var e=Array.isArray(t)?t[0]:t;return e.ownerDocument.body},Fj=new WeakMap,$ue=new WeakMap,Due={},w2e=0,oTt=function(t){return t&&(t.host||oTt(t.parentNode))},mUn=function(t,e){return e.map(function(n){if(t.contains(n))return n;var r=oTt(n);return r&&t.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",t,". Doing nothing"),null)}).filter(function(n){return!!n})},hUn=function(t,e,n,r){var o=mUn(e,Array.isArray(t)?t:[t]);Due[n]||(Due[n]=new WeakMap);var i=Due[n],s=[],a=new Set,l=new Set(o),c=function(d){!d||a.has(d)||(a.add(d),c(d.parentNode))};o.forEach(c);var u=function(d){!d||l.has(d)||Array.prototype.forEach.call(d.children,function(f){if(a.has(f))u(f);else try{var p=f.getAttribute(r),m=p!==null&&p!=="false",h=(Fj.get(f)||0)+1,g=(i.get(f)||0)+1;Fj.set(f,h),i.set(f,g),s.push(f),h===1&&m&&$ue.set(f,!0),g===1&&f.setAttribute(n,"true"),m||f.setAttribute(r,"true")}catch(v){console.error("aria-hidden: cannot operate on ",f,v)}})};return u(e),a.clear(),w2e++,function(){s.forEach(function(d){var f=Fj.get(d)-1,p=i.get(d)-1;Fj.set(d,f),i.set(d,p),f||($ue.has(d)||d.removeAttribute(r),$ue.delete(d)),p||d.removeAttribute(n)}),w2e--,w2e||(Fj=new WeakMap,Fj=new WeakMap,$ue=new WeakMap,Due={})}},Fue=function(t,e,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(t)?t:[t]),o=e||pUn(t);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),hUn(r,o,n,"aria-hidden")):function(){return null}}});function Uue(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(t);o<r.length;o++)e.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(t,r[o])&&(n[r[o]]=t[r[o]]);return n}function iTt(t,e,n){if(n||arguments.length===2)for(var r=0,o=e.length,i;r<o;r++)(i||!(r in e))&&(i||(i=Array.prototype.slice.call(e,0,r)),i[r]=e[r]);return t.concat(i||Array.prototype.slice.call(e))}var vm,Uj=b(()=>{vm=function(){return vm=Object.assign||function(e){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},vm.apply(this,arguments)}});var dR,fR,_2e,x2e,jue=b(()=>{dR="right-scroll-bar-position",fR="width-before-scroll-bar",_2e="with-scroll-bars-hidden",x2e="--removed-body-scroll-bar-size"});function Bue(t,e){return typeof t=="function"?t(e):t&&(t.current=e),t}var sTt=b(()=>{});function lTt(t,e){var n=(0,aTt.useState)(function(){return{value:t,callback:e,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=e,n.facade}var aTt,cTt=b(()=>{aTt=L(B())});function S2e(t,e){var n=lTt(e||null,function(r){return t.forEach(function(o){return Bue(o,r)})});return gUn(function(){var r=uTt.get(n);if(r){var o=new Set(r),i=new Set(t),s=n.current;o.forEach(function(a){i.has(a)||Bue(a,null)}),i.forEach(function(a){o.has(a)||Bue(a,s)})}uTt.set(n,t)},[t]),n}var zue,gUn,uTt,dTt=b(()=>{zue=L(B());sTt();cTt();gUn=typeof window<"u"?zue.useLayoutEffect:zue.useEffect,uTt=new WeakMap});var fTt=b(()=>{dTt()});function yUn(t){return t}function vUn(t,e){e===void 0&&(e=yUn);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:t},useMedium:function(i){var s=e(i,r);return n.push(s),function(){n=n.filter(function(a){return a!==s})}},assignSyncMedium:function(i){for(r=!0;n.length;){var s=n;n=[],s.forEach(i)}n={push:function(a){return i(a)},filter:function(){return n}}},assignMedium:function(i){r=!0;var s=[];if(n.length){var a=n;n=[],a.forEach(i),s=n}var l=function(){var u=s;s=[],u.forEach(i)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(u){s.push(u),c()},filter:function(u){return s=s.filter(u),n}}}};return o}function C2e(t){t===void 0&&(t={});var e=vUn(null);return e.options=vm({async:!0,ssr:!1},t),e}var pTt=b(()=>{Uj()});function k2e(t,e){return t.useMedium(e),hTt}var mTt,hTt,gTt=b(()=>{Uj();mTt=L(B()),hTt=function(t){var e=t.sideCar,n=Uue(t,["sideCar"]);if(!e)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=e.read();if(!r)throw new Error("Sidecar medium not found");return mTt.createElement(r,vm({},n))};hTt.isSideCarExport=!0});var I2e=b(()=>{pTt();gTt()});var Hue,T2e=b(()=>{I2e();Hue=C2e()});var of,P2e,uZ,yTt=b(()=>{Uj();of=L(B());jue();fTt();T2e();P2e=function(){},uZ=of.forwardRef(function(t,e){var n=of.useRef(null),r=of.useState({onScrollCapture:P2e,onWheelCapture:P2e,onTouchMoveCapture:P2e}),o=r[0],i=r[1],s=t.forwardProps,a=t.children,l=t.className,c=t.removeScrollBar,u=t.enabled,d=t.shards,f=t.sideCar,p=t.noRelative,m=t.noIsolation,h=t.inert,g=t.allowPinchZoom,v=t.as,y=v===void 0?"div":v,w=t.gapMode,_=Uue(t,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),S=f,I=S2e([n,e]),C=vm(vm({},_),o);return of.createElement(of.Fragment,null,u&&of.createElement(S,{sideCar:Hue,removeScrollBar:c,shards:d,noRelative:p,noIsolation:m,inert:h,setCallbacks:i,allowPinchZoom:!!g,lockRef:n,gapMode:w}),s?of.cloneElement(of.Children.only(a),vm(vm({},C),{ref:I})):of.createElement(y,vm({},C,{className:l,ref:I}),a))});uZ.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};uZ.classNames={fullWidth:fR,zeroRight:dR}});var vTt,wTt,bTt=b(()=>{wTt=function(){if(vTt)return vTt;if(typeof __webpack_nonce__<"u")return __webpack_nonce__}});function wUn(){if(!document)return null;var t=document.createElement("style");t.type="text/css";var e=wTt();return e&&t.setAttribute("nonce",e),t}function bUn(t,e){t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e))}function _Un(t){var e=document.head||document.getElementsByTagName("head")[0];e.appendChild(t)}var A2e,E2e=b(()=>{bTt();A2e=function(){var t=0,e=null;return{add:function(n){t==0&&(e=wUn())&&(bUn(e,n),_Un(e)),t++},remove:function(){t--,!t&&e&&(e.parentNode&&e.parentNode.removeChild(e),e=null)}}}});var _Tt,M2e,O2e=b(()=>{_Tt=L(B());E2e();M2e=function(){var t=A2e();return function(e,n){_Tt.useEffect(function(){return t.add(e),function(){t.remove()}},[e&&n])}}});var dZ,xTt=b(()=>{O2e();dZ=function(){var t=M2e(),e=function(n){var r=n.styles,o=n.dynamic;return t(r,o),null};return e}});var N2e=b(()=>{xTt();E2e();O2e()});var xUn,R2e,SUn,L2e,$2e=b(()=>{xUn={left:0,top:0,right:0,gap:0},R2e=function(t){return parseInt(t||"",10)||0},SUn=function(t){var e=window.getComputedStyle(document.body),n=e[t==="padding"?"paddingLeft":"marginLeft"],r=e[t==="padding"?"paddingTop":"marginTop"],o=e[t==="padding"?"paddingRight":"marginRight"];return[R2e(n),R2e(r),R2e(o)]},L2e=function(t){if(t===void 0&&(t="margin"),typeof window>"u")return xUn;var e=SUn(t),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:e[0],top:e[1],right:e[2],gap:Math.max(0,r-n+e[2]-e[0])}}});var Bj,CUn,jj,kUn,STt,IUn,D2e,CTt=b(()=>{Bj=L(B());N2e();jue();$2e();CUn=dZ(),jj="data-scroll-locked",kUn=function(t,e,n,r){var o=t.left,i=t.top,s=t.right,a=t.gap;return n===void 0&&(n="margin"),`
.`.concat(_2e,` {
overflow: hidden `).concat(r,`;
padding-right: `).concat(a,"px ").concat(r,`;
}
body[`).concat(jj,`] {
overflow: hidden `).concat(r,`;
overscroll-behavior: contain;
`).concat([e&&"position: relative ".concat(r,";"),n==="margin"&&`
padding-left: `.concat(o,`px;
padding-top: `).concat(i,`px;
padding-right: `).concat(s,`px;
margin-left:0;
margin-top:0;
margin-right: `).concat(a,"px ").concat(r,`;
`),n==="padding"&&"padding-right: ".concat(a,"px ").concat(r,";")].filter(Boolean).join(""),`
}
.`).concat(dR,` {
right: `).concat(a,"px ").concat(r,`;
}
.`).concat(fR,` {
margin-right: `).concat(a,"px ").concat(r,`;
}
.`).concat(dR," .").concat(dR,` {
right: 0 `).concat(r,`;
}
.`).concat(fR," .").concat(fR,` {
margin-right: 0 `).concat(r,`;
}
body[`).concat(jj,`] {
`).concat(x2e,": ").concat(a,`px;
}
`)},STt=function(){var t=parseInt(document.body.getAttribute(jj)||"0",10);return isFinite(t)?t:0},IUn=function(){Bj.useEffect(function(){return document.body.setAttribute(jj,(STt()+1).toString()),function(){var t=STt()-1;t<=0?document.body.removeAttribute(jj):document.body.setAttribute(jj,t.toString())}},[])},D2e=function(t){var e=t.noRelative,n=t.noImportant,r=t.gapMode,o=r===void 0?"margin":r;IUn();var i=Bj.useMemo(function(){return L2e(o)},[o]);return Bj.createElement(CUn,{styles:kUn(i,!e,o,n?"":"!important")})}});var kTt=b(()=>{CTt();jue();$2e()});var F2e,fZ,pR,ITt=b(()=>{F2e=!1;if(typeof window<"u")try{fZ=Object.defineProperty({},"passive",{get:function(){return F2e=!0,!0}}),window.addEventListener("test",fZ,fZ),window.removeEventListener("test",fZ,fZ)}catch{F2e=!1}pR=F2e?{passive:!1}:!1});var TUn,TTt,PUn,AUn,U2e,EUn,MUn,PTt,ATt,OUn,ETt,MTt=b(()=>{TUn=function(t){return t.tagName==="TEXTAREA"},TTt=function(t,e){if(!(t instanceof Element))return!1;var n=window.getComputedStyle(t);return n[e]!=="hidden"&&!(n.overflowY===n.overflowX&&!TUn(t)&&n[e]==="visible")},PUn=function(t){return TTt(t,"overflowY")},AUn=function(t){return TTt(t,"overflowX")},U2e=function(t,e){var n=e.ownerDocument,r=e;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var o=PTt(t,r);if(o){var i=ATt(t,r),s=i[1],a=i[2];if(s>a)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},EUn=function(t){var e=t.scrollTop,n=t.scrollHeight,r=t.clientHeight;return[e,n,r]},MUn=function(t){var e=t.scrollLeft,n=t.scrollWidth,r=t.clientWidth;return[e,n,r]},PTt=function(t,e){return t==="v"?PUn(e):AUn(e)},ATt=function(t,e){return t==="v"?EUn(e):MUn(e)},OUn=function(t,e){return t==="h"&&e==="rtl"?-1:1},ETt=function(t,e,n,r,o){var i=OUn(t,window.getComputedStyle(e).direction),s=i*r,a=n.target,l=e.contains(a),c=!1,u=s>0,d=0,f=0;do{if(!a)break;var p=ATt(t,a),m=p[0],h=p[1],g=p[2],v=h-g-i*m;(m||v)&&PTt(t,a)&&(d+=v,f+=m);var y=a.parentNode;a=y&&y.nodeType===Node.DOCUMENT_FRAGMENT_NODE?y.host:y}while(!l&&a!==document.body||l&&(e.contains(a)||e===a));return(u&&(o&&Math.abs(d)<1||!o&&s>d)||!u&&(o&&Math.abs(f)<1||!o&&-s>f))&&(c=!0),c}});function RTt(t){var e=qs.useRef([]),n=qs.useRef([0,0]),r=qs.useRef(),o=qs.useState(LUn++)[0],i=qs.useState(dZ)[0],s=qs.useRef(t);qs.useEffect(function(){s.current=t},[t]),qs.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=iTt([t.lockRef.current],(t.shards||[]).map(NTt),!0).filter(Boolean);return h.forEach(function(g){return g.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),h.forEach(function(g){return g.classList.remove("allow-interactivity-".concat(o))})}}},[t.inert,t.lockRef.current,t.shards]);var a=qs.useCallback(function(h,g){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!s.current.allowPinchZoom;var v=Wue(h),y=n.current,w="deltaX"in h?h.deltaX:y[0]-v[0],_="deltaY"in h?h.deltaY:y[1]-v[1],S,I=h.target,C=Math.abs(w)>Math.abs(_)?"h":"v";if("touches"in h&&C==="h"&&I.type==="range")return!1;var k=U2e(C,I);if(!k)return!0;if(k?S=C:(S=C==="v"?"h":"v",k=U2e(C,I)),!k)return!1;if(!r.current&&"changedTouches"in h&&(w||_)&&(r.current=S),!S)return!0;var T=r.current||S;return ETt(T,g,h,T==="h"?w:_,!0)},[]),l=qs.useCallback(function(h){var g=h;if(!(!zj.length||zj[zj.length-1]!==i)){var v="deltaY"in g?OTt(g):Wue(g),y=e.current.filter(function(S){return S.name===g.type&&(S.target===g.target||g.target===S.shadowParent)&&NUn(S.delta,v)})[0];if(y&&y.should){g.cancelable&&g.preventDefault();return}if(!y){var w=(s.current.shards||[]).map(NTt).filter(Boolean).filter(function(S){return S.contains(g.target)}),_=w.length>0?a(g,w[0]):!s.current.noIsolation;_&&g.cancelable&&g.preventDefault()}}},[]),c=qs.useCallback(function(h,g,v,y){var w={name:h,delta:g,target:v,should:y,shadowParent:$Un(v)};e.current.push(w),setTimeout(function(){e.current=e.current.filter(function(_){return _!==w})},1)},[]),u=qs.useCallback(function(h){n.current=Wue(h),r.current=void 0},[]),d=qs.useCallback(function(h){c(h.type,OTt(h),h.target,a(h,t.lockRef.current))},[]),f=qs.useCallback(function(h){c(h.type,Wue(h),h.target,a(h,t.lockRef.current))},[]);qs.useEffect(function(){return zj.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",l,pR),document.addEventListener("touchmove",l,pR),document.addEventListener("touchstart",u,pR),function(){zj=zj.filter(function(h){return h!==i}),document.removeEventListener("wheel",l,pR),document.removeEventListener("touchmove",l,pR),document.removeEventListener("touchstart",u,pR)}},[]);var p=t.removeScrollBar,m=t.inert;return qs.createElement(qs.Fragment,null,m?qs.createElement(i,{styles:RUn(o)}):null,p?qs.createElement(D2e,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function $Un(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var qs,Wue,OTt,NTt,NUn,RUn,LUn,zj,LTt=b(()=>{Uj();qs=L(B());kTt();N2e();ITt();MTt();Wue=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},OTt=function(t){return[t.deltaX,t.deltaY]},NTt=function(t){return t&&"current"in t?t.current:t},NUn=function(t,e){return t[0]===e[0]&&t[1]===e[1]},RUn=function(t){return`
.block-interactivity-`.concat(t,` {pointer-events: none;}
.allow-interactivity-`).concat(t,` {pointer-events: all;}
`)},LUn=0,zj=[]});var $Tt,DTt=b(()=>{I2e();LTt();T2e();$Tt=k2e(Hue,RTt)});var Vue,FTt,pZ,UTt=b(()=>{Uj();Vue=L(B());yTt();DTt();FTt=Vue.forwardRef(function(t,e){return Vue.createElement(uZ,vm({},t,{ref:e,sideCar:$Tt}))});FTt.classNames=uZ.classNames;pZ=FTt});var j2e=b(()=>{UTt()});function cPt(t){return t?"open":"closed"}function Kue(t){return t==="indeterminate"}function Y2e(t){return Kue(t)?"indeterminate":t?"checked":"unchecked"}function sjn(t){let e=document.activeElement;for(let n of t)if(n===e||(n.focus(),document.activeElement!==e))return}function ajn(t,e){return t.map((n,r)=>t[(e+r)%t.length])}function ljn(t,e,n){let o=e.length>1&&Array.from(e).every(c=>c===e[0])?e[0]:e,i=n?t.indexOf(n):-1,s=ajn(t,Math.max(i,0));o.length===1&&(s=s.filter(c=>c!==n));let l=s.find(c=>c.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function cjn(t,e){let{x:n,y:r}=t,o=!1;for(let i=0,s=e.length-1;i<e.length;s=i++){let a=e[i],l=e[s],c=a.x,u=a.y,d=l.x,f=l.y;u>r!=f>r&&n<(d-c)*(r-u)/(f-u)+c&&(o=!o)}return o}function ujn(t,e){if(!e)return!1;let n={x:t.clientX,y:t.clientY};return cjn(n,e)}function gZ(t){return e=>e.pointerType==="mouse"?t(e):void 0}var Mn,Tr,B2e,DUn,BTt,FUn,UUn,jUn,yZ,hZ,BUn,zUn,mR,z2e,vZ,zTt,HTt,MP,HUn,wZ,WTt,WUn,H2e,W2e,VUn,VTt,qTt,$y,qUn,V2e,KTt,KUn,GUn,ZUn,q2e,YUn,K2e,JUn,GTt,que,jTt,Gue,ZTt,XUn,YTt,JTt,QUn,ejn,XTt,QTt,ePt,G2e,tPt,tjn,nPt,njn,rPt,rjn,oPt,Z2e,ojn,iPt,ijn,mZ,sPt,aPt,lPt,uPt,dPt,fPt,pPt,mPt,hPt,gPt,yPt,vPt,wPt,bPt,_Pt,xPt,SPt,CPt,J2e=b(()=>{"use client";Mn=L(B(),1);CCt();nue();rue();LCt();DCt();aue();$Fe();zFe();Skt();lR();lR();Tue();S0t();P0t();v2e();v2e();c2e();rTt();b2e();j2e();Tr=L(Mt(),1),B2e=["Enter"," "],DUn=["ArrowDown","PageUp","Home"],BTt=["ArrowUp","PageDown","End"],FUn=[...DUn,...BTt],UUn={ltr:[...B2e,"ArrowRight"],rtl:[...B2e,"ArrowLeft"]},jUn={ltr:["ArrowLeft"],rtl:["ArrowRight"]},yZ="Menu",[hZ,BUn,zUn]=Cj(yZ),[mR,z2e]=RCt(yZ,[zUn,bk,y2e]),vZ=bk(),zTt=y2e(),[HTt,MP]=mR(yZ),[HUn,wZ]=mR(yZ),WTt=t=>{let{__scopeMenu:e,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=t,a=vZ(e),[l,c]=Mn.useState(null),u=Mn.useRef(!1),d=Lue(i),f=$Ct(o);return Mn.useEffect(()=>{let p=()=>{u.current=!0,document.addEventListener("pointerdown",m,{capture:!0,once:!0}),document.addEventListener("pointermove",m,{capture:!0,once:!0})},m=()=>u.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",m,{capture:!0}),document.removeEventListener("pointermove",m,{capture:!0})}},[]),(0,Tr.jsx)(sR,{...a,children:(0,Tr.jsx)(HTt,{scope:e,open:n,onOpenChange:d,content:l,onContentChange:c,children:(0,Tr.jsx)(HUn,{scope:e,onClose:Mn.useCallback(()=>d(!1),[d]),isUsingKeyboardRef:u,dir:f,modal:s,children:r})})})};WTt.displayName=yZ;WUn="MenuAnchor",H2e=Mn.forwardRef((t,e)=>{let{__scopeMenu:n,...r}=t,o=vZ(n);return(0,Tr.jsx)(aR,{...o,...r,ref:e})});H2e.displayName=WUn;W2e="MenuPortal",[VUn,VTt]=mR(W2e,{forceMount:void 0}),qTt=t=>{let{__scopeMenu:e,forceMount:n,children:r,container:o}=t,i=MP(W2e,e);return(0,Tr.jsx)(VUn,{scope:e,forceMount:n,children:(0,Tr.jsx)(Rj,{present:n||i.open,children:(0,Tr.jsx)(cR,{asChild:!0,container:o,children:r})})})};qTt.displayName=W2e;$y="MenuContent",[qUn,V2e]=mR($y),KTt=Mn.forwardRef((t,e)=>{let n=VTt($y,t.__scopeMenu),{forceMount:r=n.forceMount,...o}=t,i=MP($y,t.__scopeMenu),s=wZ($y,t.__scopeMenu);return(0,Tr.jsx)(hZ.Provider,{scope:t.__scopeMenu,children:(0,Tr.jsx)(Rj,{present:r||i.open,children:(0,Tr.jsx)(hZ.Slot,{scope:t.__scopeMenu,children:s.modal?(0,Tr.jsx)(KUn,{...o,ref:e}):(0,Tr.jsx)(GUn,{...o,ref:e})})})})}),KUn=Mn.forwardRef((t,e)=>{let n=MP($y,t.__scopeMenu),r=Mn.useRef(null),o=TP(e,r);return Mn.useEffect(()=>{let i=r.current;if(i)return Fue(i)},[]),(0,Tr.jsx)(q2e,{...t,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:qa(t.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),GUn=Mn.forwardRef((t,e)=>{let n=MP($y,t.__scopeMenu);return(0,Tr.jsx)(q2e,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),ZUn=Eue("MenuContent.ScrollLock"),q2e=Mn.forwardRef((t,e)=>{let{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:a,onEntryFocus:l,onEscapeKeyDown:c,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:f,onDismiss:p,disableOutsideScroll:m,...h}=t,g=MP($y,n),v=wZ($y,n),y=vZ(n),w=zTt(n),_=BUn(n),[S,I]=Mn.useState(null),C=Mn.useRef(null),k=TP(e,C,g.onContentChange),T=Mn.useRef(0),P=Mn.useRef(""),E=Mn.useRef(0),O=Mn.useRef(null),$=Mn.useRef("right"),U=Mn.useRef(0),V=m?pZ:Mn.Fragment,K=m?{as:ZUn,allowPinchZoom:!0}:void 0,se=Q=>{let ne=P.current+Q,ee=_().filter(R=>!R.disabled),ae=document.activeElement,q=ee.find(R=>R.ref.current===ae)?.textValue,F=ee.map(R=>R.textValue),z=ljn(F,ne,q),N=ee.find(R=>R.textValue===z)?.ref.current;(function R(X){P.current=X,window.clearTimeout(T.current),X!==""&&(T.current=window.setTimeout(()=>R(""),1e3))})(ne),N&&setTimeout(()=>N.focus())};Mn.useEffect(()=>()=>window.clearTimeout(T.current),[]),lue();let le=Mn.useCallback(Q=>$.current===O.current?.side&&ujn(Q,O.current?.area),[]);return(0,Tr.jsx)(qUn,{scope:n,searchRef:P,onItemEnter:Mn.useCallback(Q=>{le(Q)&&Q.preventDefault()},[le]),onItemLeave:Mn.useCallback(Q=>{le(Q)||(C.current?.focus(),I(null))},[le]),onTriggerLeave:Mn.useCallback(Q=>{le(Q)&&Q.preventDefault()},[le]),pointerGraceTimerRef:E,onPointerGraceIntentChange:Mn.useCallback(Q=>{O.current=Q},[]),children:(0,Tr.jsx)(V,{...K,children:(0,Tr.jsx)(tZ,{asChild:!0,trapped:o,onMountAutoFocus:qa(i,Q=>{Q.preventDefault(),C.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:s,children:(0,Tr.jsx)(QN,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:f,onDismiss:p,children:(0,Tr.jsx)(tTt,{asChild:!0,...w,dir:v.dir,orientation:"vertical",loop:r,currentTabStopId:S,onCurrentTabStopIdChange:I,onEntryFocus:qa(l,Q=>{v.isUsingKeyboardRef.current||Q.preventDefault()}),preventScrollOnEntryFocus:!0,children:(0,Tr.jsx)(Oj,{role:"menu","aria-orientation":"vertical","data-state":cPt(g.open),"data-radix-menu-content":"",dir:v.dir,...y,...h,ref:k,style:{outline:"none",...h.style},onKeyDown:qa(h.onKeyDown,Q=>{let ee=Q.target.closest("[data-radix-menu-content]")===Q.currentTarget,ae=Q.ctrlKey||Q.altKey||Q.metaKey,q=Q.key.length===1;ee&&(Q.key==="Tab"&&Q.preventDefault(),!ae&&q&&se(Q.key));let F=C.current;if(Q.target!==F||!FUn.includes(Q.key))return;Q.preventDefault();let N=_().filter(R=>!R.disabled).map(R=>R.ref.current);BTt.includes(Q.key)&&N.reverse(),sjn(N)}),onBlur:qa(t.onBlur,Q=>{Q.currentTarget.contains(Q.target)||(window.clearTimeout(T.current),P.current="")}),onPointerMove:qa(t.onPointerMove,gZ(Q=>{let ne=Q.target,ee=U.current!==Q.clientX;if(Q.currentTarget.contains(ne)&&ee){let ae=Q.clientX>U.current?"right":"left";$.current=ae,U.current=Q.clientX}}))})})})})})})});KTt.displayName=$y;YUn="MenuGroup",K2e=Mn.forwardRef((t,e)=>{let{__scopeMenu:n,...r}=t;return(0,Tr.jsx)(Lj.div,{role:"group",...r,ref:e})});K2e.displayName=YUn;JUn="MenuLabel",GTt=Mn.forwardRef((t,e)=>{let{__scopeMenu:n,...r}=t;return(0,Tr.jsx)(Lj.div,{...r,ref:e})});GTt.displayName=JUn;que="MenuItem",jTt="menu.itemSelect",Gue=Mn.forwardRef((t,e)=>{let{disabled:n=!1,onSelect:r,...o}=t,i=Mn.useRef(null),s=wZ(que,t.__scopeMenu),a=V2e(que,t.__scopeMenu),l=TP(e,i),c=Mn.useRef(!1),u=()=>{let d=i.current;if(!n&&d){let f=new CustomEvent(jTt,{bubbles:!0,cancelable:!0});d.addEventListener(jTt,p=>r?.(p),{once:!0}),T0t(d,f),f.defaultPrevented?c.current=!1:s.onClose()}};return(0,Tr.jsx)(ZTt,{...o,ref:l,disabled:n,onClick:qa(t.onClick,u),onPointerDown:d=>{t.onPointerDown?.(d),c.current=!0},onPointerUp:qa(t.onPointerUp,d=>{c.current||d.currentTarget?.click()}),onKeyDown:qa(t.onKeyDown,d=>{let f=a.searchRef.current!=="";n||f&&d.key===" "||B2e.includes(d.key)&&(d.currentTarget.click(),d.preventDefault())})})});Gue.displayName=que;ZTt=Mn.forwardRef((t,e)=>{let{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=t,s=V2e(que,n),a=zTt(n),l=Mn.useRef(null),c=TP(e,l),[u,d]=Mn.useState(!1),[f,p]=Mn.useState("");return Mn.useEffect(()=>{let m=l.current;m&&p((m.textContent??"").trim())},[i.children]),(0,Tr.jsx)(hZ.ItemSlot,{scope:n,disabled:r,textValue:o??f,children:(0,Tr.jsx)(nTt,{asChild:!0,...a,focusable:!r,children:(0,Tr.jsx)(Lj.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...i,ref:c,onPointerMove:qa(t.onPointerMove,gZ(m=>{r?s.onItemLeave(m):(s.onItemEnter(m),m.defaultPrevented||m.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:qa(t.onPointerLeave,gZ(m=>s.onItemLeave(m))),onFocus:qa(t.onFocus,()=>d(!0)),onBlur:qa(t.onBlur,()=>d(!1))})})})}),XUn="MenuCheckboxItem",YTt=Mn.forwardRef((t,e)=>{let{checked:n=!1,onCheckedChange:r,...o}=t;return(0,Tr.jsx)(tPt,{scope:t.__scopeMenu,checked:n,children:(0,Tr.jsx)(Gue,{role:"menuitemcheckbox","aria-checked":Kue(n)?"mixed":n,...o,ref:e,"data-state":Y2e(n),onSelect:qa(o.onSelect,()=>r?.(Kue(n)?!0:!n),{checkForDefaultPrevented:!1})})})});YTt.displayName=XUn;JTt="MenuRadioGroup",[QUn,ejn]=mR(JTt,{value:void 0,onValueChange:()=>{}}),XTt=Mn.forwardRef((t,e)=>{let{value:n,onValueChange:r,...o}=t,i=Lue(r);return(0,Tr.jsx)(QUn,{scope:t.__scopeMenu,value:n,onValueChange:i,children:(0,Tr.jsx)(K2e,{...o,ref:e})})});XTt.displayName=JTt;QTt="MenuRadioItem",ePt=Mn.forwardRef((t,e)=>{let{value:n,...r}=t,o=ejn(QTt,t.__scopeMenu),i=n===o.value;return(0,Tr.jsx)(tPt,{scope:t.__scopeMenu,checked:i,children:(0,Tr.jsx)(Gue,{role:"menuitemradio","aria-checked":i,...r,ref:e,"data-state":Y2e(i),onSelect:qa(r.onSelect,()=>o.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});ePt.displayName=QTt;G2e="MenuItemIndicator",[tPt,tjn]=mR(G2e,{checked:!1}),nPt=Mn.forwardRef((t,e)=>{let{__scopeMenu:n,forceMount:r,...o}=t,i=tjn(G2e,n);return(0,Tr.jsx)(Rj,{present:r||Kue(i.checked)||i.checked===!0,children:(0,Tr.jsx)(Lj.span,{...o,ref:e,"data-state":Y2e(i.checked)})})});nPt.displayName=G2e;njn="MenuSeparator",rPt=Mn.forwardRef((t,e)=>{let{__scopeMenu:n,...r}=t;return(0,Tr.jsx)(Lj.div,{role:"separator","aria-orientation":"horizontal",...r,ref:e})});rPt.displayName=njn;rjn="MenuArrow",oPt=Mn.forwardRef((t,e)=>{let{__scopeMenu:n,...r}=t,o=vZ(n);return(0,Tr.jsx)(Nj,{...o,...r,ref:e})});oPt.displayName=rjn;Z2e="MenuSub",[ojn,iPt]=mR(Z2e),ijn=t=>{let{__scopeMenu:e,children:n,open:r=!1,onOpenChange:o}=t,i=MP(Z2e,e),s=vZ(e),[a,l]=Mn.useState(null),[c,u]=Mn.useState(null),d=Lue(o);return Mn.useEffect(()=>(i.open===!1&&d(!1),()=>d(!1)),[i.open,d]),(0,Tr.jsx)(sR,{...s,children:(0,Tr.jsx)(HTt,{scope:e,open:r,onOpenChange:d,content:c,onContentChange:u,children:(0,Tr.jsx)(ojn,{scope:e,contentId:VFe(),triggerId:VFe(),trigger:a,onTriggerChange:l,children:n})})})};ijn.displayName=Z2e;mZ="MenuSubTrigger",sPt=Mn.forwardRef((t,e)=>{let n=MP(mZ,t.__scopeMenu),r=wZ(mZ,t.__scopeMenu),o=iPt(mZ,t.__scopeMenu),i=V2e(mZ,t.__scopeMenu),s=Mn.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:l}=i,c={__scopeMenu:t.__scopeMenu},u=Mn.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return Mn.useEffect(()=>u,[u]),Mn.useEffect(()=>{let d=a.current;return()=>{window.clearTimeout(d),l(null)}},[a,l]),(0,Tr.jsx)(H2e,{asChild:!0,...c,children:(0,Tr.jsx)(ZTt,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":cPt(n.open),...t,ref:eZ(e,o.onTriggerChange),onClick:d=>{t.onClick?.(d),!(t.disabled||d.defaultPrevented)&&(d.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:qa(t.onPointerMove,gZ(d=>{i.onItemEnter(d),!d.defaultPrevented&&!t.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),u()},100))})),onPointerLeave:qa(t.onPointerLeave,gZ(d=>{u();let f=n.content?.getBoundingClientRect();if(f){let p=n.content?.dataset.side,m=p==="right",h=m?-5:5,g=f[m?"left":"right"],v=f[m?"right":"left"];i.onPointerGraceIntentChange({area:[{x:d.clientX+h,y:d.clientY},{x:g,y:f.top},{x:v,y:f.top},{x:v,y:f.bottom},{x:g,y:f.bottom}],side:p}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(d),d.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:qa(t.onKeyDown,d=>{let f=i.searchRef.current!=="";t.disabled||f&&d.key===" "||UUn[r.dir].includes(d.key)&&(n.onOpenChange(!0),n.content?.focus(),d.preventDefault())})})})});sPt.displayName=mZ;aPt="MenuSubContent",lPt=Mn.forwardRef((t,e)=>{let n=VTt($y,t.__scopeMenu),{forceMount:r=n.forceMount,...o}=t,i=MP($y,t.__scopeMenu),s=wZ($y,t.__scopeMenu),a=iPt(aPt,t.__scopeMenu),l=Mn.useRef(null),c=TP(e,l);return(0,Tr.jsx)(hZ.Provider,{scope:t.__scopeMenu,children:(0,Tr.jsx)(Rj,{present:r||i.open,children:(0,Tr.jsx)(hZ.Slot,{scope:t.__scopeMenu,children:(0,Tr.jsx)(q2e,{id:a.contentId,"aria-labelledby":a.triggerId,...o,ref:c,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:u=>{s.isUsingKeyboardRef.current&&l.current?.focus(),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:qa(t.onFocusOutside,u=>{u.target!==a.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:qa(t.onEscapeKeyDown,u=>{s.onClose(),u.preventDefault()}),onKeyDown:qa(t.onKeyDown,u=>{let d=u.currentTarget.contains(u.target),f=jUn[s.dir].includes(u.key);d&&f&&(i.onOpenChange(!1),a.trigger?.focus(),u.preventDefault())})})})})})});lPt.displayName=aPt;uPt=WTt,dPt=H2e,fPt=qTt,pPt=KTt,mPt=K2e,hPt=GTt,gPt=Gue,yPt=YTt,vPt=XTt,wPt=ePt,bPt=nPt,_Pt=rPt,xPt=oPt,SPt=sPt,CPt=lPt});function Q2e(t){let[e,n]=X2e.useState(fjn());return Jce(()=>{t||n(r=>r??String(pjn++))},[t]),t||(e?`radix-${e}`:"")}var X2e,fjn,pjn,kPt=b(()=>{X2e=L(B(),1);SFe();fjn=X2e[" useId ".trim().toString()]||(()=>{}),pjn=0});var Pc,Pu,Zue,mjn,dso,cp,hjn,IPt,bZ,TPt,_Z,gjn,PPt,APt,EPt,yjn,vjn,wjn,MPt,bjn,OPt,_jn,NPt,xjn,Sjn,Cjn,RPt,kjn,LPt,Ijn,$Pt,Tjn,Pjn,Ajn,DPt,Ejn,FPt,UPt,jPt,BPt,eUe,tUe,nUe,rUe,oUe,iUe,sUe,aUe,lUe,cUe=b(()=>{"use client";Pc=L(B(),1);uCt();xFe();mCt();yCt();SCt();J2e();J2e();kPt();Pu=L(Mt(),1),Zue="DropdownMenu",[mjn,dso]=pCt(Zue,[z2e]),cp=z2e(),[hjn,IPt]=mjn(Zue),bZ=t=>{let{__scopeDropdownMenu:e,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:a=!0}=t,l=cp(e),c=Pc.useRef(null),[u,d]=gCt({prop:o,defaultProp:i??!1,onChange:s,caller:Zue});return(0,Pu.jsx)(hjn,{scope:e,triggerId:Q2e(),triggerRef:c,contentId:Q2e(),open:u,onOpenChange:d,onOpenToggle:Pc.useCallback(()=>d(f=>!f),[d]),modal:a,children:(0,Pu.jsx)(uPt,{...l,open:u,onOpenChange:d,dir:r,modal:a,children:n})})};bZ.displayName=Zue;TPt="DropdownMenuTrigger",_Z=Pc.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,disabled:r=!1,...o}=t,i=IPt(TPt,n),s=cp(n);return(0,Pu.jsx)(dPt,{asChild:!0,...s,children:(0,Pu.jsx)(xCt.button,{type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...o,ref:Yce(e,i.triggerRef),onPointerDown:Q8(t.onPointerDown,a=>{!r&&a.button===0&&a.ctrlKey===!1&&(i.onOpenToggle(),i.open||a.preventDefault())}),onKeyDown:Q8(t.onKeyDown,a=>{r||(["Enter"," "].includes(a.key)&&i.onOpenToggle(),a.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});_Z.displayName=TPt;gjn="DropdownMenuPortal",PPt=t=>{let{__scopeDropdownMenu:e,...n}=t,r=cp(e);return(0,Pu.jsx)(fPt,{...r,...n})};PPt.displayName=gjn;APt="DropdownMenuContent",EPt=Pc.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=IPt(APt,n),i=cp(n),s=Pc.useRef(!1);return(0,Pu.jsx)(pPt,{id:o.contentId,"aria-labelledby":o.triggerId,...i,...r,ref:e,onCloseAutoFocus:Q8(t.onCloseAutoFocus,a=>{s.current||o.triggerRef.current?.focus(),s.current=!1,a.preventDefault()}),onInteractOutside:Q8(t.onInteractOutside,a=>{let l=a.detail.originalEvent,c=l.button===0&&l.ctrlKey===!0,u=l.button===2||c;(!o.modal||u)&&(s.current=!0)}),style:{...t.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});EPt.displayName=APt;yjn="DropdownMenuGroup",vjn=Pc.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=cp(n);return(0,Pu.jsx)(mPt,{...o,...r,ref:e})});vjn.displayName=yjn;wjn="DropdownMenuLabel",MPt=Pc.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=cp(n);return(0,Pu.jsx)(hPt,{...o,...r,ref:e})});MPt.displayName=wjn;bjn="DropdownMenuItem",OPt=Pc.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=cp(n);return(0,Pu.jsx)(gPt,{...o,...r,ref:e})});OPt.displayName=bjn;_jn="DropdownMenuCheckboxItem",NPt=Pc.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=cp(n);return(0,Pu.jsx)(yPt,{...o,...r,ref:e})});NPt.displayName=_jn;xjn="DropdownMenuRadioGroup",Sjn=Pc.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=cp(n);return(0,Pu.jsx)(vPt,{...o,...r,ref:e})});Sjn.displayName=xjn;Cjn="DropdownMenuRadioItem",RPt=Pc.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=cp(n);return(0,Pu.jsx)(wPt,{...o,...r,ref:e})});RPt.displayName=Cjn;kjn="DropdownMenuItemIndicator",LPt=Pc.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=cp(n);return(0,Pu.jsx)(bPt,{...o,...r,ref:e})});LPt.displayName=kjn;Ijn="DropdownMenuSeparator",$Pt=Pc.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=cp(n);return(0,Pu.jsx)(_Pt,{...o,...r,ref:e})});$Pt.displayName=Ijn;Tjn="DropdownMenuArrow",Pjn=Pc.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=cp(n);return(0,Pu.jsx)(xPt,{...o,...r,ref:e})});Pjn.displayName=Tjn;Ajn="DropdownMenuSubTrigger",DPt=Pc.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=cp(n);return(0,Pu.jsx)(SPt,{...o,...r,ref:e})});DPt.displayName=Ajn;Ejn="DropdownMenuSubContent",FPt=Pc.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=cp(n);return(0,Pu.jsx)(CPt,{...o,...r,ref:e,style:{...t.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});FPt.displayName=Ejn;UPt=bZ,jPt=_Z,BPt=PPt,eUe=EPt,tUe=MPt,nUe=OPt,rUe=NPt,oUe=RPt,iUe=LPt,sUe=$Pt,aUe=DPt,lUe=FPt});var fs,zPt,up,dp,Ojn,Njn,Ac,co,Rjn,Ljn,uUe,$jn,Djn,xk=b(()=>{fs=L(B());cUe();Re();zPt=require("obsidian");De();up=UPt,dp=jPt,Ojn=fs.forwardRef(({className:t,inset:e,children:n,...r},o)=>fs.createElement(aUe,{ref:o,className:J("tw-flex tw-cursor-default tw-select-none tw-items-center tw-gap-2 tw-rounded-sm tw-px-2 tw-py-1.5 tw-text-sm tw-outline-none focus:tw-bg-modifier-hover data-[state=open]:tw-bg-modifier-hover [&_svg]:tw-pointer-events-none [&_svg]:tw-size-4 [&_svg]:tw-shrink-0",e&&"tw-pl-8",t),...r},n,fs.createElement(Vi,{className:"tw-ml-auto"})));Ojn.displayName=aUe.displayName;Njn=fs.forwardRef(({className:t,...e},n)=>fs.createElement(lUe,{ref:n,className:J("tw-z-[50] tw-min-w-32 tw-overflow-hidden tw-rounded-md tw-border tw-bg-primary tw-p-1 tw-text-normal tw-shadow-lg data-[state=open]:tw-animate-in data-[state=closed]:tw-animate-out data-[state=closed]:tw-fade-out-0 data-[state=open]:tw-fade-in-0 data-[state=closed]:tw-zoom-out-95 data-[state=open]:tw-zoom-in-95 data-[side=bottom]:tw-slide-in-from-top-2 data-[side=left]:tw-slide-in-from-right-2 data-[side=right]:tw-slide-in-from-left-2 data-[side=top]:tw-slide-in-from-bottom-2",t),...e}));Njn.displayName=lUe.displayName;Ac=fs.forwardRef(({className:t,sideOffset:e=4,container:n,...r},o)=>fs.createElement(BPt,{container:n??activeDocument.body},fs.createElement(eUe,{ref:o,sideOffset:e,hideWhenDetached:zPt.Platform.isMobile,className:J("tw-z-[50] tw-min-w-32 tw-overflow-hidden tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-1 tw-text-normal tw-shadow-md","data-[state=open]:tw-animate-in data-[state=closed]:tw-animate-out data-[state=closed]:tw-fade-out-0 data-[state=open]:tw-fade-in-0 data-[state=closed]:tw-zoom-out-95 data-[state=open]:tw-zoom-in-95 data-[side=bottom]:tw-slide-in-from-top-2 data-[side=left]:tw-slide-in-from-right-2 data-[side=right]:tw-slide-in-from-left-2 data-[side=top]:tw-slide-in-from-bottom-2",t),...r})));Ac.displayName=eUe.displayName;co=fs.forwardRef(({className:t,inset:e,...n},r)=>fs.createElement(nUe,{ref:r,className:J("tw-relative tw-flex tw-cursor-default tw-select-none tw-items-center tw-gap-2 tw-rounded-sm tw-px-2 tw-py-1.5 tw-text-sm tw-outline-none tw-transition-colors focus:tw-bg-modifier-hover focus:tw-text-normal data-[disabled]:tw-pointer-events-none data-[disabled]:tw-opacity-50 [&>svg]:tw-size-4 [&>svg]:tw-shrink-0",e&&"tw-pl-8",t),...n}));co.displayName=nUe.displayName;Rjn=fs.forwardRef(({className:t,children:e,checked:n,...r},o)=>fs.createElement(rUe,{ref:o,className:J("tw-relative tw-flex tw-cursor-default tw-select-none tw-items-center tw-rounded-sm tw-py-1.5 tw-pl-8 tw-pr-2 tw-text-sm tw-outline-none tw-transition-colors focus:tw-bg-modifier-hover focus:tw-text-normal data-[disabled]:tw-pointer-events-none data-[disabled]:tw-opacity-50",t),checked:n,...r},fs.createElement("span",{className:"tw-absolute tw-left-2 tw-flex tw-size-3.5 tw-items-center tw-justify-center"},fs.createElement(iUe,null,fs.createElement(Hr,{className:"tw-size-4"}))),e));Rjn.displayName=rUe.displayName;Ljn=fs.forwardRef(({className:t,children:e,...n},r)=>fs.createElement(oUe,{ref:r,className:J("tw-relative tw-flex tw-cursor-default tw-select-none tw-items-center tw-rounded-sm tw-py-1.5 tw-pl-8 tw-pr-2 tw-text-sm tw-outline-none tw-transition-colors focus:tw-bg-modifier-hover focus:tw-text-normal data-[disabled]:tw-pointer-events-none data-[disabled]:tw-opacity-50",t),...n},fs.createElement("span",{className:"tw-absolute tw-left-2 tw-flex tw-size-3.5 tw-items-center tw-justify-center"},fs.createElement(iUe,null,fs.createElement(iG,{className:"tw-size-2 tw-fill-current"}))),e));Ljn.displayName=oUe.displayName;uUe=fs.forwardRef(({className:t,inset:e,...n},r)=>fs.createElement(tUe,{ref:r,className:J("tw-px-2 tw-py-1.5 tw-text-sm tw-font-semibold",e&&"tw-pl-8",t),...n}));uUe.displayName=tUe.displayName;$jn=fs.forwardRef(({className:t,...e},n)=>fs.createElement(sUe,{ref:n,className:J("-tw-mx-1 tw-my-1 tw-h-px",t),...e}));$jn.displayName=sUe.displayName;Djn=({className:t,...e})=>fs.createElement("span",{className:J("tw-ml-auto tw-text-xs tw-tracking-widest tw-opacity-60",t),...e});Djn.displayName="DropdownMenuShortcut"});function hR(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var vso,HPt=b(()=>{vso=!!(typeof window<"u"&&window.document&&window.document.createElement)});function WPt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function dUe(...t){return e=>{let n=!1,r=t.map(o=>{let i=WPt(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():WPt(t[o],null)}}}}function xZ(...t){return VPt.useCallback(dUe(...t),t)}var VPt,Yue=b(()=>{VPt=L(B(),1)});function KPt(t,e=[]){let n=[];function r(i,s){let a=Sk.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=Sk.useMemo(()=>m,Object.values(m));return(0,qPt.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=Sk.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>Sk.createContext(s));return function(a){let l=a?.[t]||i;return Sk.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,Fjn(o,...e)]}function Fjn(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return Sk.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var Sk,qPt,GPt=b(()=>{Sk=L(B(),1),qPt=L(Mt(),1)});var ZPt,gR,Jue=b(()=>{ZPt=L(B(),1),gR=globalThis?.document?ZPt.useLayoutEffect:()=>{}});function YPt(t){let[e,n]=fUe.useState(Ujn());return gR(()=>{t||n(r=>r??String(jjn++))},[t]),t||(e?`radix-${e}`:"")}var fUe,Ujn,jjn,JPt=b(()=>{fUe=L(B(),1);Jue();Ujn=fUe[" useId ".trim().toString()]||(()=>{}),jjn=0});function Bjn(t,e){return XPt.useReducer((n,r)=>e[n][r]??n,t)}function zjn(t){let[e,n]=wm.useState(),r=wm.useRef(null),o=wm.useRef(t),i=wm.useRef("none"),s=t?"mounted":"unmounted",[a,l]=Bjn(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return wm.useEffect(()=>{let c=Xue(r.current);i.current=a==="mounted"?c:"none"},[a]),gR(()=>{let c=r.current,u=o.current;if(u!==t){let f=i.current,p=Xue(c);t?l("MOUNT"):p==="none"||c?.display==="none"?l("UNMOUNT"):l(u&&f!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,l]),gR(()=>{if(e){let c,u=e.ownerDocument.defaultView??window,d=p=>{let h=Xue(r.current).includes(CSS.escape(p.animationName));if(p.target===e&&h&&(l("ANIMATION_END"),!o.current)){let g=e.style.animationFillMode;e.style.animationFillMode="forwards",c=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=g)})}},f=p=>{p.target===e&&(i.current=Xue(r.current))};return e.addEventListener("animationstart",f),e.addEventListener("animationcancel",d),e.addEventListener("animationend",d),()=>{u.clearTimeout(c),e.removeEventListener("animationstart",f),e.removeEventListener("animationcancel",d),e.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:wm.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function Xue(t){return t?.animationName||"none"}function Hjn(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var wm,XPt,Que,QPt=b(()=>{"use client";wm=L(B(),1);Yue();Jue();XPt=L(B(),1);Que=t=>{let{present:e,children:n}=t,r=zjn(e),o=typeof n=="function"?n({present:r.isPresent}):wm.Children.only(n),i=xZ(r.ref,Hjn(o));return typeof n=="function"||r.isPresent?wm.cloneElement(o,{ref:i}):null};Que.displayName="Presence"});function eAt(t){let e=Wjn(t),n=Ec.forwardRef((r,o)=>{let{children:i,...s}=r,a=Ec.Children.toArray(i),l=a.find(Vjn);if(l){let c=l.props.children,u=a.map(d=>d===l?Ec.Children.count(c)>1?Ec.Children.only(null):Ec.isValidElement(c)?c.props.children:null:d);return(0,Hj.jsx)(e,{...s,ref:o,children:Ec.isValidElement(c)?Ec.cloneElement(c,void 0,u):null})}return(0,Hj.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function Wjn(t){let e=Ec.forwardRef((n,r)=>{let{children:o,...i}=n;if(Ec.isValidElement(o)){let s=Kjn(o),a=qjn(i,o.props);return o.type!==Ec.Fragment&&(a.ref=r?dUe(r,s):s),Ec.cloneElement(o,a)}return Ec.Children.count(o)>1?Ec.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}function nAt(t){let e=({children:n})=>(0,Hj.jsx)(Hj.Fragment,{children:n});return e.displayName=`${t}.Slottable`,e.__radixId=tAt,e}function Vjn(t){return Ec.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===tAt}function qjn(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function Kjn(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Ec,Hj,tAt,pUe=b(()=>{Ec=L(B(),1);Yue();Hj=L(Mt(),1);tAt=Symbol("radix.slottable")});var rAt,Gjn,oAt,Zjn,iAt,sAt=b(()=>{rAt=L(B(),1),Gjn=L(Es(),1);pUe();oAt=L(Mt(),1),Zjn=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],iAt=Zjn.reduce((t,e)=>{let n=eAt(`Primitive.${e}`),r=rAt.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,oAt.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{})});function aAt({prop:t,defaultProp:e,onChange:n=()=>{},caller:r}){let[o,i,s]=Jjn({defaultProp:e,onChange:n}),a=t!==void 0,l=a?t:o;{let u=Dy.useRef(t!==void 0);Dy.useEffect(()=>{let d=u.current;d!==a&&console.warn(`${r} is changing from ${d?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=a},[a,r])}let c=Dy.useCallback(u=>{if(a){let d=Xjn(u)?u(t):u;d!==t&&s.current?.(d)}else i(u)},[a,t,i,s]);return[l,c]}function Jjn({defaultProp:t,onChange:e}){let[n,r]=Dy.useState(t),o=Dy.useRef(n),i=Dy.useRef(e);return Yjn(()=>{i.current=e},[e]),Dy.useEffect(()=>{o.current!==n&&(i.current?.(n),o.current=n)},[n,o]),[n,r,i]}function Xjn(t){return typeof t=="function"}var Dy,ede,Yjn,Nso,lAt=b(()=>{Dy=L(B(),1);Jue();ede=L(B(),1),Yjn=Dy[" useInsertionEffect ".trim().toString()]||gR;Nso=Symbol("RADIX:SYNC_STATE")});function cAt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function uAt(...t){return e=>{let n=!1,r=t.map(o=>{let i=cAt(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():cAt(t[o],null)}}}}var Qjn,dAt=b(()=>{Qjn=L(B(),1)});function fAt(t){let e=eBn(t),n=Mc.forwardRef((r,o)=>{let{children:i,...s}=r,a=Mc.Children.toArray(i),l=a.find(nBn);if(l){let c=l.props.children,u=a.map(d=>d===l?Mc.Children.count(c)>1?Mc.Children.only(null):Mc.isValidElement(c)?c.props.children:null:d);return(0,tde.jsx)(e,{...s,ref:o,children:Mc.isValidElement(c)?Mc.cloneElement(c,void 0,u):null})}return(0,tde.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function eBn(t){let e=Mc.forwardRef((n,r)=>{let{children:o,...i}=n;if(Mc.isValidElement(o)){let s=oBn(o),a=rBn(i,o.props);return o.type!==Mc.Fragment&&(a.ref=r?uAt(r,s):s),Mc.cloneElement(o,a)}return Mc.Children.count(o)>1?Mc.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}function nBn(t){return Mc.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===tBn}function rBn(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function oBn(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Mc,tde,tBn,pAt=b(()=>{Mc=L(B(),1);dAt();tde=L(Mt(),1);tBn=Symbol("radix.slottable")});var mAt,iBn,hAt,sBn,gAt,yAt=b(()=>{mAt=L(B(),1),iBn=L(Es(),1);pAt();hAt=L(Mt(),1),sBn=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],gAt=sBn.reduce((t,e)=>{let n=fAt(`Primitive.${e}`),r=mAt.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,hAt.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{})});var vAt,wAt,aBn,lBn,bAt,_At,xAt=b(()=>{vAt=L(B(),1);yAt();wAt=L(Mt(),1),aBn=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),lBn="VisuallyHidden",bAt=vAt.forwardRef((t,e)=>(0,wAt.jsx)(gAt.span,{...t,ref:e,style:{...aBn,...t.style}}));bAt.displayName=lBn;_At=bAt});function bBn(t,e){let n=Math.abs(e.top-t.y),r=Math.abs(e.bottom-t.y),o=Math.abs(e.right-t.x),i=Math.abs(e.left-t.x);switch(Math.min(n,r,o,i)){case i:return"left";case o:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function _Bn(t,e,n=5){let r=[];switch(e){case"top":r.push({x:t.x-n,y:t.y+n},{x:t.x+n,y:t.y+n});break;case"bottom":r.push({x:t.x-n,y:t.y-n},{x:t.x+n,y:t.y-n});break;case"left":r.push({x:t.x+n,y:t.y-n},{x:t.x+n,y:t.y+n});break;case"right":r.push({x:t.x-n,y:t.y-n},{x:t.x-n,y:t.y+n});break}return r}function xBn(t){let{top:e,right:n,bottom:r,left:o}=t;return[{x:o,y:e},{x:n,y:e},{x:n,y:r},{x:o,y:r}]}function SBn(t,e){let{x:n,y:r}=t,o=!1;for(let i=0,s=e.length-1;i<e.length;s=i++){let a=e[i],l=e[s],c=a.x,u=a.y,d=l.x,f=l.y;u>r!=f>r&&n<(d-c)*(r-u)/(f-u)+c&&(o=!o)}return o}function CBn(t){let e=t.slice();return e.sort((n,r)=>n.x<r.x?-1:n.x>r.x?1:n.y<r.y?-1:n.y>r.y?1:0),kBn(e)}function kBn(t){if(t.length<=1)return t.slice();let e=[];for(let r=0;r<t.length;r++){let o=t[r];for(;e.length>=2;){let i=e[e.length-1],s=e[e.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))e.pop();else break}e.push(o)}e.pop();let n=[];for(let r=t.length-1;r>=0;r--){let o=t[r];for(;n.length>=2;){let i=n[n.length-1],s=n[n.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))n.pop();else break}n.push(o)}return n.pop(),e.length===1&&n.length===1&&e[0].x===n[0].x&&e[0].y===n[0].y?e:e.concat(n)}var qr,zl,nde,Xso,rde,SAt,uBn,mUe,dBn,gUe,CAt,SZ,fBn,CZ,kAt,hUe,IAt,yUe,pBn,mBn,TAt,Wj,PAt,hBn,gBn,yBn,vBn,AAt,EAt,wBn,Vj,MAt,OAt,NAt,vUe,ode=b(()=>{"use client";qr=L(B(),1);HPt();Yue();GPt();aue();JPt();lR();lR();Tue();QPt();sAt();pUe();lAt();xAt();zl=L(Mt(),1),[nde,Xso]=KPt("Tooltip",[bk]),rde=bk(),SAt="TooltipProvider",uBn=700,mUe="tooltip.open",[dBn,gUe]=nde(SAt),CAt=t=>{let{__scopeTooltip:e,delayDuration:n=uBn,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=t,s=qr.useRef(!0),a=qr.useRef(!1),l=qr.useRef(0);return qr.useEffect(()=>{let c=l.current;return()=>window.clearTimeout(c)},[]),(0,zl.jsx)(dBn,{scope:e,isOpenDelayedRef:s,delayDuration:n,onOpen:qr.useCallback(()=>{window.clearTimeout(l.current),s.current=!1},[]),onClose:qr.useCallback(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.current=!0,r)},[r]),isPointerInTransitRef:a,onPointerInTransitChange:qr.useCallback(c=>{a.current=c},[]),disableHoverableContent:o,children:i})};CAt.displayName=SAt;SZ="Tooltip",[fBn,CZ]=nde(SZ),kAt=t=>{let{__scopeTooltip:e,children:n,open:r,defaultOpen:o,onOpenChange:i,disableHoverableContent:s,delayDuration:a}=t,l=gUe(SZ,t.__scopeTooltip),c=rde(e),[u,d]=qr.useState(null),f=YPt(),p=qr.useRef(0),m=s??l.disableHoverableContent,h=a??l.delayDuration,g=qr.useRef(!1),[v,y]=aAt({prop:r,defaultProp:o??!1,onChange:C=>{C?(l.onOpen(),document.dispatchEvent(new CustomEvent(mUe))):l.onClose(),i?.(C)},caller:SZ}),w=qr.useMemo(()=>v?g.current?"delayed-open":"instant-open":"closed",[v]),_=qr.useCallback(()=>{window.clearTimeout(p.current),p.current=0,g.current=!1,y(!0)},[y]),S=qr.useCallback(()=>{window.clearTimeout(p.current),p.current=0,y(!1)},[y]),I=qr.useCallback(()=>{window.clearTimeout(p.current),p.current=window.setTimeout(()=>{g.current=!0,y(!0),p.current=0},h)},[h,y]);return qr.useEffect(()=>()=>{p.current&&(window.clearTimeout(p.current),p.current=0)},[]),(0,zl.jsx)(sR,{...c,children:(0,zl.jsx)(fBn,{scope:e,contentId:f,open:v,stateAttribute:w,trigger:u,onTriggerChange:d,onTriggerEnter:qr.useCallback(()=>{l.isOpenDelayedRef.current?I():_()},[l.isOpenDelayedRef,I,_]),onTriggerLeave:qr.useCallback(()=>{m?S():(window.clearTimeout(p.current),p.current=0)},[S,m]),onOpen:_,onClose:S,disableHoverableContent:m,children:n})})};kAt.displayName=SZ;hUe="TooltipTrigger",IAt=qr.forwardRef((t,e)=>{let{__scopeTooltip:n,...r}=t,o=CZ(hUe,n),i=gUe(hUe,n),s=rde(n),a=qr.useRef(null),l=xZ(e,a,o.onTriggerChange),c=qr.useRef(!1),u=qr.useRef(!1),d=qr.useCallback(()=>c.current=!1,[]);return qr.useEffect(()=>()=>document.removeEventListener("pointerup",d),[d]),(0,zl.jsx)(aR,{asChild:!0,...s,children:(0,zl.jsx)(iAt.button,{"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute,...r,ref:l,onPointerMove:hR(t.onPointerMove,f=>{f.pointerType!=="touch"&&!u.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),u.current=!0)}),onPointerLeave:hR(t.onPointerLeave,()=>{o.onTriggerLeave(),u.current=!1}),onPointerDown:hR(t.onPointerDown,()=>{o.open&&o.onClose(),c.current=!0,document.addEventListener("pointerup",d,{once:!0})}),onFocus:hR(t.onFocus,()=>{c.current||o.onOpen()}),onBlur:hR(t.onBlur,o.onClose),onClick:hR(t.onClick,o.onClose)})})});IAt.displayName=hUe;yUe="TooltipPortal",[pBn,mBn]=nde(yUe,{forceMount:void 0}),TAt=t=>{let{__scopeTooltip:e,forceMount:n,children:r,container:o}=t,i=CZ(yUe,e);return(0,zl.jsx)(pBn,{scope:e,forceMount:n,children:(0,zl.jsx)(Que,{present:n||i.open,children:(0,zl.jsx)(cR,{asChild:!0,container:o,children:r})})})};TAt.displayName=yUe;Wj="TooltipContent",PAt=qr.forwardRef((t,e)=>{let n=mBn(Wj,t.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=t,s=CZ(Wj,t.__scopeTooltip);return(0,zl.jsx)(Que,{present:r||s.open,children:s.disableHoverableContent?(0,zl.jsx)(AAt,{side:o,...i,ref:e}):(0,zl.jsx)(hBn,{side:o,...i,ref:e})})}),hBn=qr.forwardRef((t,e)=>{let n=CZ(Wj,t.__scopeTooltip),r=gUe(Wj,t.__scopeTooltip),o=qr.useRef(null),i=xZ(e,o),[s,a]=qr.useState(null),{trigger:l,onClose:c}=n,u=o.current,{onPointerInTransitChange:d}=r,f=qr.useCallback(()=>{a(null),d(!1)},[d]),p=qr.useCallback((m,h)=>{let g=m.currentTarget,v={x:m.clientX,y:m.clientY},y=bBn(v,g.getBoundingClientRect()),w=_Bn(v,y),_=xBn(h.getBoundingClientRect()),S=CBn([...w,..._]);a(S),d(!0)},[d]);return qr.useEffect(()=>()=>f(),[f]),qr.useEffect(()=>{if(l&&u){let m=g=>p(g,u),h=g=>p(g,l);return l.addEventListener("pointerleave",m),u.addEventListener("pointerleave",h),()=>{l.removeEventListener("pointerleave",m),u.removeEventListener("pointerleave",h)}}},[l,u,p,f]),qr.useEffect(()=>{if(s){let m=h=>{let g=h.target,v={x:h.clientX,y:h.clientY},y=l?.contains(g)||u?.contains(g),w=!SBn(v,s);y?f():w&&(f(),c())};return document.addEventListener("pointermove",m),()=>document.removeEventListener("pointermove",m)}},[l,u,s,c,f]),(0,zl.jsx)(AAt,{...t,ref:i})}),[gBn,yBn]=nde(SZ,{isInside:!1}),vBn=nAt("TooltipContent"),AAt=qr.forwardRef((t,e)=>{let{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...a}=t,l=CZ(Wj,n),c=rde(n),{onClose:u}=l;return qr.useEffect(()=>(document.addEventListener(mUe,u),()=>document.removeEventListener(mUe,u)),[u]),qr.useEffect(()=>{if(l.trigger){let d=f=>{f.target?.contains(l.trigger)&&u()};return window.addEventListener("scroll",d,{capture:!0}),()=>window.removeEventListener("scroll",d,{capture:!0})}},[l.trigger,u]),(0,zl.jsx)(QN,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:d=>d.preventDefault(),onDismiss:u,children:(0,zl.jsxs)(Oj,{"data-state":l.stateAttribute,...c,...a,ref:e,style:{...a.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[(0,zl.jsx)(vBn,{children:r}),(0,zl.jsx)(gBn,{scope:n,isInside:!0,children:(0,zl.jsx)(_At,{id:l.contentId,role:"tooltip",children:o||r})})]})})});PAt.displayName=Wj;EAt="TooltipArrow",wBn=qr.forwardRef((t,e)=>{let{__scopeTooltip:n,...r}=t,o=rde(n);return yBn(EAt,n).isInside?null:(0,zl.jsx)(Nj,{...o,...r,ref:e})});wBn.displayName=EAt;Vj=CAt,MAt=kAt,OAt=IAt,NAt=TAt,vUe=PAt});var kZ,sf,hr,gr,fr,Oc=b(()=>{kZ=L(B());ode();De();sf=Vj,hr=MAt,gr=OAt,fr=kZ.forwardRef(({className:t,sideOffset:e=4,...n},r)=>kZ.createElement(NAt,{container:activeDocument.body},kZ.createElement(vUe,{ref:r,sideOffset:e,className:J("tw-z-[50] tw-overflow-hidden tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-secondary tw-px-3 tw-py-1.5 tw-text-xs tw-text-normal tw-animate-in tw-fade-in-0 tw-zoom-in-95 data-[state=closed]:tw-animate-out data-[state=closed]:tw-fade-out-0 data-[state=closed]:tw-zoom-out-95 data-[side=bottom]:tw-slide-in-from-top-2 data-[side=left]:tw-slide-in-from-right-2 data-[side=right]:tw-slide-in-from-left-2 data-[side=top]:tw-slide-in-from-bottom-2",t),...n})));fr.displayName=vUe.displayName});var qw,RAt,rs,Lh=b(()=>{yt();Oc();Re();qw=L(B()),RAt=require("obsidian"),rs=({content:t,children:e,side:n="bottom",delayDuration:r=0,contentClassName:o,buttonClassName:i})=>{let s=RAt.Platform.isMobile,[a,l]=(0,qw.useState)(!1),c=qw.default.useRef(!1),u=()=>{s&&(c.current=!0)},d=()=>{s&&(l(!a),window.setTimeout(()=>{c.current=!1},100))};return qw.default.createElement(sf,{delayDuration:r},qw.default.createElement(hr,{open:a,onOpenChange:f=>{s&&c.current||l(f)}},qw.default.createElement(gr,{asChild:!0},e?qw.default.createElement("div",{onClick:d,onTouchStart:u,className:"tw-cursor-pointer"},e):qw.default.createElement(oe,{variant:"ghost",size:"sm",onClick:d,onTouchStart:u,className:`tw-inline-flex tw-size-6 tw-items-center tw-justify-center tw-p-0 hover:tw-bg-transparent hover:tw-text-normal ${i||""}`},qw.default.createElement(xh,{className:"tw-size-4"}))),qw.default.createElement(fr,{side:n,className:o},t)))}});function Fy({className:t,stopPropagation:e=!0}){return ide.default.createElement("span",{onClick:e?n=>n.stopPropagation():void 0,className:J("tw-flex tw-shrink-0 tw-items-center tw-text-warning",t)},ide.default.createElement(rs,{content:IBn,side:"top",delayDuration:0},ide.default.createElement(Wr,{className:"tw-size-3.5"})))}var ide,IBn,qj=b(()=>{De();Lh();Re();ide=L(B()),IBn="Bypasses Self-Host Mode \u2014 sends prompts to the cloud. Pick a self-hosted option to keep everything on your machine."});function xn(t){let e=LAt.get(t);if(e)return e;let n=(...r)=>{t(...r).catch(o=>{H("safeAsyncHandler: async handler rejected:",o)})};return LAt.set(t,n),n}var LAt,Hl=b(()=>{pe();LAt=new WeakMap});var $At,Eo,DAt,TBn,PBn,FAt=b(()=>{pm();yt();Sj();xk();De();qj();X8();V9();Re();$At=require("obsidian"),Eo=L(B());fm();ko();pe();Hl();DAt=({groups:t,onConfigure:e,onRemove:n,emptyMessage:r})=>{let o=(0,Eo.useRef)(null);return t.length===0?Eo.default.createElement("div",{className:J("tw-flex tw-flex-col tw-items-center tw-justify-center","tw-rounded-md tw-border tw-border-solid tw-border-border tw-p-6","tw-text-center tw-text-sm tw-text-muted"),"data-testid":"byok-table-empty"},r??"No providers yet \u2014 click + Add a provider to start."):Eo.default.createElement("div",{ref:o,className:"tw-flex tw-w-full tw-flex-col tw-gap-3",role:"list"},t.map(i=>Eo.default.createElement(TBn,{key:i.provider.providerId,group:i,onConfigure:()=>e(i.provider.providerId),onRemove:()=>n(i.provider.providerId),containerRef:o})))},TBn=({group:t,onConfigure:e,onRemove:n,containerRef:r})=>{let{provider:o,models:i}=t,[s,a]=(0,Eo.useState)(!1),l=Ey(),c=vn(),u=()=>{let m=Fw(o),h="tw-rounded-full tw-bg-success tw-text-success";return m?o.apiKeyKeychainId?{label:"API key set",variant:"default",className:h}:{label:"No key",variant:"secondary",className:"tw-rounded-full"}:{label:"Running",variant:"default",className:h}},d=async(m,h)=>{new _i(c,async()=>{try{await l.coordinator.removeConfiguredModel(m)}catch(v){H("[ByokGlobalTable] removeConfiguredModel failed",v),new $At.Notice("Failed to remove model.")}},`Remove ${h} from ${o.displayName}?`,"Remove model","Remove","Cancel").open()},f=u(),p=()=>Fw(o)?i.length===0?"No models added":`${i.length} ${i.length===1?"model":"models"}`:"Local models on your machine";return Eo.default.createElement(dx,{open:s,onOpenChange:a},Eo.default.createElement("div",{className:J("tw-rounded-xl tw-border tw-border-solid tw-border-border tw-bg-primary","tw-overflow-hidden"),role:"listitem","data-testid":`byok-provider-${o.providerId}`},Eo.default.createElement(fx,{asChild:!0},Eo.default.createElement("div",{role:"button",tabIndex:0,"aria-expanded":s,className:J("tw-flex tw-w-full tw-cursor-pointer tw-items-center tw-gap-2 tw-p-3","tw-transition-colors hover:tw-bg-modifier-hover","focus-visible:tw-outline-none focus-visible:tw-ring-2 focus-visible:tw-ring-ring"),onClick:()=>a(!s),onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),a(!s))}},Eo.default.createElement(Vi,{className:J("tw-size-4 tw-shrink-0 tw-text-muted tw-transition-transform tw-duration-200",s&&"tw-rotate-90"),"aria-hidden":"true"}),Eo.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-col tw-gap-0.5"},Eo.default.createElement("span",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-1"},Eo.default.createElement("span",{className:"tw-truncate tw-text-sm tw-font-semibold tw-text-normal"},o.displayName),t.needsSelfHostWarning&&Eo.default.createElement(Fy,null)),Eo.default.createElement("span",{className:"tw-text-xs tw-text-muted"},p())),Eo.default.createElement("div",{className:"tw-flex-1"}),Eo.default.createElement(ei,{variant:f.variant,className:J("tw-shrink-0",f.className)},f.label),Eo.default.createElement(up,null,Eo.default.createElement(dp,{asChild:!0},Eo.default.createElement(oe,{variant:"ghost",size:"icon",onClick:m=>m.stopPropagation(),"aria-label":`More actions for ${o.displayName}`,className:"tw-shrink-0"},Eo.default.createElement(vy,{className:"tw-size-4"}))),Eo.default.createElement(Ac,{align:"end",container:r.current},Eo.default.createElement(co,{onClick:m=>{m.stopPropagation(),e()}},Eo.default.createElement(RG,{className:"tw-mr-2 tw-size-4"}),"Edit key"),Eo.default.createElement(co,{onClick:m=>{m.stopPropagation(),n()},className:"tw-text-error"},Eo.default.createElement(Ts,{className:"tw-mr-2 tw-size-4"}),"Remove"))))),Eo.default.createElement(px,{className:"tw-overflow-hidden tw-transition-all tw-duration-200 data-[state=open]:tw-animate-in data-[state=closed]:tw-animate-out data-[state=closed]:tw-fade-out-0 data-[state=open]:tw-fade-in-0 data-[state=closed]:tw-slide-out-to-top-1 data-[state=open]:tw-slide-in-from-top-1"},i.length>0&&Eo.default.createElement("div",{className:"tw-flex tw-flex-col tw-pb-2"},i.map(m=>Eo.default.createElement(PBn,{key:m.configuredModelId,model:m,onRemove:xn(()=>d(m.configuredModelId,m.info.displayName))}))))))},PBn=({model:t,onRemove:e})=>Eo.default.createElement("div",{role:"listitem","data-testid":`byok-model-${t.configuredModelId}`,className:J("tw-group tw-relative tw-flex tw-items-center tw-gap-2","tw-px-3 tw-py-1.5 tw-pl-10 tw-text-sm tw-text-normal","tw-transition-colors hover:tw-bg-modifier-hover")},Eo.default.createElement("span",{className:"tw-flex-1 tw-truncate"},t.info.displayName),Eo.default.createElement(oe,{variant:"ghost",size:"icon",className:J("tw-size-6 tw-shrink-0 tw-text-muted hover:tw-text-warning","tw-opacity-0 tw-transition-opacity group-hover:tw-opacity-100","focus-visible:tw-opacity-100 focus-visible:tw-ring-2 focus-visible:tw-ring-ring"),onClick:n=>{n.stopPropagation(),e()},"aria-label":`Remove ${t.info.displayName}`,tabIndex:0},Eo.default.createElement(pn,{className:"tw-size-4"})))});var UAt,Uy,Kj=b(()=>{Pa();UAt=require("obsidian"),Uy=class extends UAt.Modal{constructor(n,r,o){super(n);this.root=null;r&&this.titleEl.setText(r),o&&this.modalEl.addClass(o)}onOpen(){let{contentEl:n}=this;n.empty(),this.root=Er(n,this.app),this.root.render(this.renderContent(()=>this.close()))}onClose(){this.root?.unmount(),this.root=null,this.contentEl.empty()}}});function BAt(t){return{id:t.id,displayName:t.displayName,providerType:t.providerType,defaultBaseUrl:t.defaultBaseUrl,requiresApiKey:!0,modelInputHint:EBn[t.providerType]??"Add a model id",catalogProviderId:t.id}}function bUe(t,e){let n=e.trim().toLowerCase();return n?t.displayName.toLowerCase().includes(n):!0}var Io,jAt,ABn,EBn,MBn,_Ue,HAt,OBn,zAt,NBn,sde,WAt=b(()=>{Kj();pk();De();Re();Io=L(B()),jAt=["anthropic","openai","google"],ABn={anthropic:"Claude family",openai:"GPT family",google:"Gemini family"},EBn={anthropic:"e.g. claude-sonnet-5",google:"e.g. gemini-2.5-pro","openai-compatible":"e.g. gpt-5",azure:"matches your Azure deployment name"};MBn=({catalogProviders:t,localTemplates:e,customTemplate:n,onPick:r})=>{let[o,i]=(0,Io.useState)(""),{recommended:s,local:a,more:l}=(0,Io.useMemo)(()=>{let u=new Map(t.map(m=>[m.id,m])),d=jAt.map(m=>u.get(m)).filter(m=>m!==void 0&&bUe(m,o)),f=e.filter(m=>bUe(m,o)),p=t.filter(m=>!jAt.includes(m.id)&&bUe(m,o)).sort((m,h)=>m.displayName.localeCompare(h.displayName));return{recommended:d,local:f,more:p}},[t,e,o]),c=s.length===0&&a.length===0&&l.length===0;return Io.default.createElement("div",{className:"tw-flex tw-h-full tw-min-h-0 tw-flex-col tw-gap-4 tw-overflow-hidden tw-px-2"},Io.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Pick a provider to configure."),Io.default.createElement(rf,{value:o,onChange:i,placeholder:"Search providers\u2026"}),Io.default.createElement("div",{className:"tw-flex tw-min-h-0 tw-flex-1 tw-flex-col tw-gap-4 tw-overflow-y-auto"},s.length>0&&Io.default.createElement("section",{"data-testid":"add-provider-recommended"},Io.default.createElement("div",{className:"tw-mb-2 tw-text-ui-smaller tw-font-medium tw-uppercase tw-tracking-wide tw-text-muted"},"Recommended"),Io.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-0.5"},s.map(u=>Io.default.createElement(zAt,{key:u.id,provider:u,description:ABn[u.id],onClick:()=>r(BAt(u))})))),a.length>0&&Io.default.createElement("section",{"data-testid":"add-provider-local"},Io.default.createElement("div",{className:"tw-mb-2 tw-text-ui-smaller tw-font-medium tw-uppercase tw-tracking-wide tw-text-muted"},"Self Host"),Io.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-0.5"},a.map(u=>Io.default.createElement(OBn,{key:u.id,template:u,onClick:()=>r(u)})))),l.length>0&&Io.default.createElement("section",{"data-testid":"add-provider-more"},Io.default.createElement("div",{className:"tw-mb-2 tw-text-ui-smaller tw-font-medium tw-uppercase tw-tracking-wide tw-text-muted"},"More providers"),Io.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-0.5"},l.map(u=>Io.default.createElement(zAt,{key:u.id,provider:u,onClick:()=>r(BAt(u))})))),c&&Io.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-dashed tw-border-border tw-px-4 tw-py-6 tw-text-center tw-text-sm tw-text-muted"},"No providers match your search.")),Io.default.createElement(NBn,{onClick:()=>r(n)}))},_Ue=({onClick:t,className:e,testId:n,ariaLabel:r,children:o})=>Io.default.createElement("div",{role:"button",tabIndex:0,onClick:t,onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),t())},"data-testid":n,"aria-label":r,className:e},o),HAt=J("tw-flex tw-w-full tw-cursor-pointer tw-items-center tw-gap-3 tw-rounded-md","tw-border tw-border-solid tw-border-transparent tw-px-3 tw-py-1.5 tw-text-left","hover:tw-border-border hover:tw-bg-primary-alt/40"),OBn=({template:t,onClick:e})=>{let n=t.defaultBaseUrl?t.defaultBaseUrl.replace(/^https?:\/\//,""):"custom endpoint";return Io.default.createElement(_Ue,{onClick:e,testId:`add-provider-template-${t.id}`,ariaLabel:`Add ${t.displayName} provider`,className:HAt},Io.default.createElement("span",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-items-baseline tw-gap-1.5 tw-truncate"},Io.default.createElement("span",{className:"tw-truncate tw-text-sm tw-text-normal"},t.displayName),Io.default.createElement("span",{className:"tw-truncate tw-text-ui-smaller tw-text-muted"},"\u2014 ",n)),Io.default.createElement(zs,{className:"tw-size-4 tw-shrink-0 tw-text-muted"}))},zAt=({provider:t,onClick:e,description:n})=>Io.default.createElement(_Ue,{onClick:e,testId:`add-provider-card-${t.id}`,ariaLabel:`Add ${t.displayName} provider`,className:HAt},Io.default.createElement("span",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-items-baseline tw-gap-1.5 tw-truncate"},Io.default.createElement("span",{className:"tw-truncate tw-text-sm tw-text-normal"},t.displayName),n&&Io.default.createElement("span",{className:"tw-truncate tw-text-ui-smaller tw-text-muted"},"\u2014 ",n)),Io.default.createElement(zs,{className:"tw-size-4 tw-shrink-0 tw-text-muted"})),NBn=({onClick:t})=>Io.default.createElement(_Ue,{onClick:t,testId:"add-provider-custom-cta",ariaLabel:"Add a custom provider",className:J("tw-mt-2 tw-flex tw-w-full tw-items-center tw-justify-center tw-gap-1.5 tw-rounded-md tw-px-4 tw-py-5","tw-border tw-border-solid tw-bg-interactive-accent/10 tw-border-interactive-accent/40","tw-cursor-pointer tw-font-medium tw-text-accent tw-shadow-none hover:tw-bg-interactive-accent/20")},Io.default.createElement(zs,{className:"tw-size-4"}),"Add a custom provider"),sde=class extends Uy{constructor(n,r){super(n,"Add a provider");this.opts=r}onOpen(){this.modalEl.addClasses(["tw-flex","tw-h-[70vh]","tw-flex-col"]),this.contentEl.addClasses(["tw-flex","tw-min-h-0","tw-flex-1","tw-flex-col","tw-overflow-hidden"]),super.onOpen()}renderContent(n){return Io.default.createElement(MBn,{catalogProviders:this.opts.catalogProviders,localTemplates:this.opts.localTemplates,customTemplate:this.opts.customTemplate,onPick:r=>{this.opts.onPick(r),n()}})}}});function VAt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function qAt(...t){return e=>{let n=!1,r=t.map(o=>{let i=VAt(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():VAt(t[o],null)}}}}var RBn,KAt=b(()=>{RBn=L(B(),1)});function GAt(t){let e=LBn(t),n=Nc.forwardRef((r,o)=>{let{children:i,...s}=r,a=Nc.Children.toArray(i),l=a.find(DBn);if(l){let c=l.props.children,u=a.map(d=>d===l?Nc.Children.count(c)>1?Nc.Children.only(null):Nc.isValidElement(c)?c.props.children:null:d);return(0,ade.jsx)(e,{...s,ref:o,children:Nc.isValidElement(c)?Nc.cloneElement(c,void 0,u):null})}return(0,ade.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function LBn(t){let e=Nc.forwardRef((n,r)=>{let{children:o,...i}=n;if(Nc.isValidElement(o)){let s=UBn(o),a=FBn(i,o.props);return o.type!==Nc.Fragment&&(a.ref=r?qAt(r,s):s),Nc.cloneElement(o,a)}return Nc.Children.count(o)>1?Nc.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}function DBn(t){return Nc.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===$Bn}function FBn(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function UBn(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Nc,ade,$Bn,ZAt=b(()=>{Nc=L(B(),1);KAt();ade=L(Mt(),1);$Bn=Symbol("radix.slottable")});var YAt,jBn,JAt,BBn,XAt,QAt=b(()=>{YAt=L(B(),1),jBn=L(Es(),1);ZAt();JAt=L(Mt(),1),BBn=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],XAt=BBn.reduce((t,e)=>{let n=GAt(`Primitive.${e}`),r=YAt.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,JAt.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{})});var eEt,tEt,zBn,nEt,xUe,rEt=b(()=>{"use client";eEt=L(B(),1);QAt();tEt=L(Mt(),1),zBn="Label",nEt=eEt.forwardRef((t,e)=>(0,tEt.jsx)(XAt.label,{...t,ref:e,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(t.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));nEt.displayName=zBn;xUe=nEt});var lde,WBn,$h,IZ=b(()=>{lde=L(B());rEt();nse();De();WBn=$2("tw-text-sm tw-font-medium tw-leading-none peer-disabled:tw-cursor-not-allowed peer-disabled:tw-opacity-70"),$h=lde.forwardRef(({className:t,...e},n)=>lde.createElement(xUe,{ref:n,className:J(WBn(),t),...e}));$h.displayName=xUe.displayName});var Gj,Dh,Zj=b(()=>{Gj=L(B());IZ();Dh=({label:t,required:e=!1,error:n=!1,description:r,errorMessage:o="This field is required",children:i})=>Gj.default.createElement("div",{className:"tw-space-y-2"},t&&Gj.default.createElement($h,{className:n?"tw-text-error":""},t," ",e&&Gj.default.createElement("span",{className:"tw-text-error"},"*")),r&&Gj.default.createElement("p",{className:"tw-text-sm tw-text-muted"},r),i,n&&Gj.default.createElement("p",{className:"tw-text-xs tw-text-error"},o))});function Yj({value:t,onChange:e,placeholder:n,disabled:r,className:o}){let[i,s]=(0,jy.useState)(!1),a=(0,jy.useRef)(null);return(0,jy.useEffect)(()=>{a.current&&(a.current.value=t??"")},[t]),jy.default.createElement("div",{className:J("tw-relative",o)},jy.default.createElement(Ir,{ref:a,type:i?"text":"password",onChange:l=>e?.(l.target.value),placeholder:n,disabled:r,className:J("tw-w-full !tw-pr-7")}),jy.default.createElement("div",{onClick:()=>!r&&s(!i),className:J("tw-absolute tw-inset-y-0 tw-right-2 tw-flex tw-items-center tw-justify-center","tw-cursor-pointer",r&&"tw-cursor-not-allowed tw-opacity-50"),role:"button","aria-label":i?"Hide password":"Show password"},i?jy.default.createElement($C,{className:J("tw-size-3.5","tw-text-muted/60 hover:tw-text-accent","tw-transition-colors tw-duration-200")}):jy.default.createElement(fG,{className:J("tw-size-3.5","tw-text-muted/60 hover:tw-text-accent","tw-transition-colors tw-duration-200")})))}var jy,cde=b(()=>{jy=L(B());hl();De();Re()});var TZ,fp,OP=b(()=>{TZ=L(B());De();fp=TZ.forwardRef(({checked:t=!1,onCheckedChange:e,disabled:n=!1,className:r,...o},i)=>{let s=()=>{n||e?.(!t)},a=l=>{n||(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),e?.(!t))};return TZ.createElement("div",{role:"switch","aria-checked":t,"aria-disabled":n,"data-state":t?"checked":"unchecked","data-disabled":n?"":void 0,ref:i,tabIndex:n?-1:0,className:J("tw-relative tw-inline-flex tw-h-[calc(var(--toggle-s-thumb-height)_+_var(--toggle-s-border-width)*2)] tw-w-[var(--toggle-s-width)] tw-shrink-0 tw-cursor-pointer tw-items-center tw-rounded-[var(--toggle-radius)] tw-transition-colors","focus-visible:tw-outline-none focus-visible:tw-ring-2 focus-visible:tw-ring-ring focus-visible:tw-ring-offset-2",t?"tw-bg-interactive-accent":"tw-bg-[--background-modifier-border-hover]",n&&"tw-cursor-not-allowed tw-opacity-50",r),onClick:s,onKeyDown:a,...o},TZ.createElement("div",{className:J("tw-pointer-events-none tw-block tw-h-[var(--toggle-s-thumb-height)] tw-w-[var(--toggle-s-thumb-width)] tw-rounded-[var(--toggle-thumb-radius)] tw-bg-toggle-thumb tw-shadow-sm tw-ring-0 tw-transition-transform",t?"tw-translate-x-[calc(var(--toggle-s-width)_-_var(--toggle-s-thumb-width)_-_var(--toggle-s-border-width))]":"tw-translate-x-[var(--toggle-s-border-width)]")}))});fp.displayName="SettingSwitch"});var Kw,VBn,oEt,iEt=b(()=>{yt();OP();Oc();Re();Kw=L(B()),VBn="Some Quick Chat models require CORS compatibility to connect. When enabled, responses appear only after they finish instead of streaming token by token.",oEt=({checked:t,onCheckedChange:e})=>Kw.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-gap-4"},Kw.default.createElement("div",{className:"tw-inline-flex tw-items-center tw-gap-1"},Kw.default.createElement("span",{className:"tw-text-sm tw-font-medium tw-text-normal"},"Enable CORS"),Kw.default.createElement(sf,{delayDuration:0},Kw.default.createElement(hr,null,Kw.default.createElement(gr,{asChild:!0},Kw.default.createElement(oe,{type:"button",variant:"ghost",size:"sm","aria-label":"About Quick Chat CORS compatibility",className:"tw-size-6 tw-p-0 tw-text-muted hover:tw-bg-transparent hover:tw-text-normal"},Kw.default.createElement(jC,{className:"tw-size-4"}))),Kw.default.createElement(fr,{side:"top",className:"tw-w-72"},VBn)))),Kw.default.createElement(fp,{checked:t,onCheckedChange:e,"aria-label":"Enable CORS"}))});function sEt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function SUe(...t){return e=>{let n=!1,r=t.map(o=>{let i=sEt(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():sEt(t[o],null)}}}}function PZ(...t){return aEt.useCallback(SUe(...t),t)}var aEt,ude=b(()=>{aEt=L(B(),1)});function cEt(t,e=[]){let n=[];function r(i,s){let a=Ck.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=Ck.useMemo(()=>m,Object.values(m));return(0,lEt.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=Ck.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>Ck.createContext(s));return function(a){let l=a?.[t]||i;return Ck.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,qBn(o,...e)]}function qBn(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return Ck.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var Ck,lEt,uEt=b(()=>{Ck=L(B(),1),lEt=L(Mt(),1)});function CUe(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var rlo,dEt=b(()=>{rlo=!!(typeof window<"u"&&window.document&&window.document.createElement)});var fEt,yR,dde=b(()=>{fEt=L(B(),1),yR=globalThis?.document?fEt.useLayoutEffect:()=>{}});function pEt({prop:t,defaultProp:e,onChange:n=()=>{},caller:r}){let[o,i,s]=GBn({defaultProp:e,onChange:n}),a=t!==void 0,l=a?t:o;{let u=By.useRef(t!==void 0);By.useEffect(()=>{let d=u.current;d!==a&&console.warn(`${r} is changing from ${d?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=a},[a,r])}let c=By.useCallback(u=>{if(a){let d=ZBn(u)?u(t):u;d!==t&&s.current?.(d)}else i(u)},[a,t,i,s]);return[l,c]}function GBn({defaultProp:t,onChange:e}){let[n,r]=By.useState(t),o=By.useRef(n),i=By.useRef(e);return KBn(()=>{i.current=e},[e]),By.useEffect(()=>{o.current!==n&&(i.current?.(n),o.current=n)},[n,o]),[n,r,i]}function ZBn(t){return typeof t=="function"}var By,fde,KBn,alo,mEt=b(()=>{By=L(B(),1);dde();fde=L(B(),1),KBn=By[" useInsertionEffect ".trim().toString()]||yR;alo=Symbol("RADIX:SYNC_STATE")});function hEt(t){let e=pde.useRef({value:t,previous:t});return pde.useMemo(()=>(e.current.value!==t&&(e.current.previous=e.current.value,e.current.value=t),e.current.previous),[t])}var pde,gEt=b(()=>{pde=L(B(),1)});function vEt(t){let[e,n]=yEt.useState(void 0);return yR(()=>{if(t){n({width:t.offsetWidth,height:t.offsetHeight});let r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;let i=o[0],s,a;if("borderBoxSize"in i){let l=i.borderBoxSize,c=Array.isArray(l)?l[0]:l;s=c.inlineSize,a=c.blockSize}else s=t.offsetWidth,a=t.offsetHeight;n({width:s,height:a})});return r.observe(t,{box:"border-box"}),()=>r.unobserve(t)}else n(void 0)},[t]),e}var yEt,wEt=b(()=>{yEt=L(B(),1);dde()});function YBn(t,e){return bEt.useReducer((n,r)=>e[n][r]??n,t)}function JBn(t){let[e,n]=bm.useState(),r=bm.useRef(null),o=bm.useRef(t),i=bm.useRef("none"),s=t?"mounted":"unmounted",[a,l]=YBn(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return bm.useEffect(()=>{let c=mde(r.current);i.current=a==="mounted"?c:"none"},[a]),yR(()=>{let c=r.current,u=o.current;if(u!==t){let f=i.current,p=mde(c);t?l("MOUNT"):p==="none"||c?.display==="none"?l("UNMOUNT"):l(u&&f!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,l]),yR(()=>{if(e){let c,u=e.ownerDocument.defaultView??window,d=p=>{let h=mde(r.current).includes(CSS.escape(p.animationName));if(p.target===e&&h&&(l("ANIMATION_END"),!o.current)){let g=e.style.animationFillMode;e.style.animationFillMode="forwards",c=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=g)})}},f=p=>{p.target===e&&(i.current=mde(r.current))};return e.addEventListener("animationstart",f),e.addEventListener("animationcancel",d),e.addEventListener("animationend",d),()=>{u.clearTimeout(c),e.removeEventListener("animationstart",f),e.removeEventListener("animationcancel",d),e.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:bm.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function mde(t){return t?.animationName||"none"}function XBn(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var bm,bEt,kUe,_Et=b(()=>{"use client";bm=L(B(),1);ude();dde();bEt=L(B(),1);kUe=t=>{let{present:e,children:n}=t,r=JBn(e),o=typeof n=="function"?n({present:r.isPresent}):bm.Children.only(n),i=PZ(r.ref,XBn(o));return typeof n=="function"||r.isPresent?bm.cloneElement(o,{ref:i}):null};kUe.displayName="Presence"});function xEt(t){let e=QBn(t),n=Rc.forwardRef((r,o)=>{let{children:i,...s}=r,a=Rc.Children.toArray(i),l=a.find(tzn);if(l){let c=l.props.children,u=a.map(d=>d===l?Rc.Children.count(c)>1?Rc.Children.only(null):Rc.isValidElement(c)?c.props.children:null:d);return(0,hde.jsx)(e,{...s,ref:o,children:Rc.isValidElement(c)?Rc.cloneElement(c,void 0,u):null})}return(0,hde.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function QBn(t){let e=Rc.forwardRef((n,r)=>{let{children:o,...i}=n;if(Rc.isValidElement(o)){let s=rzn(o),a=nzn(i,o.props);return o.type!==Rc.Fragment&&(a.ref=r?SUe(r,s):s),Rc.cloneElement(o,a)}return Rc.Children.count(o)>1?Rc.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}function tzn(t){return Rc.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===ezn}function nzn(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function rzn(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Rc,hde,ezn,SEt=b(()=>{Rc=L(B(),1);ude();hde=L(Mt(),1);ezn=Symbol("radix.slottable")});var CEt,ozn,kEt,izn,gde,IEt=b(()=>{CEt=L(B(),1),ozn=L(Es(),1);SEt();kEt=L(Mt(),1),izn=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],gde=izn.reduce((t,e)=>{let n=xEt(`Primitive.${e}`),r=CEt.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,kEt.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{})});function lzn(t){let{__scopeCheckbox:e,checked:n,children:r,defaultChecked:o,disabled:i,form:s,name:a,onCheckedChange:l,required:c,value:u="on",internal_do_not_use_render:d}=t,[f,p]=pEt({prop:n,defaultProp:o??!1,onChange:l,caller:yde}),[m,h]=pp.useState(null),[g,v]=pp.useState(null),y=pp.useRef(!1),w=m?!!s||!!m.closest("form"):!0,_={checked:f,disabled:i,setChecked:p,control:m,setControl:h,name:a,form:s,value:u,hasConsumerStoppedPropagationRef:y,required:c,defaultChecked:NP(o)?!1:o,isFormControl:w,bubbleInput:g,setBubbleInput:v};return(0,Fh.jsx)(azn,{scope:e,..._,children:czn(d)?d(_):r})}function czn(t){return typeof t=="function"}function NP(t){return t==="indeterminate"}function OEt(t){return NP(t)?"indeterminate":t?"checked":"unchecked"}var pp,Fh,yde,szn,Tlo,azn,IUe,TEt,PEt,vde,AEt,TUe,EEt,MEt,NEt=b(()=>{"use client";pp=L(B(),1);ude();uEt();dEt();mEt();gEt();wEt();_Et();IEt();Fh=L(Mt(),1),yde="Checkbox",[szn,Tlo]=cEt(yde),[azn,IUe]=szn(yde);TEt="CheckboxTrigger",PEt=pp.forwardRef(({__scopeCheckbox:t,onKeyDown:e,onClick:n,...r},o)=>{let{control:i,value:s,disabled:a,checked:l,required:c,setControl:u,setChecked:d,hasConsumerStoppedPropagationRef:f,isFormControl:p,bubbleInput:m}=IUe(TEt,t),h=PZ(o,u),g=pp.useRef(l);return pp.useEffect(()=>{let v=i?.form;if(v){let y=()=>d(g.current);return v.addEventListener("reset",y),()=>v.removeEventListener("reset",y)}},[i,d]),(0,Fh.jsx)(gde.button,{type:"button",role:"checkbox","aria-checked":NP(l)?"mixed":l,"aria-required":c,"data-state":OEt(l),"data-disabled":a?"":void 0,disabled:a,value:s,...r,ref:h,onKeyDown:CUe(e,v=>{v.key==="Enter"&&v.preventDefault()}),onClick:CUe(n,v=>{d(y=>NP(y)?!0:!y),m&&p&&(f.current=v.isPropagationStopped(),f.current||v.stopPropagation())})})});PEt.displayName=TEt;vde=pp.forwardRef((t,e)=>{let{__scopeCheckbox:n,name:r,checked:o,defaultChecked:i,required:s,disabled:a,value:l,onCheckedChange:c,form:u,...d}=t;return(0,Fh.jsx)(lzn,{__scopeCheckbox:n,checked:o,defaultChecked:i,disabled:a,required:s,onCheckedChange:c,name:r,form:u,value:l,internal_do_not_use_render:({isFormControl:f})=>(0,Fh.jsxs)(Fh.Fragment,{children:[(0,Fh.jsx)(PEt,{...d,ref:e,__scopeCheckbox:n}),f&&(0,Fh.jsx)(MEt,{__scopeCheckbox:n})]})})});vde.displayName=yde;AEt="CheckboxIndicator",TUe=pp.forwardRef((t,e)=>{let{__scopeCheckbox:n,forceMount:r,...o}=t,i=IUe(AEt,n);return(0,Fh.jsx)(kUe,{present:r||NP(i.checked)||i.checked===!0,children:(0,Fh.jsx)(gde.span,{"data-state":OEt(i.checked),"data-disabled":i.disabled?"":void 0,...o,ref:e,style:{pointerEvents:"none",...t.style}})})});TUe.displayName=AEt;EEt="CheckboxBubbleInput",MEt=pp.forwardRef(({__scopeCheckbox:t,...e},n)=>{let{control:r,hasConsumerStoppedPropagationRef:o,checked:i,defaultChecked:s,required:a,disabled:l,name:c,value:u,form:d,bubbleInput:f,setBubbleInput:p}=IUe(EEt,t),m=PZ(n,p),h=hEt(i),g=vEt(r);pp.useEffect(()=>{let y=f;if(!y)return;let w=window.HTMLInputElement.prototype,S=Object.getOwnPropertyDescriptor(w,"checked").set,I=!o.current;if(h!==i&&S){let C=new Event("click",{bubbles:I});y.indeterminate=NP(i),S.call(y,NP(i)?!1:i),y.dispatchEvent(C)}},[f,h,i,o]);let v=pp.useRef(NP(i)?!1:i);return(0,Fh.jsx)(gde.input,{type:"checkbox","aria-hidden":!0,defaultChecked:s??v.current,required:a,disabled:l,name:c,value:u,form:d,...e,tabIndex:-1,ref:m,style:{...e.style,...g,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});MEt.displayName=EEt});var Jj,Wl,RP=b(()=>{Jj=L(B());NEt();Re();De();Wl=Jj.forwardRef(({className:t,...e},n)=>Jj.createElement(vde,{ref:n,className:J("tw-border-solid !tw-bg-transparent tw-p-0 !tw-shadow tw-transition-colors","hover:!tw-bg-interactive-accent hover:!tw-text-on-accent data-[state=checked]:!tw-bg-interactive-accent data-[state=checked]:!tw-text-on-accent","tw-peer tw-size-4 tw-shrink-0 tw-rounded-sm tw-border tw-border-interactive-accent focus-visible:tw-outline-none focus-visible:tw-ring-1 focus-visible:tw-ring-ring disabled:tw-cursor-not-allowed disabled:tw-opacity-50",t),...e},Jj.createElement(TUe,{className:J("tw-flex tw-items-center tw-justify-center tw-text-current")},Jj.createElement(Hr,{className:"tw-size-4"}))));Wl.displayName=vde.displayName});function AZ(t){return t===void 0?!1:!t.includes("vision")}var vR,dzn,EZ,Xj,MZ=b(()=>{vR=L(B());Mie();Re();gt();Lh();dzn="This model does not support image inputs.";EZ=({capabilities:t,iconSize:e=16})=>t===void 0||t.includes("vision")?null:vR.default.createElement(rs,{content:dzn,side:"top"},vR.default.createElement($C,{className:"tw-text-muted",style:{width:e,height:e},"data-testid":"model-cap-no-vision"})),Xj=({model:t,iconSize:e=14})=>{let n=t.displayName||t.name;return vR.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-1"},vR.default.createElement("span",{className:"tw-truncate tw-text-sm hover:tw-text-normal"},n),AZ(t.capabilities)&&vR.default.createElement("div",{className:"tw-flex tw-shrink-0 tw-items-center tw-gap-0.5"},vR.default.createElement(EZ,{capabilities:t.capabilities,iconSize:e})))}});function REt(t){return t?t>=1e6?`${(t/1e6).toFixed(1).replace(/\.0$/,"")}M`:t>=1e3?`${Math.round(t/1e3)}K`:String(t):""}function LEt(t){if(!t)return"";let e=new Date(t);return isNaN(e.getTime())?"":e.toLocaleString("en-US",{month:"short",year:"2-digit",timeZone:"UTC"})}var $Et=b(()=>{});function DEt(t,e,n){let r=o=>{if(!o)return-1/0;let i=Date.parse(o);return Number.isNaN(i)?-1/0:i};return[...t].sort((o,i)=>{let s=e.has(o.id),a=e.has(i.id);if(s!==a)return s?-1:1;if(n){let l=n.has(o.id),c=n.has(i.id);if(l!==c)return l?-1:1}return r(i.releaseDate)-r(o.releaseDate)})}var FEt=b(()=>{});var $i,UEt,jEt=b(()=>{pm();yt();RP();Zj();hl();MZ();pk();De();UNe();$Et();FEt();Re();$i=L(B()),UEt=({availableModels:t,selected:e,onToggle:n,onAddId:r,onRemoveId:o,query:i,onQueryChange:s,modelInputHint:a,fetching:l,fetchError:c,customIds:u})=>{let[d,f]=(0,$i.useState)(""),p=(0,$i.useMemo)(()=>{let g=i?.trim().toLowerCase(),v=g?t.filter(y=>y.displayName.toLowerCase().includes(g)||y.id.toLowerCase().includes(g)):t;return DEt(v,e,u)},[t,i,e,u]),m=p.reduce((g,v)=>e.has(v.id)?g+1:g,0),h=()=>{let g=d.trim();g&&(r(g),f(""))};return $i.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},$i.default.createElement(Dh,{label:"Model ID"},$i.default.createElement("div",{className:"tw-flex tw-gap-2"},$i.default.createElement(Ir,{className:"tw-flex-1",value:d,onChange:g=>f(g.target.value),onKeyDown:g=>{g.key==="Enter"&&(g.preventDefault(),h())},placeholder:a??"Enter a model ID","data-testid":"model-checklist-manual-input"}),$i.default.createElement(oe,{variant:"secondary",onClick:h,disabled:!d.trim()},"Add"))),$i.default.createElement(rf,{value:i,onChange:s,placeholder:"Search available models\u2026"}),l&&$i.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2 tw-text-xs tw-text-muted"},$i.default.createElement(Dr,{className:"tw-size-3.5 tw-shrink-0 tw-animate-spin"}),$i.default.createElement("span",null,"Loading models\u2026")),c&&$i.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5 tw-text-xs tw-text-error"},$i.default.createElement(nm,{className:"tw-size-3.5 tw-shrink-0"}),$i.default.createElement("span",null,c)),p.length>0?$i.default.createElement("div",{className:J("tw-flex tw-max-h-[50vh] tw-flex-col tw-overflow-y-auto tw-rounded-md","tw-border tw-border-solid tw-border-border"),role:"list","data-testid":"model-checklist"},p.map((g,v)=>{let y=e.has(g.id),w=REt(g.limits?.context),_=LEt(g.releaseDate),S=v===m-1&&m<p.length,I=o!==void 0&&u?.has(g.id)===!0,C=Uw(g);return $i.default.createElement("label",{key:g.id,role:"listitem","data-testid":`model-row-${g.id}`,className:J("tw-group tw-grid tw-cursor-pointer tw-items-center tw-gap-3 tw-px-3 tw-py-1.5 tw-text-sm","hover:tw-bg-primary-alt/40",I?"tw-grid-cols-[auto_1fr_auto_auto_auto]":"tw-grid-cols-[auto_1fr_auto_auto]",S&&"copilot-divider-b")},$i.default.createElement(Wl,{checked:y,onCheckedChange:k=>n(g.id,k===!0)}),$i.default.createElement("span",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-2"},$i.default.createElement("span",{className:"tw-truncate tw-text-normal"},g.displayName),g.isEmbedding&&$i.default.createElement(ei,{variant:"secondary",className:"tw-shrink-0 tw-text-ui-smaller"},"Embedding"),AZ(C)&&$i.default.createElement("span",{className:"tw-flex tw-shrink-0 tw-items-center tw-gap-0.5"},$i.default.createElement(EZ,{capabilities:C,iconSize:14}))),$i.default.createElement("span",{className:"tw-shrink-0 tw-text-xs tw-text-muted"},w),$i.default.createElement("span",{className:"tw-w-20 tw-shrink-0 tw-text-right tw-text-xs tw-text-muted"},_),I&&$i.default.createElement(oe,{variant:"ghost",size:"icon","aria-label":`Remove ${g.id}`,"data-testid":`model-row-remove-${g.id}`,onClick:k=>{k.preventDefault(),k.stopPropagation(),o(g.id)}},$i.default.createElement(pn,{className:"tw-size-4"})))})):$i.default.createElement("div",{className:J("tw-rounded-md tw-border tw-border-dashed tw-border-border tw-p-4","tw-text-center tw-text-sm tw-text-muted"),"data-testid":"model-checklist-empty"},l?"Loading models\u2026":i.trim()?"No models match the current filters.":"No models discovered \u2014 enter a model ID above or test your credentials."))}});async function Qj(t,e,n=fzn){let r,o=new Promise((i,s)=>{r=window.setTimeout(()=>s(new PUe(`Timed out after ${n}ms`)),n)});try{return await Promise.race([bh(t,e),o])}finally{r!==void 0&&window.clearTimeout(r)}}async function eB(t){try{let e=(await t.text()).trim();return e.length>BEt?`${e.slice(0,BEt)}\u2026`:e}catch{return""}}var fzn,BEt,PUe,wde=b(()=>{ut();fzn=8e3,BEt=200,PUe=class extends Error{constructor(){super(...arguments);this.name="ListModelsTimeoutError"}}});async function zEt(t,e={}){let n=t.trim();if(!n)return{ok:!1,message:"Enter a base URL before fetching models."};let r=n.replace(/\/$/,"").replace(/\/v1$/,""),o={"anthropic-version":pzn};e.apiKey&&(o["x-api-key"]=e.apiKey);try{let i=await Qj(`${r}/v1/models`,{method:"GET",headers:o},e.timeoutMs);return await mzn(i)}catch(i){return{ok:!1,message:i instanceof Error?i.message:String(i)}}}async function mzn(t){let{status:e}=t;if(e===401||e===403)return{ok:!1,message:"Authentication failed \u2014 check your API key."};if(e<200||e>=300){let s=await eB(t);return{ok:!1,message:s?`HTTP ${e}: ${s}`:`HTTP ${e}`}}let n;try{n=await t.json()}catch{return{ok:!1,message:"Endpoint returned an unreadable response."}}let r=n?.data;if(!Array.isArray(r))return{ok:!1,message:"Endpoint did not return a model list."};let o=new Set,i=[];for(let s of r){let a=s?.id;if(typeof a!="string")continue;let l=a.trim();!l||o.has(l)||(o.add(l),i.push(l))}return{ok:!0,modelIds:i}}var pzn,HEt=b(()=>{wde();pzn="2023-06-01"});async function VEt(t,e={}){let n=t.trim();if(!n)return{ok:!1,message:"Enter a base URL before fetching models."};let r=n.replace(/\/$/,"").replace(/\/v1(beta)?$/,""),o=e.apiKey?`?key=${encodeURIComponent(e.apiKey)}`:"",i=`${r}/v1beta/models${o}`;try{let s=await Qj(i,{method:"GET",headers:{}},e.timeoutMs);return await hzn(s)}catch(s){return{ok:!1,message:s instanceof Error?s.message:String(s)}}}async function hzn(t){let{status:e}=t;if(e===401||e===403)return{ok:!1,message:"Authentication failed \u2014 check your API key."};if(e<200||e>=300){let s=await eB(t);return{ok:!1,message:s?`HTTP ${e}: ${s}`:`HTTP ${e}`}}let n;try{n=await t.json()}catch{return{ok:!1,message:"Endpoint returned an unreadable response."}}let r=n?.models;if(!Array.isArray(r))return{ok:!1,message:"Endpoint did not return a model list."};let o=new Set,i=[];for(let s of r){let a=s?.name;if(typeof a!="string")continue;let l=a.trim();if(!l)continue;let c=l.startsWith(WEt)?l.slice(WEt.length):l;!c||o.has(c)||(o.add(c),i.push(c))}return{ok:!0,modelIds:i}}var WEt,qEt=b(()=>{wde();WEt="models/"});async function KEt(t,e={}){let n=t.trim();if(!n)return{ok:!1,message:"Enter a base URL before fetching models."};let r=n.replace(/\/$/,""),o={};e.apiKey&&(o.Authorization=`Bearer ${e.apiKey}`),e.openAIOrgId&&(o["OpenAI-Organization"]=e.openAIOrgId);let i=await gzn(r,o,e.timeoutMs);return i.ok?{ok:!0,modelIds:i.modelIds}:{ok:!1,message:i.status===404&&!/\/v1(\/|$)/.test(r)?`${i.message} If your endpoint serves the OpenAI API under /v1, add it to the base URL.`:i.message}}async function gzn(t,e,n){try{let r=await Qj(`${t}/models`,{method:"GET",headers:e},n);return await yzn(r)}catch(r){return{ok:!1,message:r instanceof Error?r.message:String(r)}}}async function yzn(t){let{status:e}=t;if(e===401||e===403)return{ok:!1,message:"Authentication failed \u2014 check your API key.",status:e};if(e<200||e>=300){let s=await eB(t);return{ok:!1,message:s?`HTTP ${e}: ${s}`:`HTTP ${e}`,status:e}}let n;try{n=await t.json()}catch{return{ok:!1,message:"Endpoint returned an unreadable response.",status:e}}let r=n?.data;if(!Array.isArray(r))return{ok:!1,message:"Endpoint did not return a model list.",status:e};let o=new Set,i=[];for(let s of r){let a=s?.id;if(typeof a!="string")continue;let l=a.trim();!l||o.has(l)||(o.add(l),i.push(l))}return{ok:!0,modelIds:i}}var GEt=b(()=>{wde()});async function ZEt(t,e,n={}){switch(t){case"openai-compatible":{let r=typeof n.extras?.openAIOrgId=="string"?n.extras.openAIOrgId:void 0;return KEt(e,{apiKey:n.apiKey,openAIOrgId:r,timeoutMs:n.timeoutMs})}case"anthropic":return zEt(e,{apiKey:n.apiKey,timeoutMs:n.timeoutMs});case"google":return VEt(e,{apiKey:n.apiKey,timeoutMs:n.timeoutMs});case"azure":return W(`Listing provider models for ${t} is not yet supported`),null}}var YEt=b(()=>{HEt();qEt();GEt();pe()});function JEt({mode:t,providerId:e,providerType:n,effectiveBaseUrl:r,existingModels:o,catalogMetadata:i,apiKey:s,extras:a,requiresApiKey:l,providerHydrated:c,api:u}){let[d,f]=(0,Ks.useState)(()=>t==="edit"?new Set(o.map(Q=>Q.info.id)):new Set),[p,m]=(0,Ks.useState)([]),[h,g]=(0,Ks.useState)([]),[v,y]=(0,Ks.useState)(()=>new Set),[w,_]=(0,Ks.useState)(!1),[S,I]=(0,Ks.useState)(null),C=(0,Ks.useMemo)(()=>new Map(o.map(Q=>[Q.info.id,Q.info])),[o]),k=(0,Ks.useCallback)(Q=>i[Q]??C.get(Q)??{id:Q,displayName:Q,...D9(Q)?{isEmbedding:!0}:{}},[i,C]),T=(0,Ks.useMemo)(()=>{let Q=new Set,ne=[],ee=ae=>{Q.has(ae)||(Q.add(ae),ne.push(k(ae)))};for(let ae of o)v.has(ae.info.id)||ee(ae.info.id);for(let ae of p)ee(ae);for(let ae of h)ee(ae);return ne},[o,p,h,k,v]),P=(0,Ks.useMemo)(()=>{let Q=new Set(h),ne=new Set(p);for(let ee of o)v.has(ee.info.id)||!i[ee.info.id]&&!ne.has(ee.info.id)&&Q.add(ee.info.id);return Q},[h,p,o,i,v]),E=(0,Ks.useRef)(new Set);(0,Ks.useEffect)(()=>{let Q=new Set;for(let ne of C.keys())Q.add(ne);for(let ne of p)Q.add(ne);for(let ne of h)Q.add(ne);E.current=Q},[C,p,h]);let O=(0,Ks.useCallback)(async()=>{if(!(!n||!r)){_(!0),I(null);try{let Q=s||null;!Q&&t==="edit"&&e&&(Q=await u.providerRegistry.getApiKey(e));let ne=await ZEt(n,r,{apiKey:Q,extras:a});if(ne===null)return;if(ne.ok){let ee=E.current,ae=ne.modelIds.filter(q=>!ee.has(q));ae.length>0&&m(q=>[...q,...ae])}else I(ne.message)}catch(Q){I(Q instanceof Error?Q.message:String(Q))}finally{_(!1)}}},[n,r,s,a,t,e,u]),$=(0,Ks.useRef)(r),U=(0,Ks.useRef)(!1);(0,Ks.useEffect)(()=>{U.current||!n||!r||t==="new"&&!$.current||t==="edit"&&!c||t==="new"&&l&&!s||(U.current=!0,O())},[t,c,n,r,l,s,O]);let V=(0,Ks.useCallback)((Q,ne)=>{f(ee=>{let ae=new Set(ee);return ne?ae.add(Q):ae.delete(Q),ae})},[]),K=(0,Ks.useCallback)(Q=>{g(ne=>ne.includes(Q)?ne:[...ne,Q]),f(ne=>{if(ne.has(Q))return ne;let ee=new Set(ne);return ee.add(Q),ee})},[]),se=(0,Ks.useCallback)(Q=>{m(ne=>ne.filter(ee=>ee!==Q)),g(ne=>ne.filter(ee=>ee!==Q)),f(ne=>{if(!ne.has(Q))return ne;let ee=new Set(ne);return ee.delete(Q),ee}),C.has(Q)&&y(ne=>{if(ne.has(Q))return ne;let ee=new Set(ne);return ee.add(Q),ee})},[C]),le=(0,Ks.useCallback)(()=>[...d].map(Q=>k(Q)),[d,k]);return{availableModels:T,customIds:P,selectedWireIds:d,removedExistingIds:v,fetching:w,fetchError:S,resolveModelInfo:k,buildSelectedModelInfos:le,toggle:V,addId:K,removeId:se,fetchModels:O}}var Ks,XEt=b(()=>{Fae();YEt();Ks=L(B())});function AUe(t){return t!==void 0&&_zn.includes(t)}async function xzn({providerId:t,apiKey:e,initialApiKey:n,displayName:r,effectiveBaseUrl:o,enableCors:i,extras:s,existingModels:a,selectedWireIds:l,selectedInfos:c,api:u}){e!==(n??"")&&(e.trim().length>0?await u.providerRegistry.setApiKey(t,e):await u.providerRegistry.clearApiKey(t)),await u.providerRegistry.update(t,{displayName:r,baseUrl:o||void 0,enableCors:i,extras:Object.keys(s).length>0?s:void 0});let d=a.filter(m=>!l.has(m.info.id)).map(m=>m.configuredModelId),f=new Set(a.map(m=>m.info.id)),p=await u.configuredModelRegistry.bulkSet(t,c);d.length>0&&await u.backendConfigRegistry.removeRefs(d);for(let m=0;m<c.length;m++)if(!f.has(c[m].id)&&!c[m].isEmbedding)for(let h of VN)await u.backendConfigRegistry.enableModel(h,p[m])}var bde,fn,QEt,eMt,vzn,wzn,bzn,_zn,OZ,tMt=b(()=>{fm();Kj();pm();yt();Zj();hl();cde();ko();pe();W8();V9();Hce();iEt();jEt();X8();Se();Us();Re();bde=require("obsidian"),fn=L(B());XEt();Hl();QEt={anthropic:"https://api.anthropic.com",openai:"https://api.openai.com/v1",google:"https://generativelanguage.googleapis.com"},eMt=Object.freeze({}),vzn=Object.freeze([]),wzn=({state:t,onClose:e})=>{let n=Ey(),r=Ar(zce,{store:on}),o=Ar(ux,{store:on}),i=(0,fn.useMemo)(()=>t.mode==="edit"?r.find(f=>f.providerId===t.providerId):void 0,[t,r]),s=(0,fn.useMemo)(()=>t.mode==="edit"?o.filter(f=>f.providerId===t.providerId):vzn,[t,o]),a=t.mode==="edit"?t.providerId:null,[l,c]=(0,fn.useState)(null),[u,d]=(0,fn.useState)(a===null);return(0,fn.useEffect)(()=>{if(a===null)return;let f=!1;return n.providerRegistry.getApiKey(a).then(p=>{f||(c(p),d(!0))}).catch(()=>{f||d(!0)}),()=>{f=!0}},[a,n]),t.mode==="edit"&&(!i||!u)?fn.default.createElement("div",{className:"tw-flex tw-h-full tw-items-center tw-justify-center"},fn.default.createElement(Dr,{className:"tw-size-5 tw-animate-spin tw-text-muted"})):fn.default.createElement(bzn,{state:t,onClose:e,provider:i,existingModels:s,initialApiKey:l})},bzn=({state:t,onClose:e,provider:n,existingModels:r,initialApiKey:o})=>{let i=Ey(),s=vn(),a=t.mode==="new"?t.source.providerType:n?.providerType,l=t.mode==="new"?t.source.catalogProviderId:n?.origin.kind==="byok"?n.origin.catalogProviderId:void 0,[c,u]=(0,fn.useState)(0);(0,fn.useEffect)(()=>{let G=!1,ce=()=>{G||u(te=>te+1)},Z=i.catalogService.onChange(ce);return i.catalogService.ensureLoaded().then(ce).catch(te=>H("[ConfigureProviderDialog] catalog ensureLoaded failed",te)),()=>{G=!0,Z()}},[i]);let d=(0,fn.useMemo)(()=>l?i.catalogService.getProvider(l)?.models??eMt:eMt,[l,i,c]),[f,p]=(0,fn.useState)(()=>t.mode==="new"?t.source.displayName:n?.displayName??""),[m,h]=(0,fn.useState)(()=>o??""),[g,v]=(0,fn.useState)(()=>t.mode==="edit"?n?.baseUrl??"":""),[y,w]=(0,fn.useState)(()=>t.mode==="edit"?n?.enableCors??!1:!1),[_]=(0,fn.useState)(()=>t.mode==="edit"?n?.extras??{}:{}),[S,I]=(0,fn.useState)(null),[C,k]=(0,fn.useState)(!1),[T,P]=(0,fn.useState)(!1),[E,O]=(0,fn.useState)(""),$=t.mode==="new"?t.source.requiresApiKey:Fw(n),U=t.mode==="new"?t.source.defaultBaseUrl??QEt[t.source.catalogProviderId??""]??"":n?.baseUrl??QEt[l??""]??"",V=g.trim()||U,K=JEt({mode:t.mode,providerId:t.mode==="edit"?t.providerId:void 0,providerType:a,effectiveBaseUrl:V,existingModels:r,catalogMetadata:d,apiKey:m,extras:_,requiresApiKey:$,providerHydrated:t.mode==="edit"?!!n:!0,api:i}),se=async()=>{if(t.mode==="new"){let G={providerId:"test",providerType:a,displayName:f,baseUrl:V||void 0,requiresApiKey:t.source.requiresApiKey,extras:_,origin:{kind:"byok",...t.source.catalogProviderId?{catalogProviderId:t.source.catalogProviderId}:{}},addedAt:Date.now()};return i.adapters.verifyCredentials(a,{provider:G,apiKey:m||null,extras:_??{}})}return i.adapters.verifyCredentials(a,{provider:{...n,displayName:f,baseUrl:V||void 0,extras:_},apiKey:m||null,extras:_??{}})},le=async()=>{if(a){if($&&m.trim().length===0){I({ok:!1,code:"missing_api_key",message:"Enter an API key to verify this provider.",checkedAt:Date.now()});return}k(!0);try{let G=await se();I(G),G.ok&&await K.fetchModels()}catch(G){I({ok:!1,message:G instanceof Error?G.message:String(G),checkedAt:Date.now()})}finally{k(!1)}}},Q=async()=>{if(!(t.mode!=="new"||!a)){P(!0);try{if(m.trim().length>0){let G=await se();if(!G.ok&&AUe(G.code)){I(G);return}}await i.setup.byok.setupProvider({catalogProviderId:t.source.catalogProviderId,providerType:a,displayName:f,baseUrl:V||void 0,enableCors:y,apiKey:m||void 0,requiresApiKey:t.source.requiresApiKey,extras:Object.keys(_).length>0?_:void 0,models:K.buildSelectedModelInfos()}),e()}catch(G){H("[ConfigureProviderDialog] setupProvider failed",G),new bde.Notice("Failed to save provider. See console for details.")}finally{P(!1)}}},ne=async()=>{if(!(t.mode!=="edit"||!n)){P(!0);try{if(m!==(o??"")&&m.trim().length>0){let ce=await se();if(!ce.ok&&AUe(ce.code)){I(ce);return}}await xzn({providerId:t.providerId,apiKey:m,initialApiKey:o,displayName:f,effectiveBaseUrl:V,enableCors:y,extras:_,existingModels:r,selectedWireIds:K.selectedWireIds,selectedInfos:K.buildSelectedModelInfos(),api:i}),e()}catch(G){H("[ConfigureProviderDialog] save changes failed",G),new bde.Notice("Failed to save changes. See console for details.")}finally{P(!1)}}},ee=()=>{h(""),I(null)},ae=()=>{if(t.mode!=="edit"||!n)return;new _i(s,async()=>{try{await i.coordinator.removeProvider(t.providerId),e()}catch(ce){H("[ConfigureProviderDialog] removeProvider failed",ce),new bde.Notice("Failed to remove provider.")}},`Remove ${n.displayName}? This also removes all of its models from every model picker.`,"Remove provider","Remove","Cancel").open()},q=t.mode==="new"?t.source.displayName:n?.displayName??f,F=$&&m.trim().length===0,z=AUe(S?.code),N=a==="openai-compatible"&&!l&&!V,R=K.selectedWireIds.size>0&&!N&&!F&&!z,X=S?.ok===!1,D=t.mode==="new"?t.source.modelInputHint:void 0;return fn.default.createElement("div",{className:"tw-flex tw-h-full tw-min-h-0 tw-flex-col tw-gap-4 tw-overflow-hidden"},fn.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1 tw-border-b tw-border-border tw-px-2 tw-pb-3"},fn.default.createElement("div",{className:"tw-text-lg tw-font-semibold tw-leading-none tw-tracking-tight"},"Configure ",q),fn.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Enter credentials and choose which models to enable.")),fn.default.createElement("div",{className:"tw-flex tw-min-h-0 tw-flex-1 tw-flex-col tw-gap-4 tw-overflow-y-auto tw-px-2 tw-py-1"},fn.default.createElement(Dh,{label:"Display name"},fn.default.createElement(Ir,{value:f,onChange:G=>p(G.target.value)})),fn.default.createElement(Dh,{label:fn.default.createElement("span",{className:"tw-inline-flex tw-items-center tw-gap-2"},"API key",fn.default.createElement("span",{className:"tw-text-ui-smaller tw-font-normal tw-text-muted"},$?"required":"optional"),S?.ok===!0&&fn.default.createElement(ei,{className:"tw-gap-1 tw-bg-success tw-text-success"},fn.default.createElement(Xf,{className:"tw-size-3"}),"Verified"))},fn.default.createElement("div",{className:"tw-flex tw-gap-2"},fn.default.createElement(Yj,{className:"tw-flex-1",value:m,onChange:G=>{h(G),I(null)},placeholder:t.mode==="edit"?"No API key set":"Paste your API key"}),fn.default.createElement(oe,{variant:"secondary",onClick:xn(le),disabled:C},C?fn.default.createElement(Dr,{className:"tw-size-4 tw-animate-spin"}):"Test"),t.mode==="edit"&&m.length>0&&fn.default.createElement(oe,{variant:"destructive",onClick:ee,"data-testid":"api-key-clear"},"Clear")),X?fn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5 tw-text-xs tw-text-error"},fn.default.createElement(nm,{className:"tw-size-3.5 tw-shrink-0"}),fn.default.createElement("span",null,S?.message||"Verification failed")):F&&fn.default.createElement("div",{className:"tw-text-xs tw-text-muted"},"An API key is required for this provider.")),fn.default.createElement(Dh,{label:"Base URL"},fn.default.createElement(Ir,{value:g,onChange:G=>{v(G.target.value),I(null)},placeholder:U})),fn.default.createElement(oEt,{checked:y,onCheckedChange:w}),fn.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},fn.default.createElement("div",{className:"tw-text-sm tw-font-medium tw-text-normal"},"Models"),fn.default.createElement(UEt,{availableModels:K.availableModels,selected:K.selectedWireIds,onToggle:K.toggle,onAddId:K.addId,onRemoveId:K.removeId,customIds:K.customIds,query:E,onQueryChange:O,modelInputHint:D,fetching:K.fetching,fetchError:K.fetchError}))),t.mode==="new"?fn.default.createElement("div",{className:"tw-flex tw-flex-col-reverse tw-gap-2 tw-px-2 sm:tw-flex-row sm:tw-justify-end"},fn.default.createElement(oe,{variant:"secondary",onClick:e,disabled:T},"Cancel"),fn.default.createElement(oe,{variant:"default",onClick:xn(Q),disabled:!R||T},T?fn.default.createElement(Dr,{className:"tw-size-4 tw-animate-spin"}):"Save")):fn.default.createElement("div",{className:"tw-flex tw-flex-col-reverse tw-gap-2 tw-px-2 sm:tw-flex-row sm:tw-justify-between"},fn.default.createElement(oe,{variant:"destructive",onClick:ae,disabled:T},"Remove provider"),fn.default.createElement("div",{className:"tw-flex tw-gap-2"},fn.default.createElement(oe,{variant:"secondary",onClick:e,disabled:T},"Cancel"),fn.default.createElement(oe,{variant:"default",onClick:xn(ne),disabled:!R||T},T?fn.default.createElement(Dr,{className:"tw-size-4 tw-animate-spin"}):"Save"))))},_zn=["invalid_api_key","missing_api_key","missing_base_url"];OZ=class extends Uy{constructor(n,r){super(n);this.opts=r}onOpen(){this.modalEl.addClasses(["tw-flex","tw-max-h-[85vh]","tw-flex-col"]),this.contentEl.addClasses(["tw-flex","tw-min-h-0","tw-flex-1","tw-flex-col","tw-overflow-hidden"]),super.onOpen()}renderContent(n){return fn.default.createElement(J8,{api:this.opts.api},fn.default.createElement(wzn,{state:this.opts.state,onClose:n}))}}});var nMt,fa,Szn,Czn,EUe,rMt=b(()=>{fm();yt();pk();ko();pe();LSt();Hce();H9();X8();FAt();WAt();tMt();Se();Us();Re();nMt=require("obsidian"),fa=L(B()),Szn=Object.freeze([]),Czn=Object.freeze([]),EUe=()=>{let t=Ey(),e=vn(),n=Ar(aFe,{store:on}),r=Ar(ux,{store:on}),o=xt().enableSelfHostMode,[i,s]=(0,fa.useState)(Szn),[a,l]=(0,fa.useState)("loading"),[c,u]=(0,fa.useState)("");(0,fa.useEffect)(()=>{let m=!1,h=()=>{m||s(t.catalogService.getAllProviders())},g=t.catalogService.onChange(h);return t.catalogService.ensureLoaded().then(()=>{m||(h(),l("ready"))}).catch(v=>{H("[ByokPanel] catalog ensureLoaded failed",v),m||l("ready")}),()=>{m=!0,g()}},[t]);let d=(0,fa.useMemo)(()=>{let m=new Map;for(let g of r){let v=m.get(g.providerId);v?v.push(g):m.set(g.providerId,[g])}let h=c.trim().toLowerCase();return n.map(g=>{let v=o&&rx(g,{enableSelfHostMode:o}),y=m.get(g.providerId)??Czn;if(!h||g.displayName.toLowerCase().includes(h))return{provider:g,models:y,needsSelfHostWarning:v};let w=y.filter(_=>_.info.displayName.toLowerCase().includes(h)||_.info.id.toLowerCase().includes(h));return{provider:g,models:w,needsSelfHostWarning:v}}).filter(g=>!h||g.models.length>0||g.provider.displayName.toLowerCase().includes(h))},[n,r,c,o]),f=()=>{new sde(e,{catalogProviders:i,localTemplates:lFe,customTemplate:cFe,onPick:m=>new OZ(e,{state:{mode:"new",source:m},api:t}).open()}).open()},p=m=>{let h=n.find(v=>v.providerId===m);if(!h)return;new _i(e,async()=>{try{await t.coordinator.removeProvider(m)}catch(v){H("[ByokPanel] removeProvider failed",v),new nMt.Notice("Failed to remove provider.")}},`Remove ${h.displayName}? This also removes all of its models from every model picker.`,"Remove provider","Remove","Cancel").open()};return fa.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4 tw-py-4"},fa.default.createElement("div",{className:"tw-flex tw-items-start tw-justify-between tw-gap-4"},fa.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1"},fa.default.createElement("div",{className:"tw-text-xl tw-font-bold tw-text-normal"},"Bring Your Own Key"),fa.default.createElement("div",{className:"tw-max-w-xl tw-text-sm tw-text-muted"},"Set up your own providers and models to use in Copilot.")),fa.default.createElement(oe,{className:"tw-shrink-0",onClick:f},fa.default.createElement(zs,{className:"tw-size-4"}),"Add a provider")),o&&fa.default.createElement("div",{className:"tw-flex tw-items-start tw-gap-2 tw-rounded-lg tw-border tw-border-solid tw-px-3 tw-py-2.5 tw-text-xs tw-text-normal tw-bg-interactive-accent/10 tw-border-interactive-accent/30"},fa.default.createElement(Tw,{className:"tw-mt-0.5 tw-size-4 tw-shrink-0 tw-text-accent"}),fa.default.createElement("div",{className:"tw-leading-relaxed"},fa.default.createElement("span",{className:"tw-font-semibold"},"Self-Host Mode is on.")," Cloud providers stay available but are flagged and listed below your local and self-hosted endpoints \u2014 their prompts leave your machine. You decide whether to use them.")),fa.default.createElement(rf,{value:c,onChange:u,placeholder:"Search providers\u2026"}),fa.default.createElement("div",{className:"tw-flex tw-flex-col"},a==="loading"?fa.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Loading catalog\u2026"):fa.default.createElement(DAt,{groups:d,emptyMessage:c.trim()&&n.length>0?"No providers match your search.":void 0,onConfigure:m=>new OZ(e,{state:{mode:"edit",providerId:m},api:t}).open(),onRemove:p})))}});var mp=b(()=>{INe();ENe();ONe();H9();V9();NNe();RNe();LNe();Zae();DNe();lwt();UNe();GDe();W8();QDe();tFe();ISt();TSt();Hce();X8();rMt()});function _de(t,e,n){let r=t.backends[e]?.enabledModels??[];if(r.length===0)return oMt;let o=new Map;for(let s of t.configuredModels)o.set(s.configuredModelId,s);let i=[];for(let s of r){let a=o.get(s);a&&i.push({baseModelId:n(a.info.id).selection.baseModelId,name:a.info.displayName||a.info.id,description:a.info.description,credentialState:"ok",capabilities:Uw(a.info)})}return i.length===0?oMt:i}var oMt,MUe=b(()=>{mp();oMt=Object.freeze([])});var sMt=wi((_uo,iMt)=>{iMt.exports={createRequire:function(t){return typeof require<"u"?require:function(n){throw new Error('Dynamic require of "'+n+'" is not supported in this environment')}}}});var lMt=wi((xuo,aMt)=>{aMt.exports={createRequire:function(t){return typeof require<"u"?require:function(n){throw new Error('Dynamic require of "'+n+'" is not supported in this environment')}}}});function Azn(t){return this[t]}function Nzn(t,e){this[t]=Ozn.bind(null,e)}function QUe(t=lHn){let e=new AbortController;return(0,MNt.setMaxListeners)(t,e.signal),e}function eje(t){return process.platform==="darwin"?t.normalize("NFC"):t}function fHn(t){return/^[\\/]{2}/.test(t)}function pHn(t){return/^[\\/]{2}wsl(\$|\.localhost)[\\/]/i.test(t)}function mHn(t){return t.startsWith("\\\\?\\UNC\\")?"\\\\"+t.slice(8):t.startsWith("\\\\?\\")&&t.length>=7&&t[5]===":"?t.slice(4):t}function hHn(t){if(/^\\\\\?\\volume\{/i.test(t))return uMt(t);let e=mHn(t);return e!==t&&uMt(e)?!0:fHn(e)&&!pHn(e)}function uMt(t){return/(^|[\\/])\.{1,2}([\\/]|$)/.test(t)||t.includes("/")}function spe(t,e,n){return new Promise((r,o)=>{if(e?.aborted){n?.throwOnAbort||n?.abortError?o(n.abortError?.()??Error("aborted")):r();return}let i=setTimeout((a,l,c)=>{a?.removeEventListener("abort",l),c()},t,e,s,r);function s(){clearTimeout(i),n?.throwOnAbort||n?.abortError?o(n.abortError?.()??Error("aborted")):r()}e?.addEventListener("abort",s,{once:!0}),n?.unref&&i.unref()})}function gHn(t,e){t(Error(e))}function l7(t,e,n){let r,o=new Promise((i,s)=>{r=setTimeout(gHn,e,s,n)});return Promise.race([t,o]).finally(()=>{r!==void 0&&clearTimeout(r)})}function $Nt(){return process.versions.bun!==void 0}function xm(t){if(!t)return!1;if(typeof t=="boolean")return t;let e=String(t).toLowerCase().trim();return["1","true","yes","on"].includes(e)}function U7(){let t=new Set;return{subscribe(e){let n=yHn(e);return t.add(n),()=>{t.delete(n)}},emit(...e){let n;for(let r of t)try{r(...e)}catch(o){(n??(n=[])).push(o)}if(n)throw n.length===1?n[0]:AggregateError(n,"Signal listener(s) threw")},clear(){t.clear()}}}function CHn(t){var e=xHn.call(t,NZ),n=t[NZ];try{t[NZ]=void 0;var r=!0}catch{}var o=SHn.call(t);return r&&(e?t[NZ]=n:delete t[NZ]),o}function PHn(t){return THn.call(t)}function OHn(t){return t==null?t===void 0?MHn:EHn:fMt&&fMt in Object(t)?kHn(t):AHn(t)}function NHn(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}function FHn(t){if(!Nk(t))return!1;var e=DR(t);return e==LHn||e==$Hn||e==RHn||e==DHn}function jHn(t){return!!pMt&&pMt in t}function WHn(t){if(t!=null){try{return HHn.call(t)}catch{}try{return t+""}catch{}}return""}function XHn(t){if(!Nk(t)||BHn(t))return!1;var e=uBe(t)?JHn:qHn;return e.test(FR(t))}function eWn(t,e){return t?.[e]}function nWn(t,e){var n=tWn(t,e);return QHn(n)?n:void 0}function oWn(){this.__data__=d7?d7(null):{},this.size=0}function sWn(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}function dWn(t){var e=this.__data__;if(d7){var n=e[t];return n===lWn?void 0:n}return uWn.call(e,t)?e[t]:void 0}function hWn(t){var e=this.__data__;return d7?e[t]!==void 0:mWn.call(e,t)}function vWn(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=d7&&e===void 0?yWn:e,this}function WB(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function bWn(){this.__data__=[],this.size=0}function xWn(t,e){return t===e||t!==t&&e!==e}function SWn(t,e){for(var n=t.length;n--;)if(ape(t[n][0],e))return n;return-1}function IWn(t){var e=this.__data__,n=lpe(e,t);if(n<0)return!1;var r=e.length-1;return n==r?e.pop():kWn.call(e,n,1),--this.size,!0}function PWn(t){var e=this.__data__,n=lpe(e,t);return n<0?void 0:e[n][1]}function EWn(t){return lpe(this.__data__,t)>-1}function OWn(t,e){var n=this.__data__,r=lpe(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this}function VB(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function LWn(){this.size=0,this.__data__={hash:new mMt,map:new(f7||cpe),string:new mMt}}function DWn(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function UWn(t,e){var n=t.__data__;return FWn(e)?n[typeof e=="string"?"string":"hash"]:n.map}function jWn(t){var e=upe(this,t).delete(t);return this.size-=e?1:0,e}function zWn(t){return upe(this,t).get(t)}function WWn(t){return upe(this,t).has(t)}function qWn(t,e){var n=upe(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this}function qB(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function dBe(t,e){if(typeof t!="function"||e!=null&&typeof e!="function")throw TypeError(GWn);var n=function(){var r=arguments,o=e?e.apply(this,r):r[0],i=n.cache;if(i.has(o))return i.get(o);var s=t.apply(this,r);return n.cache=i.set(o,s)||i,s};return n.cache=new(dBe.Cache||dpe),n}function _e(t,e,n){function r(a,l){var c;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(c=a._zod).traits??(c.traits=new Set),a._zod.traits.add(t),e(a,l);for(let u in s.prototype)u in a||Object.defineProperty(a,u,{value:s.prototype[u].bind(a)});a._zod.constr=s,a._zod.def=l}let o=n?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:t});function s(a){var l;let c=n?.Parent?new i:this;r(c,a),(l=c._zod).deferred??(l.deferred=[]);for(let u of c._zod.deferred)u();return c}return Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(s,"name",{value:t}),s}function wp(t){return t&&Object.assign(Yde,t),Yde}function ZWn(t){return t}function YWn(t){return t}function JWn(t){}function XWn(t){throw Error()}function QWn(t){}function fBe(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,r])=>e.indexOf(+n)===-1).map(([n,r])=>r)}function Ot(t,e="|"){return t.map(n=>to(n)).join(e)}function WNt(t,e){return typeof e=="bigint"?e.toString():e}function fpe(t){return{get value(){{let e=t();return Object.defineProperty(this,"value",{value:e}),e}throw Error("cached value already set")}}}function jR(t){return t==null}function ppe(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function VNt(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,i=Number.parseInt(t.toFixed(o).replace(".","")),s=Number.parseInt(e.toFixed(o).replace(".",""));return i%s/10**o}function Di(t,e,n){Object.defineProperty(t,e,{get(){{let r=n();return t[e]=r,r}throw Error("cached value already set")},set(r){Object.defineProperty(t,e,{value:r})},configurable:!0})}function pBe(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function e6n(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function t6n(t){let e=Object.keys(t),n=e.map(r=>t[r]);return Promise.all(n).then(r=>{let o={};for(let i=0;i<e.length;i++)o[e[i]]=r[i];return o})}function n6n(t=10){let e="";for(let n=0;n<t;n++)e+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return e}function cB(t){return JSON.stringify(t)}function p7(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function m7(t){if(p7(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let n=e.prototype;return!(p7(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function r6n(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}function BR(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function lb(t,e,n){let r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function bt(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function i6n(t){let e;return new Proxy({},{get(n,r,o){return e??(e=t()),Reflect.get(e,r,o)},set(n,r,o,i){return e??(e=t()),Reflect.set(e,r,o,i)},has(n,r){return e??(e=t()),Reflect.has(e,r)},deleteProperty(n,r){return e??(e=t()),Reflect.deleteProperty(e,r)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,r){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,r)},defineProperty(n,r,o){return e??(e=t()),Reflect.defineProperty(e,r,o)}})}function to(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function GNt(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function s6n(t,e){let n={},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw Error(`Unrecognized key: "${o}"`);e[o]&&(n[o]=r.shape[o])}return lb(t,{...t._zod.def,shape:n,checks:[]})}function a6n(t,e){let n={...t._zod.def.shape},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw Error(`Unrecognized key: "${o}"`);e[o]&&delete n[o]}return lb(t,{...t._zod.def,shape:n,checks:[]})}function l6n(t,e){if(!m7(e))throw Error("Invalid input to extend: expected a plain object");let n={...t._zod.def,get shape(){let r={...t._zod.def.shape,...e};return pBe(this,"shape",r),r},checks:[]};return lb(t,n)}function c6n(t,e){return lb(t,{...t._zod.def,get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return pBe(this,"shape",n),n},catchall:e._zod.def.catchall,checks:[]})}function u6n(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let i in n){if(!(i in r))throw Error(`Unrecognized key: "${i}"`);n[i]&&(o[i]=t?new t({type:"optional",innerType:r[i]}):r[i])}else for(let i in r)o[i]=t?new t({type:"optional",innerType:r[i]}):r[i];return lb(e,{...e._zod.def,shape:o,checks:[]})}function d6n(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let i in n){if(!(i in o))throw Error(`Unrecognized key: "${i}"`);n[i]&&(o[i]=new t({type:"nonoptional",innerType:r[i]}))}else for(let i in r)o[i]=new t({type:"nonoptional",innerType:r[i]});return lb(e,{...e._zod.def,shape:o,checks:[]})}function mB(t,e=0){for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function Vy(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function QZ(t){return typeof t=="string"?t:t?.message}function ob(t,e,n){let r={...t,path:t.path??[]};if(!t.message){let o=QZ(t.inst?._zod.def?.error?.(t))??QZ(e?.error?.(t))??QZ(n.customError?.(t))??QZ(n.localeError?.(t))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,!e?.reportInput&&delete r.input,r}function mpe(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function hpe(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function JNt(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function f6n(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function gBe(t,e=n=>n.message){let n={},r=[];for(let o of t.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:n}}function yBe(t,e){let n=e||function(i){return i.message},r={_errors:[]},o=i=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>o({issues:a}));else if(s.code==="invalid_key")o({issues:s.issues});else if(s.code==="invalid_element")o({issues:s.issues});else if(s.path.length===0)r._errors.push(n(s));else{let a=r,l=0;for(;l<s.path.length;){let c=s.path[l];l!==s.path.length-1?a[c]=a[c]||{_errors:[]}:(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(s))),a=a[c],l++}}};return o(t),r}function QNt(t,e){let n=e||function(i){return i.message},r={errors:[]},o=(i,s=[])=>{var a,l;for(let c of i.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(u=>o({issues:u},c.path));else if(c.code==="invalid_key")o({issues:c.issues},c.path);else if(c.code==="invalid_element")o({issues:c.issues},c.path);else{let u=[...s,...c.path];if(u.length===0){r.errors.push(n(c));continue}let d=r,f=0;for(;f<u.length;){let p=u[f],m=f===u.length-1;typeof p=="string"?(d.properties??(d.properties={}),(a=d.properties)[p]??(a[p]={errors:[]}),d=d.properties[p]):(d.items??(d.items=[]),(l=d.items)[p]??(l[p]={errors:[]}),d=d.items[p]),m&&d.errors.push(n(c)),f++}}};return o(t),r}function eRt(t){let e=[];for(let n of t)typeof n=="number"?e.push(`[${n}]`):typeof n=="symbol"?e.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?e.push(`[${JSON.stringify(n)}]`):(e.length&&e.push("."),e.push(n));return e.join("")}function tRt(t){let e=[],n=[...t.issues].sort((r,o)=>r.path.length-o.path.length);for(let r of n)e.push(`\u2716 ${r.message}`),r.path?.length&&e.push(` \u2192 at ${eRt(r.path)}`);return e.join(`
`)}function dRt(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}function _Rt(t){return typeof t.precision=="number"?t.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":t.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${t.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function xRt(t){return new RegExp(`^${_Rt(t)}$`)}function SRt(t){let e=_Rt({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\d{2}:\\d{2})");let r=`${e}(?:${n.join("|")})`;return new RegExp(`^${wRt}T(?:${r})$`)}function hMt(t,e,n){t.issues.length&&e.issues.push(...Vy(n,t.issues))}function PBe(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function wLt(t){if(!kBe.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return PBe(n)}function xLt(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function gMt(t,e,n){t.issues.length&&e.issues.push(...Vy(n,t.issues)),e.value[n]=t.value}function xde(t,e,n){t.issues.length&&e.issues.push(...Vy(n,t.issues)),e.value[n]=t.value}function yMt(t,e,n,r){t.issues.length?r[n]===void 0?n in r?e.value[n]=void 0:e.value[n]=t.value:e.issues.push(...Vy(n,t.issues)):t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function vMt(t,e,n,r){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(o=>o.issues.map(i=>ob(i,r,wp())))}),e}function nje(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(m7(t)&&m7(e)){let n=Object.keys(e),r=Object.keys(t).filter(i=>n.indexOf(i)!==-1),o={...t,...e};for(let i of r){let s=nje(t[i],e[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<t.length;r++){let o=t[r],i=e[r],s=nje(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function wMt(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),mB(t))return t;let r=nje(e.value,n.value);if(!r.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return t.value=r.data,t}function Sde(t,e,n){t.issues.length&&e.issues.push(...Vy(n,t.issues)),e.value[n]=t.value}function bMt(t,e,n,r,o,i,s){t.issues.length&&(Jde.has(typeof r)?n.issues.push(...Vy(r,t.issues)):n.issues.push({origin:"map",code:"invalid_key",input:o,inst:i,issues:t.issues.map(a=>ob(a,s,wp()))})),e.issues.length&&(Jde.has(typeof r)?n.issues.push(...Vy(r,e.issues)):n.issues.push({origin:"map",code:"invalid_element",input:o,inst:i,key:r,issues:e.issues.map(a=>ob(a,s,wp()))})),n.value.set(t.value,e.value)}function _Mt(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}function xMt(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function SMt(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function CMt(t,e,n){return mB(t)?t:e.out._zod.run({value:t.value,issues:t.issues},n)}function kMt(t){return t.value=Object.freeze(t.value),t}function IMt(t,e,n,r){if(!t){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),e.issues.push(JNt(o))}}function C6n(){return{localeError:S6n()}}function I6n(){return{localeError:k6n()}}function TMt(t,e,n,r){let o=Math.abs(t),i=o%10,s=o%100;return s>=11&&s<=19?r:i===1?e:i>=2&&i<=4?n:r}function P6n(){return{localeError:T6n()}}function E6n(){return{localeError:A6n()}}function O6n(){return{localeError:M6n()}}function R6n(){return{localeError:N6n()}}function t1t(){return{localeError:$6n()}}function U6n(){return{localeError:F6n()}}function B6n(){return{localeError:j6n()}}function H6n(){return{localeError:z6n()}}function V6n(){return{localeError:W6n()}}function K6n(){return{localeError:q6n()}}function Z6n(){return{localeError:G6n()}}function J6n(){return{localeError:Y6n()}}function Q6n(){return{localeError:X6n()}}function tVn(){return{localeError:eVn()}}function rVn(){return{localeError:nVn()}}function iVn(){return{localeError:oVn()}}function aVn(){return{localeError:sVn()}}function cVn(){return{localeError:lVn()}}function dVn(){return{localeError:uVn()}}function pVn(){return{localeError:fVn()}}function hVn(){return{localeError:mVn()}}function yVn(){return{localeError:gVn()}}function wVn(){return{localeError:vVn()}}function _Vn(){return{localeError:bVn()}}function SVn(){return{localeError:xVn()}}function kVn(){return{localeError:CVn()}}function PMt(t,e,n,r){let o=Math.abs(t),i=o%10,s=o%100;return s>=11&&s<=19?r:i===1?e:i>=2&&i<=4?n:r}function TVn(){return{localeError:IVn()}}function AVn(){return{localeError:PVn()}}function MVn(){return{localeError:EVn()}}function NVn(){return{localeError:OVn()}}function LVn(){return{localeError:RVn()}}function FVn(){return{localeError:DVn()}}function jVn(){return{localeError:UVn()}}function zVn(){return{localeError:BVn()}}function WVn(){return{localeError:HVn()}}function qVn(){return{localeError:VVn()}}function GVn(){return{localeError:KVn()}}function FBe(){return new h7}function o1t(t,e){return new t({type:"string",...bt(e)})}function i1t(t,e){return new t({type:"string",coerce:!0,...bt(e)})}function UBe(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...bt(e)})}function nfe(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...bt(e)})}function jBe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...bt(e)})}function BBe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...bt(e)})}function zBe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...bt(e)})}function HBe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...bt(e)})}function WBe(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...bt(e)})}function VBe(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...bt(e)})}function qBe(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...bt(e)})}function KBe(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...bt(e)})}function GBe(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...bt(e)})}function ZBe(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...bt(e)})}function YBe(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...bt(e)})}function JBe(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...bt(e)})}function XBe(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...bt(e)})}function QBe(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...bt(e)})}function eze(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...bt(e)})}function tze(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...bt(e)})}function nze(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...bt(e)})}function rze(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...bt(e)})}function oze(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...bt(e)})}function ize(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...bt(e)})}function a1t(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...bt(e)})}function l1t(t,e){return new t({type:"string",format:"date",check:"string_format",...bt(e)})}function c1t(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...bt(e)})}function u1t(t,e){return new t({type:"string",format:"duration",check:"string_format",...bt(e)})}function d1t(t,e){return new t({type:"number",checks:[],...bt(e)})}function f1t(t,e){return new t({type:"number",coerce:!0,checks:[],...bt(e)})}function p1t(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...bt(e)})}function m1t(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float32",...bt(e)})}function h1t(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float64",...bt(e)})}function g1t(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"int32",...bt(e)})}function y1t(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"uint32",...bt(e)})}function v1t(t,e){return new t({type:"boolean",...bt(e)})}function w1t(t,e){return new t({type:"boolean",coerce:!0,...bt(e)})}function b1t(t,e){return new t({type:"bigint",...bt(e)})}function _1t(t,e){return new t({type:"bigint",coerce:!0,...bt(e)})}function x1t(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...bt(e)})}function S1t(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...bt(e)})}function C1t(t,e){return new t({type:"symbol",...bt(e)})}function k1t(t,e){return new t({type:"undefined",...bt(e)})}function I1t(t,e){return new t({type:"null",...bt(e)})}function T1t(t){return new t({type:"any"})}function rfe(t){return new t({type:"unknown"})}function P1t(t,e){return new t({type:"never",...bt(e)})}function A1t(t,e){return new t({type:"void",...bt(e)})}function E1t(t,e){return new t({type:"date",...bt(e)})}function M1t(t,e){return new t({type:"date",coerce:!0,...bt(e)})}function O1t(t,e){return new t({type:"nan",...bt(e)})}function AR(t,e){return new IBe({check:"less_than",...bt(e),value:t,inclusive:!1})}function nb(t,e){return new IBe({check:"less_than",...bt(e),value:t,inclusive:!0})}function ER(t,e){return new TBe({check:"greater_than",...bt(e),value:t,inclusive:!1})}function qh(t,e){return new TBe({check:"greater_than",...bt(e),value:t,inclusive:!0})}function N1t(t){return ER(0,t)}function R1t(t){return AR(0,t)}function L1t(t){return nb(0,t)}function $1t(t){return qh(0,t)}function g7(t,e){return new RRt({check:"multiple_of",...bt(e),value:t})}function ype(t,e){return new DRt({check:"max_size",...bt(e),maximum:t})}function y7(t,e){return new FRt({check:"min_size",...bt(e),minimum:t})}function sze(t,e){return new URt({check:"size_equals",...bt(e),size:t})}function vpe(t,e){return new jRt({check:"max_length",...bt(e),maximum:t})}function SB(t,e){return new BRt({check:"min_length",...bt(e),minimum:t})}function wpe(t,e){return new zRt({check:"length_equals",...bt(e),length:t})}function aze(t,e){return new HRt({check:"string_format",format:"regex",...bt(e),pattern:t})}function lze(t){return new WRt({check:"string_format",format:"lowercase",...bt(t)})}function cze(t){return new VRt({check:"string_format",format:"uppercase",...bt(t)})}function uze(t,e){return new qRt({check:"string_format",format:"includes",...bt(e),includes:t})}function dze(t,e){return new KRt({check:"string_format",format:"starts_with",...bt(e),prefix:t})}function fze(t,e){return new GRt({check:"string_format",format:"ends_with",...bt(e),suffix:t})}function D1t(t,e,n){return new ZRt({check:"property",property:t,schema:e,...bt(n)})}function pze(t,e){return new YRt({check:"mime_type",mime:t,...bt(e)})}function zR(t){return new JRt({check:"overwrite",tx:t})}function mze(t){return zR(e=>e.normalize(t))}function hze(){return zR(t=>t.trim())}function gze(){return zR(t=>t.toLowerCase())}function yze(){return zR(t=>t.toUpperCase())}function vze(t,e,n){return new t({type:"array",element:e,...bt(n)})}function ZVn(t,e,n){return new t({type:"union",options:e,...bt(n)})}function YVn(t,e,n,r){return new t({type:"union",options:n,discriminator:e,...bt(r)})}function JVn(t,e,n){return new t({type:"intersection",left:e,right:n})}function F1t(t,e,n,r){let o=n instanceof Mr;return new t({type:"tuple",items:e,rest:o?n:null,...bt(o?r:n)})}function XVn(t,e,n,r){return new t({type:"record",keyType:e,valueType:n,...bt(r)})}function QVn(t,e,n,r){return new t({type:"map",keyType:e,valueType:n,...bt(r)})}function e3n(t,e,n){return new t({type:"set",valueType:e,...bt(n)})}function t3n(t,e,n){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new t({type:"enum",entries:r,...bt(n)})}function n3n(t,e,n){return new t({type:"enum",entries:e,...bt(n)})}function r3n(t,e,n){return new t({type:"literal",values:Array.isArray(e)?e:[e],...bt(n)})}function U1t(t,e){return new t({type:"file",...bt(e)})}function o3n(t,e){return new t({type:"transform",transform:e})}function i3n(t,e){return new t({type:"optional",innerType:e})}function s3n(t,e){return new t({type:"nullable",innerType:e})}function a3n(t,e,n){return new t({type:"default",innerType:e,get defaultValue(){return typeof n=="function"?n():n}})}function l3n(t,e,n){return new t({type:"nonoptional",innerType:e,...bt(n)})}function c3n(t,e){return new t({type:"success",innerType:e})}function u3n(t,e,n){return new t({type:"catch",innerType:e,catchValue:typeof n=="function"?n:()=>n})}function d3n(t,e,n){return new t({type:"pipe",in:e,out:n})}function f3n(t,e){return new t({type:"readonly",innerType:e})}function p3n(t,e,n){return new t({type:"template_literal",parts:e,...bt(n)})}function m3n(t,e){return new t({type:"lazy",getter:e})}function h3n(t,e){return new t({type:"promise",innerType:e})}function j1t(t,e,n){let r=bt(n);return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}function B1t(t,e,n){return new t({type:"custom",check:"custom",fn:e,...bt(n)})}function z1t(t,e){let n=bt(e),r=n.truthy??["true","1","yes","on","y","enabled"],o=n.falsy??["false","0","no","off","n","disabled"];n.case!=="sensitive"&&(r=r.map(f=>typeof f=="string"?f.toLowerCase():f),o=o.map(f=>typeof f=="string"?f.toLowerCase():f));let i=new Set(r),s=new Set(o),a=t.Pipe??$Be,l=t.Boolean??EBe,c=t.String??z7,u=new(t.Transform??LBe)({type:"transform",transform:(f,p)=>{let m=f;return n.case!=="sensitive"&&(m=m.toLowerCase()),i.has(m)?!0:s.has(m)?!1:(p.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...s],input:p.value,inst:u}),{})},error:n.error}),d=new a({type:"pipe",in:new c({type:"string",error:n.error}),out:u,error:n.error});return new a({type:"pipe",in:d,out:new l({type:"boolean",error:n.error}),error:n.error})}function H1t(t,e,n,r={}){let o=bt(r),i={...bt(r),check:"string_format",type:"string",format:e,fn:typeof n=="function"?n:s=>n.test(s),...o};return n instanceof RegExp&&(i.pattern=n),new t(i)}function W1t(t){return new ofe({type:"function",input:Array.isArray(t?.input)?F1t(gpe,t?.input):t?.input??vze(OBe,rfe(tfe)),output:t?.output??rfe(tfe)})}function V1t(t,e){if(t instanceof h7){let r=new v7(e),o={};for(let a of t._idmap.entries()){let[l,c]=a;r.process(c)}let i={},s={registry:t,uri:e?.uri||(a=>a),defs:o};for(let a of t._idmap.entries()){let[l,c]=a;i[l]=r.emit(c,{...e,external:s})}if(Object.keys(o).length>0){let a=r.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[a]:o}}return{schemas:i}}let n=new v7(e);return n.process(t),n.emit(t,e)}function Lc(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let r=t._zod.def;switch(r.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Lc(r.element,n);case"object":{for(let o in r.shape)if(Lc(r.shape[o],n))return!0;return!1}case"union":{for(let o of r.options)if(Lc(o,n))return!0;return!1}case"intersection":return Lc(r.left,n)||Lc(r.right,n);case"tuple":{for(let o of r.items)if(Lc(o,n))return!0;return!!(r.rest&&Lc(r.rest,n))}case"record":return Lc(r.keyType,n)||Lc(r.valueType,n);case"map":return Lc(r.keyType,n)||Lc(r.valueType,n);case"set":return Lc(r.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Lc(r.innerType,n);case"lazy":return Lc(r.getter(),n);case"default":return Lc(r.innerType,n);case"prefault":return Lc(r.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return Lc(r.in,n)||Lc(r.out,n);case"success":return!1;case"catch":return!1;default:}throw Error(`Unknown schema type: ${r.type}`)}function q1t(t){return a1t(bze,t)}function K1t(t){return l1t(_ze,t)}function G1t(t){return c1t(xze,t)}function Z1t(t){return u1t(Sze,t)}function ke(t){return o1t(bpe,t)}function v3n(t){return UBe(kze,t)}function w3n(t){return nfe(ife,t)}function b3n(t){return jBe(Ok,t)}function _3n(t){return BBe(Ok,t)}function x3n(t){return zBe(Ok,t)}function S3n(t){return HBe(Ok,t)}function C3n(t){return WBe(Ize,t)}function k3n(t){return VBe(Tze,t)}function I3n(t){return qBe(Pze,t)}function T3n(t){return KBe(Aze,t)}function P3n(t){return GBe(Eze,t)}function A3n(t){return ZBe(Mze,t)}function E3n(t){return YBe(Oze,t)}function M3n(t){return JBe(Nze,t)}function O3n(t){return XBe(Rze,t)}function N3n(t){return QBe(Lze,t)}function R3n(t){return eze($ze,t)}function L3n(t){return tze(Dze,t)}function $3n(t){return nze(Fze,t)}function D3n(t){return rze(Uze,t)}function F3n(t){return oze(jze,t)}function U3n(t){return ize(Bze,t)}function j3n(t,e,n={}){return H1t(t$t,t,e,n)}function xi(t){return d1t(_pe,t)}function rje(t){return p1t(KB,t)}function B3n(t){return m1t(KB,t)}function z3n(t){return h1t(KB,t)}function H3n(t){return g1t(KB,t)}function W3n(t){return y1t(KB,t)}function Fc(t){return v1t(xpe,t)}function V3n(t){return b1t(Spe,t)}function q3n(t){return x1t(zze,t)}function K3n(t){return S1t(zze,t)}function G3n(t){return C1t(n$t,t)}function Z3n(t){return k1t(r$t,t)}function Hze(t){return I1t(o$t,t)}function Y3n(){return T1t(i$t)}function ma(){return rfe(s$t)}function Cpe(t){return P1t(a$t,t)}function J3n(t){return A1t(l$t,t)}function X3n(t){return E1t(Wze,t)}function Oo(t,e){return vze(c$t,t,e)}function Q3n(t){let e=t._zod.def.shape;return In(Object.keys(e))}function qt(t,e){let n={type:"object",get shape(){return Mo.assignProp(this,"shape",{...t}),this.shape},...Mo.normalizeParams(e)};return new kpe(n)}function eqn(t,e){return new kpe({type:"object",get shape(){return Mo.assignProp(this,"shape",{...t}),this.shape},catchall:Cpe(),...Mo.normalizeParams(e)})}function vp(t,e){return new kpe({type:"object",get shape(){return Mo.assignProp(this,"shape",{...t}),this.shape},catchall:ma(),...Mo.normalizeParams(e)})}function gs(t,e){return new Vze({type:"union",options:t,...Mo.normalizeParams(e)})}function qze(t,e,n){return new u$t({type:"union",options:e,discriminator:t,...Mo.normalizeParams(n)})}function Ipe(t,e){return new d$t({type:"intersection",left:t,right:e})}function tqn(t,e,n){let r=e instanceof Mr,o=r?n:e;return new f$t({type:"tuple",items:t,rest:r?e:null,...Mo.normalizeParams(o)})}function hs(t,e,n){return new Kze({type:"record",keyType:t,valueType:e,...Mo.normalizeParams(n)})}function nqn(t,e,n){return new Kze({type:"record",keyType:gs([t,Cpe()]),valueType:e,...Mo.normalizeParams(n)})}function rqn(t,e,n){return new p$t({type:"map",keyType:t,valueType:e,...Mo.normalizeParams(n)})}function oqn(t,e){return new m$t({type:"set",valueType:t,...Mo.normalizeParams(e)})}function Im(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new w7({type:"enum",entries:n,...Mo.normalizeParams(e)})}function iqn(t,e){return new w7({type:"enum",entries:t,...Mo.normalizeParams(e)})}function In(t,e){return new h$t({type:"literal",values:Array.isArray(t)?t:[t],...Mo.normalizeParams(e)})}function sqn(t){return U1t(g$t,t)}function Zze(t){return new Gze({type:"transform",transform:t})}function Js(t){return new Yze({type:"optional",innerType:t})}function sfe(t){return new y$t({type:"nullable",innerType:t})}function aqn(t){return Js(sfe(t))}function w$t(t,e){return new v$t({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function _$t(t,e){return new b$t({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function x$t(t,e){return new Jze({type:"nonoptional",innerType:t,...Mo.normalizeParams(e)})}function lqn(t){return new S$t({type:"success",innerType:t})}function k$t(t,e){return new C$t({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function cqn(t){return O1t(I$t,t)}function afe(t,e){return new Xze({type:"pipe",in:t,out:e})}function P$t(t){return new T$t({type:"readonly",innerType:t})}function uqn(t,e){return new A$t({type:"template_literal",parts:t,...Mo.normalizeParams(e)})}function M$t(t){return new E$t({type:"lazy",getter:t})}function dqn(t){return new O$t({type:"promise",innerType:t})}function N$t(t,e){let n=new wl({check:"custom",...Mo.normalizeParams(e)});return n._zod.check=t,n}function R$t(t,e){return j1t(Tpe,t??(()=>!0),e)}function L$t(t,e={}){return B1t(Tpe,t,e)}function $$t(t,e){let n=N$t(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(Mo.issue(o,r.value,n._zod.def));else{let i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=n),i.continue??(i.continue=!n._zod.def.abort),r.issues.push(Mo.issue(i))}},t(r.value,r)),e);return n}function fqn(t,e={error:`Input not instance of ${t.name}`}){let n=new Tpe({type:"custom",check:"custom",fn:r=>r instanceof t,abort:!0,...Mo.normalizeParams(e)});return n._zod.bag.Class=t,n}function mqn(t){let e=M$t(()=>gs([ke(t),xi(),Fc(),Hze(),Oo(e),hs(ke(),e)]));return e}function Qze(t,e){return afe(Zze(t),e)}function gqn(t){wp({customError:t})}function yqn(){return wp().customError}function vqn(t){return i1t(bpe,t)}function wqn(t){return f1t(_pe,t)}function bqn(t){return w1t(xpe,t)}function _qn(t){return _1t(Spe,t)}function xqn(t){return M1t(Wze,t)}function Ze(t){let e;return()=>e??(e=t())}function Eqn(t){return t.replace(/-0$/,"")}function Ht(t,e,n,r,o){if(r==="m")throw TypeError("Private method is not writable");if(r==="a"&&!o)throw TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(t,n):o?o.value=n:e.set(t,n),n}function xe(t,e,n,r){if(n==="a"&&!r)throw TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)}function b7(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}function sje(t){return typeof t!="object"?{}:t??{}}function EMt(t){if(!t)return!0;for(let e in t)return!1;return!0}function Nqn(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Dqn(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function Uqn(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:n}of t){let r=n.exec(navigator.userAgent);if(r){let o=r[1]||0,i=r[2]||0,s=r[3]||0;return{browser:e,version:`${o}.${i}.${s}`}}}return null}function jqn(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function H$t(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function W$t(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return H$t({start(){},async pull(n){let{done:r,value:o}=await e.next();r?n.close():n.enqueue(o)},async cancel(){await e.return?.()}})}function n4e(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){let n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Bqn(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),n=e.cancel();e.releaseLock(),await n}function Hqn(t){return Object.entries(t).filter(([e,n])=>typeof n<"u").map(([e,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(e)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(e)}=`;throw new Vn(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}function q$t(t){if(!t)return;let e;try{e=new URL(t)}catch(r){throw new ms(`Invalid token endpoint base URL "${t}": ${r}`)}if(e.protocol==="https:")return;let n=e.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(!(e.protocol==="http:"&&(n==="localhost"||n==="127.0.0.1"||n==="::1")))throw new ms(`Refusing to send credential over non-https token endpoint "${t}"`)}async function K$t(t,e){let n=await Yqn(t),r;try{r=JSON.parse(n)}catch{throw new ms(`Token endpoint returned non-JSON response (status ${t.status})`,t.status,qy(n),e)}if(!r.access_token)throw new ms(`Token endpoint response missing access_token: ${JSON.stringify(qy(r))}`,t.status,qy(r),e);if(r.token_type&&r.token_type.toLowerCase()!=="bearer")throw new ms(`Token endpoint response: unsupported token_type "${r.token_type}" (want Bearer)`,t.status,qy(r),e);return r}function qy(t){if(t==null)return t;if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch{return t.length<=NUe?t:t.slice(0,NUe)+`... <${t.length-NUe} more chars>`}return JSON.stringify(qy(e))}if(typeof t=="object"&&!Array.isArray(t)){let e={};for(let[n,r]of Object.entries(t))Zqn.has(n)&&(e[n]=r);return e}return null}async function G$t(t,e=n=>console.warn(`anthropic-sdk: ${n}`)){if(typeof process>"u"||process.platform==="win32")return;let n=await import("node:fs"),r=t,o;try{r=await n.promises.realpath(t),o=await n.promises.stat(r)}catch{return}let i=o.mode&511;if(i&18)throw new ms(`Credentials file at ${r} is group/world-writable (mode 0o${i.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${r}\`.`);if(i&36)throw new ms(`Credentials file at ${r} is group/world-readable (mode 0o${i.toString(8)}); run \`chmod 600 ${r}\` before retrying.`);typeof process.getuid=="function"&&o.uid!==process.getuid()&&e(`credentials file at ${r} is owned by uid ${o.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function Z$t(t,e){let n=await import("node:fs"),r=(await import("node:path")).dirname(t);await n.promises.mkdir(r,{recursive:!0,mode:448});let o=`${t}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{let i=await n.promises.open(o,"w",384);try{await i.writeFile(JSON.stringify(e,null,2)),await i.sync()}finally{await i.close()}await n.promises.rename(o,t)}catch(i){throw await n.promises.unlink(o).catch(()=>{}),i}try{let i=await n.promises.open(r,"r");try{await i.sync()}finally{await i.close()}}catch{}}async function Yqn(t){if(!t.body)return"";let e=t.body.getReader(),n=[],r=0;for(;;){let{done:i,value:s}=await e.read();if(i)break;if(r+s.length>RMt){let a=RMt-r;a>0&&n.push(s.subarray(0,a)),await e.cancel();break}n.push(s),r+=s.length}let o;if(n.length===1)o=n[0];else{o=new Uint8Array(n.reduce((s,a)=>s+a.length,0));let i=0;for(let s of n)o.set(s,i),i+=s.length}return new TextDecoder("utf-8").decode(o)}function TR(){return Math.floor(Date.now()/1e3)}function Jqn(t){let e=0;for(let o of t)e+=o.length;let n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.length;return n}function o4e(t){let e;return(LMt??(e=new globalThis.TextEncoder,LMt=e.encode.bind(e)))(t)}function DMt(t){let e;return($Mt??(e=new globalThis.TextDecoder,$Mt=e.decode.bind(e)))(t)}function e7(){}function Cde(t,e,n){return!e||wfe[t]>wfe[n]?e7:e[t].bind(e)}function Mu(t){let e=t.logger,n=t.logLevel??"off";if(!e)return Xqn;let r=UMt.get(e);if(r&&r[0]===n)return r[1];let o={error:Cde("error",e,n),warn:Cde("warn",e,n),info:Cde("info",e,n),debug:Cde("debug",e,n)};return UMt.set(e,[n,o]),o}function J$t(t){if(!t)throw Error("profile name is empty");if(t==="."||t==="..")throw Error(`profile name "${t}" is not allowed`);if(t.includes("/")||t.includes("\\"))throw Error(`profile name "${t}" must not contain path separators`);if(!Qqn.test(t))throw Error(`profile name "${t}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}function jMt(t){if(!t)throw new Vn("Identity token file path is empty");return async()=>{let e=await import("node:fs"),n;try{n=await e.promises.readFile(t,"utf-8")}catch(o){throw new Vn(`Failed to read identity token file at ${t}: ${o}`)}let r=n.trim();if(!r)throw new Vn(`Identity token file at ${t} is empty`);return r}}function r5n(t){if(!t)throw new Vn("Identity token value is empty");return()=>t}function o5n(t){return async()=>{q$t(t.baseURL);let e=await t.identityTokenProvider();if(e.length>16384)throw new ms(`Identity token is ${Math.ceil(e.length/1024)} KiB, exceeds the 16 KiB assertion limit`);let n={grant_type:Wqn,assertion:e,federation_rule_id:t.federationRuleId,organization_id:t.organizationId};t.serviceAccountId&&(n.service_account_id=t.serviceAccountId),t.workspaceId&&(n.workspace_id=t.workspaceId);let r=`${t.baseURL}${V$t}`,o;try{o=await t.fetch(r,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${vfe},${qqn}`,"User-Agent":t.userAgent||`anthropic-sdk-typescript/${HP} oidcFederationProvider`},body:JSON.stringify(n)})}catch(l){throw new ms(`Failed to reach token endpoint ${r}: ${l}`)}let i=o.headers.get("Request-Id");if(!o.ok){let l=await o.text().catch(()=>""),c=qy(l),u="";throw o.status===401&&(u=` Ensure your federation rule matches your identity token. ${t.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`),new ms(`Token exchange failed with status ${o.status}${i?` (request-id ${i})`:""}: ${c}${u}`,o.status,c,i)}let s=await K$t(o,i),a=Number(s.expires_in);if(!Number.isFinite(a))throw new ms(`Token endpoint response missing required fields: ${JSON.stringify(qy(s))}`,o.status,qy(s),i);return{token:s.access_token,expiresAt:TR()+a}}}function i5n(t){return async e=>{let n=await import("node:fs");await G$t(t.credentialsPath,t.onSafetyWarning);let r;try{r=await n.promises.readFile(t.credentialsPath,"utf-8")}catch(g){throw new ms(`Credentials file not found at ${t.credentialsPath}: ${g}`)}let o;try{o=JSON.parse(r)}catch(g){throw new ms(`Credentials file at ${t.credentialsPath} is not valid JSON: ${g}`)}let i=o.access_token;if(!i)throw new ms(`Credentials file at ${t.credentialsPath} must include 'access_token'`);let s=o.expires_at;if(!e?.forceRefresh&&(s==null||TR()<s-r4e))return{token:i,expiresAt:s??null};let a=o.refresh_token;if(!t.clientId||!a)throw new ms(`Access token at ${t.credentialsPath} has expired and no refresh is available (client_id ${t.clientId?"set":"empty"}, refresh_token ${a?"set":"empty"})`);q$t(t.baseURL);let l={grant_type:Vqn,refresh_token:a,client_id:t.clientId},c=`${t.baseURL}${V$t}`,u;try{u=await t.fetch(c,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":vfe,"User-Agent":t.userAgent||`anthropic-sdk-typescript/${HP} userOAuthProvider`},body:JSON.stringify(l)})}catch(g){throw new ms(`User OAuth refresh failed to reach token endpoint: ${g}`)}let d=u.headers.get("Request-Id");if(!u.ok){let g=await u.text().catch(()=>"");throw new ms(`User OAuth refresh failed (HTTP ${u.status}): ${qy(g)}`,u.status,qy(g),d)}let f=await K$t(u,d),p=Number(f.expires_in);if(!Number.isFinite(p))throw new ms(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(qy(f))}`,u.status,qy(f),d);let m=TR()+p,h=f.refresh_token||a;return await Z$t(t.credentialsPath,{...o,version:Y$t,type:"oauth_token",access_token:f.access_token,expires_at:m,refresh_token:h}),{token:f.access_token,expiresAt:m}}}function Q$t(t,e){let n=t.authentication.credentials_path??null,r=(t.base_url||e.baseURL).replace(/\/+$/,""),o=a5n(t,n,r,e),i={};return t.workspace_id&&t.authentication.type==="user_oauth"&&(i["anthropic-workspace-id"]=t.workspace_id),{provider:o,extraHeaders:i,baseURL:t.base_url||void 0}}async function s5n(t,e){let n=await e5n(e);if(!n)return null;let{config:r,fromFile:o}=n,i=r.authentication.credentials_path||!o?r:{...r,authentication:{...r.authentication,credentials_path:await t5n(r,e)??void 0}};return Q$t(i,t)}function a5n(t,e,n,r){switch(t.authentication.type){case"oidc_federation":{let o=t.authentication,i=l5n(o);if(!i)throw new ms("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)");if(!o.federation_rule_id)throw new ms("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).");if(!t.organization_id)throw new ms("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");let s=o5n({identityTokenProvider:i,federationRuleId:o.federation_rule_id,organizationId:t.organization_id,serviceAccountId:o.service_account_id,workspaceId:t.workspace_id,baseURL:n,fetch:r.fetch,userAgent:r.userAgent});return e?c5n(s,e,r.onCacheWriteError,r.onSafetyWarning):s}case"user_oauth":{if(!e)throw new ms("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return i5n({credentialsPath:e,clientId:t.authentication.client_id,baseURL:n,fetch:r.fetch,userAgent:r.userAgent,onSafetyWarning:r.onSafetyWarning})}default:{let o=t.authentication.type;throw new ms(`authentication.type "${o}" is not a known authentication type`)}}}function l5n(t){if(t.identity_token){let r=t.identity_token.source;if(r!=="file")throw new ms(`identity_token.source "${r}" is not supported by this SDK version (only "file")`);if(!t.identity_token.path)throw new ms('identity_token.source "file" requires a non-empty path');return jMt(t.identity_token.path)}let e=ps("ANTHROPIC_IDENTITY_TOKEN_FILE");if(e)return jMt(e);let n=ps("ANTHROPIC_IDENTITY_TOKEN");return n?r5n(n):null}function c5n(t,e,n,r){return async o=>{let i=await import("node:fs");await G$t(e,r);let s;try{let l=await i.promises.readFile(e,"utf-8");s=JSON.parse(l);let c=s?.access_token;if(c&&!o?.forceRefresh){let u=s?.expires_at;if(u==null||TR()<u-r4e)return{token:c,expiresAt:u??null}}}catch(l){l?.code!=="ENOENT"&&!(l instanceof SyntaxError)&&n?.(l)}let a=await t(o);try{await Z$t(e,{...s??{},version:Y$t,type:"oauth_token",access_token:a.token,expires_at:a.expiresAt})}catch(l){n?.(l)}return a}}function u5n(t,e){for(let n=e??0;n<t.length;n++){if(t[n]===10)return{preceding:n,index:n+1,carriage:!1};if(t[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function d5n(t){for(let e=0;e<t.length-1;e++){if(t[e]===10&&t[e+1]===10||t[e]===13&&t[e+1]===13)return e+2;if(t[e]===13&&t[e+1]===10&&e+3<t.length&&t[e+2]===13&&t[e+3]===10)return e+4}return-1}async function*f5n(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Vn("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new Vn("Attempted to iterate over a response with no body");let n=new lje,r=new MR,o=n4e(t.body);for await(let i of p5n(o))for(let s of r.decode(i)){let a=n.decode(s);a&&(yield a)}for(let i of r.flush()){let s=n.decode(i);s&&(yield s)}}async function*p5n(t){let e=new Uint8Array;for await(let n of t){if(n==null)continue;let r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?o4e(n):n,o=new Uint8Array(e.length+r.length);o.set(e),o.set(r,e.length),e=o;let i;for(;(i=d5n(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function m5n(t,e){let n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}async function eDt(t,e){let{response:n,requestLogID:r,retryOfRequestLogID:o,startTime:i}=e,s=await(async()=>{if(e.options.stream)return Mu(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller):OR.fromSSEResponse(n,e.controller);if(n.status===204)return null;if(e.options.__binaryResponse)return n;let a=n.headers.get("content-type")?.split(";")[0]?.trim();if(a?.includes("application/json")||a?.endsWith("+json")){if(n.headers.get("content-length")==="0")return;let l=await n.json();return tDt(l,n)}return await n.text()})();return Mu(t).debug(`[${r}] response parsed`,xR({retryOfRequestLogID:o,url:n.url,status:n.status,body:s,durationMs:Date.now()-i})),s}function tDt(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}function hB(t,e,n){return nDt(),new File(t,e??"unknown_file",n)}function Bde(t,e){let n=typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"";return e?n.split(/[\\/]/).pop()||void 0:n}function h5n(t){let e=typeof t=="function"?t:t.fetch,n=BMt.get(e);if(n)return n;let r=(async()=>{try{let o="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new o(i).text()}catch{return!0}})();return BMt.set(e,r),r}async function b5n(t,e,n){if(nDt(),t=await t,e||(e=Bde(t,!0)),v5n(t))return t instanceof File&&e==null&&n==null?t:hB([await t.arrayBuffer()],e??t.name,{type:t.type,lastModified:t.lastModified,...n});if(w5n(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),hB(await dje(o),e,n)}let r=await dje(t);if(!n?.type){let o=r.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof o=="string"&&(n={...n,type:o})}return hB(r,e,n)}async function dje(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(oDt(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(rDt(t))for await(let n of t)e.push(...await dje(n));else{let n=t?.constructor?.name;throw Error(`Unexpected data type: ${typeof t}${n?`; constructor: ${n}`:""}${_5n(t)}`)}return e}function _5n(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(e=>`"${e}"`).join(", ")}]`}function*x5n(t){if(!t)return;if(iDt in t){let{values:r,nulls:o}=t;yield*r.entries();for(let i of o)yield[i,null];return}let e=!1,n;t instanceof Headers?n=t.entries():AMt(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let r of n){let o=r[0];if(typeof o!="string")throw TypeError("expected header name to be a string");let i=AMt(r[1])?r[1]:[r[1]],s=!1;for(let a of i)a!==void 0&&(e&&!s&&(s=!0,yield[o,null]),yield[o,a])}}function sDt(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}function zde(t){return typeof t=="object"&&t!==null&&c7 in t}function aDt(t,e){let n=new Set;if(t)for(let r of t)zde(r)&&n.add(r[c7]);if(e){for(let r of e)if(zde(r)&&n.add(r[c7]),Array.isArray(r.content))for(let o of r.content)zde(o)&&n.add(o[c7])}return Array.from(n)}function lDt(t,e){let n=aDt(t,e);return n.length===0?{}:{"x-stainless-helper":n.join(", ")}}function C5n(t){return zde(t)?{"x-stainless-helper":t[c7]}:{}}function uDt(t){return t?.output_format??t?.output_config?.format}function HMt(t,e,n){let r=uDt(e);return!e||!("parse"in(r??{}))?{...t,content:t.content.map(o=>{if(o.type==="text"){let i=Object.defineProperty({...o},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(i,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return o}),parsed_output:null}:dDt(t,e,n)}function dDt(t,e,n){let r=null,o=t.content.map(i=>{if(i.type==="text"){let s=k5n(e,i.text);r===null&&(r=s);let a=Object.defineProperty({...i},"parsed_output",{value:s,enumerable:!1});return Object.defineProperty(a,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),s},enumerable:!1})}return i});return{...t,content:o,parsed_output:r}}function k5n(t,e){let n=uDt(t);if(n?.type!=="json_schema")return null;try{return"parse"in n?n.parse(e):JSON.parse(e)}catch(r){throw new Vn(`Failed to parse structured output: ${r}`)}}function KMt(t){return t.type==="tool_use"||t.type==="server_tool_use"||t.type==="mcp_tool_use"}function ZMt(){let t,e;return{promise:new Promise((n,r)=>{t=n,e=r}),resolve:t,reject:e}}async function M5n(t,e=t.messages.at(-1),n){if(!e||e.role!=="assistant"||!e.content||typeof e.content=="string")return null;let r=e.content.filter(o=>o.type==="tool_use");return r.length===0?null:{role:"user",content:await Promise.all(r.map(async o=>{let i=t.tools.find(s=>("name"in s?s.name:s.mcp_server_name)===o.name);if(!i||!("run"in i))return{type:"tool_result",tool_use_id:o.id,content:`Error: Tool '${o.name}' not found`,is_error:!0};try{let s=o.input;"parse"in i&&i.parse&&(s=i.parse(s));let a=await i.run(s,{toolUseBlock:o,signal:n?.signal});return{type:"tool_result",tool_use_id:o.id,content:a}}catch(s){return{type:"tool_result",tool_use_id:o.id,content:s instanceof Mfe?s.content:`Error: ${s instanceof Error?s.message:String(s)}`,is_error:!0}}}))}}function JMt(t){if(!t.output_format)return t;if(t.output_config?.format)throw new Vn("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:e,...n}=t;return{...n,output_config:{...t.output_config,format:e}}}function pDt(t){return t?.output_config?.format}function XMt(t,e,n){let r=pDt(e);return!e||!("parse"in(r??{}))?{...t,content:t.content.map(o=>o.type==="text"?Object.defineProperty({...o},"parsed_output",{value:null,enumerable:!1}):o),parsed_output:null}:mDt(t,e,n)}function mDt(t,e,n){let r=null,o=t.content.map(i=>{if(i.type==="text"){let s=N5n(e,i.text);return r===null&&(r=s),Object.defineProperty({...i},"parsed_output",{value:s,enumerable:!1})}return i});return{...t,content:o,parsed_output:r}}function N5n(t,e){let n=pDt(t);if(n?.type!=="json_schema")return null;try{return"parse"in n?n.parse(e):JSON.parse(e)}catch(r){throw new Vn(`Failed to parse structured output: ${r}`)}}function nOt(t){return t.type==="tool_use"||t.type==="server_tool_use"}function l4e(t){return t}function Ppe(t){return t instanceof Error?t:Error(String(t))}function Wde(t){return t instanceof Error?t.message:String(t)}function Ky(t){if(t&&typeof t=="object"&&"code"in t&&typeof t.code=="string")return t.code}function c4e(t){return Ky(t)==="ENOENT"}function gDt(t){return Ky(t)==="EISDIR"}function U5n(t){let e=Ky(t);return e!==void 0&&F5n.has(e)}function W5n(t,e){if(process.platform!=="win32")return!1;let n=Ky(t);return n!==void 0&&B5n.has(n)&&e<z5n-1}async function V5n(t,e,n=Gy.rename){let r=!1;for(let o=0;;o++)try{return await n(t,e),r}catch(i){if(W5n(i,o)){r=!0,await spe(H5n);continue}throw i}}async function K5n(t,e,n){let r=`${t}.tmp.${(0,wDt.randomBytes)(4).toString("hex")}`;try{await(0,Gy.writeFile)(r,e,{encoding:"utf8",mode:n});try{await V5n(r,t)}catch(o){let i=Ky(o);if(i===void 0||!j5n.has(i))throw o;try{await(0,Gy.copyFile)(r,t),n!==void 0&&await(0,Gy.chmod)(t,n).catch(()=>{})}catch(s){throw q5n.has(Ky(s)??"")&&await(0,Gy.unlink)(t).catch(()=>{}),s}await(0,Gy.unlink)(r).catch(()=>{})}}catch(o){throw await(0,Gy.unlink)(r).catch(()=>{}),o}}function HUe(t,e,n){if(!Number.isInteger(n)||n<0)throw RangeError(`${t}: ${e} must be a non-negative integer, got ${n}`)}async function oOt(t,e,n){if(n===0)return Buffer.alloc(0);let r=Buffer.alloc(n),o=0;for(;o<n;){let{bytesRead:i}=await t.read(r,o,n-o,e+o);if(i===0)break;o+=i}return o===n?r:Buffer.from(r.subarray(0,o))}function bDt(){return G5n.getStore()??new vje}function _Dt(){if(oB)return oB;if(!xm(process.env.DEBUG_CLAUDE_AGENT_SDK))return PR=null,oB=Promise.resolve(),oB;let t=(0,yje.join)(e4e(),"debug");return PR=(0,yje.join)(t,`sdk-${(0,yDt.randomUUID)()}.txt`),process.stderr.write(`SDK debug logs: ${PR}
`),oB=bDt().mkdir(t).catch(()=>{}),oB}function Z5n(){return _Dt(),PR??null}function yx(t){if(PR===null)return;let e=`${new Date().toISOString()} ${t}
`;_Dt().then(()=>{PR&&bDt().append(PR,e).catch(()=>{})})}function Y5n(){this.__data__=new cpe,this.size=0}function X5n(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n}function eKn(t){return this.__data__.get(t)}function nKn(t){return this.__data__.has(t)}function iKn(t,e){var n=this.__data__;if(n instanceof cpe){var r=n.__data__;if(!f7||r.length<oKn-1)return r.push([t,e]),this.size=++n.size,this;n=this.__data__=new dpe(r)}return n.set(t,e),this.size=n.size,this}function GB(t){var e=this.__data__=new cpe(t);this.size=e.size}function cKn(t,e,n){e=="__proto__"&&jfe?jfe(t,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):t[e]=n}function fKn(t,e,n){var r=t[e];(!(dKn.call(t,e)&&ape(r,n))||n===void 0&&!(e in t))&&u4e(t,e,n)}function pKn(t,e,n,r){var o=!n;n||(n={});for(var i=-1,s=e.length;++i<s;){var a=e[i],l=r?r(n[a],t[a],a,n,t):void 0;l===void 0&&(l=t[a]),o?u4e(n,a,l):xDt(n,a,l)}return n}function hKn(t,e){for(var n=-1,r=Array(t);++n<t;)r[n]=e(n);return r}function yKn(t){return t!=null&&typeof t=="object"}function wKn(t){return ZB(t)&&DR(t)==vKn}function CKn(){return!1}function MKn(t,e){var n=typeof t;return e=e??AKn,!!e&&(n=="number"||n!="symbol"&&EKn.test(t))&&t>-1&&t%1==0&&t<e}function NKn(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=OKn}function oGn(t){return ZB(t)&&f4e(t.length)&&!!Ys[DR(t)]}function sGn(t){return function(e){return t(e)}}function pGn(t,e){var n=ZP(t),r=!n&&k7(t),o=!n&&!r&&d4e(t),i=!n&&!r&&!o&&IDt(t),s=n||r||o||i,a=s?gKn(t.length,String):[],l=a.length;for(var c in t)(e||fGn.call(t,c))&&!(s&&(c=="length"||o&&(c=="offset"||c=="parent")||i&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||Ape(c,l)))&&a.push(c);return a}function gGn(t){var e=t&&t.constructor,n=typeof e=="function"&&e.prototype||hGn;return t===n}function yGn(t,e){return function(n){return t(e(n))}}function wGn(t){return t!=null&&f4e(t.length)&&!uBe(t)}function bGn(t){var e=[];if(t!=null)for(var n in Object(t))e.push(n);return e}function CGn(t){if(!Nk(t))return _Gn(t);var e=TDt(t),n=[];for(var r in t)r=="constructor"&&(e||!SGn.call(t,r))||n.push(r);return n}function IGn(t){return p4e(t)?mGn(t,!0):kGn(t)}function PGn(t,e){if(e)return t.slice();var n=t.length,r=dOt?dOt(n):new t.constructor(n);return t.copy(r),r}function AGn(t,e){var n=-1,r=t.length;for(e||(e=Array(r));++n<r;)e[n]=t[n];return e}function OGn(t,e){for(var n=-1,r=e.length,o=t.length;++n<r;)t[o+n]=e[n];return t}function qGn(t){var e=new t.constructor(t.byteLength);return new yOt(e).set(new yOt(t)),e}function GGn(t,e){var n=e?KGn(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)}function XGn(t){return typeof t.constructor=="function"&&!TDt(t)?JGn(ODt(t)):{}}function t9n(t){return this.__data__.set(t,e9n),this}function r9n(t){return this.__data__.has(t)}function kje(t){var e=-1,n=t==null?0:t.length;for(this.__data__=new dpe;++e<n;)this.add(t[e])}function l9n(t){return typeof t=="symbol"||ZB(t)&&DR(t)==a9n}function d9n(t,e){if(ZP(t))return!1;var n=typeof t;return n=="number"||n=="symbol"||n=="boolean"||t==null||m4e(t)?!0:u9n.test(t)||!c9n.test(t)||e!=null&&t in Object(e)}function m9n(t){var e=Za(t,function(r){return n.size===p9n&&n.clear(),r}),n=e.cache;return e}function b9n(t,e){for(var n=-1,r=t==null?0:t.length,o=Array(r);++n<r;)o[n]=e(t[n],n,t);return o}function NDt(t){if(typeof t=="string")return t;if(ZP(t))return _9n(t,NDt)+"";if(m4e(t))return _Ot?_Ot.call(t):"";var e=t+"";return e=="0"&&1/t==-x9n?"-0":e}function C9n(t){return t==null?"":S9n(t)}function I9n(t,e){return ZP(t)?t:f9n(t,e)?[t]:w9n(k9n(t))}function P9n(t){if(typeof t=="string"||m4e(t))return t;var e=t+"";return e=="0"&&1/t==-T9n?"-0":e}function A9n(t,e){e=Epe(e,t);for(var n=0,r=e.length;t!=null&&n<r;)t=t[h4e(e[n++])];return n&&n==r?t:void 0}function M9n(t,e){return t!=null&&e in Object(t)}function N9n(t,e,n){e=Epe(e,t);for(var r=-1,o=e.length,i=!1;++r<o;){var s=h4e(e[r]);if(!(i=t!=null&&n(t,s)))break;t=t[s]}return i||++r!=o?i:(o=t==null?0:t.length,!!o&&f4e(o)&&Ape(s,o)&&(ZP(t)||k7(t)))}function L9n(t,e){return t!=null&&R9n(t,e,O9n)}function D9n(t){return t}function F9n(t,e){let n=Buffer.from(e.replace(/-/g,""),"hex"),r=(0,$Dt.createHash)("sha1").update(n).update(Buffer.from(t,"utf8")).digest();r[6]=r[6]&15|80,r[8]=r[8]&63|128;let o=r.subarray(0,16).toString("hex");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20,32)}`}function j9n(){let t=process.env.CLAUDE_CODE_REMOTE_SESSION_ID?.trim();return t?F9n(t,U9n):null}function B9n(){return{sent:new Set,rejected:new Set}}function H9n(){let t="";if(typeof process<"u"&&typeof process.cwd=="function"&&typeof Cje.realpathSync=="function"){let e=(0,LDt.cwd)();try{t=xOt((0,Cje.realpathSync)(e))}catch{t=xOt(e)}}return{originalCwd:t,projectRoot:t,totalCostUSD:0,totalAPIDuration:0,totalAPIDurationWithoutRetries:0,totalToolDuration:0,startTime:Date.now(),sessionLogicalStartTime:void 0,lastInteractionTime:Date.now(),totalLinesAdded:0,totalLinesRemoved:0,hasUnknownModelCost:!1,cwd:t,modelUsage:{},mainLoopModelOverride:void 0,refusalFallbackOccurred:!1,refusalFallbackModelLatch:void 0,sdkDialogHostActive:!1,sdkSupportedDialogKinds:void 0,sdkSupportedDialogKindsSource:void 0,replConfigArgv:[],settingsEffortAtStartup:void 0,initialMainLoopModel:void 0,resolvedOrgDefault:void 0,modelStrings:null,isInteractive:!1,thinkingDisplayExplicit:!1,permissionPromptToolName:void 0,attacherCaps:null,hasStreamingInput:!1,modelOverrideOptOutForSession:!1,rendererMode:void 0,strictToolResultPairing:!1,memoryToggledOff:!1,teamMemoryServerStatus:void 0,sdkAgentProgressSummariesEnabled:!1,userMsgOptIn:!1,searchToolsOptIn:!1,clientType:"cli",sessionSource:void 0,sessionStartType:"fresh",questionPreviewFormat:void 0,sessionIngressToken:void 0,oauthTokenFromFd:void 0,oauthTokenFromBgSnapshot:!1,oauthScopesFromFd:void 0,apiKeyFromFd:void 0,gatewayAuth:null,gatewayRefreshInFlight:null,startupPolicySnapshot:void 0,flagSettingsPath:void 0,flagSettingsExpectedContent:void 0,flagSettingsInline:null,parentManagedSettings:null,allowedSettingSources:["userSettings","projectSettings","localSettings","flagSettings","policySettings"],meter:null,sessionCounter:null,locCounter:null,prCounter:null,commitCounter:null,costCounter:null,tokenCounter:null,codeEditToolDecisionCounter:null,activeTimeCounter:null,statsStore:null,sessionId:j9n()??(0,Bfe.randomUUID)(),mainAgentId:null,parentSessionId:void 0,loggerProvider:null,eventLogger:null,pendingOTelEvents:[],meterProvider:null,tracerProvider:null,cachedTelemetryResource:null,cachedOtlpHttpAgentFactory:{direct:null,proxied:null},foundryDeploymentCapabilities:new Map,agentColorMap:new Map,agentColorIndex:0,lastAPIRequest:null,lastCancelledAPIMessageId:null,lastAPIRequestMessages:null,lastClassifierRequests:null,cachedClaudeMdContent:null,inMemoryErrorLog:[],inlinePlugins:[],inlinePluginsNoMcp:[],inlinePluginUrls:[],syncedPluginDirs:[],chromeFlagOverride:void 0,teammateAgentId:void 0,onboardingShownThisSession:!1,useCoworkPlugins:!1,disableSlashCommands:!1,sessionBypassPermissionsMode:!1,scheduledTasksEnabled:!1,sessionPrResolved:!1,sessionCronTasks:[],loopChainStartedAt:Object.create(null),loopTickInFlightPrompt:null,loopConsecutiveKeepalives:0,loopEnded:!1,sessionCreatedTeams:new Set,surfacedHookSpawnFailures:new Set,bareMcpServerMatchersWarned:new Set,inheritedTeamName:void 0,sessionTrustAccepted:!1,sessionPersistenceDisabled:!1,hasExitedPlanMode:!1,needsPlanModeExitAttachment:!1,needsAutoModeExitAttachment:!1,lspRecommendationShownThisSession:!1,initJsonSchema:null,registeredHooks:null,planSlugCache:new Map,teleportedSessionInfo:null,invokedSkills:new Map,slowOperations:[],sdkBetas:void 0,longContext1mCreditsBlocked:!1,fableCreditsRequired:!1,fableConsentSessionFallback:!1,fableBridgeDialogTimedOut:!1,fableConsentDialogInteracted:!1,sdkOAuthTokenRefreshCallback:null,hostAuthTokenRefreshCallback:null,mainThreadAgentType:void 0,mainThreadAgentHooks:void 0,sessionSkillAllowlist:void 0,caps:z9n,replBridgeActive:!1,mainLoopBusy:!1,directConnectServerUrl:void 0,mcpConnectNonBlocking:!1,strictMcpConfig:!1,cliSessionConfigCarried:!1,sessionApprovedMcpServers:[],activeRoutine:void 0,systemPromptSectionCache:new Map,lastEmittedDate:null,additionalDirectoriesForClaudeMd:[],allowedChannels:[],hasDevChannels:!1,sessionProjectDir:null,promptCache1hAllowlist:null,stickyBetas:B9n(),thinkingTypeOverrides:new Map,inferenceProfileBackingModels:new Map,promptId:null,promptIndex:0,lastMainRequestId:void 0,lastMainThreadCacheTtlMs:null,lastApiCompletionTimestamp:null,pendingPostCompaction:!1}}function FDt(){return V9n()?.sessionId??W9n.sessionId}function xOt(t){return process.platform==="darwin"?t.normalize("NFC"):t}function J9n({writeFn:t,flushIntervalMs:e=1e3,maxBufferSize:n=100,maxBufferBytes:r=1/0,immediateMode:o=!1}){let i=[],s=0,a=null,l=null;function c(){a&&(clearTimeout(a),a=null)}function u(m){try{t(m)}catch{}}function d(){l&&(u(l.join("")),l=null),i.length!==0&&(u(i.join("")),i=[],s=0,c())}function f(){a||(a=setTimeout(d,e))}function p(){if(l){l.push(...i),i=[],s=0,c();return}let m=i;i=[],s=0,c(),l=m,setImmediate(()=>{let h=l;l=null,h&&u(h.join(""))})}return{write(m){if(o){u(m);return}i.push(m),s+=m.length,f(),(i.length>=n||s>=r)&&p()},flush:d,dispose(){d()}}}function X9n(t){return typeof t=="function"?t:Symbol.asyncDispose in t?()=>t[Symbol.asyncDispose]():()=>t[Symbol.dispose]()}function e8n(t){return Q9n.register(t)}function n8n(t){let e=[],n=t.match(/^MCP server ["']([^"']+)["']/);if(n&&n[1])e.push("mcp"),e.push(n[1].toLowerCase());else{let i=t.match(/^([^:[]+):/);i&&i[1]&&e.push(i[1].trim().toLowerCase())}let r=t.match(/^\[([^\]]+)]/);r&&r[1]&&e.push(r[1].trim().toLowerCase()),t.toLowerCase().includes("1p event:")&&e.push("1p");let o=t.match(/:\s*([^:]+?)(?:\s+(?:type|mode|status|event))?:/);if(o&&o[1]){let i=o[1].trim().toLowerCase();i.length<30&&!i.includes(" ")&&e.push(i)}return Array.from(new Set(e))}function r8n(t,e){return e?t.length===0?!1:e.isExclusive?!t.some(n=>e.exclude.includes(n)):t.some(n=>e.include.includes(n)):!0}function o8n(t,e){if(!e)return!0;let n=n8n(t);return r8n(n,e)}function Vde(){return s8n}function a8n(t,e){t.destroyed||t.write(e)}function l8n(t){a8n(process.stderr,t)}function c8n(t){return t.charAt(0).toUpperCase()+t.slice(1)}function m8n(t){return p8n.map(e=>({id:e.id,confidence:e.confidence,re:new RegExp(e.source,t?(e.flags??"").replace("g","")+"g":e.flags??"")}))}function h8n(t,e){if(typeof e!="string")return"[REDACTED]";let n=e.length>=2&&(e[0]==='"'||e[0]==="'")&&e.at(-1)===e[0]?e[0]:"",r=t.lastIndexOf(e);return`${t.slice(0,r)}${n}[REDACTED]${n}${t.slice(r+e.length)}`}function v8n(t){let e=t.length<=g8n;if(e){let r=ZZ.get(t);if(r!==void 0)return r}kOt??(kOt=m8n(!0));let n=t;for(let r of kOt)n=n.replace(r.re,h8n);return e&&(ZZ.size>=y8n&&ZZ.delete(ZZ.keys().next().value),ZZ.set(t,n)),n}function Mpe(){if(typeof process>"u"||!Array.isArray(process.argv))return[];let t=process.argv.indexOf("--");return t===-1?process.argv:process.argv.slice(0,t)}function IOt(t){return hHn(t)?null:(0,wx.resolve)(t)}function x8n(t){if(!jDt()||typeof process>"u"||typeof process.versions>"u"||typeof process.versions.node>"u")return!1;let e=_8n();return o8n(t,e)}async function k8n(t,e,n=C8n){if(JZ<0?JZ=await(0,cf.stat)(t).then(r=>r.size).catch(()=>0):JZ+=e,!(JZ<=n||qUe)){qUe=!0;try{let r=t.endsWith(".txt")?`${t.slice(0,-4)}.1.txt`:`${t}.1`;try{await(0,cf.rename)(t,r)}catch(o){c4e(o)||(await(0,cf.unlink)(r).catch(()=>{}),await(0,cf.rename)(t,r).catch(()=>(0,cf.unlink)(t).catch(()=>{})))}JZ=0}finally{qUe=!1}}}function HDt(t){return Tje=(0,wx.join)(t,`${FDt()}.txt`),Tje}async function I8n(t,e,n,r){t&&await(0,cf.mkdir)(e,{recursive:!0}).catch(()=>{});let o=n;try{await(0,cf.appendFile)(n,r)}catch(i){if(!gDt(i))throw i;o=HDt(n),await(0,cf.appendFile)(o,r)}await k8n(o,Buffer.byteLength(r)).catch(WDt),A8n()}function WDt(){}function T8n(){dB.shift()}function P8n(){if(!YZ){let t=null;YZ=J9n({writeFn:e=>{if(i7){dB.push(e),i7();return}let n=Pje(),r=(0,wx.dirname)(n),o=t!==r;t=r,dB.push(e),VUe=VUe.then(I8n.bind(null,o,r,n,e)).catch(WDt).then(T8n)},flushIntervalMs:1e3,maxBufferSize:100,immediateMode:jDt()}),e8n(async()=>{YZ?.dispose(),await VUe}),!TOt&&process.on("exit",TOt=()=>{i7=()=>{if(dB.length===0)return;let e=dB.join("");dB.length=0;let n=Pje();try{Vde().mkdirSync((0,wx.dirname)(n))}catch{}try{Vde().appendFileSync(n,e)}catch(r){if(gDt(r))try{Vde().appendFileSync(HDt(n),e)}catch{}}},YZ?.flush(),i7()})}return YZ}function Ka(t,{level:e}={level:"debug"}){if(Ije[e]<Ije[w8n()]||!x8n(t))return;S8n&&t.includes(`
`)&&(t=yp(t));let n=`${new Date().toISOString()} [${e.toUpperCase()}] ${v8n(t.trim())}
`;if(BDt()){l8n(n);return}let r=P8n();r.write(n),i7&&r.flush()}function Pje(){return zDt()??Tje??process.env.CLAUDE_CODE_DEBUG_LOGS_DIR??(0,wx.join)(e4e(),"debug",`${FDt()}.txt`)}function M8n(){return E8n}function yp(t,e,n){let r=[];try{let s=gl(r,vl`JSON.stringify(${t})`,0);return JSON.stringify(t,e,n)}catch(s){var o=s,i=1}finally{yl(r,o,i)}}function O8n(t){let e=t.trim();return e.startsWith("{")&&e.endsWith("}")}function N8n(t,e){let n={...t};if(e){let r=e.enabled===!0&&e.failIfUnavailable===void 0?{...e,failIfUnavailable:!0}:e,o=n.settings;if(o&&!O8n(o))throw Error("Cannot use both a settings file path and the sandbox option. Include the sandbox configuration in your settings file instead.");let i={sandbox:r};if(o)try{i={...g4e(o),sandbox:r}}catch{}n.settings=yp(i)}return n}function L8n(){for(let t of Hfe)if(!t.killed)if(process.platform==="win32")try{t.stdin.end()}catch{}else t.kill("SIGTERM")}function $8n(t){Hfe.add(t),!POt&&(POt=!0,process.on("exit",L8n))}function D8n(t){return![".js",".mjs",".tsx",".ts",".jsx"].some(e=>t.endsWith(e))}function F8n(t,e){return(0,NNt.existsSync)(t)?e?`Claude Code native binary at ${t} exists but failed to launch. This usually means the binary does not match this system's libc \u2014 e.g. spawning a musl-linked binary on a glibc Linux host fails because the musl dynamic loader (/lib/ld-musl-*) is missing. Specify a matching binary with options.pathToClaudeCodeExecutable.`:`Claude Code executable at ${t} exists but failed to launch.`:e?`Claude Code native binary not found at ${t}. Please ensure Claude Code is installed via native installer or specify a valid path with options.pathToClaudeCodeExecutable.`:`Claude Code executable not found at ${t}. Is options.pathToClaudeCodeExecutable set?`}function U8n(){if(process.platform!=="linux")return!1;let t=typeof process.report?.getReport=="function"?process.report.getReport():null;return t!=null&&t.header?.glibcVersionRuntime===void 0}function j8n(t,e=process.platform,n=process.arch,r=VDt.existsSync,o=U8n()){let i=e==="win32"?".exe":"",s=(e==="android"?[`${sB}-linux-${n}-android`]:e==="linux"?o?[`${sB}-linux-${n}-musl`,`${sB}-linux-${n}`]:[`${sB}-linux-${n}`,`${sB}-linux-${n}-musl`]:[`${sB}-${e}-${n}`]).map(a=>`${a}/claude${i}`);for(let a of s)try{let l=t(a);if(r(l))return l}catch{}return null}function B8n(){return{eventQueue:[],sink:null}}function y4e(t,e){let n=z8n;if(n.sink===null){n.eventQueue.push({eventName:t,metadata:e,async:!1});return}n.sink.logEvent(t,e)}function H8n(t,e){y4e("tengu_feature_ok",{feature_name:l4e(t),...e})}function W8n(t,e,n){y4e("tengu_feature_bad",{...n,feature_name:l4e(t),error_code:e})}async function Wy(t,e,n){try{let r=await e();return H8n(t),r}catch(r){throw W8n(t,n?.(r)??"error"),r}}function J8n(t){let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n)|0;return e}function Q8n(t){return typeof t!="string"?null:X8n.test(t)?t:null}async function EOt(t,e){return eZn(t,e,"w")}async function eZn(t,e,n){let r=(0,GDt.createWriteStream)(t,{mode:384,flags:n});try{for(let o of e)r.write(JSON.stringify(o)+`
`)||await(0,Rje.once)(r,"drain");r.end(),await(0,Rje.once)(r,"finish")}catch(o){throw r.destroy(),o}}function tZn(t){return Math.abs(J8n(t)).toString(36)}function nZn(t){let e=t.replace(/[^a-zA-Z0-9]/g,"-");return e.length<=MOt?e:`${e.slice(0,MOt)}-${tZn(t)}`}function nFt(t,e){let n=0;for(let r of t)n+=+!!e(r);return n}function cZn(t){return[...new Set(t)]}function uZn(){return"prod"}function gZn(){let t=process.env.CLAUDE_LOCAL_OAUTH_API_BASE?.replace(/\/$/,"")??"http://localhost:8000",e=process.env.CLAUDE_LOCAL_OAUTH_APPS_BASE?.replace(/\/$/,"")??"http://localhost:4000",n=process.env.CLAUDE_LOCAL_OAUTH_CONSOLE_BASE?.replace(/\/$/,"")??"http://localhost:3000";return{BASE_API_URL:t,CONSOLE_AUTHORIZE_URL:`${n}/oauth/authorize`,CLAUDE_AI_AUTHORIZE_URL:`${e}/oauth/authorize`,CLAUDE_AI_ORIGIN:e,TOKEN_URL:`${t}/v1/oauth/token`,API_KEY_URL:`${t}/api/oauth/claude_cli/create_api_key`,ROLES_URL:`${t}/api/oauth/claude_cli/roles`,CONSOLE_SUCCESS_URL:`${n}/buy_credits?returnUrl=/oauth/code/success%3Fapp%3Dclaude-code`,CLAUDEAI_SUCCESS_URL:`${n}/oauth/code/success?app=claude-code`,MANUAL_REDIRECT_URL:`${n}/oauth/code/callback`,CLIENT_ID:"22422756-60c9-4084-8eb7-27705fd5cf9a",DESIGN_CLIENT_ID:"00000000-0000-4000-8000-000000000000",OAUTH_FILE_SUFFIX:"-local-oauth",MCP_PROXY_URL:"http://localhost:8205",MCP_PROXY_PATH:"/v1/toolbox/shttp/mcp/{server_id}"}}function vZn(){let t=(()=>{switch(uZn()){case"local":return gZn();case"staging":return hZn??OOt;case"prod":return OOt}})(),e=process.env.CLAUDE_CODE_CUSTOM_OAUTH_URL;if(e){let r=e.replace(/\/$/,"");if(!yZn.includes(r))throw Error("CLAUDE_CODE_CUSTOM_OAUTH_URL is not an approved endpoint.");t={...t,BASE_API_URL:r,CONSOLE_AUTHORIZE_URL:`${r}/oauth/authorize`,CLAUDE_AI_AUTHORIZE_URL:`${r}/oauth/authorize`,CLAUDE_AI_ORIGIN:r,TOKEN_URL:`${r}/v1/oauth/token`,API_KEY_URL:`${r}/api/oauth/claude_cli/create_api_key`,ROLES_URL:`${r}/api/oauth/claude_cli/roles`,CONSOLE_SUCCESS_URL:`${r}/oauth/code/success?app=claude-code`,CLAUDEAI_SUCCESS_URL:`${r}/oauth/code/success?app=claude-code`,MANUAL_REDIRECT_URL:`${r}/oauth/code/callback`,OAUTH_FILE_SUFFIX:"-custom-oauth"}}let n=process.env.CLAUDE_CODE_OAUTH_CLIENT_ID;return n&&(t={...t,CLIENT_ID:n}),t}function bZn(t=""){let e=process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR,n=e!==void 0?!e:!process.env.CLAUDE_CONFIG_DIR,r=e!==void 0?e.normalize("NFC"):e4e(),o=n?"":`-${(0,eFt.createHash)("sha256").update(r).digest("hex").substring(0,8)}`;return`Claude Code${vZn().OAUTH_FILE_SUFFIX}${t}${o}`}function xZn(){if(process.platform==="win32")return"claude-code-user";let t;try{t=process.env.USER||(0,tFt.userInfo)().username}catch{t="claude-code-user"}return _Zn.test(t)?t:"claude-code-user"}function SZn(t,e){if(t==="bypassPermissions")return"canUseTool will not be invoked: permissionMode 'bypassPermissions' auto-approves every tool call (except explicit deny rules) before the callback is consulted. To gate every tool call, use a PreToolUse hook instead.";let n=e.filter(r=>r.length>0&&!r.includes("("));if(n.length!==0)return`canUseTool will not be invoked for: ${n.join(", ")}. Bare allowedTools entries auto-approve the whole tool before the callback is consulted. To gate every tool call, use a PreToolUse hook; or remove the bare names from allowedTools so they fall through to canUseTool. Allow rules from settings files can also shadow the callback but are not visible here.`}function CZn(t,e,n){if(!t)return;let r=SZn(e,n);r!==void 0&&process.emitWarning(r,{code:"CLAUDE_SDK_CAN_USE_TOOL_SHADOWED"})}function Lje(){return IZn}function Ut(t,e){let n=Lje(),r=$je({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===I7?void 0:I7].filter(o=>!!o)});t.common.issues.push(r)}function Kr(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,s)=>{let{message:a}=t;return i.code==="invalid_enum_value"?{message:a??s.defaultError}:typeof s.data>"u"?{message:a??r??s.defaultError}:i.code!=="invalid_type"?{message:s.defaultError}:{message:a??n??s.defaultError}},description:o}}function iFt(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function HZn(t){return new RegExp(`^${iFt(t)}$`)}function WZn(t){let e=`${oFt}T${iFt(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function VZn(t,e){return!!((e==="v4"||!e)&&$Zn.test(t)||(e==="v6"||!e)&&FZn.test(t))}function qZn(t,e){if(!OZn.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function KZn(t,e){return!!((e==="v4"||!e)&&DZn.test(t)||(e==="v6"||!e)&&UZn.test(t))}function GZn(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,i=Number.parseInt(t.toFixed(o).replace(".","")),s=Number.parseInt(e.toFixed(o).replace(".",""));return i%s/10**o}function fB(t){if(t instanceof Gh){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=rb.create(fB(r))}return new Gh({...t._def,shape:()=>e})}else return t instanceof YP?new YP({...t._def,type:fB(t.element)}):t instanceof rb?rb.create(fB(t.unwrap())):t instanceof Lk?Lk.create(fB(t.unwrap())):t instanceof Rk?Rk.create(t.items.map(e=>fB(e))):t}function Fje(t,e){let n=zP(t),r=zP(e);if(t===e)return{valid:!0,data:t};if(n===Zt.object&&r===Zt.object){let o=ti.objectKeys(e),i=ti.objectKeys(t).filter(a=>o.indexOf(a)!==-1),s={...t,...e};for(let a of i){let l=Fje(t[a],e[a]);if(!l.valid)return{valid:!1};s[a]=l.data}return{valid:!0,data:s}}else if(n===Zt.array&&r===Zt.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let i=0;i<t.length;i++){let s=t[i],a=e[i],l=Fje(s,a);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===Zt.date&&r===Zt.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function sFt(t,e){return new $B({values:t,typeName:vr.ZodEnum,...Kr(e)})}function HYn(t){return t.startsWith("\uFEFF")?t.slice(1):t}function KYn(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),Gfe.default.platform==="darwin"?WYn(t):Gfe.default.platform==="win32"?VYn(t):qYn(t)}function GYn(){return process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC?"essential-traffic":process.env.DISABLE_TELEMETRY||xm(process.env.DO_NOT_TRACK)?"no-telemetry":"default"}function ZYn(){return GYn()==="essential-traffic"}function JYn(t){ZUe.length>=YYn&&ZUe.shift(),ZUe.push(t)}function MFt(t){let e=Ppe(t);try{if(xm(process.env.CLAUDE_CODE_USE_BEDROCK)||xm(process.env.CLAUDE_CODE_USE_VERTEX)||xm(process.env.CLAUDE_CODE_USE_FOUNDRY)||xm(process.env.CLAUDE_CODE_USE_ANTHROPIC_AWS)||xm(process.env.CLAUDE_CODE_USE_MANTLE)||process.env.DISABLE_ERROR_REPORTING||ZYn())return;let n={error:e.stack||e.message,timestamp:new Date().toISOString()};if(JYn(n),WOt===null){XYn.push({type:"error",error:e});return}WOt.logError(e)}catch{}}function eJn(t,e,n=100){let r=new Hje({max:n}),o=(...i)=>{let s=e(...i),a=r.get(s);if(a!==void 0)return a;let l=t(...i);return r.set(s,l),l};return o.cache={clear:()=>r.clear(),size:()=>r.size,delete:i=>r.delete(i),get:i=>r.peek(i),has:i=>r.has(i)},o}function $Ft(t,e){try{return{ok:!0,value:JSON.parse(HYn(t))}}catch(n){return e&&MFt(D5n(n,`safeParseJSON: invalid JSON (${n instanceof Error?n.constructor.name:typeof n}, ${t.length} bytes)`)),{ok:!1}}}function rJn(t,e,n){(n!==void 0&&!ape(t[e],n)||n===void 0&&!(e in t))&&u4e(t,e,n)}function oJn(t){return function(e,n,r){for(var o=-1,i=Object(e),s=r(e),a=s.length;a--;){var l=s[t?a:++o];if(n(i[l],l,i)===!1)break}return e}}function lJn(t){return ZB(t)&&p4e(t)}function hJn(t){if(!ZB(t)||DR(t)!=uJn)return!1;var e=ODt(t);if(e===null)return!0;var n=pJn.call(e,"constructor")&&e.constructor;return typeof n=="function"&&n instanceof n&&zFt.call(n)==mJn}function yJn(t,e){if(!(e==="constructor"&&typeof t[e]=="function")&&e!="__proto__")return t[e]}function vJn(t){return mKn(t,ADt(t))}function bJn(t,e,n,r,o,i,s){var a=Zje(t,n),l=Zje(e,n),c=s.get(l);if(c){Gje(t,n,c);return}var u=i?i(a,l,n+"",t,e,s):void 0,d=u===void 0;if(d){var f=ZP(l),p=!f&&d4e(l),m=!f&&!p&&IDt(l);u=l,f||p||m?ZP(a)?u=a:cJn(a)?u=EGn(a):p?(d=!1,u=MDt(l,!0)):m?(d=!1,u=ZGn(l,!0)):u=[]:gJn(l)||k7(l)?(u=a,k7(a)?u=wJn(a):(!Nk(a)||uBe(a))&&(u=QGn(l))):d=!1}d&&(s.set(l,u),o(u,l,r,i,s),s.delete(l)),Gje(t,n,u)}function HFt(t,e,n,r,o){t!==e&&aJn(e,function(i,s){if(o||(o=new aKn),Nk(i))_Jn(t,e,s,n,HFt,r,o);else{var a=r?r(Zje(t,s),i,s+"",t,e,o):void 0;a===void 0&&(a=i),Gje(t,s,a)}},ADt)}function SJn(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}function kJn(t,e,n){return e=KOt(e===void 0?t.length-1:e,0),function(){for(var r=arguments,o=-1,i=KOt(r.length-e,0),s=Array(i);++o<i;)s[o]=r[e+o];o=-1;for(var a=Array(e+1);++o<e;)a[o]=r[o];return a[e]=n(s),CJn(t,this,a)}}function IJn(t){return function(){return t}}function NJn(t){var e=0,n=0;return function(){var r=OJn(),o=MJn-(r-n);if(n=r,o>0){if(++e>=EJn)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function $Jn(t,e){return VFt(WFt(t,e,RDt),t+"")}function FJn(t,e,n){if(!Nk(n))return!1;var r=typeof e;return(r=="number"?p4e(n)&&Ape(e,n.length):r=="string"&&e in n)?ape(n[e],t):!1}function jJn(t){return DJn(function(e,n){var r=-1,o=n.length,i=o>1?n[o-1]:void 0,s=o>2?n[2]:void 0;for(i=t.length>3&&typeof i=="function"?(o--,i):void 0,s&&UJn(n[0],n[1],s)&&(i=o<3?void 0:i,o=1),e=Object(e);++r<o;){var a=n[r];a&&t(e,a,r,i)}return e})}function zJn(t,e,n,r){if(!Nk(t))return t;e=Epe(e,t);for(var o=-1,i=e.length,s=i-1,a=t;a!=null&&++o<i;){var l=h4e(e[o]),c=n;if(l==="__proto__"||l==="constructor"||l==="prototype")return t;if(o!=s){var u=a[l];c=r?r(u,l,a):void 0,c===void 0&&(c=Nk(u)?u:Ape(e[o+1])?[]:{})}xDt(a,l,c),a=a[l]}return t}function WJn(t,e,n){for(var r=-1,o=e.length,i={};++r<o;){var s=e[r],a=E9n(t,s);n(a,s)&&HJn(i,Epe(s,t),a)}return i}function qJn(t,e){return VJn(t,e,function(n,r){return $9n(t,r)})}function GJn(t){return ZP(t)||k7(t)||!!(GOt&&t&&t[GOt])}function qFt(t,e,n,r,o){var i=-1,s=t.length;for(n||(n=ZJn),o||(o=[]);++i<s;){var a=t[i];e>0&&n(a)?e>1?qFt(a,e-1,n,r,o):NGn(o,a):r||(o[o.length]=a)}return o}function JJn(t){var e=t==null?0:t.length;return e?YJn(t,1):[]}function QJn(t){return VFt(WFt(t,void 0,XJn),t+"")}function E4e(t){return t==="manual"?"default":t}function _Xn(){let t=A.object({type:A.literal("command").describe("Shell command hook type"),command:A.string().describe("Shell command to execute"),args:A.array(A.string()).optional().describe("Argument list for exec form. When present, `command` is resolved as an executable and spawned directly with these arguments \u2014 no shell. Path placeholders like ${CLAUDE_PLUGIN_ROOT} are substituted per-element as plain strings, so paths with quotes, $, or backticks never reach a shell parser. When absent, `command` runs through a shell (bash on POSIX, PowerShell on Windows without Git Bash)."),if:XZ(),shell:A.enum(bXn).optional().describe("Shell interpreter. 'bash' uses your $SHELL (bash/zsh/sh); 'powershell' uses pwsh. Defaults to bash (powershell on Windows without Git Bash)."),timeout:A.number().positive().optional().describe("Timeout in seconds for this specific command"),statusMessage:A.string().optional().describe("Custom status message to display in spinner while hook runs"),once:A.boolean().optional().describe("If true, hook runs once and is removed after execution"),async:A.boolean().optional().describe("If true, hook runs in background without blocking"),asyncRewake:A.boolean().optional().describe("If true, hook runs in background and wakes the model on exit code 2 (blocking error). Implies async."),rewakeMessage:A.string().min(1).optional().describe("@internal Custom prefix for the system-reminder shown to the model when an asyncRewake hook exits with code 2. The hook output is appended after this prefix."),rewakeSummary:A.string().min(1).optional().describe('@internal One-line summary shown to the user in the terminal when an asyncRewake hook exits with code 2. Defaults to "Stop hook feedback".')}),e=A.object({type:A.literal("prompt").describe("LLM prompt hook type"),prompt:A.string().describe("Prompt to evaluate with LLM. Use $ARGUMENTS placeholder for hook input JSON."),if:XZ(),timeout:A.number().positive().optional().describe("Timeout in seconds for this specific prompt evaluation"),model:A.string().optional().describe('Model to use for this prompt hook (e.g., "claude-sonnet-5"). If not specified, uses the default small fast model.'),continueOnBlock:A.boolean().optional().describe(`Sets the continue value for the decision:"block" produced when ok is false. Default false (turn ends). Whether continue:true lets the turn proceed depends on the event's decision:"block" semantics. On PostToolUse, the reason is fed back to Claude and the turn continues.`),statusMessage:A.string().optional().describe("Custom status message to display in spinner while hook runs"),once:A.boolean().optional().describe("If true, hook runs once and is removed after execution")}),n=A.object({type:A.literal("mcp_tool").describe("MCP tool hook type"),server:A.string().describe("Name of an already-configured MCP server to invoke"),tool:A.string().describe("Name of the tool on that server to call"),input:A.record(A.string(),A.unknown()).optional().describe('Arguments passed to the MCP tool. String values support ${path} interpolation from the hook input JSON (e.g. "${tool_input.file_path}").'),if:XZ(),timeout:A.number().positive().optional().describe("Timeout in seconds for this specific tool call"),statusMessage:A.string().optional().describe("Custom status message to display in spinner while hook runs"),once:A.boolean().optional().describe("If true, hook runs once and is removed after execution")}),r=A.object({type:A.literal("http").describe("HTTP hook type"),url:A.string().url().describe("URL to POST the hook input JSON to"),if:XZ(),timeout:A.number().positive().optional().describe("Timeout in seconds for this specific request"),headers:A.record(A.string(),A.string()).optional().describe('Additional headers to include in the request. Values may reference environment variables using $VAR_NAME or ${VAR_NAME} syntax (e.g., "Authorization": "Bearer $MY_TOKEN"). Only variables listed in allowedEnvVars will be interpolated.'),allowedEnvVars:A.array(A.string()).optional().describe("Explicit list of environment variable names that may be interpolated in header values. Only variables listed here will be resolved; all other $VAR references are left as empty strings. Required for env var interpolation to work."),statusMessage:A.string().optional().describe("Custom status message to display in spinner while hook runs"),once:A.boolean().optional().describe("If true, hook runs once and is removed after execution")}),o=A.object({type:A.literal("agent").describe("Agentic verifier hook type"),prompt:A.string().describe('Prompt describing what to verify (e.g. "Verify that unit tests ran and passed."). Use $ARGUMENTS placeholder for hook input JSON.'),if:XZ(),timeout:A.number().positive().optional().describe("Timeout in seconds for agent execution (default 60)"),model:A.string().optional().describe('Model to use for this agent hook (e.g., "claude-sonnet-5"). If not specified, uses Haiku.'),statusMessage:A.string().optional().describe("Custom status message to display in spinner while hook runs"),once:A.boolean().optional().describe("If true, hook runs once and is removed after execution")});return{BashCommandHookSchema:t,PromptHookSchema:e,HttpHookSchema:r,AgentHookSchema:o,McpToolHookSchema:n}}function JFt({request_timeout_ms:t,...e}){return{...e,...e.timeout===void 0&&t!==void 0&&{timeout:Math.min(t,CXn)}}}function FXn(t){return e2t.has(t.toLowerCase())?!1:DXn.test(t)?!0:$Xn.test(t)}function aQn(t){let e=A.record(A.string(),A.unknown()).safeParse(t);if(!e.success)return;let n=Object.create(null),r=0;for(let[o,i]of Object.entries(e.data)){if(r>=iQn)break;let s=sQn().safeParse(i);rQn.test(o)&&s.success&&(n[o]=s.data,r++)}return r>0?n:void 0}function yQn(t){let e=hQn();return t.flatMap((n,r)=>{let o=e.safeParse(n);if(o.success)return[o.data];let i=gQn().safeParse(n).data?.name,s=o.error.issues.map(a=>`${a.path.join(".")}: ${a.message}`).join(", ");return i?(Ka(`Stubbing unparseable marketplace plugin entry (${i}): ${s}`,{level:"warn"}),[{name:i,source:{source:"unsupported"},strict:!0}]):(Ka(`Dropping unparseable marketplace plugin entry (index ${r}): ${s}`,{level:"warn"}),[])})}function c2t(){return IQn.filter(t=>Dpe[t].buildGate())}function TQn(t){let e={};for(let n of t)e={...e,...Dpe[n].shape()};return e}function PQn(t){let e={};for(let n of t)e={...e,...Dpe[n].permissionsShape?.()};return e}function AQn(t){let e=[];for(let n of t)e.push(...Dpe[n].permissionModes?.()??[]);return e}function u2t(t){let e=t.split("__"),[n,r,...o]=e;if(n!=="mcp"||!r)return null;let i=o.length>0?o.join("__"):void 0;return{serverName:r,toolName:i}}function lB(t){return Object.hasOwn(XOt,t)?XOt[t]:t}function QOt(t){return t.includes("*")}function EQn(t){return t.replaceAll("\\(","(").replaceAll("\\)",")").replaceAll("\\\\","\\")}function MQn(t){let e=OQn(t,"(");if(e===-1)return{toolName:lB(t)};let n=NQn(t,")");if(n===-1||n<=e)return{toolName:lB(t)};if(n!==t.length-1)return{toolName:lB(t)};let r=t.substring(0,e),o=t.substring(e+1,n);if(!r)return{toolName:lB(t)};if(o===""||o==="*")return{toolName:lB(r)};let i=EQn(o);return{toolName:lB(r),ruleContent:i}}function OQn(t,e){for(let n=0;n<t.length;n++)if(t[n]===e){let r=0,o=n-1;for(;o>=0&&t[o]==="\\";)r++,o--;if(r%2===0)return n}return-1}function NQn(t,e){for(let n=t.length-1;n>=0;n--)if(t[n]===e){let r=0,o=n-1;for(;o>=0&&t[o]==="\\";)r++,o--;if(r%2===0)return n}return-1}function RQn(t){return Xfe.filePatternTools.includes(t)}function LQn(t){return Xfe.bashPrefixTools.includes(t)}function $Qn(t){return Object.hasOwn(Xfe.customValidation,t)?Xfe.customValidation[t]:void 0}function f2t(t,e){let n=0,r=e-1;for(;r>=0&&t[r]==="\\";)n++,r--;return n%2!==0}function JUe(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&!f2t(t,r)&&n++;return n}function DQn(t){for(let e=0;e<t.length-1;e++)if(t[e]==="("&&t[e+1]===")"&&!f2t(t,e))return!0;return!1}function eNt(t){if(!QOt(t))return null;let e=u2t(t);return e&&!QOt(e.serverName)?null:{valid:!1,error:`Wildcard tool name "${t}" is not supported in allow rules`,suggestion:"An allow pattern must name the scope it widens \u2014 globs are permitted only in the tool position after a literal mcp__<server>__ prefix. Deny and ask rules accept wildcards anywhere",examples:["mcp__puppeteer__*","mcp__github__get_*"]}}function FQn(t,e){if(!t||t.trim()==="")return{valid:!1,error:"Permission rule cannot be empty"};let n=JUe(t,"("),r=JUe(t,")");if(n!==r)return{valid:!1,error:"Mismatched parentheses",suggestion:"Ensure all opening parentheses have matching closing parentheses"};if(DQn(t)){let a=t.substring(0,t.indexOf("("));return a?{valid:!1,error:"Empty parentheses",suggestion:`Either specify a pattern or use just "${a}" without parentheses`,examples:[`${a}`,`${a}(some-pattern)`]}:{valid:!1,error:"Empty parentheses with no tool name",suggestion:"Specify a tool name before the parentheses"}}let o=MQn(t),i=u2t(o.toolName);if(i){if(o.ruleContent!==void 0||JUe(t,"(")>0)return{valid:!1,error:"MCP rules do not support patterns in parentheses",suggestion:`Use "${o.toolName}" without parentheses, or use "mcp__${i.serverName}__*" for all tools`,examples:[`mcp__${i.serverName}`,`mcp__${i.serverName}__*`,i.toolName&&i.toolName!=="*"?`mcp__${i.serverName}__${i.toolName}`:void 0].filter(Boolean)};if(e==="allow"){let a=eNt(o.toolName);if(a)return a}return{valid:!0}}if(!o.toolName||o.toolName.length===0)return{valid:!1,error:"Tool name cannot be empty"};if(e==="allow"){let a=eNt(o.toolName);if(a)return a}if(!o.toolName.includes("_")&&o.toolName[0]!==o.toolName[0]?.toUpperCase())return{valid:!1,error:"Tool names must start with uppercase",suggestion:`Use "${c8n(String(o.toolName))}"`};let s=$Qn(o.toolName);if(s&&o.ruleContent!==void 0){let a=s(o.ruleContent);if(!a.valid)return a}if(LQn(o.toolName)&&o.ruleContent!==void 0){let a=o.ruleContent;if(a.includes(":*")&&!a.endsWith(":*"))return{valid:!1,error:"The :* pattern must be at the end",suggestion:"Move :* to the end for prefix matching, or use * for wildcard matching",examples:["Bash(npm run:*) - prefix matching (legacy)","Bash(npm run *) - wildcard matching"]};if(a===":*")return{valid:!1,error:"Prefix cannot be empty before :*",suggestion:"Specify a command prefix before :*",examples:["Bash(npm *)","Bash(git *)"]}}return RQn(o.toolName)&&o.ruleContent!==void 0&&o.ruleContent.includes(":*")?{valid:!1,error:'The ":*" syntax is only for Bash prefix rules',suggestion:'Use glob patterns like "*" or "**" for file matching',examples:[`${o.toolName}(*.ts) - matches .ts files`,`${o.toolName}(src/**) - matches all files in src`,`${o.toolName}(**/*.test.ts) - matches test files`]}:{valid:!0}}function p2t(t){return A.string().superRefine((e,n)=>{let r=FQn(e,t);if(!r.valid){let o=r.error;r.suggestion&&(o+=`. ${r.suggestion}`),r.examples&&r.examples.length>0&&(o+=`. Examples: ${r.examples.join(", ")}`),n.addIssue({code:A.ZodIssueCode.custom,message:o,params:{received:e}})}})}function m2t(t){return A.object({allow:A.array(UQn()).optional().describe("List of permission rules for allowed operations"),deny:A.array(tNt()).optional().describe("List of permission rules for denied operations"),ask:A.array(tNt()).optional().describe("List of permission rules that should always prompt for confirmation"),defaultMode:A.preprocess(E4e,A.enum([...A4e,...AQn(t)])).optional().describe("Default permission mode when Claude Code needs access ('manual' is accepted as an alias for 'default')"),disableBypassPermissionsMode:A.enum(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),...PQn(t),additionalDirectories:A.array(A.string()).optional().describe("Additional directories to include in the permission scope")}).passthrough()}function qQn(t){return A.object({$schema:A.string().optional().describe("JSON Schema reference for Claude Code settings"),apiKeyHelper:A.string().optional().describe("Path to a script that outputs authentication values"),proxyAuthHelper:A.string().optional().describe("Shell command that outputs a Proxy-Authorization header value (EAP)"),awsCredentialExport:A.string().optional().describe("Path to a script that exports AWS credentials"),awsAuthRefresh:A.string().optional().describe("Path to a script that refreshes AWS authentication"),gcpAuthRefresh:A.string().optional().describe("Command to refresh GCP authentication (e.g., gcloud auth application-default login)"),policyHelper:WQn().optional().describe("Executable that computes managed settings at startup. Honored only from admin-controlled policy sources."),...xm(process.env.CLAUDE_CODE_ENABLE_XAA)&&{xaaIdp:A.object({issuer:A.string().url().describe("IdP issuer URL for OIDC discovery"),clientId:A.string().describe("Claude Code's client_id registered at the IdP"),callbackPort:A.number().int().positive().optional().describe("Fixed loopback callback port for the IdP OIDC login. Only needed if the IdP does not honor RFC 8252 port-any matching.")}).optional().describe("XAA (SEP-990) IdP connection. Configure once; all XAA-enabled MCP servers reuse this.")},fileSuggestion:A.object({type:A.literal("command"),command:A.string()}).optional().describe("Custom file suggestion configuration for @ mentions"),respectGitignore:A.boolean().optional().describe("Whether file picker should respect .gitignore files (default: true). Note: .ignore files are always respected."),breakReminder:A.object({enabled:A.boolean().optional().describe("Show a friendly nudge after sustained continuous use (default false). Must be true for the reminder to fire."),intervalMinutes:A.number().int().positive().optional().describe("Minutes of continuous use before the reminder fires (default 30). Re-fires every interval until you take a break."),breakThresholdMinutes:A.number().int().positive().optional().describe("Minutes of inactivity that count as a break and reset the timer (default 10)"),message:A.string().optional().describe("Custom reminder text. Leave unset for a rotating set of friendly nudges.")}).optional().describe("@internal Opt-in break reminder. When enabled, shows a dismissible nudge after sustained continuous use. Never blocks \u2014 just a friendly heads-up."),quietHours:A.object({enabled:A.boolean().optional().describe("Show a one-time nudge when you start or keep using the CLI inside your quiet-hours window (default false)."),start:A.string().regex(/^([01]?\d|2[0-3]):[0-5]\d$/,'Expected 24-hour local time "HH:MM" (e.g. "22:00")').optional().describe('Start of the quiet-hours window, 24-hour local time "HH:MM".'),end:A.string().regex(/^([01]?\d|2[0-3]):[0-5]\d$/,'Expected 24-hour local time "HH:MM" (e.g. "07:00")').optional().describe('End of the quiet-hours window, 24-hour local time "HH:MM". May be earlier than start for an overnight range.')}).optional().describe("@internal Opt-in quiet hours. When enabled, shows a single soft nudge per session while inside the configured local-time window. Never blocks."),cleanupPeriodDays:A.number().int().positive().optional().describe("Number of days to retain chat transcripts before automatic cleanup (default: 30). Minimum 1. Use a large value for long retention; use --no-session-persistence to disable transcript writes entirely."),skillListingMaxDescChars:A.number().int().positive().optional().describe("Per-skill description character cap in the skill listing sent to Claude (default: 1536). Descriptions longer than this are truncated. Raise to opt in to higher per-turn context cost."),skillListingBudgetFraction:A.number().gt(0).lte(1).optional().describe("Fraction of the context window (in characters) reserved for the skill listing sent to Claude (default: 0.01 = 1%). When the listing exceeds this, descriptions are shortened to fit. Raise to opt in to higher per-turn context cost."),wslInheritsWindowsSettings:A.boolean().optional().describe("When set to true in either admin-only Windows source \u2014 the HKLM SOFTWARE/Policies/ClaudeCode registry key or C:/Program Files/ClaudeCode/managed-settings.json \u2014 WSL reads managed settings from the full Windows policy chain (HKLM, C:/Program Files/ClaudeCode via DrvFs, HKCU) in addition to /etc/claude-code. Windows sources take priority. The flag is also required in HKCU itself for HKCU policy to apply on WSL (double opt-in: admin enables the chain, user confirms HKCU). On native Windows the flag has no effect."),env:jQn().optional().describe("Environment variables to set for Claude Code sessions"),attribution:A.object({commit:A.string().optional().describe("Attribution text for git commits, including any trailers. Empty string hides attribution."),pr:A.string().optional().describe("Attribution text for pull request descriptions. Empty string hides attribution."),sessionUrl:A.boolean().optional().describe("Whether to append the claude.ai session link to commits and PRs created from web or Remote Control sessions (default: true). Set to false to omit the Claude-Session trailer and PR-body link.")}).optional().describe("Customize attribution text for commits and PRs. Each field defaults to the standard Claude Code attribution if not set."),includeCoAuthoredBy:A.boolean().optional().describe("Deprecated: Use attribution instead. Whether to include Claude's co-authored by attribution in commits and PRs (defaults to true)"),includeGitInstructions:A.boolean().optional().describe("Include built-in commit and PR workflow instructions in Claude's system prompt (default: true)"),permissions:m2t(t).optional().describe("Tool usage permissions configuration"),model:A.string().optional().describe("Override the default model used by Claude Code"),fallbackModel:A.array(A.string()).optional().describe('Fallback model(s) tried in order when the primary model is overloaded or unavailable. Each element accepts a model name or alias; "default" expands to the default model. CLI --fallback-model takes precedence.'),availableModels:A.array(A.string()).optional().describe('Allowlist of models that users can select. Accepts family aliases ("opus" allows any opus version), version prefixes ("opus-4-5" allows only that version), and full model IDs. If undefined, all models are available. If empty array, only the default model is available. Typically set in managed settings by enterprise administrators.'),enforceAvailableModels:A.boolean().optional().describe("When true and availableModels is a non-empty array, the Default model selection is also constrained: if the default model for the user tier is not in availableModels, Default resolves to the first allowed availableModels entry instead. Has no effect when availableModels is unset or an empty array. Typically set in managed settings by enterprise administrators."),modelOverrides:A.record(A.string(),A.string()).optional().describe('Override mapping from Anthropic model ID (e.g. "claude-opus-4-6") to provider-specific model ID (e.g. a Bedrock inference profile ARN). Typically set in managed settings by enterprise administrators.'),enableAllProjectMcpServers:A.boolean().optional().describe("Whether to automatically approve all MCP servers in the project"),enabledMcpjsonServers:A.array(A.string()).optional().describe("List of approved MCP servers from .mcp.json"),disabledMcpjsonServers:A.array(A.string()).optional().describe("List of rejected MCP servers from .mcp.json"),disableClaudeAiConnectors:A.boolean().optional().describe("When true in any settings source, claude.ai MCP cloud connectors are not auto-fetched or connected. Only gates auto-fetched connectors \u2014 a claudeai-proxy server passed explicitly (e.g. via --mcp-config or the SDK mcpServers option) still follows the normal MCP config trust flow. Any-source-true wins: a project can opt out, but a project-level false cannot override a user-level true."),skillOverrides:A.record(A.string(),A.enum(["on","name-only","user-invocable-only","off"])).optional().describe('Per-skill listing overrides keyed by skill name. "name-only" lists the skill without its description; "user-invocable-only" hides it from the model but keeps /name; "off" hides it from both. Absent = on.'),disableBundledSkills:A.boolean().optional().describe("Disable the skills and workflows that ship with Claude Code: bundled skills and workflows are removed entirely; built-in slash commands stay typable but are hidden from the model. Plugins, .claude/skills/, and .claude/commands/ are unaffected. Equivalent to CLAUDE_CODE_DISABLE_BUNDLED_SKILLS=1."),allowedMcpServers:A.array(zQn()).optional().describe("Enterprise allowlist of MCP servers that can be used. Applies to all scopes including enterprise servers from managed-mcp.json. If undefined, all servers are allowed. If empty array, no servers are allowed. Denylist takes precedence - if a server is on both lists, it is denied."),deniedMcpServers:A.array(HQn()).optional().describe("Enterprise denylist of MCP servers that are explicitly blocked. If a server is on the denylist, it will be blocked across all scopes including enterprise. Denylist takes precedence over allowlist - if a server is on both lists, it is denied."),hooks:Yfe().optional().describe("Custom commands to run before/after tool executions"),worktree:A.object({symlinkDirectories:A.array(A.string()).optional().describe('Directories to symlink from main repository to worktrees to avoid disk bloat. Must be explicitly configured - no directories are symlinked by default. Common examples: "node_modules", ".cache", ".bin"'),sparsePaths:A.array(A.string()).optional().describe("Directories to include when creating worktrees, via git sparse-checkout (cone mode). Dramatically faster in large monorepos \u2014 only the listed paths are written to disk."),baseRef:A.enum(["fresh","head"]).optional().describe("Which ref new worktrees branch from. 'fresh' (default) branches from origin/<default-branch> for a clean tree. 'head' branches from your current local HEAD so unpushed commits and feature-branch state are present. Applies to --worktree, EnterWorktree, and agent isolation."),bgIsolation:A.enum(["worktree","none"]).optional().catch(void 0).describe("Isolation mode for background sessions in this repo. 'worktree' (default) blocks Edit/Write in the main checkout until EnterWorktree is called. 'none' lets background jobs edit the working copy directly.")}).optional().describe("Git worktree configuration for --worktree flag."),disableAllHooks:A.boolean().optional().describe("Disable all hooks and statusLine execution"),disableAgentView:A.boolean().optional().describe("Disable agent view (`claude agents`, `--bg`, /background, the on-demand daemon). Typically set in managed settings. Equivalent to CLAUDE_CODE_DISABLE_AGENT_VIEW=1."),disableRemoteControl:A.boolean().optional().describe("Disable Remote Control (claude.ai/code, `claude remote-control`, `--remote-control`/`--rc`, auto-start, and the in-session toggle). Typically set in managed settings."),disableWorkflows:A.boolean().optional().describe("Disable the Workflows feature (also via CLAUDE_CODE_DISABLE_WORKFLOWS)."),disableArtifact:A.boolean().optional().describe("Disable the Artifact tool (also via CLAUDE_CODE_DISABLE_ARTIFACT)."),enableArtifact:A.boolean().optional().describe("Enable or disable the Artifact tool for this user. Unset defaults to enabled once the feature is available."),enableWorkflows:A.boolean().optional().describe("Enable or disable the Workflows feature for this user. Unset = default by plan once the feature is available."),workflowKeywordTriggerEnabled:A.boolean().optional().describe('Enable the "ultracode" keyword trigger: including the keyword in a prompt opts that turn into the Workflow tool. Set to false to disable the trigger. Default: true.'),disableSkillShellExecution:A.boolean().optional().describe("Disable inline shell execution in skills and custom slash commands from user, project, or plugin sources. Commands are replaced with a placeholder instead of being run."),defaultShell:A.enum(["bash","powershell"]).optional().describe("Default shell for input-box ! commands. Defaults to 'bash' on all platforms (no Windows auto-flip)."),respondToBashCommands:A.boolean().optional().describe("Whether Claude responds after an input-box ! bash command runs. Set to false to add the command output to context without a response. Default: true."),allowManagedHooksOnly:A.boolean().optional().describe("When true (and set in managed settings), only hooks from managed settings run. User, project, and local hooks are ignored."),allowedHttpHookUrls:A.array(A.string()).optional().describe('Allowlist of URL patterns that HTTP hooks may target. Supports * as a wildcard (e.g. "https://hooks.example.com/*"). When set, HTTP hooks with non-matching URLs are blocked. If undefined, all URLs are allowed. If empty array, no HTTP hooks are allowed. Arrays merge across settings sources (same semantics as allowedMcpServers).'),httpHookAllowedEnvVars:A.array(A.string()).optional().describe("Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook's effective allowedEnvVars is the intersection with this list. If undefined, no restriction is applied. Arrays merge across settings sources (same semantics as allowedMcpServers)."),allowManagedPermissionRulesOnly:A.boolean().optional().describe("When true (and set in managed settings), only permission rules (allow/deny/ask) from managed settings are respected. User, project, local, and CLI argument permission rules are ignored."),allowManagedMcpServersOnly:A.boolean().optional().describe("When true (and set in managed settings), allowedMcpServers is only read from managed settings. deniedMcpServers still merges from all sources, so users can deny servers for themselves. Users can still add their own MCP servers, but only the admin-defined allowlist applies."),allowAllClaudeAiMcps:A.boolean().optional().describe("When true (and set in managed settings), claude.ai cloud MCP connectors load alongside managed-mcp.json instead of being suppressed by its exclusive-control lockdown. Default off preserves the lockdown. Read from managed settings only."),strictPluginOnlyCustomization:A.preprocess(e=>Array.isArray(e)?e.filter(n=>nNt.includes(n)):e,A.union([A.boolean(),A.array(A.enum(nNt))])).optional().catch(void 0).describe('When set in managed settings, blocks non-plugin customization sources for the listed surfaces. Array form locks specific surfaces (e.g. ["skills", "hooks"]); `true` locks all four; `false` is an explicit no-op. Blocked: ~/.claude/{surface}/, .claude/{surface}/ (project), settings.json hooks, .mcp.json. NOT blocked: managed (policySettings) sources, plugin-provided customizations. Composes with strictKnownMarketplaces for end-to-end admin control \u2014 plugins gated by marketplace allowlist, everything else blocked here.'),statusLine:A.object({type:A.literal("command"),command:A.string(),padding:A.number().optional(),refreshInterval:A.number().min(1).optional().catch(void 0).describe("Re-run the status line command every N seconds in addition to event-driven updates"),hideVimModeIndicator:A.boolean().optional().describe("Hide the built-in `-- INSERT --` / `-- VISUAL --` indicator below the prompt. Use this when your status line script renders `vim.mode` itself.")}).optional().describe("Custom status line display configuration"),prUrlTemplate:A.string().optional().describe('URL template for PR links in the footer link badges and inline messages. The detected git PR is rendered as the first footer-link badge. Placeholders: {host} {owner} {repo} {number} {url}. Example: "https://reviews.example.com/{owner}/{repo}/pull/{number}"'),footerLinksRegexes:A.array(VQn().catch(rNt)).transform(e=>e.filter(n=>n!==rNt)).optional().catch(void 0).describe("Extra clickable footer badges that appear when a regex matches turn output (tool results and assistant responses). Read from user, flag, and managed settings only; ignored in project .claude/settings.json and local .claude/settings.local.json. At most 5 badges render; the oldest is displaced by newer matches and /clear removes them. Use to surface IDs printed by project CLIs as session links."),subagentStatusLine:A.object({type:A.literal("command"),command:A.string()}).optional().describe("Custom per-subagent status line shown in the agent panel; receives row context as JSON on stdin"),enabledPlugins:A.record(A.string(),A.union([A.array(A.string()),A.boolean(),A.undefined()])).optional().describe('Enabled plugins using plugin-id@marketplace-id format. Example: { "formatter@anthropic-tools": true }. Also supports extended format with version constraints. Settings precedence is user < project < local < flag < policy, so to disable a plugin that project settings enable, set it to false in .claude/settings.local.json \u2014 setting false in ~/.claude/settings.json is overridden by the project.'),extraKnownMarketplaces:A.record(A.string(),BQn()).check(e=>{for(let[n,r]of Object.entries(e.value))r.source.source==="settings"&&r.source.name!==n&&e.issues.push({code:"custom",input:r.source.name,path:[n,"source","name"],message:`Settings-sourced marketplace name must match its extraKnownMarketplaces key (got key "${n}" but source.name "${r.source.name}")`})}).optional().describe("Additional marketplaces to make available for this repository. Typically used in repository .claude/settings.json to ensure team members have required plugin sources."),strictKnownMarketplaces:A.array(Jfe()).optional().describe("Enterprise strict list of allowed marketplace sources. When set in managed settings, ONLY these exact sources can be added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem. Note: this is a policy gate only \u2014 it does NOT register marketplaces. To pre-register allowed marketplaces for users, also set extraKnownMarketplaces."),blockedMarketplaces:A.array(Jfe()).optional().describe("Enterprise blocklist of marketplace sources. When set in managed settings, these exact sources are blocked from being added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem."),disableSideloadFlags:A.boolean().optional().describe("When true (and set in managed settings), rejects the --plugin-dir, --plugin-url, --agents, and non-sdk --mcp-config CLI flags at startup. Closes the CLI-flag bypass of strictKnownMarketplaces. Pair with allowedMcpServers for per-server MCP control; this setting does not gate other MCP entry points (SDK setMcpServers, claude mcp add, .mcp.json). Also blocks surfaces that spawn the CLI with these flags internally (see settings documentation). Only honored from managed settings; ignored in user/project/local settings."),pluginSuggestionMarketplaces:A.array(A.string()).optional().describe("Marketplace names whose plugins may surface as contextual install suggestions (relevance-based tips). No marketplace-declared suggestions surface without this allowlist; the built-in first-party frontend-design tip is unaffected. Only honored when set in managed settings (policy scope); the key is ignored in user, project, and local settings. A name only takes effect when the marketplace is registered on the machine AND its registered source is also declared in managed settings, either as the extraKnownMarketplaces entry for that name or as an entry of strictKnownMarketplaces. A marketplace registered from a different source under an allowlisted name is ignored. The official marketplace is exempt from the source requirement: allowlisting its name alone suffices, since that name can only register from the official Anthropic source."),forceLoginMethod:A.enum(["claudeai","console","gateway"]).optional().catch(void 0).describe('Force a specific login method: "claudeai" for Claude Pro/Max, "console" for Console billing, "gateway" for the Cloud gateway OIDC device flow'),forceLoginGatewayUrl:A.string().url().optional().catch(void 0).describe('@internal Cloud gateway URL to pre-fill and auto-connect to during login. Typically set in local managed settings alongside forceLoginMethod: "gateway" so users never type the URL. Hidden from public SDK types until Cloud gateway is documented.'),parentSettingsBehavior:A.enum(["first-wins","merge"]).optional().describe(`Controls whether the SDK parent tier (Options.managedSettings / --managed-settings) layers under this admin tier. "first-wins" (default): parent is dropped \u2014 admin tiers are the only policy source. "merge": parent's restrictive-only-filtered settings union under the admin winner. Has no effect when no admin tier exists (parent applies as the sole policy tier, still filtered restrictive-only).`),forceLoginOrgUUID:A.union([A.string(),A.array(A.string())]).optional().describe("Organization UUID to require for OAuth login. Accepts a single UUID string or an array of UUIDs (any one is permitted). When set in managed settings, login fails if the authenticated account does not belong to a listed organization."),forceRemoteSettingsRefresh:A.boolean().optional().describe("When set in managed settings, the CLI blocks startup until remote managed settings are freshly fetched, and exits if the fetch fails"),otelHeadersHelper:A.string().optional().describe("Path to a script that outputs OpenTelemetry headers"),outputStyle:A.string().optional().describe("Controls the output style for assistant responses"),viewMode:A.enum(["default","verbose","focus"]).optional().catch(void 0).describe("Default transcript view mode on startup"),language:A.string().optional().describe('Preferred language for Claude responses and voice dictation (e.g., "japanese", "spanish")'),skipWebFetchPreflight:A.boolean().optional().describe("Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"),sandbox:fXn().optional(),feedbackSurveyRate:A.number().min(0).max(1).optional().describe("Probability (0\u20131) that the session quality survey appears when eligible. 0.05 is a reasonable starting point."),spinnerTipsEnabled:A.boolean().optional().describe("Whether to show tips in the spinner"),spinnerVerbs:A.object({mode:A.enum(["append","replace"]),verbs:A.array(A.string())}).optional().describe('Customize spinner verbs. mode: "append" adds verbs to defaults, "replace" uses only your verbs.'),spinnerTipsOverride:A.object({excludeDefault:A.boolean().optional(),tips:A.array(A.string())}).optional().describe("Override spinner tips. tips: array of tip strings. excludeDefault: if true, only show custom tips (default: false)."),syntaxHighlightingDisabled:A.boolean().optional().describe("Whether to disable syntax highlighting in diffs"),terminalTitleFromRename:A.boolean().optional().describe("Whether /rename updates the terminal tab title (defaults to true). Set to false to keep auto-generated topic titles."),alwaysThinkingEnabled:A.boolean().optional().describe("When false, thinking is disabled. When absent or true, thinking is enabled automatically for supported models."),effortLevel:A.enum(["low","medium","high","xhigh"]).optional().catch(void 0).describe("Persisted effort level for supported models."),ultracode:A.boolean().optional().catch(void 0).describe("Enable ultracode for the session: xhigh effort plus standing dynamic-workflow orchestration. Session-scoped \u2014 typically provided via --settings or the apply_flag_settings control request; interactive toggles never persist it. Requires workflows to be enabled and an xhigh-capable model."),autoCompactWindow:A.number().int().min(1e5).max(1e6).optional().catch(void 0).describe("Auto-compact window size"),advisorModel:A.string().optional().describe("Advisor model for the server-side advisor tool."),fastMode:A.boolean().optional().describe("When true, fast mode is enabled. When absent or false, fast mode is off."),fastModePerSessionOptIn:A.boolean().optional().describe("When true, fast mode does not persist across sessions. Each session starts with fast mode off."),promptSuggestionEnabled:A.boolean().optional().describe("When false, prompt suggestions are disabled. When absent or true, prompt suggestions are enabled."),awaySummaryEnabled:A.boolean().optional().describe("@internal When false, the session recap (shown when you return after being away for 5+ minutes) is disabled. When absent or true, recap is enabled. Hidden from public SDK types until external launch."),showClearContextOnPlanAccept:A.boolean().optional().describe('When true, the plan-approval dialog offers a "clear context" option. Defaults to false.'),askUserQuestionTimeout:A.enum(["60s","5m","10m","never"]).optional().catch(void 0).describe("Idle time before Claude's questions auto-continue with any answers selected so far. Defaults to never \u2014 auto-continue only runs when explicitly set to 60s/5m/10m."),agent:A.string().optional().describe("Name of an agent (built-in or custom) to use for the main thread. Applies the agent's system prompt, tool restrictions, and model."),companyAnnouncements:A.array(A.string()).optional().describe("Company announcements to display at startup (one will be randomly selected if multiple are provided)"),pluginConfigs:A.record(A.string(),A.object({mcpServers:A.record(A.string(),A.record(A.string(),A.union([A.string(),A.number(),A.boolean(),A.array(A.string())]))).optional().describe("User configuration values for MCP servers keyed by server name"),options:A.record(A.string(),A.union([A.string(),A.number(),A.boolean(),A.array(A.string())])).optional().describe("Non-sensitive option values from plugin manifest userConfig, keyed by option name. Sensitive values go to secure storage instead.")}).or(A.undefined())).optional().describe("Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format)"),remote:A.object({defaultEnvironmentId:A.string().optional().describe("Default environment ID to use for cloud sessions")}).optional().describe("Cloud session configuration"),autoUpdatesChannel:A.enum(["latest","stable","rc"]).optional().describe("Release channel for auto-updates (latest or stable)"),minimumVersion:A.string().optional().describe("Minimum version to stay on - prevents downgrades when switching to stable channel"),requiredMinimumVersion:A.string().optional().describe("Minimum Claude Code version required to start. If the running version is older, Claude Code exits at startup with instructions to update. Only enforced from managed (policy) settings."),requiredMaximumVersion:A.string().optional().describe("Maximum Claude Code version allowed to start. If the running version is newer, Claude Code exits at startup with instructions to install an approved version. Only enforced from managed (policy) settings."),plansDirectory:A.string().optional().describe("Custom directory for plan files, relative to project root. If not set, defaults to ~/.claude/plans/"),tui:A.enum(["default","fullscreen"]).optional().describe('Terminal UI renderer. "fullscreen" uses the flicker-free alt-screen renderer with virtualized scrollback (equivalent to CLAUDE_CODE_NO_FLICKER=1). "default" uses the classic main-screen renderer.'),voice:A.object({enabled:A.boolean().optional(),mode:A.enum(["hold","tap"]).optional().describe("'hold' (default): hold to talk. 'tap': tap to start, tap to stop+submit."),autoSubmit:A.boolean().optional().describe("Submit the prompt when hold-to-talk is released (hold mode only)")}).optional().describe("Voice mode settings (hold-to-talk / tap-to-toggle dictation)"),channelsEnabled:A.boolean().optional().describe("Managed-org opt-in for channel notifications (MCP servers with the claude/channel capability pushing inbound messages). claude.ai Teams/Enterprise: default off. Console: default on unless managed settings exist. Set true to allow; users then select servers via --channels."),allowedChannelPlugins:A.array(A.object({marketplace:A.string(),plugin:A.string()})).optional().describe("Managed-org allowlist of channel plugins. When set, replaces the default Anthropic allowlist \u2014 admins decide which plugins may push inbound messages. Undefined falls back to the default. Requires channelsEnabled: true."),prefersReducedMotion:A.boolean().optional().describe("Reduce or disable animations for accessibility (spinner shimmer, flash effects, etc.)"),doneMeansMerged:A.boolean().optional().describe("@internal When true, Claude keeps working until the PR is ready for you to merge, a cron/Monitor is armed to resume later, or it hands you a self-contained next step."),totalTokensReminder:A.enum(["off","infinite","fixed","countdown","padded-countdown"]).optional().describe("@internal Emit a <total_tokens>N tokens left</total_tokens> block in the system prompt, after each tool result, and (when totalTokensReminderAfterUserTurn is on) after each regular user prompt. 'infinite' uses the literal value Infinite, 'fixed' uses 5000000, 'countdown' uses the live remaining context-window tokens, 'padded-countdown' counts down from totalTokensReminderBudget (re-anchoring to the full budget on each regular user prompt when totalTokensReminderAfterUserTurn is on \u2014 task-budget semantics). Defaults to off. Env var CLAUDE_CODE_TOTAL_TOKENS_REMINDER overrides."),totalTokensReminderBudget:A.number().int().positive().optional().describe("@internal Starting budget (tokens) for totalTokensReminder 'padded-countdown' mode. Defaults to 15000000. Server-controlled via GrowthBook; env var CLAUDE_CODE_TOTAL_TOKENS_REMINDER_BUDGET overrides."),totalTokensReminderAfterUserTurn:A.boolean().optional().describe("@internal When true, emit the totalTokensReminder block after each regular user prompt and (for 'padded-countdown') re-anchor the task budget to the full configured value at the start of each user turn. When false, the reminder appears only in the system prompt and after each tool-result batch, and 'padded-countdown' counts down over the whole session. Defaults to off. Env var CLAUDE_CODE_TOTAL_TOKENS_REMINDER_AFTER_USER_TURN overrides; server-controlled via GrowthBook tengu_lapis_anchor_user_turn."),autoMemoryEnabled:A.boolean().optional().describe("Enable auto-memory for this project. When false, Claude will not read from or write to the auto-memory directory."),autoMemoryDirectory:A.string().optional().describe("Custom directory path for auto-memory storage. Supports ~/ prefix for home directory expansion. Ignored if set in projectSettings (checked-in .claude/settings.json) for security. When unset, defaults to ~/.claude/projects/<sanitized-cwd>/memory/."),autoDreamEnabled:A.boolean().optional().describe("Enable background memory consolidation (auto-dream). When set, overrides the server-side default."),showThinkingSummaries:A.boolean().optional().describe("Request API-side thinking summaries and show them in the conversation and in the transcript view (ctrl+o). Set explicitly to override the default for your install."),skipDangerousModePermissionPrompt:A.boolean().optional().describe("Whether the user has accepted the bypass permissions mode dialog"),skipWorkflowUsageWarning:A.boolean().optional().describe("@internal Whether the user has accepted the multi-agent workflow usage warning. Until set, auto permission mode prompts before running a workflow."),disableAutoMode:A.enum(["disable"]).optional().describe("Disable auto mode"),sshConfigs:A.array(A.object({id:A.string().describe("Unique identifier for this SSH config. Used to match configs across settings sources."),name:A.string().describe("Display name for the SSH connection"),sshHost:A.string().describe('SSH host in format "user@hostname" or "hostname", or a host alias from ~/.ssh/config'),sshPort:A.number().int().optional().describe("SSH port (default: 22)"),sshIdentityFile:A.string().optional().describe("Path to SSH identity file (private key)"),startDirectory:A.string().optional().describe("Default working directory on the remote host. Supports tilde expansion (e.g. ~/projects). If not specified, defaults to the remote user home directory. Can be overridden by the [dir] positional argument in `claude ssh <config> [dir]`.")})).optional().describe("SSH connection configurations for remote environments. Typically set in managed settings by enterprise administrators to pre-configure SSH connections for team members."),claudeMd:A.string().optional().describe("CLAUDE.md-style instructions injected as organization-managed memory. Only honored from managed/policy settings."),claudeMdExcludes:A.array(A.string()).optional().describe('Glob patterns or absolute paths of CLAUDE.md files to exclude from loading. Patterns are matched against absolute file paths using picomatch. Only applies to User, Project, and Local memory types (Managed/policy files cannot be excluded). Examples: "/home/user/monorepo/CLAUDE.md", "**/code/CLAUDE.md", "**/some-dir/.claude/rules/**"'),pluginTrustMessage:A.string().optional().describe('Custom message to append to the plugin trust warning shown before installation. Only read from policy settings (managed-settings.json / MDM). Useful for enterprise administrators to add organization-specific context (e.g., "All plugins from our internal marketplace are vetted and approved.").'),theme:A.union([A.enum(wXn),A.string().startsWith("custom:").transform(e=>e)]).optional().catch(void 0).describe("Color theme for the UI"),editorMode:A.enum(gXn).optional().catch(void 0).describe("Key binding mode for the prompt input"),verbose:A.boolean().optional().describe("Show full tool output instead of truncated summaries"),preferredNotifChannel:A.enum(hXn).optional().catch(void 0).describe("Preferred OS notification channel"),autoCompactEnabled:A.boolean().optional().describe("Automatically compact conversation when context fills"),precomputeCompactionEnabled:A.boolean().optional().describe("@internal Precompute the compaction summary in the background before it is needed. Only applies when auto-compact is on."),switchModelsOnFlag:A.boolean().optional().describe("When safety measures flag a message, automatically switch to a different model to keep chatting. When off, your session will pause instead."),autoScrollEnabled:A.boolean().optional().describe("Auto-scroll the conversation view to bottom (fullscreen mode only)"),wheelScrollAccelerationEnabled:A.boolean().optional().describe("Ramp mouse-wheel scroll speed during fast scrolls (fullscreen mode only)"),fileCheckpointingEnabled:A.boolean().optional().describe("Snapshot files before edits so /rewind can restore them"),showTurnDuration:A.boolean().optional().describe('Show "Cooked for Nm Ns" after each assistant turn'),showMessageTimestamps:A.boolean().optional().describe("Stamp each assistant message with its arrival time"),terminalProgressBarEnabled:A.boolean().optional().describe("Emit OSC 9;4 progress sequences during long operations"),todoFeatureEnabled:A.boolean().optional().describe("Enable the todo / task tracking panel"),teammateMode:A.enum(yXn).optional().catch(void 0).describe("How spawned teammates execute (tmux, iterm2, in-process, auto)"),remoteControlAtStartup:A.boolean().optional().describe("Start Remote Control bridge automatically each session"),isolatePeerMachines:A.boolean().optional().describe("Require explicit approval before SendMessage can reach a peer session on another machine via Remote Control"),daemonColdStart:A.enum(["transient","ask"]).optional().describe("When no background service is running: 'transient' spawns one for this login session; 'ask' offers to install it persistently"),autoUploadSessions:A.boolean().optional().describe("Mirror local sessions to claude.ai as view-only (no remote control)"),inputNeededNotifEnabled:A.boolean().optional().describe("Push to mobile when a permission prompt or question is waiting"),agentPushNotifEnabled:A.boolean().optional().describe("Allow Claude to push proactive mobile notifications"),...TQn(t)}).passthrough()}async function YQn(t,e){try{await(0,Sm.copyFile)(t,e)}catch(n){if(!c4e(n))throw n}}async function JQn(t,e){if(!t)return;let n=t;try{let r=g4e(t);r?.claudeAiOauth?.refreshToken&&(delete r.claudeAiOauth.refreshToken,n=yp(r))}catch{}await(0,Sm.writeFile)(e,n,{mode:384})}function XQn(){if(process.platform!=="darwin")return Promise.resolve(void 0);let t=bZn(wZn);return new Promise(e=>{(0,TNt.execFile)("security",["find-generic-password","-a",xZn(),"-w","-s",t],{encoding:"utf-8",timeout:5e3,windowsHide:!0},(n,r)=>e(n?void 0:r.trim()||void 0))})}async function QQn(t,e,n,r,o=6e4){if(!Q8n(e))return;let i=g2t(n),s=await l7(t.load({projectKey:i,sessionId:e}),o,`SessionStore.load() timed out after ${o}ms for session ${e}`);if(!s||s.length===0)return;let a=(0,os.join)((0,_B.tmpdir)(),`claude-resume-${(0,PNt.randomUUID)()}`);try{let l=(0,os.join)(a,"projects",i);await(0,Sm.mkdir)(l,{recursive:!0});let c=(0,os.join)(l,`${e}.jsonl`);await EOt(c,s);let u=r?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,d=u??(0,os.join)((0,_B.homedir)(),".claude"),f;try{f=await(0,Sm.readFile)((0,os.join)(d,".credentials.json"),"utf-8")}catch(p){if(!c4e(p))throw p}if(!u&&!(r??process.env).ANTHROPIC_API_KEY&&!(r??process.env).CLAUDE_CODE_OAUTH_TOKEN&&(f=await XQn()??f),await JQn(f,(0,os.join)(a,".credentials.json")),await YQn((0,os.join)(u??(0,_B.homedir)(),".claude.json"),(0,os.join)(a,".claude.json")),t.listSubkeys){let p=(0,os.join)(l,e),m=await l7(t.listSubkeys({projectKey:i,sessionId:e}),o,`SessionStore.listSubkeys() timed out after ${o}ms for session ${e}`);for(let h of m){let g=(0,os.resolve)(p,h+".jsonl");if(!h||(0,os.isAbsolute)(h)||h.split(/[\\/]/).includes("..")||!g.startsWith(p+os.sep)){Ka(`[SessionStore] skipping unsafe subpath from listSubkeys: ${h}`,{level:"warn"});continue}let v=await l7(t.load({projectKey:i,sessionId:e,subpath:h}),o,`SessionStore.load() timed out after ${o}ms for session ${e} subpath ${h}`);if(!v||v.length===0)continue;let y=[],w=[];for(let _ of v)rer(_)?y.push(_):w.push(_);if(w.length>0&&(await(0,Sm.mkdir)((0,os.dirname)(g),{recursive:!0}),await EOt(g,w)),y.length>0){let _=y.at(-1),S=(0,os.resolve)(p,h+".meta.json");await(0,Sm.mkdir)((0,os.dirname)(S),{recursive:!0});let{type:I,...C}=_;await(0,Sm.writeFile)(S,yp(C),{mode:384})}}}return a}catch(l){throw await h2t(a),l}}function oNt(t,e,n,r){let{systemPrompt:o,settings:i,managedSettings:s,settingSources:a,sandbox:l,...c}=t??{},u,d,f;o===void 0?u="":typeof o=="string"||Array.isArray(o)?u=o:o.type==="preset"&&(d=o.append,f=o.excludeDynamicSections),process.env.CLAUDE_AGENT_SDK_VERSION="0.3.206";let{abortController:p=QUe(),additionalDirectories:m=[],agent:h,agents:g,allowedTools:v=[],betas:y,canUseTool:w,continue:_,cwd:S,debug:I,debugFile:C,disallowedTools:k=[],tools:T,env:P,executable:E=$Nt()?"bun":"node",executableArgs:O=[],extraArgs:$={},fallbackModel:U,enableFileCheckpointing:V,toolConfig:K,forkSession:se,hooks:le,includeHookEvents:Q,includePartialMessages:ne,forwardSubagentText:ee,onElicitation:ae,onUserDialog:q,supportedDialogKinds:F,persistSession:z,sessionStore:N,sessionStoreFlush:R,thinking:X,effort:D,maxThinkingTokens:G,maxTurns:ce,maxBudgetUsd:Z,taskBudget:te,mcpServers:fe,model:de,outputFormat:ye,permissionMode:Te="default",allowDangerouslySkipPermissions:Be=!1,permissionPromptToolName:qe,plugins:Ae,getOAuthToken:Xt,getHostAuthToken:Ve,workload:Ee,resume:st,resumeSessionAt:Ne,sessionId:He,skills:et,stderr:it,strictMcpConfig:Br}=c;if(N&&z===!1)throw Error("sessionStore cannot be used with persistSession: false -- the storage adapter requires local writes to mirror from. Use CLAUDE_CONFIG_DIR=/tmp for ephemeral local writes with external mirroring.");if(F!==void 0&&F.length>0&&!q)throw Error("supportedDialogKinds requires an onUserDialog callback -- declaring dialog kinds without a handler would park dialogs nothing can answer. Provide onUserDialog, or omit supportedDialogKinds.");if(N&&_&&!st&&!N.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(N&&V)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");N&&c.spawnClaudeCodeProcess&&Ka("sessionStore with custom spawnClaudeCodeProcess: ensure the subprocess CLAUDE_CONFIG_DIR matches the parent (same path, same separators) or transcript_mirror frames will be dropped.",{level:"warn"}),CZn(!!w,Te,v);let Xr=c.pathToClaudeCodeExecutable;if(!Xr){let fl=(0,ENt.fileURLToPath)(import_meta.url),wu=(0,ANt.createRequire)(fl),ct=j8n(Qt=>wu.resolve(Qt));if(!ct)throw Error(`Native CLI binary for ${process.platform}-${process.arch} not found. Reinstall @anthropic-ai/claude-agent-sdk without --omit=optional, or set options.pathToClaudeCodeExecutable.`);Xr=ct}let An=ye?.type==="json_schema"?ye.schema:void 0,zn=P?{...P}:{...process.env};zn.CLAUDE_CODE_ENTRYPOINT||(zn.CLAUDE_CODE_ENTRYPOINT="sdk-ts"),zn.CLAUDE_AGENT_SDK_VERSION||(zn.CLAUDE_AGENT_SDK_VERSION="0.3.206"),V&&(zn.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true"),Xt&&(zn.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1"),Ve&&(zn.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1"),K?.askUserQuestion?.previewFormat&&(zn.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=K.askUserQuestion.previewFormat);let Yp={};if(AOt.propagation.inject(AOt.context.active(),Yp),"traceparent"in Yp)for(let fl of["TRACEPARENT","TRACESTATE"])fl in(P??{})||delete zn[fl];for(let[fl,wu]of Object.entries(Yp)){let ct=fl.toUpperCase();ct in(P??{})||(zn[ct]=wu)}let la={},vu=new Map;if(fe)for(let[fl,wu]of Object.entries(fe))wu.type==="sdk"&&wu.instance?vu.set(fl,wu.instance):la[fl]=wu;let Ds;if(X)switch(X.type){case"adaptive":Ds={type:"adaptive",display:X.display};break;case"enabled":Ds={type:"enabled",budgetTokens:X.budgetTokens,display:X.display};break;case"disabled":Ds={type:"disabled"};break}else G!==void 0&&(Ds=G===0?{type:"disabled"}:{type:"enabled",budgetTokens:G});n&&(zn.CLAUDE_CONFIG_DIR=n,process.platform==="win32"&&(zn.CLAUDE_SECURESTORAGE_CONFIG_DIR=P?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??P?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""));let hh=new Aje({abortController:p,additionalDirectories:m,agent:h,betas:y,cwd:S,debug:I,debugFile:C,executable:E,executableArgs:O,extraArgs:Ee?{...$,workload:Ee}:$,pathToClaudeCodeExecutable:Xr,env:zn,forkSession:se,stderr:it,thinkingConfig:Ds,effort:D,maxTurns:ce,maxBudgetUsd:Z,taskBudget:te,model:de,fallbackModel:U,jsonSchema:An,permissionMode:Te,allowDangerouslySkipPermissions:Be,permissionPromptToolName:qe,continueConversation:N?void 0:_,resume:st,resumeSessionAt:Ne,sessionId:He,settings:typeof i=="object"?yp(i):i,managedSettings:s?yp(s):void 0,settingSources:a,skills:et,allowedTools:v,disallowedTools:k,tools:T,mcpServers:la,strictMcpConfig:Br,canUseTool:!!w,hooks:!!le,includeHookEvents:Q,includePartialMessages:ne,persistSession:z,sessionMirror:!!N,plugins:Ae,sandbox:l,spawnClaudeCodeProcess:c.spawnClaudeCodeProcess,deferSpawn:r}),N_={systemPrompt:u,appendSystemPrompt:d,planModeInstructions:c.planModeInstructions,appendSubagentSystemPrompt:c.appendSubagentSystemPrompt,toolAliases:c.toolAliases,excludeDynamicSections:f,agents:g,title:c.title,skills:et,webSearchIsolationExemptMcpServers:c.webSearchIsolationExemptMcpServers,promptSuggestions:c.promptSuggestions,agentProgressSummaries:c.agentProgressSummaries,forwardSubagentText:ee,supportedDialogKinds:F},ty=new Oje(hh,e,w,le,p,vu,An,N_,ae,Xt,Ve,q);if(N){let fl=()=>(0,os.join)(zn.CLAUDE_CONFIG_DIR??(0,os.join)((0,_B.homedir)(),".claude"),"projects"),wu=R==="eager",ct=new Nje(async(Qt,ir)=>{let Ct=sNt(Qt,fl());Ct?await N.append(Ct,ir):Ka(`[SessionStore] dropping mirror frame: filePath ${Qt} is not under ${fl()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},void 0,(Qt,ir)=>{let Ct=sNt(Qt,fl());Ct&&ty.reportMirrorError(Ct,ir.message)},wu?0:qDt,wu?0:KDt);ty.setTranscriptMirrorBatcher(ct)}return{queryInstance:ty,transport:hh,abortController:p,processEnv:zn}}function iNt(t,e,n,r){typeof n=="string"?e.write(yp({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:n}]},parent_tool_use_id:null})+`
`):t.streamInput(n).catch(o=>r.abort(o))}async function h2t(t){for(let e=0;;e++)try{return await(0,Sm.rm)(t,{recursive:!0,force:!0})}catch(n){if(e>=4||!eer.has(Ky(n)??""))return;await spe((e+1)*100)}}function ter(t,e){t.waitForExit().catch(()=>{}).finally(()=>h2t(e))}function Fpe({prompt:t,options:e}){if((e?.resume||e?.continue)&&e?.sessionStore){let{queryInstance:i,transport:s,abortController:a,processEnv:l}=oNt({...e},typeof t=="string",void 0,!0),c=(0,os.resolve)(e.cwd??"."),u=e.sessionStore,d=e.loadTimeoutMs??6e4,f=e.resume;return(async()=>{if(f||(f=(await l7(u.listSessions(g2t(c)),d,`SessionStore.listSessions() timed out after ${d}ms`)).slice().sort((p,m)=>m.mtime-p.mtime)[0]?.sessionId),!!f)return QQn(u,f,c,e.env,e.loadTimeoutMs)})().then(p=>{if(p){s.updateResume(f);let m={CLAUDE_CONFIG_DIR:p};if(process.platform==="win32"){let h=e.env?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??e.env?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??"";m.CLAUDE_SECURESTORAGE_CONFIG_DIR=h,l.CLAUDE_SECURESTORAGE_CONFIG_DIR=h}s.updateEnv(m),l.CLAUDE_CONFIG_DIR=p,i.addCleanupCallback(()=>ter(s,p))}i.isClosed()||s.spawn()}).catch(p=>{let m=Ppe(p);s.spawnAbort(m),i.setError(m)}),iNt(i,s,t,a),i}let{queryInstance:n,transport:r,abortController:o}=oNt(e,typeof t=="string");return iNt(n,r,t,o),n}function ner(t){let e=(0,os.resolve)(t??"."),n;try{n=(0,lBe.realpathSync)(e)}catch{n=e}return eje(n)}function g2t(t){return nZn(ner(t))}function rer(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="agent_metadata"}function sNt(t,e){let n=(0,os.relative)(e,t),r=n.split(os.sep);if(r[0]===".."||(0,os.isAbsolute)(n)||r.length<2)return null;let o=r[0],i=r[1];if(r.length===2&&i.endsWith(".jsonl"))return{projectKey:o,sessionId:i.replace(/\.jsonl$/,"")};if(r.length>=4){let s=r.slice(2),a=s.length-1;return s[a]=s.at(-1).replace(/\.jsonl$/,""),{projectKey:o,sessionId:i,subpath:s.join("/")}}return null}var cNt,TNt,PNt,lBe,Sm,ANt,_B,os,aHn,ENt,MNt,dHn,cBe,ONt,NNt,RNt,UNt,jNt,yDt,yje,vDt,Ma,wDt,Gy,Cje,LDt,Bfe,$Dt,cf,wx,Or,No,W7,VDt,q8n,Rje,GDt,Ope,K8n,ZDt,YDt,G8n,Z8n,Y8n,JDt,XDt,oZn,Npe,iZn,sZn,aZn,QDt,lZn,eFt,tFt,jYn,BYn,zYn,pa,k4e,Gfe,DFt,FFt,T4e,P4e,tXn,sXn,Yje,GQn,ZQn,kzn,Izn,XUe,Tzn,Pzn,Ezn,Mzn,eBe,Le,Ozn,_x,Suo,Rzn,Lzn,gl,yl,$zn,Dzn,Fzn,uNt,Uzn,zB,jzn,tBe,Bzn,HB,zzn,Hzn,dNt,epe,Wzn,fNt,Vzn,pNt,qzn,tpe,mNt,nBe,rBe,hNt,oBe,gNt,yNt,Kzn,vNt,Gzn,Zzn,Yzn,Jzn,Xzn,Qzn,e4n,t4n,n4n,r4n,o4n,i4n,s4n,a4n,l4n,c4n,u4n,d4n,Gde,cMt,uo,ni,JP,npe,f4n,wNt,bNt,Zde,p4n,ab,m4n,h4n,_Nt,g4n,rpe,ope,iBe,ipe,sBe,y4n,xNt,v4n,w4n,b4n,_4n,x4n,S4n,C4n,k4n,I4n,T4n,P4n,A4n,E4n,M4n,O4n,aBe,N4n,R4n,L4n,$4n,SNt,CNt,D4n,F4n,U4n,j4n,B4n,kNt,z4n,H4n,W4n,V4n,q4n,K4n,G4n,Z4n,Y4n,J4n,X4n,Q4n,eHn,tHn,nHn,rHn,INt,oHn,iHn,sHn,lHn,Cuo,cHn,kuo,uHn,Iuo,LNt,Ek,dMt,yHn,vHn,DNt,wHn,bHn,xx,_Hn,vx,FNt,xHn,SHn,NZ,kHn,IHn,THn,AHn,EHn,MHn,fMt,DR,Nk,RHn,LHn,$Hn,DHn,uBe,UHn,OUe,pMt,BHn,zHn,HHn,FR,VHn,qHn,KHn,GHn,ZHn,YHn,JHn,QHn,tWn,UR,rWn,d7,iWn,aWn,lWn,cWn,uWn,fWn,pWn,mWn,gWn,yWn,wWn,mMt,_Wn,ape,lpe,CWn,kWn,TWn,AWn,MWn,NWn,cpe,RWn,f7,$Wn,FWn,upe,BWn,HWn,VWn,KWn,dpe,GWn,Za,A,BNt,zNt,HNt,GP,Yde,Mo,mBe,qNt,o6n,Jde,KNt,ZNt,YNt,tje,XNt,hBe,j7,vBe,Xde,wBe,Qde,bBe,_Be,xBe,SBe,CBe,nRt,rRt,oRt,iRt,sRt,aRt,lRt,p6n,cRt,xB,m6n,h6n,g6n,uRt,y6n,v6n,w6n,b6n,_6n,fRt,pRt,mRt,hRt,gRt,kBe,yRt,x6n,vRt,wRt,bRt,CRt,kRt,IRt,TRt,PRt,ARt,ERt,MRt,ORt,wl,NRt,IBe,TBe,RRt,LRt,$Rt,DRt,FRt,URt,jRt,BRt,zRt,B7,HRt,WRt,VRt,qRt,KRt,GRt,ZRt,YRt,JRt,efe,XRt,Mr,z7,Ms,QRt,eLt,tLt,nLt,rLt,oLt,iLt,sLt,aLt,lLt,cLt,uLt,dLt,fLt,pLt,mLt,hLt,gLt,yLt,vLt,bLt,_Lt,SLt,CLt,ABe,kLt,EBe,MBe,ILt,TLt,PLt,ALt,ELt,tfe,MLt,OLt,NLt,OBe,NBe,RBe,RLt,LLt,gpe,$Lt,DLt,FLt,ULt,jLt,BLt,LBe,zLt,HLt,WLt,VLt,qLt,KLt,GLt,ZLt,$Be,YLt,JLt,XLt,QLt,e1t,DBe,S6n,k6n,T6n,A6n,M6n,N6n,L6n,$6n,D6n,F6n,j6n,z6n,W6n,q6n,G6n,Y6n,X6n,eVn,nVn,oVn,sVn,lVn,uVn,fVn,mVn,gVn,vVn,bVn,xVn,CVn,IVn,PVn,EVn,OVn,RVn,$Vn,DVn,UVn,BVn,HVn,VVn,KVn,n1t,r1t,h7,CR,s1t,ofe,v7,g3n,wze,bze,_ze,xze,Sze,Y1t,y3n,H7,J1t,X1t,Q1t,e$t,po,Cze,bpe,Qs,kze,ife,Ok,Ize,Tze,Pze,Aze,Eze,Mze,Oze,Nze,Rze,Lze,$ze,Dze,Fze,Uze,jze,Bze,t$t,_pe,KB,xpe,Spe,zze,n$t,r$t,o$t,i$t,s$t,a$t,l$t,Wze,c$t,kpe,Vze,u$t,d$t,f$t,Kze,p$t,m$t,w7,h$t,g$t,Gze,Yze,y$t,v$t,b$t,Jze,S$t,C$t,I$t,Xze,T$t,A$t,E$t,O$t,Tpe,pqn,hqn,D$t,Sqn,lfe,Cqn,kqn,F$t,Iqn,Tqn,Pqn,Aqn,U$t,j$t,Tuo,Puo,e4e,Auo,Euo,B$t,oje,Vn,bp,Kh,CB,cfe,ufe,dfe,ffe,pfe,mfe,hfe,gfe,yfe,Mqn,Oqn,ije,AMt,Rqn,z$t,Lqn,HP,$qn,Fqn,MMt,OMt,NMt,t4e,zqn,Wqn,Vqn,V$t,vfe,qqn,Kqn,r4e,Gqn,RMt,NUe,Zqn,ms,aje,ps,LMt,$Mt,wfe,FMt,Xqn,UMt,xR,Y$t,Qqn,e5n,t5n,i4e,n5n,X$t,jh,Bh,MR,RZ,OR,lje,t7,bfe,kde,_fe,cje,NR,lf,nDt,rDt,s4e,BMt,g5n,y5n,uje,oDt,v5n,w5n,Xs,iDt,lt,zMt,S5n,mn,xfe,c7,Sfe,Cfe,kfe,Ife,_7,Tfe,Pfe,kB,Afe,Efe,cDt,I5n,uB,T5n,P5n,fDt,zy,LP,tB,LZ,Ide,$Z,DZ,Tde,FZ,kk,UZ,Pde,Ade,wR,Ede,Mde,jZ,RUe,WMt,Ode,LUe,$Ue,DUe,VMt,qMt,fje,Mfe,A5n,E5n,BZ,nB,bR,$c,_m,Uh,Mk,$P,zZ,GMt,pje,Ofe,YMt,O5n,RR,Nfe,Rfe,IB,Lfe,x7,$fe,S7,Cm,Dfe,Hy,DP,rB,HZ,Nde,WZ,VZ,Rde,qZ,Ik,KZ,Lde,$de,_R,Dde,Fde,GZ,FUe,QMt,UUe,jUe,BUe,zUe,eOt,tOt,mje,Ffe,C7,rOt,R5n,Ufe,hje,a4e,Hde,hDt,L5n,$5n,Ga,TB,gje,D5n,F5n,j5n,B5n,z5n,H5n,Muo,q5n,vje,G5n,PR,oB,J5n,Q5n,tKn,rKn,oKn,sKn,aKn,lKn,jfe,u4e,uKn,dKn,xDt,mKn,gKn,ZB,vKn,iOt,SDt,bKn,_Kn,xKn,k7,SKn,ZP,n7,kKn,CDt,sOt,IKn,aOt,TKn,PKn,d4e,AKn,EKn,Ape,OKn,f4e,RKn,LKn,$Kn,DKn,FKn,UKn,jKn,BKn,zKn,HKn,WKn,VKn,qKn,KKn,GKn,ZKn,YKn,JKn,XKn,QKn,eGn,tGn,nGn,rGn,Ys,iGn,aGn,r7,kDt,u7,lGn,WUe,cGn,wje,lOt,uGn,IDt,dGn,fGn,mGn,hGn,TDt,PDt,Ouo,vGn,Nuo,p4e,_Gn,xGn,SGn,kGn,ADt,o7,EDt,cOt,TGn,uOt,dOt,MDt,EGn,MGn,Ruo,NGn,RGn,ODt,LGn,bje,$Gn,_je,DGn,xje,FGn,Sje,fOt,UGn,pOt,mOt,hOt,gOt,jGn,BGn,zGn,HGn,WGn,iB,VGn,yOt,KGn,ZGn,vOt,YGn,JGn,QGn,e9n,n9n,o9n,wOt,Luo,i9n,$uo,s9n,Duo,a9n,m4e,c9n,u9n,f9n,p9n,h9n,g9n,y9n,v9n,w9n,_9n,x9n,bOt,_Ot,S9n,k9n,Epe,T9n,h4e,E9n,O9n,R9n,$9n,RDt,DDt,Uuo,juo,U9n,z9n,W9n,V9n,q9n,Buo,K9n,zuo,G9n,Huo,Z9n,Wuo,Y9n,Vuo,VP,zfe,Q9n,quo,t8n,Ude,i8n,s8n,Kuo,Guo,u8n,SOt,UDt,d8n,COt,f8n,p8n,kOt,g8n,y8n,ZZ,Ije,w8n,b8n,jDt,_8n,BDt,zDt,S8n,C8n,YZ,VUe,dB,i7,TOt,JZ,qUe,Tje,A8n,Zuo,E8n,vl,g4e,R8n,Hfe,POt,Aje,sB,Eje,z8n,Mje,KUe,Qfe,Oje,qDt,KDt,V8n,Nje,AOt,Quo,X8n,MOt,edo,tdo,rZn,ndo,dZn,rFt,fZn,pZn,mZn,odo,OOt,hZn,yZn,wZn,_Zn,ti,NOt,Zt,zP,at,Zy,kZn,I7,IZn,$je,_p,yr,s7,km,ROt,LOt,PB,Wfe,Sn,Yy,$Ot,fo,TZn,PZn,AZn,EZn,MZn,OZn,NZn,RZn,LZn,GUe,$Zn,DZn,FZn,UZn,jZn,BZn,oFt,zZn,AB,T7,P7,A7,E7,M7,EB,MB,O7,KP,bx,N7,YP,Gh,OB,Tk,Dje,NB,Rk,Uje,R7,L7,jje,RB,LB,$B,DB,LR,ib,rb,Lk,FB,UB,$7,ido,Vfe,qfe,jB,sdo,vr,ado,ldo,cdo,udo,ddo,fdo,pdo,mdo,hdo,gdo,ydo,vdo,wdo,bdo,_do,xdo,Sdo,Cdo,kdo,Ido,Tdo,Pdo,Ado,Edo,Mdo,Odo,Ndo,Rdo,Ldo,$do,Ddo,Fdo,Udo,jdo,ZZn,Bdo,YZn,Rpe,Uc,aFt,lFt,zdo,JZn,XZn,v4e,Zh,Lpe,hd,Jy,Xy,gd,$pe,QZn,e7n,cFt,DOt,uFt,Hdo,Wdo,dFt,t7n,fFt,n7n,V7,BB,pFt,r7n,o7n,i7n,s7n,a7n,l7n,c7n,u7n,d7n,f7n,mFt,p7n,m7n,hFt,h7n,q7,K7,g7n,G7,gFt,y7n,yFt,vFt,wFt,bFt,Vdo,_Ft,xFt,SFt,qdo,CFt,kFt,w4e,IFt,Z7,YB,TFt,v7n,w7n,b7n,_7n,x7n,b4e,S7n,C7n,k7n,I7n,T7n,P7n,A7n,E7n,M7n,O7n,N7n,R7n,L7n,$7n,D7n,F7n,_4e,x4e,S4e,U7n,j7n,B7n,C4e,z7n,H7n,W7n,V7n,q7n,PFt,K7n,G7n,AFt,Kdo,Z7n,Y7n,J7n,Gdo,EFt,X7n,Q7n,eYn,tYn,nYn,rYn,oYn,iYn,sYn,Kfe,aYn,lYn,cYn,uYn,dYn,fYn,pYn,mYn,hYn,gYn,yYn,vYn,wYn,bYn,_Yn,xYn,SYn,CYn,kYn,IYn,TYn,PYn,AYn,EYn,MYn,OYn,NYn,RYn,LYn,$Yn,DYn,FYn,UYn,Zdo,Ydo,Jdo,Xdo,Qdo,efo,tfo,nfo,rfo,ofo,ifo,FOt,sfo,afo,UOt,lfo,cfo,jOt,BOt,zOt,HOt,WP,I4e,pB,WYn,VYn,qYn,ufo,YYn,ZUe,XYn,WOt,dfo,aB,OFt,Bje,NFt,Zfe,VOt,QYn,ffo,FP,RFt,gB,yB,SR,zje,aNt,lNt,Gw,zh,Zw,Yw,vB,wB,Dc,Jw,Vl,Zs,Rr,hp,Hh,af,Au,Xw,Eu,Qw,eb,Wh,tb,qP,gp,Nt,Wje,kR,Ak,D7,Vh,LFt,IR,bB,F7,UP,jP,Vje,qde,Kde,Gs,qje,a7,BP,Kje,N4e,Hje,tJn,qOt,pfo,UFt,jFt,BFt,hfo,gfo,yfo,nJn,vfo,Gje,iJn,sJn,aJn,cJn,uJn,dJn,fJn,zFt,pJn,mJn,gJn,Zje,wJn,_Jn,xJn,CJn,KOt,WFt,TJn,PJn,AJn,EJn,MJn,OJn,RJn,LJn,VFt,DJn,UJn,BJn,wfo,HJn,VJn,KJn,GOt,ZJn,YJn,XJn,eXn,bfo,KFt,GFt,ZFt,nXn,rXn,oXn,iXn,_fo,xfo,aXn,lXn,cXn,uXn,dXn,fXn,A4e,pXn,mXn,hXn,gXn,yXn,vXn,wXn,Sfo,Cfo,kfo,bXn,XZ,xXn,SXn,Yfe,Ifo,Tfo,JB,XP,CXn,YFt,kXn,IXn,XFt,QFt,TXn,PXn,AXn,EXn,MXn,OXn,M4e,NXn,Jje,Pfo,RXn,LXn,e2t,$Xn,DXn,sb,$R,ZOt,Xje,Qje,t2t,O4e,UXn,Afo,jXn,BXn,zXn,HXn,WXn,n2t,VXn,qXn,KXn,GXn,r2t,ZXn,YOt,YXn,JXn,o2t,XXn,QXn,JOt,eQn,tQn,i2t,nQn,s2t,rQn,oQn,iQn,sQn,lQn,cQn,uQn,dQn,Jfe,YUe,a2t,fQn,pQn,mQn,hQn,gQn,Efo,l2t,vQn,wQn,bQn,_Qn,xQn,SQn,CQn,Mfo,kQn,Ofo,IQn,jde,Dpe,XOt,d2t,Nfo,Rfo,Xfe,tNt,UQn,jQn,Lfo,BQn,zQn,HQn,WQn,nNt,rNt,VQn,KQn,$fo,Pk,Dfo,Ffo,Ufo,jfo,Bfo,eer,R4e=b(()=>{cNt=L(sMt(),1),TNt=require("child_process"),PNt=require("crypto"),lBe=require("fs"),Sm=require("fs/promises"),ANt=L(lMt(),1),_B=require("os"),os=require("path"),aHn=require("readline"),ENt=require("url"),MNt=require("events"),dHn=require("fs"),cBe=require("path"),ONt=require("child_process"),NNt=require("fs"),RNt=require("readline"),UNt=require("os"),jNt=require("path"),yDt=require("crypto"),yje=require("path"),vDt=require("async_hooks"),Ma=require("fs/promises"),wDt=require("crypto"),Gy=require("fs/promises"),Cje=require("fs"),LDt=require("process"),Bfe=require("crypto"),$Dt=require("crypto"),cf=require("fs/promises"),wx=require("path"),Or=L(require("fs"),1),No=require("fs/promises"),W7=L(require("path"),1),VDt=require("fs"),q8n=require("fs/promises"),Rje=require("events"),GDt=require("fs"),Ope=require("fs/promises"),K8n=require("path"),ZDt=require("child_process"),YDt=require("util"),G8n=require("child_process"),Z8n=require("fs"),Y8n=require("path"),JDt=require("fs/promises"),XDt=require("path"),oZn=require("fs"),Npe=require("fs/promises"),iZn=require("path"),sZn=require("crypto"),aZn=require("path"),QDt=require("fs/promises"),lZn=require("path"),eFt=require("crypto"),tFt=require("os"),jYn=require("path"),BYn=require("path"),zYn=require("path"),pa=L(require("node:path"),1),k4e=L(require("node:os"),1),Gfe=L(require("node:process"),1),DFt=require("path"),FFt=require("fs/promises"),T4e=require("os"),P4e=require("path"),tXn=require("path"),sXn=require("os"),Yje=require("path"),GQn=require("child_process"),ZQn=require("fs"),kzn=Object.create,{getPrototypeOf:Izn,defineProperty:XUe,getOwnPropertyNames:Tzn}=Object,Pzn=Object.prototype.hasOwnProperty;eBe=(t,e,n)=>{var r=t!=null&&typeof t=="object";if(r){var o=e?Ezn??(Ezn=new WeakMap):Mzn??(Mzn=new WeakMap),i=o.get(t);if(i)return i}n=t!=null?kzn(Izn(t)):{};let s=e||!t||!t.__esModule?XUe(n,"default",{value:t,enumerable:!0}):n;for(let a of Tzn(t))Pzn.call(s,a)||XUe(s,a,{get:Azn.bind(t,a),enumerable:!0});return r&&o.set(t,s),s},Le=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ozn=t=>t;_x=(t,e)=>{for(var n in e)XUe(t,n,{get:e[n],enumerable:!0,configurable:!0,set:Nzn.bind(e,n)})},Suo=(0,cNt.createRequire)(import_meta.url),Rzn=Symbol.dispose||Symbol.for("Symbol.dispose"),Lzn=Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose"),gl=(t,e,n)=>{if(e!=null){if(typeof e!="object"&&typeof e!="function")throw TypeError('Object expected to be assigned to "using" declaration');var r;if(n&&(r=e[Lzn]),r===void 0&&(r=e[Rzn]),typeof r!="function")throw TypeError("Object not disposable");t.push([n,r,e])}else n&&t.push([n]);return e},yl=(t,e,n)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(s,a,l,c){return c=Error(l),c.name="SuppressedError",c.error=s,c.suppressed=a,c},o=s=>e=n?new r(s,e,"An error was suppressed during disposal"):(n=!0,s),i=s=>{for(;s=t.pop();)try{var a=s[1]&&s[1].call(s[2]);if(s[0])return Promise.resolve(a).then(i,l=>(o(l),i()))}catch(l){o(l)}if(n)throw e};return i()},$zn=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t._globalThis=void 0,t._globalThis=typeof globalThis=="object"?globalThis:window}),Dzn=Le(t=>{var e=t&&t.__createBinding||(Object.create?function(r,o,i,s){s===void 0&&(s=i),Object.defineProperty(r,s,{enumerable:!0,get:function(){return o[i]}})}:function(r,o,i,s){s===void 0&&(s=i),r[s]=o[i]}),n=t&&t.__exportStar||function(r,o){for(var i in r)i!=="default"&&!Object.prototype.hasOwnProperty.call(o,i)&&e(o,r,i)};Object.defineProperty(t,"__esModule",{value:!0}),n($zn(),t)}),Fzn=Le(t=>{var e=t&&t.__createBinding||(Object.create?function(r,o,i,s){s===void 0&&(s=i),Object.defineProperty(r,s,{enumerable:!0,get:function(){return o[i]}})}:function(r,o,i,s){s===void 0&&(s=i),r[s]=o[i]}),n=t&&t.__exportStar||function(r,o){for(var i in r)i!=="default"&&!Object.prototype.hasOwnProperty.call(o,i)&&e(o,r,i)};Object.defineProperty(t,"__esModule",{value:!0}),n(Dzn(),t)}),uNt=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.VERSION=void 0,t.VERSION="1.9.0"}),Uzn=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isCompatible=t._makeCompatibilityCheck=void 0;var e=uNt(),n=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function r(o){let i=new Set([o]),s=new Set,a=o.match(n);if(!a)return()=>!1;let l={major:+a[1],minor:+a[2],patch:+a[3],prerelease:a[4]};if(l.prerelease!=null)return function(d){return d===o};function c(d){return s.add(d),!1}function u(d){return i.add(d),!0}return function(d){if(i.has(d))return!0;if(s.has(d))return!1;let f=d.match(n);if(!f)return c(d);let p={major:+f[1],minor:+f[2],patch:+f[3],prerelease:f[4]};return p.prerelease!=null||l.major!==p.major?c(d):l.major===0?l.minor===p.minor&&l.patch<=p.patch?u(d):c(d):l.minor<=p.minor?u(d):c(d)}}t._makeCompatibilityCheck=r,t.isCompatible=r(e.VERSION)}),zB=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.unregisterGlobal=t.getGlobal=t.registerGlobal=void 0;var e=Fzn(),n=uNt(),r=Uzn(),o=n.VERSION.split(".")[0],i=Symbol.for(`opentelemetry.js.api.${o}`),s=e._globalThis;function a(u,d,f,p=!1){var m;let h=s[i]=(m=s[i])!==null&&m!==void 0?m:{version:n.VERSION};if(!p&&h[u]){let g=Error(`@opentelemetry/api: Attempted duplicate registration of API: ${u}`);return f.error(g.stack||g.message),!1}if(h.version!==n.VERSION){let g=Error(`@opentelemetry/api: Registration of version v${h.version} for ${u} does not match previously registered API v${n.VERSION}`);return f.error(g.stack||g.message),!1}return h[u]=d,f.debug(`@opentelemetry/api: Registered a global for ${u} v${n.VERSION}.`),!0}t.registerGlobal=a;function l(u){var d,f;let p=(d=s[i])===null||d===void 0?void 0:d.version;if(!(!p||!(0,r.isCompatible)(p)))return(f=s[i])===null||f===void 0?void 0:f[u]}t.getGlobal=l;function c(u,d){d.debug(`@opentelemetry/api: Unregistering a global for ${u} v${n.VERSION}.`);let f=s[i];f&&delete f[u]}t.unregisterGlobal=c}),jzn=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DiagComponentLogger=void 0;var e=zB();class n{constructor(i){this._namespace=i.namespace||"DiagComponentLogger"}debug(...i){return r("debug",this._namespace,i)}error(...i){return r("error",this._namespace,i)}info(...i){return r("info",this._namespace,i)}warn(...i){return r("warn",this._namespace,i)}verbose(...i){return r("verbose",this._namespace,i)}}t.DiagComponentLogger=n;function r(o,i,s){let a=(0,e.getGlobal)("diag");if(a)return s.unshift(i),a[o](...s)}}),tBe=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DiagLogLevel=void 0;var e;(function(n){n[n.NONE=0]="NONE",n[n.ERROR=30]="ERROR",n[n.WARN=50]="WARN",n[n.INFO=60]="INFO",n[n.DEBUG=70]="DEBUG",n[n.VERBOSE=80]="VERBOSE",n[n.ALL=9999]="ALL"})(e=t.DiagLogLevel||(t.DiagLogLevel={}))}),Bzn=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createLogLevelDiagLogger=void 0;var e=tBe();function n(r,o){r<e.DiagLogLevel.NONE?r=e.DiagLogLevel.NONE:r>e.DiagLogLevel.ALL&&(r=e.DiagLogLevel.ALL),o=o||{};function i(s,a){let l=o[s];return typeof l=="function"&&r>=a?l.bind(o):function(){}}return{error:i("error",e.DiagLogLevel.ERROR),warn:i("warn",e.DiagLogLevel.WARN),info:i("info",e.DiagLogLevel.INFO),debug:i("debug",e.DiagLogLevel.DEBUG),verbose:i("verbose",e.DiagLogLevel.VERBOSE)}}t.createLogLevelDiagLogger=n}),HB=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DiagAPI=void 0;var e=jzn(),n=Bzn(),r=tBe(),o=zB(),i="diag";class s{constructor(){function l(d){return function(...f){let p=(0,o.getGlobal)("diag");if(p)return p[d](...f)}}let c=this,u=(d,f={logLevel:r.DiagLogLevel.INFO})=>{var p,m,h;if(d===c){let y=Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return c.error((p=y.stack)!==null&&p!==void 0?p:y.message),!1}typeof f=="number"&&(f={logLevel:f});let g=(0,o.getGlobal)("diag"),v=(0,n.createLogLevelDiagLogger)((m=f.logLevel)!==null&&m!==void 0?m:r.DiagLogLevel.INFO,d);if(g&&!f.suppressOverrideMessage){let y=(h=Error().stack)!==null&&h!==void 0?h:"<failed to generate stacktrace>";g.warn(`Current logger will be overwritten from ${y}`),v.warn(`Current logger will overwrite one already registered from ${y}`)}return(0,o.registerGlobal)("diag",v,c,!0)};c.setLogger=u,c.disable=()=>{(0,o.unregisterGlobal)(i,c)},c.createComponentLogger=d=>new e.DiagComponentLogger(d),c.verbose=l("verbose"),c.debug=l("debug"),c.info=l("info"),c.warn=l("warn"),c.error=l("error")}static instance(){return this._instance||(this._instance=new s),this._instance}}t.DiagAPI=s}),zzn=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BaggageImpl=void 0;class e{constructor(r){this._entries=r?new Map(r):new Map}getEntry(r){let o=this._entries.get(r);if(o)return Object.assign({},o)}getAllEntries(){return Array.from(this._entries.entries()).map(([r,o])=>[r,o])}setEntry(r,o){let i=new e(this._entries);return i._entries.set(r,o),i}removeEntry(r){let o=new e(this._entries);return o._entries.delete(r),o}removeEntries(...r){let o=new e(this._entries);for(let i of r)o._entries.delete(i);return o}clear(){return new e}}t.BaggageImpl=e}),Hzn=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.baggageEntryMetadataSymbol=void 0,t.baggageEntryMetadataSymbol=Symbol("BaggageEntryMetadata")}),dNt=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.baggageEntryMetadataFromString=t.createBaggage=void 0;var e=HB(),n=zzn(),r=Hzn(),o=e.DiagAPI.instance();function i(a={}){return new n.BaggageImpl(new Map(Object.entries(a)))}t.createBaggage=i;function s(a){return typeof a!="string"&&(o.error(`Cannot create baggage metadata from unknown type: ${typeof a}`),a=""),{__TYPE__:r.baggageEntryMetadataSymbol,toString(){return a}}}t.baggageEntryMetadataFromString=s}),epe=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ROOT_CONTEXT=t.createContextKey=void 0;function e(r){return Symbol.for(r)}t.createContextKey=e;class n{constructor(o){let i=this;i._currentContext=o?new Map(o):new Map,i.getValue=s=>i._currentContext.get(s),i.setValue=(s,a)=>{let l=new n(i._currentContext);return l._currentContext.set(s,a),l},i.deleteValue=s=>{let a=new n(i._currentContext);return a._currentContext.delete(s),a}}}t.ROOT_CONTEXT=new n}),Wzn=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DiagConsoleLogger=void 0;var e=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}];class n{constructor(){function o(i){return function(...s){if(console){let a=console[i];if(typeof a!="function"&&(a=console.log),typeof a=="function")return a.apply(console,s)}}}for(let i=0;i<e.length;i++)this[e[i].n]=o(e[i].c)}}t.DiagConsoleLogger=n}),fNt=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createNoopMeter=t.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=t.NOOP_OBSERVABLE_GAUGE_METRIC=t.NOOP_OBSERVABLE_COUNTER_METRIC=t.NOOP_UP_DOWN_COUNTER_METRIC=t.NOOP_HISTOGRAM_METRIC=t.NOOP_GAUGE_METRIC=t.NOOP_COUNTER_METRIC=t.NOOP_METER=t.NoopObservableUpDownCounterMetric=t.NoopObservableGaugeMetric=t.NoopObservableCounterMetric=t.NoopObservableMetric=t.NoopHistogramMetric=t.NoopGaugeMetric=t.NoopUpDownCounterMetric=t.NoopCounterMetric=t.NoopMetric=t.NoopMeter=void 0;class e{constructor(){}createGauge(p,m){return t.NOOP_GAUGE_METRIC}createHistogram(p,m){return t.NOOP_HISTOGRAM_METRIC}createCounter(p,m){return t.NOOP_COUNTER_METRIC}createUpDownCounter(p,m){return t.NOOP_UP_DOWN_COUNTER_METRIC}createObservableGauge(p,m){return t.NOOP_OBSERVABLE_GAUGE_METRIC}createObservableCounter(p,m){return t.NOOP_OBSERVABLE_COUNTER_METRIC}createObservableUpDownCounter(p,m){return t.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC}addBatchObservableCallback(p,m){}removeBatchObservableCallback(p){}}t.NoopMeter=e;class n{}t.NoopMetric=n;class r extends n{add(p,m){}}t.NoopCounterMetric=r;class o extends n{add(p,m){}}t.NoopUpDownCounterMetric=o;class i extends n{record(p,m){}}t.NoopGaugeMetric=i;class s extends n{record(p,m){}}t.NoopHistogramMetric=s;class a{addCallback(p){}removeCallback(p){}}t.NoopObservableMetric=a;class l extends a{}t.NoopObservableCounterMetric=l;class c extends a{}t.NoopObservableGaugeMetric=c;class u extends a{}t.NoopObservableUpDownCounterMetric=u,t.NOOP_METER=new e,t.NOOP_COUNTER_METRIC=new r,t.NOOP_GAUGE_METRIC=new i,t.NOOP_HISTOGRAM_METRIC=new s,t.NOOP_UP_DOWN_COUNTER_METRIC=new o,t.NOOP_OBSERVABLE_COUNTER_METRIC=new l,t.NOOP_OBSERVABLE_GAUGE_METRIC=new c,t.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=new u;function d(){return t.NOOP_METER}t.createNoopMeter=d}),Vzn=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValueType=void 0;var e;(function(n){n[n.INT=0]="INT",n[n.DOUBLE=1]="DOUBLE"})(e=t.ValueType||(t.ValueType={}))}),pNt=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultTextMapSetter=t.defaultTextMapGetter=void 0,t.defaultTextMapGetter={get(e,n){if(e!=null)return e[n]},keys(e){return e==null?[]:Object.keys(e)}},t.defaultTextMapSetter={set(e,n,r){e!=null&&(e[n]=r)}}}),qzn=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoopContextManager=void 0;var e=epe();class n{active(){return e.ROOT_CONTEXT}with(o,i,s,...a){return i.call(s,...a)}bind(o,i){return i}enable(){return this}disable(){return this}}t.NoopContextManager=n}),tpe=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextAPI=void 0;var e=qzn(),n=zB(),r=HB(),o="context",i=new e.NoopContextManager;class s{constructor(){}static getInstance(){return this._instance||(this._instance=new s),this._instance}setGlobalContextManager(l){return(0,n.registerGlobal)(o,l,r.DiagAPI.instance())}active(){return this._getContextManager().active()}with(l,c,u,...d){return this._getContextManager().with(l,c,u,...d)}bind(l,c){return this._getContextManager().bind(l,c)}_getContextManager(){return(0,n.getGlobal)(o)||i}disable(){this._getContextManager().disable(),(0,n.unregisterGlobal)(o,r.DiagAPI.instance())}}t.ContextAPI=s}),mNt=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TraceFlags=void 0;var e;(function(n){n[n.NONE=0]="NONE",n[n.SAMPLED=1]="SAMPLED"})(e=t.TraceFlags||(t.TraceFlags={}))}),nBe=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.INVALID_SPAN_CONTEXT=t.INVALID_TRACEID=t.INVALID_SPANID=void 0;var e=mNt();t.INVALID_SPANID="0000000000000000",t.INVALID_TRACEID="00000000000000000000000000000000",t.INVALID_SPAN_CONTEXT={traceId:t.INVALID_TRACEID,spanId:t.INVALID_SPANID,traceFlags:e.TraceFlags.NONE}}),rBe=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NonRecordingSpan=void 0;var e=nBe();class n{constructor(o=e.INVALID_SPAN_CONTEXT){this._spanContext=o}spanContext(){return this._spanContext}setAttribute(o,i){return this}setAttributes(o){return this}addEvent(o,i){return this}addLink(o){return this}addLinks(o){return this}setStatus(o){return this}updateName(o){return this}end(o){}isRecording(){return!1}recordException(o,i){}}t.NonRecordingSpan=n}),hNt=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSpanContext=t.setSpanContext=t.deleteSpan=t.setSpan=t.getActiveSpan=t.getSpan=void 0;var e=epe(),n=rBe(),r=tpe(),o=(0,e.createContextKey)("OpenTelemetry Context Key SPAN");function i(d){return d.getValue(o)||void 0}t.getSpan=i;function s(){return i(r.ContextAPI.getInstance().active())}t.getActiveSpan=s;function a(d,f){return d.setValue(o,f)}t.setSpan=a;function l(d){return d.deleteValue(o)}t.deleteSpan=l;function c(d,f){return a(d,new n.NonRecordingSpan(f))}t.setSpanContext=c;function u(d){var f;return(f=i(d))===null||f===void 0?void 0:f.spanContext()}t.getSpanContext=u}),oBe=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapSpanContext=t.isSpanContextValid=t.isValidSpanId=t.isValidTraceId=void 0;var e=nBe(),n=rBe(),r=/^([0-9a-f]{32})$/i,o=/^[0-9a-f]{16}$/i;function i(c){return r.test(c)&&c!==e.INVALID_TRACEID}t.isValidTraceId=i;function s(c){return o.test(c)&&c!==e.INVALID_SPANID}t.isValidSpanId=s;function a(c){return i(c.traceId)&&s(c.spanId)}t.isSpanContextValid=a;function l(c){return new n.NonRecordingSpan(c)}t.wrapSpanContext=l}),gNt=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoopTracer=void 0;var e=tpe(),n=hNt(),r=rBe(),o=oBe(),i=e.ContextAPI.getInstance();class s{startSpan(c,u,d=i.active()){if(u?.root)return new r.NonRecordingSpan;let f=d&&(0,n.getSpanContext)(d);return a(f)&&(0,o.isSpanContextValid)(f)?new r.NonRecordingSpan(f):new r.NonRecordingSpan}startActiveSpan(c,u,d,f){let p,m,h;if(arguments.length<2)return;arguments.length===2?h=u:arguments.length===3?(p=u,h=d):(p=u,m=d,h=f);let g=m??i.active(),v=this.startSpan(c,p,g),y=(0,n.setSpan)(g,v);return i.with(y,h,void 0,v)}}t.NoopTracer=s;function a(l){return typeof l=="object"&&typeof l.spanId=="string"&&typeof l.traceId=="string"&&typeof l.traceFlags=="number"}}),yNt=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ProxyTracer=void 0;var e=gNt(),n=new e.NoopTracer;class r{constructor(i,s,a,l){this._provider=i,this.name=s,this.version=a,this.options=l}startSpan(i,s,a){return this._getTracer().startSpan(i,s,a)}startActiveSpan(i,s,a,l){let c=this._getTracer();return Reflect.apply(c.startActiveSpan,c,arguments)}_getTracer(){if(this._delegate)return this._delegate;let i=this._provider.getDelegateTracer(this.name,this.version,this.options);return i?(this._delegate=i,this._delegate):n}}t.ProxyTracer=r}),Kzn=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoopTracerProvider=void 0;var e=gNt();class n{getTracer(o,i,s){return new e.NoopTracer}}t.NoopTracerProvider=n}),vNt=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ProxyTracerProvider=void 0;var e=yNt(),n=Kzn(),r=new n.NoopTracerProvider;class o{getTracer(s,a,l){var c;return(c=this.getDelegateTracer(s,a,l))!==null&&c!==void 0?c:new e.ProxyTracer(this,s,a,l)}getDelegate(){var s;return(s=this._delegate)!==null&&s!==void 0?s:r}setDelegate(s){this._delegate=s}getDelegateTracer(s,a,l){var c;return(c=this._delegate)===null||c===void 0?void 0:c.getTracer(s,a,l)}}t.ProxyTracerProvider=o}),Gzn=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SamplingDecision=void 0;var e;(function(n){n[n.NOT_RECORD=0]="NOT_RECORD",n[n.RECORD=1]="RECORD",n[n.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(e=t.SamplingDecision||(t.SamplingDecision={}))}),Zzn=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SpanKind=void 0;var e;(function(n){n[n.INTERNAL=0]="INTERNAL",n[n.SERVER=1]="SERVER",n[n.CLIENT=2]="CLIENT",n[n.PRODUCER=3]="PRODUCER",n[n.CONSUMER=4]="CONSUMER"})(e=t.SpanKind||(t.SpanKind={}))}),Yzn=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SpanStatusCode=void 0;var e;(function(n){n[n.UNSET=0]="UNSET",n[n.OK=1]="OK",n[n.ERROR=2]="ERROR"})(e=t.SpanStatusCode||(t.SpanStatusCode={}))}),Jzn=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateValue=t.validateKey=void 0;var e="[_0-9a-z-*/]",n=`[a-z]${e}{0,255}`,r=`[a-z0-9]${e}{0,240}@[a-z]${e}{0,13}`,o=new RegExp(`^(?:${n}|${r})$`),i=/^[ -~]{0,255}[!-~]$/,s=/,|=/;function a(c){return o.test(c)}t.validateKey=a;function l(c){return i.test(c)&&!s.test(c)}t.validateValue=l}),Xzn=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TraceStateImpl=void 0;var e=Jzn(),n=32,r=512,o=",",i="=";class s{constructor(l){this._internalState=new Map,l&&this._parse(l)}set(l,c){let u=this._clone();return u._internalState.has(l)&&u._internalState.delete(l),u._internalState.set(l,c),u}unset(l){let c=this._clone();return c._internalState.delete(l),c}get(l){return this._internalState.get(l)}serialize(){return this._keys().reduce((l,c)=>(l.push(c+i+this.get(c)),l),[]).join(o)}_parse(l){l.length>r||(this._internalState=l.split(o).reverse().reduce((c,u)=>{let d=u.trim(),f=d.indexOf(i);if(f!==-1){let p=d.slice(0,f),m=d.slice(f+1,u.length);(0,e.validateKey)(p)&&(0,e.validateValue)(m)&&c.set(p,m)}return c},new Map),this._internalState.size>n&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,n))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let l=new s;return l._internalState=new Map(this._internalState),l}}t.TraceStateImpl=s}),Qzn=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createTraceState=void 0;var e=Xzn();function n(r){return new e.TraceStateImpl(r)}t.createTraceState=n}),e4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.context=void 0;var e=tpe();t.context=e.ContextAPI.getInstance()}),t4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diag=void 0;var e=HB();t.diag=e.DiagAPI.instance()}),n4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NOOP_METER_PROVIDER=t.NoopMeterProvider=void 0;var e=fNt();class n{getMeter(o,i,s){return e.NOOP_METER}}t.NoopMeterProvider=n,t.NOOP_METER_PROVIDER=new n}),r4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MetricsAPI=void 0;var e=n4n(),n=zB(),r=HB(),o="metrics";class i{constructor(){}static getInstance(){return this._instance||(this._instance=new i),this._instance}setGlobalMeterProvider(a){return(0,n.registerGlobal)(o,a,r.DiagAPI.instance())}getMeterProvider(){return(0,n.getGlobal)(o)||e.NOOP_METER_PROVIDER}getMeter(a,l,c){return this.getMeterProvider().getMeter(a,l,c)}disable(){(0,n.unregisterGlobal)(o,r.DiagAPI.instance())}}t.MetricsAPI=i}),o4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.metrics=void 0;var e=r4n();t.metrics=e.MetricsAPI.getInstance()}),i4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoopTextMapPropagator=void 0;class e{inject(r,o){}extract(r,o){return r}fields(){return[]}}t.NoopTextMapPropagator=e}),s4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteBaggage=t.setBaggage=t.getActiveBaggage=t.getBaggage=void 0;var e=tpe(),n=epe(),r=(0,n.createContextKey)("OpenTelemetry Baggage Key");function o(l){return l.getValue(r)||void 0}t.getBaggage=o;function i(){return o(e.ContextAPI.getInstance().active())}t.getActiveBaggage=i;function s(l,c){return l.setValue(r,c)}t.setBaggage=s;function a(l){return l.deleteValue(r)}t.deleteBaggage=a}),a4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PropagationAPI=void 0;var e=zB(),n=i4n(),r=pNt(),o=s4n(),i=dNt(),s=HB(),a="propagation",l=new n.NoopTextMapPropagator;class c{constructor(){this.createBaggage=i.createBaggage,this.getBaggage=o.getBaggage,this.getActiveBaggage=o.getActiveBaggage,this.setBaggage=o.setBaggage,this.deleteBaggage=o.deleteBaggage}static getInstance(){return this._instance||(this._instance=new c),this._instance}setGlobalPropagator(d){return(0,e.registerGlobal)(a,d,s.DiagAPI.instance())}inject(d,f,p=r.defaultTextMapSetter){return this._getGlobalPropagator().inject(d,f,p)}extract(d,f,p=r.defaultTextMapGetter){return this._getGlobalPropagator().extract(d,f,p)}fields(){return this._getGlobalPropagator().fields()}disable(){(0,e.unregisterGlobal)(a,s.DiagAPI.instance())}_getGlobalPropagator(){return(0,e.getGlobal)(a)||l}}t.PropagationAPI=c}),l4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.propagation=void 0;var e=a4n();t.propagation=e.PropagationAPI.getInstance()}),c4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TraceAPI=void 0;var e=zB(),n=vNt(),r=oBe(),o=hNt(),i=HB(),s="trace";class a{constructor(){this._proxyTracerProvider=new n.ProxyTracerProvider,this.wrapSpanContext=r.wrapSpanContext,this.isSpanContextValid=r.isSpanContextValid,this.deleteSpan=o.deleteSpan,this.getSpan=o.getSpan,this.getActiveSpan=o.getActiveSpan,this.getSpanContext=o.getSpanContext,this.setSpan=o.setSpan,this.setSpanContext=o.setSpanContext}static getInstance(){return this._instance||(this._instance=new a),this._instance}setGlobalTracerProvider(c){let u=(0,e.registerGlobal)(s,this._proxyTracerProvider,i.DiagAPI.instance());return u&&this._proxyTracerProvider.setDelegate(c),u}getTracerProvider(){return(0,e.getGlobal)(s)||this._proxyTracerProvider}getTracer(c,u){return this.getTracerProvider().getTracer(c,u)}disable(){(0,e.unregisterGlobal)(s,i.DiagAPI.instance()),this._proxyTracerProvider=new n.ProxyTracerProvider}}t.TraceAPI=a}),u4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.trace=void 0;var e=c4n();t.trace=e.TraceAPI.getInstance()}),d4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.trace=t.propagation=t.metrics=t.diag=t.context=t.INVALID_SPAN_CONTEXT=t.INVALID_TRACEID=t.INVALID_SPANID=t.isValidSpanId=t.isValidTraceId=t.isSpanContextValid=t.createTraceState=t.TraceFlags=t.SpanStatusCode=t.SpanKind=t.SamplingDecision=t.ProxyTracerProvider=t.ProxyTracer=t.defaultTextMapSetter=t.defaultTextMapGetter=t.ValueType=t.createNoopMeter=t.DiagLogLevel=t.DiagConsoleLogger=t.ROOT_CONTEXT=t.createContextKey=t.baggageEntryMetadataFromString=void 0;var e=dNt();Object.defineProperty(t,"baggageEntryMetadataFromString",{enumerable:!0,get:function(){return e.baggageEntryMetadataFromString}});var n=epe();Object.defineProperty(t,"createContextKey",{enumerable:!0,get:function(){return n.createContextKey}}),Object.defineProperty(t,"ROOT_CONTEXT",{enumerable:!0,get:function(){return n.ROOT_CONTEXT}});var r=Wzn();Object.defineProperty(t,"DiagConsoleLogger",{enumerable:!0,get:function(){return r.DiagConsoleLogger}});var o=tBe();Object.defineProperty(t,"DiagLogLevel",{enumerable:!0,get:function(){return o.DiagLogLevel}});var i=fNt();Object.defineProperty(t,"createNoopMeter",{enumerable:!0,get:function(){return i.createNoopMeter}});var s=Vzn();Object.defineProperty(t,"ValueType",{enumerable:!0,get:function(){return s.ValueType}});var a=pNt();Object.defineProperty(t,"defaultTextMapGetter",{enumerable:!0,get:function(){return a.defaultTextMapGetter}}),Object.defineProperty(t,"defaultTextMapSetter",{enumerable:!0,get:function(){return a.defaultTextMapSetter}});var l=yNt();Object.defineProperty(t,"ProxyTracer",{enumerable:!0,get:function(){return l.ProxyTracer}});var c=vNt();Object.defineProperty(t,"ProxyTracerProvider",{enumerable:!0,get:function(){return c.ProxyTracerProvider}});var u=Gzn();Object.defineProperty(t,"SamplingDecision",{enumerable:!0,get:function(){return u.SamplingDecision}});var d=Zzn();Object.defineProperty(t,"SpanKind",{enumerable:!0,get:function(){return d.SpanKind}});var f=Yzn();Object.defineProperty(t,"SpanStatusCode",{enumerable:!0,get:function(){return f.SpanStatusCode}});var p=mNt();Object.defineProperty(t,"TraceFlags",{enumerable:!0,get:function(){return p.TraceFlags}});var m=Qzn();Object.defineProperty(t,"createTraceState",{enumerable:!0,get:function(){return m.createTraceState}});var h=oBe();Object.defineProperty(t,"isSpanContextValid",{enumerable:!0,get:function(){return h.isSpanContextValid}}),Object.defineProperty(t,"isValidTraceId",{enumerable:!0,get:function(){return h.isValidTraceId}}),Object.defineProperty(t,"isValidSpanId",{enumerable:!0,get:function(){return h.isValidSpanId}});var g=nBe();Object.defineProperty(t,"INVALID_SPANID",{enumerable:!0,get:function(){return g.INVALID_SPANID}}),Object.defineProperty(t,"INVALID_TRACEID",{enumerable:!0,get:function(){return g.INVALID_TRACEID}}),Object.defineProperty(t,"INVALID_SPAN_CONTEXT",{enumerable:!0,get:function(){return g.INVALID_SPAN_CONTEXT}});var v=e4n();Object.defineProperty(t,"context",{enumerable:!0,get:function(){return v.context}});var y=t4n();Object.defineProperty(t,"diag",{enumerable:!0,get:function(){return y.diag}});var w=o4n();Object.defineProperty(t,"metrics",{enumerable:!0,get:function(){return w.metrics}});var _=l4n();Object.defineProperty(t,"propagation",{enumerable:!0,get:function(){return _.propagation}});var S=u4n();Object.defineProperty(t,"trace",{enumerable:!0,get:function(){return S.trace}}),t.default={context:v.context,diag:y.diag,metrics:w.metrics,propagation:_.propagation,trace:S.trace}}),Gde=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends e{constructor(y){if(super(),!t.IDENTIFIER.test(y))throw Error("CodeGen: name must be a valid identifier");this.str=y}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=n;class r extends e{constructor(y){super(),this._items=typeof y=="string"?[y]:y}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let y=this._items[0];return y===""||y==='""'}get str(){var y;return(y=this._str)!==null&&y!==void 0?y:this._str=this._items.reduce((w,_)=>`${w}${_}`,"")}get names(){var y;return(y=this._names)!==null&&y!==void 0?y:this._names=this._items.reduce((w,_)=>(_ instanceof n&&(w[_.str]=(w[_.str]||0)+1),w),{})}}t._Code=r,t.nil=new r("");function o(v,...y){let w=[v[0]],_=0;for(;_<y.length;)a(w,y[_]),w.push(v[++_]);return new r(w)}t._=o;var i=new r("+");function s(v,...y){let w=[p(v[0])],_=0;for(;_<y.length;)w.push(i),a(w,y[_]),w.push(i,p(v[++_]));return l(w),new r(w)}t.str=s;function a(v,y){y instanceof r?v.push(...y._items):y instanceof n?v.push(y):v.push(d(y))}t.addCodeArg=a;function l(v){let y=1;for(;y<v.length-1;){if(v[y]===i){let w=c(v[y-1],v[y+1]);if(w!==void 0){v.splice(y-1,3,w);continue}v[y++]="+"}y++}}function c(v,y){if(y==='""')return v;if(v==='""')return y;if(typeof v=="string")return y instanceof n||v[v.length-1]!=='"'?void 0:typeof y!="string"?`${v.slice(0,-1)}${y}"`:y[0]==='"'?v.slice(0,-1)+y.slice(1):void 0;if(typeof y=="string"&&y[0]==='"'&&!(v instanceof n))return`"${v}${y.slice(1)}`}function u(v,y){return y.emptyStr()?v:v.emptyStr()?y:s`${v}${y}`}t.strConcat=u;function d(v){return typeof v=="number"||typeof v=="boolean"||v===null?v:p(Array.isArray(v)?v.join(","):v)}function f(v){return new r(p(v))}t.stringify=f;function p(v){return JSON.stringify(v).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=p;function m(v){return typeof v=="string"&&t.IDENTIFIER.test(v)?new r(`.${v}`):o`[${v}]`}t.getProperty=m;function h(v){if(typeof v=="string"&&t.IDENTIFIER.test(v))return new r(`${v}`);throw Error(`CodeGen: invalid export name: ${v}, use explicit $id name mapping`)}t.getEsmExportName=h;function g(v){return new r(v.toString())}t.regexpCode=g}),cMt=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;var e=Gde();class n extends Error{constructor(c){super(`CodeGen: "code" for ${c} not defined`),this.value=c.value}}var r;(function(l){l[l.Started=0]="Started",l[l.Completed=1]="Completed"})(r||(t.UsedValueState=r={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class o{constructor({prefixes:c,parent:u}={}){this._names={},this._prefixes=c,this._parent=u}toName(c){return c instanceof e.Name?c:this.name(c)}name(c){return new e.Name(this._newName(c))}_newName(c){let u=this._names[c]||this._nameGroup(c);return`${c}${u.index++}`}_nameGroup(c){var u,d;if(!((d=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||d===void 0)&&d.has(c)||this._prefixes&&!this._prefixes.has(c))throw Error(`CodeGen: prefix "${c}" is not allowed in this scope`);return this._names[c]={prefix:c,index:0}}}t.Scope=o;class i extends e.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:d}){this.value=c,this.scopePath=e._`.${new e.Name(u)}[${d}]`}}t.ValueScopeName=i;var s=e._`\n`;class a extends o{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?s:e.nil}}get(){return this._scope}name(c){return new i(c,this._newName(c))}value(c,u){var d;if(u.ref===void 0)throw Error("CodeGen: ref must be passed in value");let f=this.toName(c),{prefix:p}=f,m=(d=u.key)!==null&&d!==void 0?d:u.ref,h=this._values[p];if(h){let y=h.get(m);if(y)return y}else h=this._values[p]=new Map;h.set(m,f);let g=this._scope[p]||(this._scope[p]=[]),v=g.length;return g[v]=u.ref,f.setValue(u,{property:p,itemIndex:v}),f}getValue(c,u){let d=this._values[c];if(d)return d.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,d=>{if(d.scopePath===void 0)throw Error(`CodeGen: name "${d}" has no value`);return e._`${c}${d.scopePath}`})}scopeCode(c=this._values,u,d){return this._reduceValues(c,f=>{if(f.value===void 0)throw Error(`CodeGen: name "${f}" has no value`);return f.value.code},u,d)}_reduceValues(c,u,d={},f){let p=e.nil;for(let m in c){let h=c[m];if(!h)continue;let g=d[m]=d[m]||new Map;h.forEach(v=>{if(g.has(v))return;g.set(v,r.Started);let y=u(v);if(y){let w=this.opts.es5?t.varKinds.var:t.varKinds.const;p=e._`${p}${w} ${v} = ${y};${this.opts._n}`}else if(y=f?.(v))p=e._`${p}${y}${this.opts._n}`;else throw new n(v);g.set(v,r.Completed)})}return p}}t.ValueScope=a}),uo=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;var e=Gde(),n=cMt(),r=Gde();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return r.Name}});var o=cMt();Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class i{optimizeNodes(){return this}optimizeNames(F,z){return this}}class s extends i{constructor(F,z,N){super(),this.varKind=F,this.name=z,this.rhs=N}render({es5:F,_n:z}){let N=F?n.varKinds.var:this.varKind,R=this.rhs===void 0?"":` = ${this.rhs}`;return`${N} ${this.name}${R};`+z}optimizeNames(F,z){if(F[this.name.str])return this.rhs&&(this.rhs=U(this.rhs,F,z)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class a extends i{constructor(F,z,N){super(),this.lhs=F,this.rhs=z,this.sideEffects=N}render({_n:F}){return`${this.lhs} = ${this.rhs};`+F}optimizeNames(F,z){if(!(this.lhs instanceof e.Name&&!F[this.lhs.str]&&!this.sideEffects))return this.rhs=U(this.rhs,F,z),this}get names(){let F=this.lhs instanceof e.Name?{}:{...this.lhs.names};return $(F,this.rhs)}}class l extends a{constructor(F,z,N,R){super(F,N,R),this.op=z}render({_n:F}){return`${this.lhs} ${this.op}= ${this.rhs};`+F}}class c extends i{constructor(F){super(),this.label=F,this.names={}}render({_n:F}){return`${this.label}:`+F}}class u extends i{constructor(F){super(),this.label=F,this.names={}}render({_n:F}){return`break${this.label?` ${this.label}`:""};`+F}}class d extends i{constructor(F){super(),this.error=F}render({_n:F}){return`throw ${this.error};`+F}get names(){return this.error.names}}class f extends i{constructor(F){super(),this.code=F}render({_n:F}){return`${this.code};`+F}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(F,z){return this.code=U(this.code,F,z),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class p extends i{constructor(F=[]){super(),this.nodes=F}render(F){return this.nodes.reduce((z,N)=>z+N.render(F),"")}optimizeNodes(){let{nodes:F}=this,z=F.length;for(;z--;){let N=F[z].optimizeNodes();Array.isArray(N)?F.splice(z,1,...N):N?F[z]=N:F.splice(z,1)}return F.length>0?this:void 0}optimizeNames(F,z){let{nodes:N}=this,R=N.length;for(;R--;){let X=N[R];X.optimizeNames(F,z)||(V(F,X.names),N.splice(R,1))}return N.length>0?this:void 0}get names(){return this.nodes.reduce((F,z)=>O(F,z.names),{})}}class m extends p{render(F){return"{"+F._n+super.render(F)+"}"+F._n}}class h extends p{}class g extends m{}g.kind="else";class v extends m{constructor(F,z){super(z),this.condition=F}render(F){let z=`if(${this.condition})`+super.render(F);return this.else&&(z+="else "+this.else.render(F)),z}optimizeNodes(){super.optimizeNodes();let F=this.condition;if(F===!0)return this.nodes;let z=this.else;if(z){let N=z.optimizeNodes();z=this.else=Array.isArray(N)?new g(N):N}if(z)return F===!1?z instanceof v?z:z.nodes:this.nodes.length?this:new v(K(F),z instanceof v?[z]:z.nodes);if(!(F===!1||!this.nodes.length))return this}optimizeNames(F,z){var N;if(this.else=(N=this.else)===null||N===void 0?void 0:N.optimizeNames(F,z),!!(super.optimizeNames(F,z)||this.else))return this.condition=U(this.condition,F,z),this}get names(){let F=super.names;return $(F,this.condition),this.else&&O(F,this.else.names),F}}v.kind="if";class y extends m{}y.kind="for";class w extends y{constructor(F){super(),this.iteration=F}render(F){return`for(${this.iteration})`+super.render(F)}optimizeNames(F,z){if(super.optimizeNames(F,z))return this.iteration=U(this.iteration,F,z),this}get names(){return O(super.names,this.iteration.names)}}class _ extends y{constructor(F,z,N,R){super(),this.varKind=F,this.name=z,this.from=N,this.to=R}render(F){let z=F.es5?n.varKinds.var:this.varKind,{name:N,from:R,to:X}=this;return`for(${z} ${N}=${R}; ${N}<${X}; ${N}++)`+super.render(F)}get names(){let F=$(super.names,this.from);return $(F,this.to)}}class S extends y{constructor(F,z,N,R){super(),this.loop=F,this.varKind=z,this.name=N,this.iterable=R}render(F){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(F)}optimizeNames(F,z){if(super.optimizeNames(F,z))return this.iterable=U(this.iterable,F,z),this}get names(){return O(super.names,this.iterable.names)}}class I extends m{constructor(F,z,N){super(),this.name=F,this.args=z,this.async=N}render(F){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(F)}}I.kind="func";class C extends p{render(F){return"return "+super.render(F)}}C.kind="return";class k extends m{render(F){let z="try"+super.render(F);return this.catch&&(z+=this.catch.render(F)),this.finally&&(z+=this.finally.render(F)),z}optimizeNodes(){var F,z;return super.optimizeNodes(),(F=this.catch)===null||F===void 0||F.optimizeNodes(),(z=this.finally)===null||z===void 0||z.optimizeNodes(),this}optimizeNames(F,z){var N,R;return super.optimizeNames(F,z),(N=this.catch)===null||N===void 0||N.optimizeNames(F,z),(R=this.finally)===null||R===void 0||R.optimizeNames(F,z),this}get names(){let F=super.names;return this.catch&&O(F,this.catch.names),this.finally&&O(F,this.finally.names),F}}class T extends m{constructor(F){super(),this.error=F}render(F){return`catch(${this.error})`+super.render(F)}}T.kind="catch";class P extends m{render(F){return"finally"+super.render(F)}}P.kind="finally";class E{constructor(F,z={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...z,_n:z.lines?`
`:""},this._extScope=F,this._scope=new n.Scope({parent:F}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(F){return this._scope.name(F)}scopeName(F){return this._extScope.name(F)}scopeValue(F,z){let N=this._extScope.value(F,z);return(this._values[N.prefix]||(this._values[N.prefix]=new Set)).add(N),N}getScopeValue(F,z){return this._extScope.getValue(F,z)}scopeRefs(F){return this._extScope.scopeRefs(F,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(F,z,N,R){let X=this._scope.toName(z);return N!==void 0&&R&&(this._constants[X.str]=N),this._leafNode(new s(F,X,N)),X}const(F,z,N){return this._def(n.varKinds.const,F,z,N)}let(F,z,N){return this._def(n.varKinds.let,F,z,N)}var(F,z,N){return this._def(n.varKinds.var,F,z,N)}assign(F,z,N){return this._leafNode(new a(F,z,N))}add(F,z){return this._leafNode(new l(F,t.operators.ADD,z))}code(F){return typeof F=="function"?F():F!==e.nil&&this._leafNode(new f(F)),this}object(...F){let z=["{"];for(let[N,R]of F)z.length>1&&z.push(","),z.push(N),(N!==R||this.opts.es5)&&(z.push(":"),(0,e.addCodeArg)(z,R));return z.push("}"),new e._Code(z)}if(F,z,N){if(this._blockNode(new v(F)),z&&N)this.code(z).else().code(N).endIf();else if(z)this.code(z).endIf();else if(N)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(F){return this._elseNode(new v(F))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(v,g)}_for(F,z){return this._blockNode(F),z&&this.code(z).endFor(),this}for(F,z){return this._for(new w(F),z)}forRange(F,z,N,R,X=this.opts.es5?n.varKinds.var:n.varKinds.let){let D=this._scope.toName(F);return this._for(new _(X,D,z,N),()=>R(D))}forOf(F,z,N,R=n.varKinds.const){let X=this._scope.toName(F);if(this.opts.es5){let D=z instanceof e.Name?z:this.var("_arr",z);return this.forRange("_i",0,e._`${D}.length`,G=>{this.var(X,e._`${D}[${G}]`),N(X)})}return this._for(new S("of",R,X,z),()=>N(X))}forIn(F,z,N,R=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(F,e._`Object.keys(${z})`,N);let X=this._scope.toName(F);return this._for(new S("in",R,X,z),()=>N(X))}endFor(){return this._endBlockNode(y)}label(F){return this._leafNode(new c(F))}break(F){return this._leafNode(new u(F))}return(F){let z=new C;if(this._blockNode(z),this.code(F),z.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(C)}try(F,z,N){if(!z&&!N)throw Error('CodeGen: "try" without "catch" and "finally"');let R=new k;if(this._blockNode(R),this.code(F),z){let X=this.name("e");this._currNode=R.catch=new T(X),z(X)}return N&&(this._currNode=R.finally=new P,this.code(N)),this._endBlockNode(T,P)}throw(F){return this._leafNode(new d(F))}block(F,z){return this._blockStarts.push(this._nodes.length),F&&this.code(F).endBlock(z),this}endBlock(F){let z=this._blockStarts.pop();if(z===void 0)throw Error("CodeGen: not in self-balancing block");let N=this._nodes.length-z;if(N<0||F!==void 0&&N!==F)throw Error(`CodeGen: wrong number of nodes: ${N} vs ${F} expected`);return this._nodes.length=z,this}func(F,z=e.nil,N,R){return this._blockNode(new I(F,z,N)),R&&this.code(R).endFunc(),this}endFunc(){return this._endBlockNode(I)}optimize(F=1){for(;F-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(F){return this._currNode.nodes.push(F),this}_blockNode(F){this._currNode.nodes.push(F),this._nodes.push(F)}_endBlockNode(F,z){let N=this._currNode;if(N instanceof F||z&&N instanceof z)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${z?`${F.kind}/${z.kind}`:F.kind}"`)}_elseNode(F){let z=this._currNode;if(!(z instanceof v))throw Error('CodeGen: "else" without "if"');return this._currNode=z.else=F,this}get _root(){return this._nodes[0]}get _currNode(){let F=this._nodes;return F[F.length-1]}set _currNode(F){let z=this._nodes;z[z.length-1]=F}}t.CodeGen=E;function O(q,F){for(let z in F)q[z]=(q[z]||0)+(F[z]||0);return q}function $(q,F){return F instanceof e._CodeOrName?O(q,F.names):q}function U(q,F,z){if(q instanceof e.Name)return N(q);if(!R(q))return q;return new e._Code(q._items.reduce((X,D)=>(D instanceof e.Name&&(D=N(D)),D instanceof e._Code?X.push(...D._items):X.push(D),X),[]));function N(X){let D=z[X.str];return D===void 0||F[X.str]!==1?X:(delete F[X.str],D)}function R(X){return X instanceof e._Code&&X._items.some(D=>D instanceof e.Name&&F[D.str]===1&&z[D.str]!==void 0)}}function V(q,F){for(let z in F)q[z]=(q[z]||0)-(F[z]||0)}function K(q){return typeof q=="boolean"||typeof q=="number"||q===null?!q:e._`!${ae(q)}`}t.not=K;var se=ee(t.operators.AND);function le(...q){return q.reduce(se)}t.and=le;var Q=ee(t.operators.OR);function ne(...q){return q.reduce(Q)}t.or=ne;function ee(q){return(F,z)=>F===e.nil?z:z===e.nil?F:e._`${ae(F)} ${q} ${ae(z)}`}function ae(q){return q instanceof e.Name?q:e._`(${q})`}}),ni=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkStrictMode=t.getErrorPath=t.Type=t.useFunc=t.setEvaluated=t.evaluatedPropsToName=t.mergeEvaluated=t.eachItem=t.unescapeJsonPointer=t.escapeJsonPointer=t.escapeFragment=t.unescapeFragment=t.schemaRefOrVal=t.schemaHasRulesButRef=t.schemaHasRules=t.checkUnknownRules=t.alwaysValidSchema=t.toHash=void 0;var e=uo(),n=Gde();function r(I){let C={};for(let k of I)C[k]=!0;return C}t.toHash=r;function o(I,C){return typeof C=="boolean"?C:Object.keys(C).length===0?!0:(i(I,C),!s(C,I.self.RULES.all))}t.alwaysValidSchema=o;function i(I,C=I.schema){let{opts:k,self:T}=I;if(!k.strictSchema||typeof C=="boolean")return;let P=T.RULES.keywords;for(let E in C)P[E]||S(I,`unknown keyword: "${E}"`)}t.checkUnknownRules=i;function s(I,C){if(typeof I=="boolean")return!I;for(let k in I)if(C[k])return!0;return!1}t.schemaHasRules=s;function a(I,C){if(typeof I=="boolean")return!I;for(let k in I)if(k!=="$ref"&&C.all[k])return!0;return!1}t.schemaHasRulesButRef=a;function l({topSchemaRef:I,schemaPath:C},k,T,P){if(!P){if(typeof k=="number"||typeof k=="boolean")return k;if(typeof k=="string")return e._`${k}`}return e._`${I}${C}${(0,e.getProperty)(T)}`}t.schemaRefOrVal=l;function c(I){return f(decodeURIComponent(I))}t.unescapeFragment=c;function u(I){return encodeURIComponent(d(I))}t.escapeFragment=u;function d(I){return typeof I=="number"?`${I}`:I.replace(/~/g,"~0").replace(/\//g,"~1")}t.escapeJsonPointer=d;function f(I){return I.replace(/~1/g,"/").replace(/~0/g,"~")}t.unescapeJsonPointer=f;function p(I,C){if(Array.isArray(I))for(let k of I)C(k);else C(I)}t.eachItem=p;function m({mergeNames:I,mergeToName:C,mergeValues:k,resultToName:T}){return(P,E,O,$)=>{let U=O===void 0?E:O instanceof e.Name?(E instanceof e.Name?I(P,E,O):C(P,E,O),O):E instanceof e.Name?(C(P,O,E),E):k(E,O);return $===e.Name&&!(U instanceof e.Name)?T(P,U):U}}t.mergeEvaluated={props:m({mergeNames:(I,C,k)=>I.if(e._`${k} !== true && ${C} !== undefined`,()=>{I.if(e._`${C} === true`,()=>I.assign(k,!0),()=>I.assign(k,e._`${k} || {}`).code(e._`Object.assign(${k}, ${C})`))}),mergeToName:(I,C,k)=>I.if(e._`${k} !== true`,()=>{C===!0?I.assign(k,!0):(I.assign(k,e._`${k} || {}`),g(I,k,C))}),mergeValues:(I,C)=>I===!0?!0:{...I,...C},resultToName:h}),items:m({mergeNames:(I,C,k)=>I.if(e._`${k} !== true && ${C} !== undefined`,()=>I.assign(k,e._`${C} === true ? true : ${k} > ${C} ? ${k} : ${C}`)),mergeToName:(I,C,k)=>I.if(e._`${k} !== true`,()=>I.assign(k,C===!0?!0:e._`${k} > ${C} ? ${k} : ${C}`)),mergeValues:(I,C)=>I===!0?!0:Math.max(I,C),resultToName:(I,C)=>I.var("items",C)})};function h(I,C){if(C===!0)return I.var("props",!0);let k=I.var("props",e._`{}`);return C!==void 0&&g(I,k,C),k}t.evaluatedPropsToName=h;function g(I,C,k){Object.keys(k).forEach(T=>I.assign(e._`${C}${(0,e.getProperty)(T)}`,!0))}t.setEvaluated=g;var v={};function y(I,C){return I.scopeValue("func",{ref:C,code:v[C.code]||(v[C.code]=new n._Code(C.code))})}t.useFunc=y;var w;(function(I){I[I.Num=0]="Num",I[I.Str=1]="Str"})(w||(t.Type=w={}));function _(I,C,k){if(I instanceof e.Name){let T=C===w.Num;return k?T?e._`"[" + ${I} + "]"`:e._`"['" + ${I} + "']"`:T?e._`"/" + ${I}`:e._`"/" + ${I}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return k?(0,e.getProperty)(I).toString():"/"+d(I)}t.getErrorPath=_;function S(I,C,k=I.opts.strictSchema){if(k){if(C=`strict mode: ${C}`,k===!0)throw Error(C);I.self.logger.warn(C)}}t.checkStrictMode=S}),JP=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=uo(),n={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};t.default=n}),npe=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;var e=uo(),n=ni(),r=JP();t.keywordError={message:({keyword:g})=>e.str`must pass "${g}" keyword validation`},t.keyword$DataError={message:({keyword:g,schemaType:v})=>v?e.str`"${g}" keyword must be ${v} ($data)`:e.str`"${g}" keyword is invalid ($data)`};function o(g,v=t.keywordError,y,w){let{it:_}=g,{gen:S,compositeRule:I,allErrors:C}=_,k=d(g,v,y);w??(I||C)?l(S,k):c(_,e._`[${k}]`)}t.reportError=o;function i(g,v=t.keywordError,y){let{it:w}=g,{gen:_,compositeRule:S,allErrors:I}=w,C=d(g,v,y);l(_,C),!(S||I)&&c(w,r.default.vErrors)}t.reportExtraError=i;function s(g,v){g.assign(r.default.errors,v),g.if(e._`${r.default.vErrors} !== null`,()=>g.if(v,()=>g.assign(e._`${r.default.vErrors}.length`,v),()=>g.assign(r.default.vErrors,null)))}t.resetErrorsCount=s;function a({gen:g,keyword:v,schemaValue:y,data:w,errsCount:_,it:S}){if(_===void 0)throw Error("ajv implementation error");let I=g.name("err");g.forRange("i",_,r.default.errors,C=>{g.const(I,e._`${r.default.vErrors}[${C}]`),g.if(e._`${I}.instancePath === undefined`,()=>g.assign(e._`${I}.instancePath`,(0,e.strConcat)(r.default.instancePath,S.errorPath))),g.assign(e._`${I}.schemaPath`,e.str`${S.errSchemaPath}/${v}`),S.opts.verbose&&(g.assign(e._`${I}.schema`,y),g.assign(e._`${I}.data`,w))})}t.extendErrors=a;function l(g,v){let y=g.const("err",v);g.if(e._`${r.default.vErrors} === null`,()=>g.assign(r.default.vErrors,e._`[${y}]`),e._`${r.default.vErrors}.push(${y})`),g.code(e._`${r.default.errors}++`)}function c(g,v){let{gen:y,validateName:w,schemaEnv:_}=g;_.$async?y.throw(e._`new ${g.ValidationError}(${v})`):(y.assign(e._`${w}.errors`,v),y.return(!1))}var u={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function d(g,v,y){let{createErrors:w}=g.it;return w===!1?e._`{}`:f(g,v,y)}function f(g,v,y={}){let{gen:w,it:_}=g,S=[p(_,y),m(g,y)];return h(g,v,S),w.object(...S)}function p({errorPath:g},{instancePath:v}){let y=v?e.str`${g}${(0,n.getErrorPath)(v,n.Type.Str)}`:g;return[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,y)]}function m({keyword:g,it:{errSchemaPath:v}},{schemaPath:y,parentSchema:w}){let _=w?v:e.str`${v}/${g}`;return y&&(_=e.str`${_}${(0,n.getErrorPath)(y,n.Type.Str)}`),[u.schemaPath,_]}function h(g,{params:v,message:y},w){let{keyword:_,data:S,schemaValue:I,it:C}=g,{opts:k,propertyName:T,topSchemaRef:P,schemaPath:E}=C;w.push([u.keyword,_],[u.params,typeof v=="function"?v(g):v||e._`{}`]),k.messages&&w.push([u.message,typeof y=="function"?y(g):y]),k.verbose&&w.push([u.schema,I],[u.parentSchema,e._`${P}${E}`],[r.default.data,S]),T&&w.push([u.propertyName,T])}}),f4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.boolOrEmptySchema=t.topBoolOrEmptySchema=void 0;var e=npe(),n=uo(),r=JP(),o={message:"boolean schema is false"};function i(l){let{gen:c,schema:u,validateName:d}=l;u===!1?a(l,!1):typeof u=="object"&&u.$async===!0?c.return(r.default.data):(c.assign(n._`${d}.errors`,null),c.return(!0))}t.topBoolOrEmptySchema=i;function s(l,c){let{gen:u,schema:d}=l;d===!1?(u.var(c,!1),a(l)):u.var(c,!0)}t.boolOrEmptySchema=s;function a(l,c){let{gen:u,data:d}=l,f={gen:u,keyword:"false schema",data:d,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:l};(0,e.reportError)(f,o,void 0,c)}}),wNt=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getRules=t.isJSONType=void 0;var e=["string","number","integer","boolean","null","object","array"],n=new Set(e);function r(i){return typeof i=="string"&&n.has(i)}t.isJSONType=r;function o(){let i={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...i,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},i.number,i.string,i.array,i.object],post:{rules:[]},all:{},keywords:{}}}t.getRules=o}),bNt=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shouldUseRule=t.shouldUseGroup=t.schemaHasRulesForType=void 0;function e({schema:o,self:i},s){let a=i.RULES.types[s];return a&&a!==!0&&n(o,a)}t.schemaHasRulesForType=e;function n(o,i){return i.rules.some(s=>r(o,s))}t.shouldUseGroup=n;function r(o,i){var s;return o[i.keyword]!==void 0||((s=i.definition.implements)===null||s===void 0?void 0:s.some(a=>o[a]!==void 0))}t.shouldUseRule=r}),Zde=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reportTypeError=t.checkDataTypes=t.checkDataType=t.coerceAndCheckDataType=t.getJSONTypes=t.getSchemaTypes=t.DataType=void 0;var e=wNt(),n=bNt(),r=npe(),o=uo(),i=ni(),s;(function(w){w[w.Correct=0]="Correct",w[w.Wrong=1]="Wrong"})(s||(t.DataType=s={}));function a(w){let _=l(w.type);if(_.includes("null")){if(w.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!_.length&&w.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');w.nullable===!0&&_.push("null")}return _}t.getSchemaTypes=a;function l(w){let _=Array.isArray(w)?w:w?[w]:[];if(_.every(e.isJSONType))return _;throw Error("type must be JSONType or JSONType[]: "+_.join(","))}t.getJSONTypes=l;function c(w,_){let{gen:S,data:I,opts:C}=w,k=d(_,C.coerceTypes),T=_.length>0&&!(k.length===0&&_.length===1&&(0,n.schemaHasRulesForType)(w,_[0]));if(T){let P=h(_,I,C.strictNumbers,s.Wrong);S.if(P,()=>{k.length?f(w,_,k):v(w)})}return T}t.coerceAndCheckDataType=c;var u=new Set(["string","number","integer","boolean","null"]);function d(w,_){return _?w.filter(S=>u.has(S)||_==="array"&&S==="array"):[]}function f(w,_,S){let{gen:I,data:C,opts:k}=w,T=I.let("dataType",o._`typeof ${C}`),P=I.let("coerced",o._`undefined`);k.coerceTypes==="array"&&I.if(o._`${T} == 'object' && Array.isArray(${C}) && ${C}.length == 1`,()=>I.assign(C,o._`${C}[0]`).assign(T,o._`typeof ${C}`).if(h(_,C,k.strictNumbers),()=>I.assign(P,C))),I.if(o._`${P} !== undefined`);for(let O of S)(u.has(O)||O==="array"&&k.coerceTypes==="array")&&E(O);I.else(),v(w),I.endIf(),I.if(o._`${P} !== undefined`,()=>{I.assign(C,P),p(w,P)});function E(O){switch(O){case"string":I.elseIf(o._`${T} == "number" || ${T} == "boolean"`).assign(P,o._`"" + ${C}`).elseIf(o._`${C} === null`).assign(P,o._`""`);return;case"number":I.elseIf(o._`${T} == "boolean" || ${C} === null
|| (${T} == "string" && ${C} && ${C} == +${C})`).assign(P,o._`+${C}`);return;case"integer":I.elseIf(o._`${T} === "boolean" || ${C} === null
|| (${T} === "string" && ${C} && ${C} == +${C} && !(${C} % 1))`).assign(P,o._`+${C}`);return;case"boolean":I.elseIf(o._`${C} === "false" || ${C} === 0 || ${C} === null`).assign(P,!1).elseIf(o._`${C} === "true" || ${C} === 1`).assign(P,!0);return;case"null":I.elseIf(o._`${C} === "" || ${C} === 0 || ${C} === false`),I.assign(P,null);return;case"array":I.elseIf(o._`${T} === "string" || ${T} === "number"
|| ${T} === "boolean" || ${C} === null`).assign(P,o._`[${C}]`)}}}function p({gen:w,parentData:_,parentDataProperty:S},I){w.if(o._`${_} !== undefined`,()=>w.assign(o._`${_}[${S}]`,I))}function m(w,_,S,I=s.Correct){let C=I===s.Correct?o.operators.EQ:o.operators.NEQ,k;switch(w){case"null":return o._`${_} ${C} null`;case"array":k=o._`Array.isArray(${_})`;break;case"object":k=o._`${_} && typeof ${_} == "object" && !Array.isArray(${_})`;break;case"integer":k=T(o._`!(${_} % 1) && !isNaN(${_})`);break;case"number":k=T();break;default:return o._`typeof ${_} ${C} ${w}`}return I===s.Correct?k:(0,o.not)(k);function T(P=o.nil){return(0,o.and)(o._`typeof ${_} == "number"`,P,S?o._`isFinite(${_})`:o.nil)}}t.checkDataType=m;function h(w,_,S,I){if(w.length===1)return m(w[0],_,S,I);let C,k=(0,i.toHash)(w);if(k.array&&k.object){let T=o._`typeof ${_} != "object"`;C=k.null?T:o._`!${_} || ${T}`,delete k.null,delete k.array,delete k.object}else C=o.nil;k.number&&delete k.integer;for(let T in k)C=(0,o.and)(C,m(T,_,S,I));return C}t.checkDataTypes=h;var g={message:({schema:w})=>`must be ${w}`,params:({schema:w,schemaValue:_})=>typeof w=="string"?o._`{type: ${w}}`:o._`{type: ${_}}`};function v(w){let _=y(w);(0,r.reportError)(_,g)}t.reportTypeError=v;function y(w){let{gen:_,data:S,schema:I}=w,C=(0,i.schemaRefOrVal)(w,I,"type");return{gen:_,keyword:"type",data:S,schema:I.type,schemaCode:C,schemaValue:C,parentSchema:I,params:{},it:w}}}),p4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.assignDefaults=void 0;var e=uo(),n=ni();function r(i,s){let{properties:a,items:l}=i.schema;if(s==="object"&&a)for(let c in a)o(i,c,a[c].default);else s==="array"&&Array.isArray(l)&&l.forEach((c,u)=>o(i,u,c.default))}t.assignDefaults=r;function o(i,s,a){let{gen:l,compositeRule:c,data:u,opts:d}=i;if(a===void 0)return;let f=e._`${u}${(0,e.getProperty)(s)}`;if(c){(0,n.checkStrictMode)(i,`default is ignored for: ${f}`);return}let p=e._`${f} === undefined`;d.useDefaults==="empty"&&(p=e._`${p} || ${f} === null || ${f} === ""`),l.if(p,e._`${f} = ${(0,e.stringify)(a)}`)}}),ab=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateUnion=t.validateArray=t.usePattern=t.callValidateCode=t.schemaProperties=t.allSchemaProperties=t.noPropertyInData=t.propertyInData=t.isOwnProperty=t.hasPropFunc=t.reportMissingProp=t.checkMissingProp=t.checkReportMissingProp=void 0;var e=uo(),n=ni(),r=JP(),o=ni();function i(w,_){let{gen:S,data:I,it:C}=w;S.if(d(S,I,_,C.opts.ownProperties),()=>{w.setParams({missingProperty:e._`${_}`},!0),w.error()})}t.checkReportMissingProp=i;function s({gen:w,data:_,it:{opts:S}},I,C){return(0,e.or)(...I.map(k=>(0,e.and)(d(w,_,k,S.ownProperties),e._`${C} = ${k}`)))}t.checkMissingProp=s;function a(w,_){w.setParams({missingProperty:_},!0),w.error()}t.reportMissingProp=a;function l(w){return w.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:e._`Object.prototype.hasOwnProperty`})}t.hasPropFunc=l;function c(w,_,S){return e._`${l(w)}.call(${_}, ${S})`}t.isOwnProperty=c;function u(w,_,S,I){let C=e._`${_}${(0,e.getProperty)(S)} !== undefined`;return I?e._`${C} && ${c(w,_,S)}`:C}t.propertyInData=u;function d(w,_,S,I){let C=e._`${_}${(0,e.getProperty)(S)} === undefined`;return I?(0,e.or)(C,(0,e.not)(c(w,_,S))):C}t.noPropertyInData=d;function f(w){return w?Object.keys(w).filter(_=>_!=="__proto__"):[]}t.allSchemaProperties=f;function p(w,_){return f(_).filter(S=>!(0,n.alwaysValidSchema)(w,_[S]))}t.schemaProperties=p;function m({schemaCode:w,data:_,it:{gen:S,topSchemaRef:I,schemaPath:C,errorPath:k},it:T},P,E,O){let $=O?e._`${w}, ${_}, ${I}${C}`:_,U=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,k)],[r.default.parentData,T.parentData],[r.default.parentDataProperty,T.parentDataProperty],[r.default.rootData,r.default.rootData]];T.opts.dynamicRef&&U.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let V=e._`${$}, ${S.object(...U)}`;return E!==e.nil?e._`${P}.call(${E}, ${V})`:e._`${P}(${V})`}t.callValidateCode=m;var h=e._`new RegExp`;function g({gen:w,it:{opts:_}},S){let I=_.unicodeRegExp?"u":"",{regExp:C}=_.code,k=C(S,I);return w.scopeValue("pattern",{key:k.toString(),ref:k,code:e._`${C.code==="new RegExp"?h:(0,o.useFunc)(w,C)}(${S}, ${I})`})}t.usePattern=g;function v(w){let{gen:_,data:S,keyword:I,it:C}=w,k=_.name("valid");if(C.allErrors){let P=_.let("valid",!0);return T(()=>_.assign(P,!1)),P}return _.var(k,!0),T(()=>_.break()),k;function T(P){let E=_.const("len",e._`${S}.length`);_.forRange("i",0,E,O=>{w.subschema({keyword:I,dataProp:O,dataPropType:n.Type.Num},k),_.if((0,e.not)(k),P)})}}t.validateArray=v;function y(w){let{gen:_,schema:S,keyword:I,it:C}=w;if(!Array.isArray(S))throw Error("ajv implementation error");if(S.some(P=>(0,n.alwaysValidSchema)(C,P))&&!C.opts.unevaluated)return;let k=_.let("valid",!1),T=_.name("_valid");_.block(()=>S.forEach((P,E)=>{let O=w.subschema({keyword:I,schemaProp:E,compositeRule:!0},T);_.assign(k,e._`${k} || ${T}`),!w.mergeValidEvaluated(O,T)&&_.if((0,e.not)(k))})),w.result(k,()=>w.reset(),()=>w.error(!0))}t.validateUnion=y}),m4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateKeywordUsage=t.validSchemaType=t.funcKeywordCode=t.macroKeywordCode=void 0;var e=uo(),n=JP(),r=ab(),o=npe();function i(p,m){let{gen:h,keyword:g,schema:v,parentSchema:y,it:w}=p,_=m.macro.call(w.self,v,y,w),S=u(h,g,_);w.opts.validateSchema!==!1&&w.self.validateSchema(_,!0);let I=h.name("valid");p.subschema({schema:_,schemaPath:e.nil,errSchemaPath:`${w.errSchemaPath}/${g}`,topSchemaRef:S,compositeRule:!0},I),p.pass(I,()=>p.error(!0))}t.macroKeywordCode=i;function s(p,m){var h;let{gen:g,keyword:v,schema:y,parentSchema:w,$data:_,it:S}=p;c(S,m);let I=!_&&m.compile?m.compile.call(S.self,y,w,S):m.validate,C=u(g,v,I),k=g.let("valid");p.block$data(k,T),p.ok((h=m.valid)!==null&&h!==void 0?h:k);function T(){if(m.errors===!1)O(),m.modifying&&a(p),$(()=>p.error());else{let U=m.async?P():E();m.modifying&&a(p),$(()=>l(p,U))}}function P(){let U=g.let("ruleErrs",null);return g.try(()=>O(e._`await `),V=>g.assign(k,!1).if(e._`${V} instanceof ${S.ValidationError}`,()=>g.assign(U,e._`${V}.errors`),()=>g.throw(V))),U}function E(){let U=e._`${C}.errors`;return g.assign(U,null),O(e.nil),U}function O(U=m.async?e._`await `:e.nil){let V=S.opts.passContext?n.default.this:n.default.self,K=!("compile"in m&&!_||m.schema===!1);g.assign(k,e._`${U}${(0,r.callValidateCode)(p,C,V,K)}`,m.modifying)}function $(U){var V;g.if((0,e.not)((V=m.valid)!==null&&V!==void 0?V:k),U)}}t.funcKeywordCode=s;function a(p){let{gen:m,data:h,it:g}=p;m.if(g.parentData,()=>m.assign(h,e._`${g.parentData}[${g.parentDataProperty}]`))}function l(p,m){let{gen:h}=p;h.if(e._`Array.isArray(${m})`,()=>{h.assign(n.default.vErrors,e._`${n.default.vErrors} === null ? ${m} : ${n.default.vErrors}.concat(${m})`).assign(n.default.errors,e._`${n.default.vErrors}.length`),(0,o.extendErrors)(p)},()=>p.error())}function c({schemaEnv:p},m){if(m.async&&!p.$async)throw Error("async keyword in sync schema")}function u(p,m,h){if(h===void 0)throw Error(`keyword "${m}" failed to compile`);return p.scopeValue("keyword",typeof h=="function"?{ref:h}:{ref:h,code:(0,e.stringify)(h)})}function d(p,m,h=!1){return!m.length||m.some(g=>g==="array"?Array.isArray(p):g==="object"?p&&typeof p=="object"&&!Array.isArray(p):typeof p==g||h&&typeof p>"u")}t.validSchemaType=d;function f({schema:p,opts:m,self:h,errSchemaPath:g},v,y){if(Array.isArray(v.keyword)?!v.keyword.includes(y):v.keyword!==y)throw Error("ajv implementation error");let w=v.dependencies;if(w?.some(_=>!Object.prototype.hasOwnProperty.call(p,_)))throw Error(`parent schema must have dependencies of ${y}: ${w.join(",")}`);if(v.validateSchema&&!v.validateSchema(p[y])){let _=`keyword "${y}" value is invalid at path "${g}": `+h.errorsText(v.validateSchema.errors);if(m.validateSchema==="log")h.logger.error(_);else throw Error(_)}}t.validateKeywordUsage=f}),h4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extendSubschemaMode=t.extendSubschemaData=t.getSubschema=void 0;var e=uo(),n=ni();function r(s,{keyword:a,schemaProp:l,schema:c,schemaPath:u,errSchemaPath:d,topSchemaRef:f}){if(a!==void 0&&c!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(a!==void 0){let p=s.schema[a];return l===void 0?{schema:p,schemaPath:e._`${s.schemaPath}${(0,e.getProperty)(a)}`,errSchemaPath:`${s.errSchemaPath}/${a}`}:{schema:p[l],schemaPath:e._`${s.schemaPath}${(0,e.getProperty)(a)}${(0,e.getProperty)(l)}`,errSchemaPath:`${s.errSchemaPath}/${a}/${(0,n.escapeFragment)(l)}`}}if(c!==void 0){if(u===void 0||d===void 0||f===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:c,schemaPath:u,topSchemaRef:f,errSchemaPath:d}}throw Error('either "keyword" or "schema" must be passed')}t.getSubschema=r;function o(s,a,{dataProp:l,dataPropType:c,data:u,dataTypes:d,propertyName:f}){if(u!==void 0&&l!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:p}=a;if(l!==void 0){let{errorPath:h,dataPathArr:g,opts:v}=a,y=p.let("data",e._`${a.data}${(0,e.getProperty)(l)}`,!0);m(y),s.errorPath=e.str`${h}${(0,n.getErrorPath)(l,c,v.jsPropertySyntax)}`,s.parentDataProperty=e._`${l}`,s.dataPathArr=[...g,s.parentDataProperty]}if(u!==void 0){let h=u instanceof e.Name?u:p.let("data",u,!0);m(h),f!==void 0&&(s.propertyName=f)}d&&(s.dataTypes=d);function m(h){s.data=h,s.dataLevel=a.dataLevel+1,s.dataTypes=[],a.definedProperties=new Set,s.parentData=a.data,s.dataNames=[...a.dataNames,h]}}t.extendSubschemaData=o;function i(s,{jtdDiscriminator:a,jtdMetadata:l,compositeRule:c,createErrors:u,allErrors:d}){c!==void 0&&(s.compositeRule=c),u!==void 0&&(s.createErrors=u),d!==void 0&&(s.allErrors=d),s.jtdDiscriminator=a,s.jtdMetadata=l}t.extendSubschemaMode=i}),_Nt=Le((t,e)=>{e.exports=function n(r,o){if(r===o)return!0;if(r&&o&&typeof r=="object"&&typeof o=="object"){if(r.constructor!==o.constructor)return!1;var i,s,a;if(Array.isArray(r)){if(i=r.length,i!=o.length)return!1;for(s=i;s--!==0;)if(!n(r[s],o[s]))return!1;return!0}if(r.constructor===RegExp)return r.source===o.source&&r.flags===o.flags;if(r.valueOf!==Object.prototype.valueOf)return r.valueOf()===o.valueOf();if(r.toString!==Object.prototype.toString)return r.toString()===o.toString();if(a=Object.keys(r),i=a.length,i!==Object.keys(o).length)return!1;for(s=i;s--!==0;)if(!Object.prototype.hasOwnProperty.call(o,a[s]))return!1;for(s=i;s--!==0;){var l=a[s];if(!n(r[l],o[l]))return!1}return!0}return r!==r&&o!==o}}),g4n=Le((t,e)=>{var n=e.exports=function(i,s,a){typeof s=="function"&&(a=s,s={}),a=s.cb||a;var l=typeof a=="function"?a:a.pre||function(){},c=a.post||function(){};r(s,l,c,i,"",i)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function r(i,s,a,l,c,u,d,f,p,m){if(l&&typeof l=="object"&&!Array.isArray(l)){s(l,c,u,d,f,p,m);for(var h in l){var g=l[h];if(Array.isArray(g)){if(h in n.arrayKeywords)for(var v=0;v<g.length;v++)r(i,s,a,g[v],c+"/"+h+"/"+v,u,c,h,l,v)}else if(h in n.propsKeywords){if(g&&typeof g=="object")for(var y in g)r(i,s,a,g[y],c+"/"+h+"/"+o(y),u,c,h,l,y)}else(h in n.keywords||i.allKeys&&!(h in n.skipKeywords))&&r(i,s,a,g,c+"/"+h,u,c,h,l)}a(l,c,u,d,f,p,m)}}function o(i){return i.replace(/~/g,"~0").replace(/\//g,"~1")}}),rpe=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSchemaRefs=t.resolveUrl=t.normalizeId=t._getFullPath=t.getFullPath=t.inlineRef=void 0;var e=ni(),n=_Nt(),r=g4n(),o=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function i(g,v=!0){return typeof g=="boolean"?!0:v===!0?!a(g):v?l(g)<=v:!1}t.inlineRef=i;var s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function a(g){for(let v in g){if(s.has(v))return!0;let y=g[v];if(Array.isArray(y)&&y.some(a)||typeof y=="object"&&a(y))return!0}return!1}function l(g){let v=0;for(let y in g){if(y==="$ref")return 1/0;if(v++,!o.has(y)&&(typeof g[y]=="object"&&(0,e.eachItem)(g[y],w=>v+=l(w)),v===1/0))return 1/0}return v}function c(g,v="",y){y!==!1&&(v=f(v));let w=g.parse(v);return u(g,w)}t.getFullPath=c;function u(g,v){return g.serialize(v).split("#")[0]+"#"}t._getFullPath=u;var d=/#\/?$/;function f(g){return g?g.replace(d,""):""}t.normalizeId=f;function p(g,v,y){return y=f(y),g.resolve(v,y)}t.resolveUrl=p;var m=/^[a-z_][-a-z0-9._]*$/i;function h(g,v){if(typeof g=="boolean")return{};let{schemaId:y,uriResolver:w}=this.opts,_=f(g[y]||v),S={"":_},I=c(w,_,!1),C={},k=new Set;return r(g,{allKeys:!0},(E,O,$,U)=>{if(U===void 0)return;let V=I+O,K=S[U];typeof E[y]=="string"&&(K=se.call(this,E[y])),le.call(this,E.$anchor),le.call(this,E.$dynamicAnchor),S[O]=K;function se(Q){let ne=this.opts.uriResolver.resolve;if(Q=f(K?ne(K,Q):Q),k.has(Q))throw P(Q);k.add(Q);let ee=this.refs[Q];return typeof ee=="string"&&(ee=this.refs[ee]),typeof ee=="object"?T(E,ee.schema,Q):Q!==f(V)&&(Q[0]==="#"?(T(E,C[Q],Q),C[Q]=E):this.refs[Q]=V),Q}function le(Q){if(typeof Q=="string"){if(!m.test(Q))throw Error(`invalid anchor "${Q}"`);se.call(this,`#${Q}`)}}}),C;function T(E,O,$){if(O!==void 0&&!n(E,O))throw P($)}function P(E){return Error(`reference "${E}" resolves to more than one schema`)}}t.getSchemaRefs=h}),ope=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getData=t.KeywordCxt=t.validateFunctionCode=void 0;var e=f4n(),n=Zde(),r=bNt(),o=Zde(),i=p4n(),s=m4n(),a=h4n(),l=uo(),c=JP(),u=rpe(),d=ni(),f=npe();function p(Z){if(I(Z)&&(k(Z),S(Z))){v(Z);return}m(Z,()=>(0,e.topBoolOrEmptySchema)(Z))}t.validateFunctionCode=p;function m({gen:Z,validateName:te,schema:fe,schemaEnv:de,opts:ye},Te){ye.code.es5?Z.func(te,l._`${c.default.data}, ${c.default.valCxt}`,de.$async,()=>{Z.code(l._`"use strict"; ${w(fe,ye)}`),g(Z,ye),Z.code(Te)}):Z.func(te,l._`${c.default.data}, ${h(ye)}`,de.$async,()=>Z.code(w(fe,ye)).code(Te))}function h(Z){return l._`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${Z.dynamicRef?l._`, ${c.default.dynamicAnchors}={}`:l.nil}}={}`}function g(Z,te){Z.if(c.default.valCxt,()=>{Z.var(c.default.instancePath,l._`${c.default.valCxt}.${c.default.instancePath}`),Z.var(c.default.parentData,l._`${c.default.valCxt}.${c.default.parentData}`),Z.var(c.default.parentDataProperty,l._`${c.default.valCxt}.${c.default.parentDataProperty}`),Z.var(c.default.rootData,l._`${c.default.valCxt}.${c.default.rootData}`),te.dynamicRef&&Z.var(c.default.dynamicAnchors,l._`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{Z.var(c.default.instancePath,l._`""`),Z.var(c.default.parentData,l._`undefined`),Z.var(c.default.parentDataProperty,l._`undefined`),Z.var(c.default.rootData,c.default.data),te.dynamicRef&&Z.var(c.default.dynamicAnchors,l._`{}`)})}function v(Z){let{schema:te,opts:fe,gen:de}=Z;m(Z,()=>{fe.$comment&&te.$comment&&U(Z),E(Z),de.let(c.default.vErrors,null),de.let(c.default.errors,0),fe.unevaluated&&y(Z),T(Z),V(Z)})}function y(Z){let{gen:te,validateName:fe}=Z;Z.evaluated=te.const("evaluated",l._`${fe}.evaluated`),te.if(l._`${Z.evaluated}.dynamicProps`,()=>te.assign(l._`${Z.evaluated}.props`,l._`undefined`)),te.if(l._`${Z.evaluated}.dynamicItems`,()=>te.assign(l._`${Z.evaluated}.items`,l._`undefined`))}function w(Z,te){let fe=typeof Z=="object"&&Z[te.schemaId];return fe&&(te.code.source||te.code.process)?l._`/*# sourceURL=${fe} */`:l.nil}function _(Z,te){if(I(Z)&&(k(Z),S(Z))){C(Z,te);return}(0,e.boolOrEmptySchema)(Z,te)}function S({schema:Z,self:te}){if(typeof Z=="boolean")return!Z;for(let fe in Z)if(te.RULES.all[fe])return!0;return!1}function I(Z){return typeof Z.schema!="boolean"}function C(Z,te){let{schema:fe,gen:de,opts:ye}=Z;ye.$comment&&fe.$comment&&U(Z),O(Z),$(Z);let Te=de.const("_errs",c.default.errors);T(Z,Te),de.var(te,l._`${Te} === ${c.default.errors}`)}function k(Z){(0,d.checkUnknownRules)(Z),P(Z)}function T(Z,te){if(Z.opts.jtd)return se(Z,[],!1,te);let fe=(0,n.getSchemaTypes)(Z.schema),de=(0,n.coerceAndCheckDataType)(Z,fe);se(Z,fe,!de,te)}function P(Z){let{schema:te,errSchemaPath:fe,opts:de,self:ye}=Z;te.$ref&&de.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(te,ye.RULES)&&ye.logger.warn(`$ref: keywords ignored in schema at path "${fe}"`)}function E(Z){let{schema:te,opts:fe}=Z;te.default!==void 0&&fe.useDefaults&&fe.strictSchema&&(0,d.checkStrictMode)(Z,"default is ignored in the schema root")}function O(Z){let te=Z.schema[Z.opts.schemaId];te&&(Z.baseId=(0,u.resolveUrl)(Z.opts.uriResolver,Z.baseId,te))}function $(Z){if(Z.schema.$async&&!Z.schemaEnv.$async)throw Error("async schema in sync schema")}function U({gen:Z,schemaEnv:te,schema:fe,errSchemaPath:de,opts:ye}){let Te=fe.$comment;if(ye.$comment===!0)Z.code(l._`${c.default.self}.logger.log(${Te})`);else if(typeof ye.$comment=="function"){let Be=l.str`${de}/$comment`,qe=Z.scopeValue("root",{ref:te.root});Z.code(l._`${c.default.self}.opts.$comment(${Te}, ${Be}, ${qe}.schema)`)}}function V(Z){let{gen:te,schemaEnv:fe,validateName:de,ValidationError:ye,opts:Te}=Z;fe.$async?te.if(l._`${c.default.errors} === 0`,()=>te.return(c.default.data),()=>te.throw(l._`new ${ye}(${c.default.vErrors})`)):(te.assign(l._`${de}.errors`,c.default.vErrors),Te.unevaluated&&K(Z),te.return(l._`${c.default.errors} === 0`))}function K({gen:Z,evaluated:te,props:fe,items:de}){fe instanceof l.Name&&Z.assign(l._`${te}.props`,fe),de instanceof l.Name&&Z.assign(l._`${te}.items`,de)}function se(Z,te,fe,de){let{gen:ye,schema:Te,data:Be,allErrors:qe,opts:Ae,self:Xt}=Z,{RULES:Ve}=Xt;if(Te.$ref&&(Ae.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(Te,Ve))){ye.block(()=>X(Z,"$ref",Ve.all.$ref.definition));return}Ae.jtd||Q(Z,te),ye.block(()=>{for(let st of Ve.rules)Ee(st);Ee(Ve.post)});function Ee(st){(0,r.shouldUseGroup)(Te,st)&&(st.type?(ye.if((0,o.checkDataType)(st.type,Be,Ae.strictNumbers)),le(Z,st),te.length===1&&te[0]===st.type&&fe&&(ye.else(),(0,o.reportTypeError)(Z)),ye.endIf()):le(Z,st),qe||ye.if(l._`${c.default.errors} === ${de||0}`))}}function le(Z,te){let{gen:fe,schema:de,opts:{useDefaults:ye}}=Z;ye&&(0,i.assignDefaults)(Z,te.type),fe.block(()=>{for(let Te of te.rules)(0,r.shouldUseRule)(de,Te)&&X(Z,Te.keyword,Te.definition,te.type)})}function Q(Z,te){Z.schemaEnv.meta||!Z.opts.strictTypes||(ne(Z,te),!Z.opts.allowUnionTypes&&ee(Z,te),ae(Z,Z.dataTypes))}function ne(Z,te){if(te.length){if(!Z.dataTypes.length){Z.dataTypes=te;return}te.forEach(fe=>{F(Z.dataTypes,fe)||N(Z,`type "${fe}" not allowed by context "${Z.dataTypes.join(",")}"`)}),z(Z,te)}}function ee(Z,te){te.length>1&&!(te.length===2&&te.includes("null"))&&N(Z,"use allowUnionTypes to allow union type keyword")}function ae(Z,te){let fe=Z.self.RULES.all;for(let de in fe){let ye=fe[de];if(typeof ye=="object"&&(0,r.shouldUseRule)(Z.schema,ye)){let{type:Te}=ye.definition;Te.length&&!Te.some(Be=>q(te,Be))&&N(Z,`missing type "${Te.join(",")}" for keyword "${de}"`)}}}function q(Z,te){return Z.includes(te)||te==="number"&&Z.includes("integer")}function F(Z,te){return Z.includes(te)||te==="integer"&&Z.includes("number")}function z(Z,te){let fe=[];for(let de of Z.dataTypes)F(te,de)?fe.push(de):te.includes("integer")&&de==="number"&&fe.push("integer");Z.dataTypes=fe}function N(Z,te){let fe=Z.schemaEnv.baseId+Z.errSchemaPath;te+=` at "${fe}" (strictTypes)`,(0,d.checkStrictMode)(Z,te,Z.opts.strictTypes)}class R{constructor(te,fe,de){if((0,s.validateKeywordUsage)(te,fe,de),this.gen=te.gen,this.allErrors=te.allErrors,this.keyword=de,this.data=te.data,this.schema=te.schema[de],this.$data=fe.$data&&te.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(te,this.schema,de,this.$data),this.schemaType=fe.schemaType,this.parentSchema=te.schema,this.params={},this.it=te,this.def=fe,this.$data)this.schemaCode=te.gen.const("vSchema",ce(this.$data,te));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,fe.schemaType,fe.allowUndefined))throw Error(`${de} value must be ${JSON.stringify(fe.schemaType)}`);("code"in fe?fe.trackErrors:fe.errors!==!1)&&(this.errsCount=te.gen.const("_errs",c.default.errors))}result(te,fe,de){this.failResult((0,l.not)(te),fe,de)}failResult(te,fe,de){this.gen.if(te),de?de():this.error(),fe?(this.gen.else(),fe(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(te,fe){this.failResult((0,l.not)(te),void 0,fe)}fail(te){if(te===void 0){this.error(),!this.allErrors&&this.gen.if(!1);return}this.gen.if(te),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(te){if(!this.$data)return this.fail(te);let{schemaCode:fe}=this;this.fail(l._`${fe} !== undefined && (${(0,l.or)(this.invalid$data(),te)})`)}error(te,fe,de){if(fe){this.setParams(fe),this._error(te,de),this.setParams({});return}this._error(te,de)}_error(te,fe){(te?f.reportExtraError:f.reportError)(this,this.def.error,fe)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(te){this.allErrors||this.gen.if(te)}setParams(te,fe){fe?Object.assign(this.params,te):this.params=te}block$data(te,fe,de=l.nil){this.gen.block(()=>{this.check$data(te,de),fe()})}check$data(te=l.nil,fe=l.nil){if(!this.$data)return;let{gen:de,schemaCode:ye,schemaType:Te,def:Be}=this;de.if((0,l.or)(l._`${ye} === undefined`,fe)),te!==l.nil&&de.assign(te,!0),(Te.length||Be.validateSchema)&&(de.elseIf(this.invalid$data()),this.$dataError(),te!==l.nil&&de.assign(te,!1)),de.else()}invalid$data(){let{gen:te,schemaCode:fe,schemaType:de,def:ye,it:Te}=this;return(0,l.or)(Be(),qe());function Be(){if(de.length){if(!(fe instanceof l.Name))throw Error("ajv implementation error");let Ae=Array.isArray(de)?de:[de];return l._`${(0,o.checkDataTypes)(Ae,fe,Te.opts.strictNumbers,o.DataType.Wrong)}`}return l.nil}function qe(){if(ye.validateSchema){let Ae=te.scopeValue("validate$data",{ref:ye.validateSchema});return l._`!${Ae}(${fe})`}return l.nil}}subschema(te,fe){let de=(0,a.getSubschema)(this.it,te);(0,a.extendSubschemaData)(de,this.it,te),(0,a.extendSubschemaMode)(de,te);let ye={...this.it,...de,items:void 0,props:void 0};return _(ye,fe),ye}mergeEvaluated(te,fe){let{it:de,gen:ye}=this;de.opts.unevaluated&&(de.props!==!0&&te.props!==void 0&&(de.props=d.mergeEvaluated.props(ye,te.props,de.props,fe)),de.items!==!0&&te.items!==void 0&&(de.items=d.mergeEvaluated.items(ye,te.items,de.items,fe)))}mergeValidEvaluated(te,fe){let{it:de,gen:ye}=this;if(de.opts.unevaluated&&(de.props!==!0||de.items!==!0))return ye.if(fe,()=>this.mergeEvaluated(te,l.Name)),!0}}t.KeywordCxt=R;function X(Z,te,fe,de){let ye=new R(Z,fe,te);"code"in fe?fe.code(ye,de):ye.$data&&fe.validate?(0,s.funcKeywordCode)(ye,fe):"macro"in fe?(0,s.macroKeywordCode)(ye,fe):(fe.compile||fe.validate)&&(0,s.funcKeywordCode)(ye,fe)}var D=/^\/(?:[^~]|~0|~1)*$/,G=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ce(Z,{dataLevel:te,dataNames:fe,dataPathArr:de}){let ye,Te;if(Z==="")return c.default.rootData;if(Z[0]==="/"){if(!D.test(Z))throw Error(`Invalid JSON-pointer: ${Z}`);ye=Z,Te=c.default.rootData}else{let Xt=G.exec(Z);if(!Xt)throw Error(`Invalid JSON-pointer: ${Z}`);let Ve=+Xt[1];if(ye=Xt[2],ye==="#"){if(Ve>=te)throw Error(Ae("property/index",Ve));return de[te-Ve]}if(Ve>te)throw Error(Ae("data",Ve));if(Te=fe[te-Ve],!ye)return Te}let Be=Te,qe=ye.split("/");for(let Xt of qe)Xt&&(Te=l._`${Te}${(0,l.getProperty)((0,d.unescapeJsonPointer)(Xt))}`,Be=l._`${Be} && ${Te}`);return Be;function Ae(Xt,Ve){return`Cannot access ${Xt} ${Ve} levels up, current level is ${te}`}}t.getData=ce}),iBe=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});class e extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}t.default=e}),ipe=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=rpe();class n extends Error{constructor(o,i,s,a){super(a||`can't resolve reference ${s} from id ${i}`),this.missingRef=(0,e.resolveUrl)(o,i,s),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(o,this.missingRef))}}t.default=n}),sBe=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resolveSchema=t.getCompilingSchema=t.resolveRef=t.compileSchema=t.SchemaEnv=void 0;var e=uo(),n=iBe(),r=JP(),o=rpe(),i=ni(),s=ope();class a{constructor(y){var w;this.refs={},this.dynamicAnchors={};let _;typeof y.schema=="object"&&(_=y.schema),this.schema=y.schema,this.schemaId=y.schemaId,this.root=y.root||this,this.baseId=(w=y.baseId)!==null&&w!==void 0?w:(0,o.normalizeId)(_?.[y.schemaId||"$id"]),this.schemaPath=y.schemaPath,this.localRefs=y.localRefs,this.meta=y.meta,this.$async=_?.$async,this.refs={}}}t.SchemaEnv=a;function l(v){let y=d.call(this,v);if(y)return y;let w=(0,o.getFullPath)(this.opts.uriResolver,v.root.baseId),{es5:_,lines:S}=this.opts.code,{ownProperties:I}=this.opts,C=new e.CodeGen(this.scope,{es5:_,lines:S,ownProperties:I}),k;v.$async&&(k=C.scopeValue("Error",{ref:n.default,code:e._`require("ajv/dist/runtime/validation_error").default`}));let T=C.scopeName("validate");v.validateName=T;let P={gen:C,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[e.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:C.scopeValue("schema",this.opts.code.source===!0?{ref:v.schema,code:(0,e.stringify)(v.schema)}:{ref:v.schema}),validateName:T,ValidationError:k,schema:v.schema,schemaEnv:v,rootId:w,baseId:v.baseId||w,schemaPath:e.nil,errSchemaPath:v.schemaPath||(this.opts.jtd?"":"#"),errorPath:e._`""`,opts:this.opts,self:this},E;try{this._compilations.add(v),(0,s.validateFunctionCode)(P),C.optimize(this.opts.code.optimize);let O=C.toString();E=`${C.scopeRefs(r.default.scope)}return ${O}`,this.opts.code.process&&(E=this.opts.code.process(E,v));let $=Function(`${r.default.self}`,`${r.default.scope}`,E)(this,this.scope.get());if(this.scope.value(T,{ref:$}),$.errors=null,$.schema=v.schema,$.schemaEnv=v,v.$async&&($.$async=!0),this.opts.code.source===!0&&($.source={validateName:T,validateCode:O,scopeValues:C._values}),this.opts.unevaluated){let{props:U,items:V}=P;$.evaluated={props:U instanceof e.Name?void 0:U,items:V instanceof e.Name?void 0:V,dynamicProps:U instanceof e.Name,dynamicItems:V instanceof e.Name},$.source&&($.source.evaluated=(0,e.stringify)($.evaluated))}return v.validate=$,v}catch(O){throw delete v.validate,delete v.validateName,E&&this.logger.error("Error compiling schema, function code:",E),O}finally{this._compilations.delete(v)}}t.compileSchema=l;function c(v,y,w){var _;w=(0,o.resolveUrl)(this.opts.uriResolver,y,w);let S=v.refs[w];if(S)return S;let I=p.call(this,v,w);if(I===void 0){let C=(_=v.localRefs)===null||_===void 0?void 0:_[w],{schemaId:k}=this.opts;C&&(I=new a({schema:C,schemaId:k,root:v,baseId:y}))}if(I!==void 0)return v.refs[w]=u.call(this,I)}t.resolveRef=c;function u(v){return(0,o.inlineRef)(v.schema,this.opts.inlineRefs)?v.schema:v.validate?v:l.call(this,v)}function d(v){for(let y of this._compilations)if(f(y,v))return y}t.getCompilingSchema=d;function f(v,y){return v.schema===y.schema&&v.root===y.root&&v.baseId===y.baseId}function p(v,y){let w;for(;typeof(w=this.refs[y])=="string";)y=w;return w||this.schemas[y]||m.call(this,v,y)}function m(v,y){let w=this.opts.uriResolver.parse(y),_=(0,o._getFullPath)(this.opts.uriResolver,w),S=(0,o.getFullPath)(this.opts.uriResolver,v.baseId,void 0);if(Object.keys(v.schema).length>0&&_===S)return g.call(this,w,v);let I=(0,o.normalizeId)(_),C=this.refs[I]||this.schemas[I];if(typeof C=="string"){let k=m.call(this,v,C);return typeof k?.schema!="object"?void 0:g.call(this,w,k)}if(typeof C?.schema=="object"){if(C.validate||l.call(this,C),I===(0,o.normalizeId)(y)){let{schema:k}=C,{schemaId:T}=this.opts,P=k[T];return P&&(S=(0,o.resolveUrl)(this.opts.uriResolver,S,P)),new a({schema:k,schemaId:T,root:v,baseId:S})}return g.call(this,w,C)}}t.resolveSchema=m;var h=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function g(v,{baseId:y,schema:w,root:_}){var S;if(((S=v.fragment)===null||S===void 0?void 0:S[0])!=="/")return;for(let k of v.fragment.slice(1).split("/")){if(typeof w=="boolean")return;let T=w[(0,i.unescapeFragment)(k)];if(T===void 0)return;w=T;let P=typeof w=="object"&&w[this.opts.schemaId];!h.has(k)&&P&&(y=(0,o.resolveUrl)(this.opts.uriResolver,y,P))}let I;if(typeof w!="boolean"&&w.$ref&&!(0,i.schemaHasRulesButRef)(w,this.RULES)){let k=(0,o.resolveUrl)(this.opts.uriResolver,y,w.$ref);I=m.call(this,_,k)}let{schemaId:C}=this.opts;if(I=I||new a({schema:w,schemaId:C,root:_,baseId:y}),I.schema!==I.root.schema)return I}}),y4n=Le((t,e)=>{e.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}}),xNt=Le((t,e)=>{var n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),o=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),i=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),s=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function a(C){let k="",T=0,P=0;for(P=0;P<C.length;P++)if(T=C[P].charCodeAt(0),T!==48){if(!(T>=48&&T<=57||T>=65&&T<=70||T>=97&&T<=102))return"";k+=C[P];break}for(P+=1;P<C.length;P++){if(T=C[P].charCodeAt(0),!(T>=48&&T<=57||T>=65&&T<=70||T>=97&&T<=102))return"";k+=C[P]}return k}var l=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function c(C){return C.length=0,!0}function u(C,k,T){if(C.length){let P=a(C);if(P!=="")k.push(P);else return T.error=!0,!1;C.length=0}return!0}function d(C){let k=0,T={error:!1,address:"",zone:""},P=[],E=[],O=!1,$=!1,U=u;for(let V=0;V<C.length;V++){let K=C[V];if(!(K==="["||K==="]"))if(K===":"){if(O===!0&&($=!0),!U(E,P,T))break;if(++k>7){T.error=!0;break}V>0&&C[V-1]===":"&&(O=!0),P.push(":");continue}else if(K==="%"){if(!U(E,P,T))break;U=c}else{E.push(K);continue}}return E.length&&(U===c?T.zone=E.join(""):$?P.push(E.join("")):P.push(a(E))),T.address=P.join(""),T}function f(C){if(p(C,":")<2)return{host:C,isIPV6:!1};let k=d(C);if(k.error)return{host:C,isIPV6:!1};{let{address:T,address:P}=k;return k.zone&&(T+="%"+k.zone,P+="%25"+k.zone),{host:T,isIPV6:!0,escapedHost:P}}}function p(C,k){let T=0;for(let P=0;P<C.length;P++)C[P]===k&&T++;return T}function m(C){let k=C,T=[],P=-1,E=0;for(;E=k.length;){if(E===1){if(k===".")break;if(k==="/"){T.push("/");break}else{T.push(k);break}}else if(E===2){if(k[0]==="."){if(k[1]===".")break;if(k[1]==="/"){k=k.slice(2);continue}}else if(k[0]==="/"&&(k[1]==="."||k[1]==="/")){T.push("/");break}}else if(E===3&&k==="/.."){T.length!==0&&T.pop(),T.push("/");break}if(k[0]==="."){if(k[1]==="."){if(k[2]==="/"){k=k.slice(3);continue}}else if(k[1]==="/"){k=k.slice(2);continue}}else if(k[0]==="/"&&k[1]==="."){if(k[2]==="/"){k=k.slice(2);continue}else if(k[2]==="."&&k[3]==="/"){k=k.slice(3),T.length!==0&&T.pop();continue}}if((P=k.indexOf("/",1))===-1){T.push(k);break}else T.push(k.slice(0,P)),k=k.slice(P)}return T.join("")}var h={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},g=/[@/?#:]/g,v=/[@/?#]/g;function y(C,k){let T=k?v:g;return T.lastIndex=0,C.replace(T,P=>h[P])}function w(C,k=!1){if(C.indexOf("%")===-1)return C;let T="";for(let P=0;P<C.length;P++){if(C[P]==="%"&&P+2<C.length){let E=C.slice(P+1,P+3);if(o(E)){let O=E.toUpperCase(),$=String.fromCharCode(parseInt(O,16));k&&i($)?T+=$:T+="%"+O,P+=2;continue}}T+=C[P]}return T}function _(C){let k="";for(let T=0;T<C.length;T++){if(C[T]==="%"&&T+2<C.length){let P=C.slice(T+1,T+3);if(o(P)){let E=P.toUpperCase(),O=String.fromCharCode(parseInt(E,16));O!=="."&&i(O)?k+=O:k+="%"+E,T+=2;continue}}s(C[T])?k+=C[T]:k+=escape(C[T])}return k}function S(C){let k="";for(let T=0;T<C.length;T++){if(C[T]==="%"&&T+2<C.length){let P=C.slice(T+1,T+3);if(o(P)){k+="%"+P.toUpperCase(),T+=2;continue}}k+=escape(C[T])}return k}function I(C){let k=[];if(C.userinfo!==void 0&&(k.push(C.userinfo),k.push("@")),C.host!==void 0){let T=unescape(C.host);if(!r(T)){let P=f(T);P.isIPV6===!0?T=`[${P.escapedHost}]`:T=y(T,!1)}k.push(T)}return(typeof C.port=="number"||typeof C.port=="string")&&(k.push(":"),k.push(String(C.port))),k.length?k.join(""):void 0}e.exports={nonSimpleDomain:l,recomposeAuthority:I,reescapeHostDelimiters:y,normalizePercentEncoding:w,normalizePathEncoding:_,escapePreservingEscapes:S,removeDotSegments:m,isIPv4:r,isUUID:n,normalizeIPv6:f,stringArrayToHexStripped:a}}),v4n=Le((t,e)=>{var{isUUID:n}=xNt(),r=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,o=["http","https","ws","wss","urn","urn:uuid"];function i(C){return o.indexOf(C)!==-1}function s(C){return C.secure===!0?!0:C.secure===!1?!1:C.scheme?C.scheme.length===3&&(C.scheme[0]==="w"||C.scheme[0]==="W")&&(C.scheme[1]==="s"||C.scheme[1]==="S")&&(C.scheme[2]==="s"||C.scheme[2]==="S"):!1}function a(C){return C.host||(C.error=C.error||"HTTP URIs must have a host."),C}function l(C){let k=String(C.scheme).toLowerCase()==="https";return(C.port===(k?443:80)||C.port==="")&&(C.port=void 0),C.path||(C.path="/"),C}function c(C){return C.secure=s(C),C.resourceName=(C.path||"/")+(C.query?"?"+C.query:""),C.path=void 0,C.query=void 0,C}function u(C){if((C.port===(s(C)?443:80)||C.port==="")&&(C.port=void 0),typeof C.secure=="boolean"&&(C.scheme=C.secure?"wss":"ws",C.secure=void 0),C.resourceName){let[k,T]=C.resourceName.split("?");C.path=k&&k!=="/"?k:void 0,C.query=T,C.resourceName=void 0}return C.fragment=void 0,C}function d(C,k){if(!C.path)return C.error="URN can not be parsed",C;let T=C.path.match(r);if(T){let P=k.scheme||C.scheme||"urn";C.nid=T[1].toLowerCase(),C.nss=T[2];let E=`${P}:${k.nid||C.nid}`,O=I(E);C.path=void 0,O&&(C=O.parse(C,k))}else C.error=C.error||"URN can not be parsed.";return C}function f(C,k){if(C.nid===void 0)throw Error("URN without nid cannot be serialized");let T=k.scheme||C.scheme||"urn",P=C.nid.toLowerCase(),E=`${T}:${k.nid||P}`,O=I(E);O&&(C=O.serialize(C,k));let $=C,U=C.nss;return $.path=`${P||k.nid}:${U}`,k.skipEscape=!0,$}function p(C,k){let T=C;return T.uuid=T.nss,T.nss=void 0,!k.tolerant&&(!T.uuid||!n(T.uuid))&&(T.error=T.error||"UUID is not valid."),T}function m(C){let k=C;return k.nss=(C.uuid||"").toLowerCase(),k}var h={scheme:"http",domainHost:!0,parse:a,serialize:l},g={scheme:"https",domainHost:h.domainHost,parse:a,serialize:l},v={scheme:"ws",domainHost:!0,parse:c,serialize:u},y={scheme:"wss",domainHost:v.domainHost,parse:v.parse,serialize:v.serialize},w={scheme:"urn",parse:d,serialize:f,skipNormalize:!0},_={scheme:"urn:uuid",parse:p,serialize:m,skipNormalize:!0},S={http:h,https:g,ws:v,wss:y,urn:w,"urn:uuid":_};Object.setPrototypeOf(S,null);function I(C){return C&&(S[C]||S[C.toLowerCase()])||void 0}e.exports={wsIsSecure:s,SCHEMES:S,isValidSchemeName:i,getSchemeHandler:I}}),w4n=Le((t,e)=>{var{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:o,normalizePercentEncoding:i,normalizePathEncoding:s,escapePreservingEscapes:a,reescapeHostDelimiters:l,isIPv4:c,nonSimpleDomain:u}=xNt(),{SCHEMES:d,getSchemeHandler:f}=v4n();function p(P,E){return typeof P=="string"?P=I(P,E):typeof P=="object"&&(P=S(v(P,E),E)),P}function m(P,E,O){let $=O?Object.assign({scheme:"null"},O):{scheme:"null"},U=h(S(P,$),S(E,$),$,!0);return $.skipEscape=!0,v(U,$)}function h(P,E,O,$){let U={};return $||(P=S(v(P,O),O),E=S(v(E,O),O)),O=O||{},!O.tolerant&&E.scheme?(U.scheme=E.scheme,U.userinfo=E.userinfo,U.host=E.host,U.port=E.port,U.path=r(E.path||""),U.query=E.query):(E.userinfo!==void 0||E.host!==void 0||E.port!==void 0?(U.userinfo=E.userinfo,U.host=E.host,U.port=E.port,U.path=r(E.path||""),U.query=E.query):(E.path?(E.path[0]==="/"?U.path=r(E.path):((P.userinfo!==void 0||P.host!==void 0||P.port!==void 0)&&!P.path?U.path="/"+E.path:P.path?U.path=P.path.slice(0,P.path.lastIndexOf("/")+1)+E.path:U.path=E.path,U.path=r(U.path)),U.query=E.query):(U.path=P.path,E.query!==void 0?U.query=E.query:U.query=P.query),U.userinfo=P.userinfo,U.host=P.host,U.port=P.port),U.scheme=P.scheme),U.fragment=E.fragment,U}function g(P,E,O){let $=k(P,O),U=k(E,O);return $!==void 0&&U!==void 0&&$.toLowerCase()===U.toLowerCase()}function v(P,E){let O={host:P.host,scheme:P.scheme,userinfo:P.userinfo,port:P.port,path:P.path,query:P.query,nid:P.nid,nss:P.nss,uuid:P.uuid,fragment:P.fragment,reference:P.reference,resourceName:P.resourceName,secure:P.secure,error:""},$=Object.assign({},E),U=[],V=f($.scheme||O.scheme);V&&V.serialize&&V.serialize(O,$),O.path!==void 0&&($.skipEscape?O.path=i(O.path):(O.path=a(O.path),O.scheme!==void 0&&(O.path=O.path.split("%3A").join(":")))),$.reference!=="suffix"&&O.scheme&&U.push(O.scheme,":");let K=o(O);if(K!==void 0&&($.reference!=="suffix"&&U.push("//"),U.push(K),O.path&&O.path[0]!=="/"&&U.push("/")),O.path!==void 0){let se=O.path;!$.absolutePath&&(!V||!V.absolutePath)&&(se=r(se)),K===void 0&&se[0]==="/"&&se[1]==="/"&&(se="/%2F"+se.slice(2)),U.push(se)}return O.query!==void 0&&U.push("?",O.query),O.fragment!==void 0&&U.push("#",O.fragment),U.join("")}var y=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function w(P,E){if(E[2]!==void 0&&P.path&&P.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof P.port=="number"&&(P.port<0||P.port>65535))return"URI port is malformed."}function _(P,E){let O=Object.assign({},E),$={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},U=!1,V=!1;O.reference==="suffix"&&(O.scheme?P=O.scheme+":"+P:P="//"+P);let K=P.match(y);if(K){$.scheme=K[1],$.userinfo=K[3],$.host=K[4],$.port=parseInt(K[5],10),$.path=K[6]||"",$.query=K[7],$.fragment=K[8],isNaN($.port)&&($.port=K[5]);let se=w($,K);if(se!==void 0&&($.error=$.error||se,U=!0),$.host)if(c($.host)===!1){let Q=n($.host);$.host=Q.host.toLowerCase(),V=Q.isIPV6}else V=!0;$.scheme===void 0&&$.userinfo===void 0&&$.host===void 0&&$.port===void 0&&$.query===void 0&&!$.path?$.reference="same-document":$.scheme===void 0?$.reference="relative":$.fragment===void 0?$.reference="absolute":$.reference="uri",O.reference&&O.reference!=="suffix"&&O.reference!==$.reference&&($.error=$.error||"URI is not a "+O.reference+" reference.");let le=f(O.scheme||$.scheme);if(!O.unicodeSupport&&(!le||!le.unicodeSupport)&&$.host&&(O.domainHost||le&&le.domainHost)&&V===!1&&u($.host))try{$.host=URL.domainToASCII($.host.toLowerCase())}catch(Q){$.error=$.error||"Host's domain name can not be converted to ASCII: "+Q}if((!le||le&&!le.skipNormalize)&&(P.indexOf("%")!==-1&&($.scheme!==void 0&&($.scheme=unescape($.scheme)),$.host!==void 0&&($.host=l(unescape($.host),V))),$.path&&($.path=s($.path)),$.fragment))try{$.fragment=encodeURI(decodeURIComponent($.fragment))}catch{$.error=$.error||"URI malformed"}le&&le.parse&&le.parse($,O)}else $.error=$.error||"URI can not be parsed.";return{parsed:$,malformedAuthorityOrPort:U}}function S(P,E){return _(P,E).parsed}function I(P,E){return C(P,E).normalized}function C(P,E){let{parsed:O,malformedAuthorityOrPort:$}=_(P,E);return{normalized:$?P:v(O,E),malformedAuthorityOrPort:$}}function k(P,E){if(typeof P=="string"){let{normalized:O,malformedAuthorityOrPort:$}=C(P,E);return $?void 0:O}if(typeof P=="object")return v(P,E)}var T={SCHEMES:d,normalize:p,resolve:m,resolveComponent:h,equal:g,serialize:v,parse:S};e.exports=T,e.exports.default=T,e.exports.fastUri=T}),b4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=w4n();e.code='require("ajv/dist/runtime/uri").default',t.default=e}),_4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var e=ope();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var n=uo();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});var r=iBe(),o=ipe(),i=wNt(),s=sBe(),a=uo(),l=rpe(),c=Zde(),u=ni(),d=y4n(),f=b4n(),p=(ne,ee)=>new RegExp(ne,ee);p.code="new RegExp";var m=["removeAdditional","useDefaults","coerceTypes"],h=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),g={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},v={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},y=200;function w(ne){var ee,ae,q,F,z,N,R,X,D,G,ce,Z,te,fe,de,ye,Te,Be,qe,Ae,Xt,Ve,Ee,st,Ne;let He=ne.strict,et=(ee=ne.code)===null||ee===void 0?void 0:ee.optimize,it=et===!0||et===void 0?1:et||0,Br=(q=(ae=ne.code)===null||ae===void 0?void 0:ae.regExp)!==null&&q!==void 0?q:p,Xr=(F=ne.uriResolver)!==null&&F!==void 0?F:f.default;return{strictSchema:(N=(z=ne.strictSchema)!==null&&z!==void 0?z:He)!==null&&N!==void 0?N:!0,strictNumbers:(X=(R=ne.strictNumbers)!==null&&R!==void 0?R:He)!==null&&X!==void 0?X:!0,strictTypes:(G=(D=ne.strictTypes)!==null&&D!==void 0?D:He)!==null&&G!==void 0?G:"log",strictTuples:(Z=(ce=ne.strictTuples)!==null&&ce!==void 0?ce:He)!==null&&Z!==void 0?Z:"log",strictRequired:(fe=(te=ne.strictRequired)!==null&&te!==void 0?te:He)!==null&&fe!==void 0?fe:!1,code:ne.code?{...ne.code,optimize:it,regExp:Br}:{optimize:it,regExp:Br},loopRequired:(de=ne.loopRequired)!==null&&de!==void 0?de:y,loopEnum:(ye=ne.loopEnum)!==null&&ye!==void 0?ye:y,meta:(Te=ne.meta)!==null&&Te!==void 0?Te:!0,messages:(Be=ne.messages)!==null&&Be!==void 0?Be:!0,inlineRefs:(qe=ne.inlineRefs)!==null&&qe!==void 0?qe:!0,schemaId:(Ae=ne.schemaId)!==null&&Ae!==void 0?Ae:"$id",addUsedSchema:(Xt=ne.addUsedSchema)!==null&&Xt!==void 0?Xt:!0,validateSchema:(Ve=ne.validateSchema)!==null&&Ve!==void 0?Ve:!0,validateFormats:(Ee=ne.validateFormats)!==null&&Ee!==void 0?Ee:!0,unicodeRegExp:(st=ne.unicodeRegExp)!==null&&st!==void 0?st:!0,int32range:(Ne=ne.int32range)!==null&&Ne!==void 0?Ne:!0,uriResolver:Xr}}class _{constructor(ee={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,ee=this.opts={...ee,...w(ee)};let{es5:ae,lines:q}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:h,es5:ae,lines:q}),this.logger=O(ee.logger);let F=ee.validateFormats;ee.validateFormats=!1,this.RULES=(0,i.getRules)(),S.call(this,g,ee,"NOT SUPPORTED"),S.call(this,v,ee,"DEPRECATED","warn"),this._metaOpts=P.call(this),ee.formats&&k.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),ee.keywords&&T.call(this,ee.keywords),typeof ee.meta=="object"&&this.addMetaSchema(ee.meta),C.call(this),ee.validateFormats=F}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:ee,meta:ae,schemaId:q}=this.opts,F=d;q==="id"&&(F={...d},F.id=F.$id,delete F.$id),ae&&ee&&this.addMetaSchema(F,F[q],!1)}defaultMeta(){let{meta:ee,schemaId:ae}=this.opts;return this.opts.defaultMeta=typeof ee=="object"?ee[ae]||ee:void 0}validate(ee,ae){let q;if(typeof ee=="string"){if(q=this.getSchema(ee),!q)throw Error(`no schema with key or ref "${ee}"`)}else q=this.compile(ee);let F=q(ae);return"$async"in q||(this.errors=q.errors),F}compile(ee,ae){let q=this._addSchema(ee,ae);return q.validate||this._compileSchemaEnv(q)}compileAsync(ee,ae){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:q}=this.opts;return F.call(this,ee,ae);async function F(G,ce){await z.call(this,G.$schema);let Z=this._addSchema(G,ce);return Z.validate||N.call(this,Z)}async function z(G){G&&!this.getSchema(G)&&await F.call(this,{$ref:G},!0)}async function N(G){try{return this._compileSchemaEnv(G)}catch(ce){if(!(ce instanceof o.default))throw ce;return R.call(this,ce),await X.call(this,ce.missingSchema),N.call(this,G)}}function R({missingSchema:G,missingRef:ce}){if(this.refs[G])throw Error(`AnySchema ${G} is loaded but ${ce} cannot be resolved`)}async function X(G){let ce=await D.call(this,G);this.refs[G]||await z.call(this,ce.$schema),this.refs[G]||this.addSchema(ce,G,ae)}async function D(G){let ce=this._loading[G];if(ce)return ce;try{return await(this._loading[G]=q(G))}finally{delete this._loading[G]}}}addSchema(ee,ae,q,F=this.opts.validateSchema){if(Array.isArray(ee)){for(let N of ee)this.addSchema(N,void 0,q,F);return this}let z;if(typeof ee=="object"){let{schemaId:N}=this.opts;if(z=ee[N],z!==void 0&&typeof z!="string")throw Error(`schema ${N} must be string`)}return ae=(0,l.normalizeId)(ae||z),this._checkUnique(ae),this.schemas[ae]=this._addSchema(ee,q,ae,F,!0),this}addMetaSchema(ee,ae,q=this.opts.validateSchema){return this.addSchema(ee,ae,!0,q),this}validateSchema(ee,ae){if(typeof ee=="boolean")return!0;let q;if(q=ee.$schema,q!==void 0&&typeof q!="string")throw Error("$schema must be a string");if(q=q||this.opts.defaultMeta||this.defaultMeta(),!q)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let F=this.validate(q,ee);if(!F&&ae){let z="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(z);else throw Error(z)}return F}getSchema(ee){let ae;for(;typeof(ae=I.call(this,ee))=="string";)ee=ae;if(ae===void 0){let{schemaId:q}=this.opts,F=new s.SchemaEnv({schema:{},schemaId:q});if(ae=s.resolveSchema.call(this,F,ee),!ae)return;this.refs[ee]=ae}return ae.validate||this._compileSchemaEnv(ae)}removeSchema(ee){if(ee instanceof RegExp)return this._removeAllSchemas(this.schemas,ee),this._removeAllSchemas(this.refs,ee),this;switch(typeof ee){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let ae=I.call(this,ee);return typeof ae=="object"&&this._cache.delete(ae.schema),delete this.schemas[ee],delete this.refs[ee],this}case"object":{let ae=ee;this._cache.delete(ae);let q=ee[this.opts.schemaId];return q&&(q=(0,l.normalizeId)(q),delete this.schemas[q],delete this.refs[q]),this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(ee){for(let ae of ee)this.addKeyword(ae);return this}addKeyword(ee,ae){let q;if(typeof ee=="string")q=ee,typeof ae=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),ae.keyword=q);else if(typeof ee=="object"&&ae===void 0){if(ae=ee,q=ae.keyword,Array.isArray(q)&&!q.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(U.call(this,q,ae),!ae)return(0,u.eachItem)(q,z=>V.call(this,z)),this;se.call(this,ae);let F={...ae,type:(0,c.getJSONTypes)(ae.type),schemaType:(0,c.getJSONTypes)(ae.schemaType)};return(0,u.eachItem)(q,F.type.length===0?z=>V.call(this,z,F):z=>F.type.forEach(N=>V.call(this,z,F,N))),this}getKeyword(ee){let ae=this.RULES.all[ee];return typeof ae=="object"?ae.definition:!!ae}removeKeyword(ee){let{RULES:ae}=this;delete ae.keywords[ee],delete ae.all[ee];for(let q of ae.rules){let F=q.rules.findIndex(z=>z.keyword===ee);F>=0&&q.rules.splice(F,1)}return this}addFormat(ee,ae){return typeof ae=="string"&&(ae=new RegExp(ae)),this.formats[ee]=ae,this}errorsText(ee=this.errors,{separator:ae=", ",dataVar:q="data"}={}){return!ee||ee.length===0?"No errors":ee.map(F=>`${q}${F.instancePath} ${F.message}`).reduce((F,z)=>F+ae+z)}$dataMetaSchema(ee,ae){let q=this.RULES.all;ee=JSON.parse(JSON.stringify(ee));for(let F of ae){let z=F.split("/").slice(1),N=ee;for(let R of z)N=N[R];for(let R in q){let X=q[R];if(typeof X!="object")continue;let{$data:D}=X.definition,G=N[R];D&&G&&(N[R]=Q(G))}}return ee}_removeAllSchemas(ee,ae){for(let q in ee){let F=ee[q];(!ae||ae.test(q))&&(typeof F=="string"?delete ee[q]:F&&!F.meta&&(this._cache.delete(F.schema),delete ee[q]))}}_addSchema(ee,ae,q,F=this.opts.validateSchema,z=this.opts.addUsedSchema){let N,{schemaId:R}=this.opts;if(typeof ee=="object")N=ee[R];else{if(this.opts.jtd)throw Error("schema must be object");if(typeof ee!="boolean")throw Error("schema must be object or boolean")}let X=this._cache.get(ee);if(X!==void 0)return X;q=(0,l.normalizeId)(N||q);let D=l.getSchemaRefs.call(this,ee,q);return X=new s.SchemaEnv({schema:ee,schemaId:R,meta:ae,baseId:q,localRefs:D}),this._cache.set(X.schema,X),z&&!q.startsWith("#")&&(q&&this._checkUnique(q),this.refs[q]=X),F&&this.validateSchema(ee,!0),X}_checkUnique(ee){if(this.schemas[ee]||this.refs[ee])throw Error(`schema with key or id "${ee}" already exists`)}_compileSchemaEnv(ee){if(ee.meta?this._compileMetaSchema(ee):s.compileSchema.call(this,ee),!ee.validate)throw Error("ajv implementation error");return ee.validate}_compileMetaSchema(ee){let ae=this.opts;this.opts=this._metaOpts;try{s.compileSchema.call(this,ee)}finally{this.opts=ae}}}_.ValidationError=r.default,_.MissingRefError=o.default,t.default=_;function S(ne,ee,ae,q="error"){for(let F in ne){let z=F;z in ee&&this.logger[q](`${ae}: option ${F}. ${ne[z]}`)}}function I(ne){return ne=(0,l.normalizeId)(ne),this.schemas[ne]||this.refs[ne]}function C(){let ne=this.opts.schemas;if(ne)if(Array.isArray(ne))this.addSchema(ne);else for(let ee in ne)this.addSchema(ne[ee],ee)}function k(){for(let ne in this.opts.formats){let ee=this.opts.formats[ne];ee&&this.addFormat(ne,ee)}}function T(ne){if(Array.isArray(ne)){this.addVocabulary(ne);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let ee in ne){let ae=ne[ee];ae.keyword||(ae.keyword=ee),this.addKeyword(ae)}}function P(){let ne={...this.opts};for(let ee of m)delete ne[ee];return ne}var E={log(){},warn(){},error(){}};function O(ne){if(ne===!1)return E;if(ne===void 0)return console;if(ne.log&&ne.warn&&ne.error)return ne;throw Error("logger must implement log, warn and error methods")}var $=/^[a-z_$][a-z0-9_$:-]*$/i;function U(ne,ee){let{RULES:ae}=this;if((0,u.eachItem)(ne,q=>{if(ae.keywords[q])throw Error(`Keyword ${q} is already defined`);if(!$.test(q))throw Error(`Keyword ${q} has invalid name`)}),!!ee&&ee.$data&&!("code"in ee||"validate"in ee))throw Error('$data keyword must have "code" or "validate" function')}function V(ne,ee,ae){var q;let F=ee?.post;if(ae&&F)throw Error('keyword with "post" flag cannot have "type"');let{RULES:z}=this,N=F?z.post:z.rules.find(({type:X})=>X===ae);if(N||(N={type:ae,rules:[]},z.rules.push(N)),z.keywords[ne]=!0,!ee)return;let R={keyword:ne,definition:{...ee,type:(0,c.getJSONTypes)(ee.type),schemaType:(0,c.getJSONTypes)(ee.schemaType)}};ee.before?K.call(this,N,R,ee.before):N.rules.push(R),z.all[ne]=R,(q=ee.implements)===null||q===void 0||q.forEach(X=>this.addKeyword(X))}function K(ne,ee,ae){let q=ne.rules.findIndex(F=>F.keyword===ae);q>=0?ne.rules.splice(q,0,ee):(ne.rules.push(ee),this.logger.warn(`rule ${ae} is not defined`))}function se(ne){let{metaSchema:ee}=ne;ee!==void 0&&(ne.$data&&this.opts.$data&&(ee=Q(ee)),ne.validateSchema=this.compile(ee,!0))}var le={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Q(ne){return{anyOf:[ne,le]}}}),x4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};t.default=e}),S4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.callRef=t.getValidate=void 0;var e=ipe(),n=ab(),r=uo(),o=JP(),i=sBe(),s=ni(),a={keyword:"$ref",schemaType:"string",code(u){let{gen:d,schema:f,it:p}=u,{baseId:m,schemaEnv:h,validateName:g,opts:v,self:y}=p,{root:w}=h;if((f==="#"||f==="#/")&&m===w.baseId)return S();let _=i.resolveRef.call(y,w,m,f);if(_===void 0)throw new e.default(p.opts.uriResolver,m,f);if(_ instanceof i.SchemaEnv)return I(_);return C(_);function S(){if(h===w)return c(u,g,h,h.$async);let k=d.scopeValue("root",{ref:w});return c(u,r._`${k}.validate`,w,w.$async)}function I(k){let T=l(u,k);c(u,T,k,k.$async)}function C(k){let T=d.scopeValue("schema",v.code.source===!0?{ref:k,code:(0,r.stringify)(k)}:{ref:k}),P=d.name("valid"),E=u.subschema({schema:k,dataTypes:[],schemaPath:r.nil,topSchemaRef:T,errSchemaPath:f},P);u.mergeEvaluated(E),u.ok(P)}}};function l(u,d){let{gen:f}=u;return d.validate?f.scopeValue("validate",{ref:d.validate}):r._`${f.scopeValue("wrapper",{ref:d})}.validate`}t.getValidate=l;function c(u,d,f,p){let{gen:m,it:h}=u,{allErrors:g,schemaEnv:v,opts:y}=h,w=y.passContext?o.default.this:r.nil;p?_():S();function _(){if(!v.$async)throw Error("async schema referenced by sync schema");let k=m.let("valid");m.try(()=>{m.code(r._`await ${(0,n.callValidateCode)(u,d,w)}`),C(d),!g&&m.assign(k,!0)},T=>{m.if(r._`!(${T} instanceof ${h.ValidationError})`,()=>m.throw(T)),I(T),!g&&m.assign(k,!1)}),u.ok(k)}function S(){u.result((0,n.callValidateCode)(u,d,w),()=>C(d),()=>I(d))}function I(k){let T=r._`${k}.errors`;m.assign(o.default.vErrors,r._`${o.default.vErrors} === null ? ${T} : ${o.default.vErrors}.concat(${T})`),m.assign(o.default.errors,r._`${o.default.vErrors}.length`)}function C(k){var T;if(!h.opts.unevaluated)return;let P=(T=f?.validate)===null||T===void 0?void 0:T.evaluated;if(h.props!==!0)if(P&&!P.dynamicProps)P.props!==void 0&&(h.props=s.mergeEvaluated.props(m,P.props,h.props));else{let E=m.var("props",r._`${k}.evaluated.props`);h.props=s.mergeEvaluated.props(m,E,h.props,r.Name)}if(h.items!==!0)if(P&&!P.dynamicItems)P.items!==void 0&&(h.items=s.mergeEvaluated.items(m,P.items,h.items));else{let E=m.var("items",r._`${k}.evaluated.items`);h.items=s.mergeEvaluated.items(m,E,h.items,r.Name)}}}t.callRef=c,t.default=a}),C4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=x4n(),n=S4n(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,n.default];t.default=r}),k4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=uo(),n=e.operators,r={maximum:{okStr:"<=",ok:n.LTE,fail:n.GT},minimum:{okStr:">=",ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},o={message:({keyword:s,schemaCode:a})=>e.str`must be ${r[s].okStr} ${a}`,params:({keyword:s,schemaCode:a})=>e._`{comparison: ${r[s].okStr}, limit: ${a}}`},i={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:o,code(s){let{keyword:a,data:l,schemaCode:c}=s;s.fail$data(e._`${l} ${r[a].fail} ${c} || isNaN(${l})`)}};t.default=i}),I4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=uo(),n={message:({schemaCode:o})=>e.str`must be multiple of ${o}`,params:({schemaCode:o})=>e._`{multipleOf: ${o}}`},r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:n,code(o){let{gen:i,data:s,schemaCode:a,it:l}=o,c=l.opts.multipleOfPrecision,u=i.let("res"),d=c?e._`Math.abs(Math.round(${u}) - ${u}) > 1e-${c}`:e._`${u} !== parseInt(${u})`;o.fail$data(e._`(${a} === 0 || (${u} = ${s}/${a}, ${d}))`)}};t.default=r}),T4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});function e(n){let r=n.length,o=0,i=0,s;for(;i<r;)o++,s=n.charCodeAt(i++),s>=55296&&s<=56319&&i<r&&(s=n.charCodeAt(i),(s&64512)===56320&&i++);return o}t.default=e,e.code='require("ajv/dist/runtime/ucs2length").default'}),P4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=uo(),n=ni(),r=T4n(),o={message({keyword:s,schemaCode:a}){let l=s==="maxLength"?"more":"fewer";return e.str`must NOT have ${l} than ${a} characters`},params:({schemaCode:s})=>e._`{limit: ${s}}`},i={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:o,code(s){let{keyword:a,data:l,schemaCode:c,it:u}=s,d=a==="maxLength"?e.operators.GT:e.operators.LT,f=u.opts.unicode===!1?e._`${l}.length`:e._`${(0,n.useFunc)(s.gen,r.default)}(${l})`;s.fail$data(e._`${f} ${d} ${c}`)}};t.default=i}),A4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ab(),n=ni(),r=uo(),o={message:({schemaCode:s})=>r.str`must match pattern "${s}"`,params:({schemaCode:s})=>r._`{pattern: ${s}}`},i={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:o,code(s){let{gen:a,data:l,$data:c,schema:u,schemaCode:d,it:f}=s,p=f.opts.unicodeRegExp?"u":"";if(c){let{regExp:m}=f.opts.code,h=m.code==="new RegExp"?r._`new RegExp`:(0,n.useFunc)(a,m),g=a.let("valid");a.try(()=>a.assign(g,r._`${h}(${d}, ${p}).test(${l})`),()=>a.assign(g,!1)),s.fail$data(r._`!${g}`)}else{let m=(0,e.usePattern)(s,u);s.fail$data(r._`!${m}.test(${l})`)}}};t.default=i}),E4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=uo(),n={message({keyword:o,schemaCode:i}){let s=o==="maxProperties"?"more":"fewer";return e.str`must NOT have ${s} than ${i} properties`},params:({schemaCode:o})=>e._`{limit: ${o}}`},r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:n,code(o){let{keyword:i,data:s,schemaCode:a}=o,l=i==="maxProperties"?e.operators.GT:e.operators.LT;o.fail$data(e._`Object.keys(${s}).length ${l} ${a}`)}};t.default=r}),M4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ab(),n=uo(),r=ni(),o={message:({params:{missingProperty:s}})=>n.str`must have required property '${s}'`,params:({params:{missingProperty:s}})=>n._`{missingProperty: ${s}}`},i={keyword:"required",type:"object",schemaType:"array",$data:!0,error:o,code(s){let{gen:a,schema:l,schemaCode:c,data:u,$data:d,it:f}=s,{opts:p}=f;if(!d&&l.length===0)return;let m=l.length>=p.loopRequired;if(f.allErrors?h():g(),p.strictRequired){let w=s.parentSchema.properties,{definedProperties:_}=s.it;for(let S of l)if(w?.[S]===void 0&&!_.has(S)){let I=f.schemaEnv.baseId+f.errSchemaPath,C=`required property "${S}" is not defined at "${I}" (strictRequired)`;(0,r.checkStrictMode)(f,C,f.opts.strictRequired)}}function h(){if(m||d)s.block$data(n.nil,v);else for(let w of l)(0,e.checkReportMissingProp)(s,w)}function g(){let w=a.let("missing");if(m||d){let _=a.let("valid",!0);s.block$data(_,()=>y(w,_)),s.ok(_)}else a.if((0,e.checkMissingProp)(s,l,w)),(0,e.reportMissingProp)(s,w),a.else()}function v(){a.forOf("prop",c,w=>{s.setParams({missingProperty:w}),a.if((0,e.noPropertyInData)(a,u,w,p.ownProperties),()=>s.error())})}function y(w,_){s.setParams({missingProperty:w}),a.forOf(w,c,()=>{a.assign(_,(0,e.propertyInData)(a,u,w,p.ownProperties)),a.if((0,n.not)(_),()=>{s.error(),a.break()})},n.nil)}}};t.default=i}),O4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=uo(),n={message({keyword:o,schemaCode:i}){let s=o==="maxItems"?"more":"fewer";return e.str`must NOT have ${s} than ${i} items`},params:({schemaCode:o})=>e._`{limit: ${o}}`},r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:n,code(o){let{keyword:i,data:s,schemaCode:a}=o,l=i==="maxItems"?e.operators.GT:e.operators.LT;o.fail$data(e._`${s}.length ${l} ${a}`)}};t.default=r}),aBe=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=_Nt();e.code='require("ajv/dist/runtime/equal").default',t.default=e}),N4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Zde(),n=uo(),r=ni(),o=aBe(),i={message:({params:{i:a,j:l}})=>n.str`must NOT have duplicate items (items ## ${l} and ${a} are identical)`,params:({params:{i:a,j:l}})=>n._`{i: ${a}, j: ${l}}`},s={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:i,code(a){let{gen:l,data:c,$data:u,schema:d,parentSchema:f,schemaCode:p,it:m}=a;if(!u&&!d)return;let h=l.let("valid"),g=f.items?(0,e.getSchemaTypes)(f.items):[];a.block$data(h,v,n._`${p} === false`),a.ok(h);function v(){let S=l.let("i",n._`${c}.length`),I=l.let("j");a.setParams({i:S,j:I}),l.assign(h,!0),l.if(n._`${S} > 1`,()=>(y()?w:_)(S,I))}function y(){return g.length>0&&!g.some(S=>S==="object"||S==="array")}function w(S,I){let C=l.name("item"),k=(0,e.checkDataTypes)(g,C,m.opts.strictNumbers,e.DataType.Wrong),T=l.const("indices",n._`{}`);l.for(n._`;${S}--;`,()=>{l.let(C,n._`${c}[${S}]`),l.if(k,n._`continue`),g.length>1&&l.if(n._`typeof ${C} == "string"`,n._`${C} += "_"`),l.if(n._`typeof ${T}[${C}] == "number"`,()=>{l.assign(I,n._`${T}[${C}]`),a.error(),l.assign(h,!1).break()}).code(n._`${T}[${C}] = ${S}`)})}function _(S,I){let C=(0,r.useFunc)(l,o.default),k=l.name("outer");l.label(k).for(n._`;${S}--;`,()=>l.for(n._`${I} = ${S}; ${I}--;`,()=>l.if(n._`${C}(${c}[${S}], ${c}[${I}])`,()=>{a.error(),l.assign(h,!1).break(k)})))}}};t.default=s}),R4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=uo(),n=ni(),r=aBe(),o={message:"must be equal to constant",params:({schemaCode:s})=>e._`{allowedValue: ${s}}`},i={keyword:"const",$data:!0,error:o,code(s){let{gen:a,data:l,$data:c,schemaCode:u,schema:d}=s;c||d&&typeof d=="object"?s.fail$data(e._`!${(0,n.useFunc)(a,r.default)}(${l}, ${u})`):s.fail(e._`${d} !== ${l}`)}};t.default=i}),L4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=uo(),n=ni(),r=aBe(),o={message:"must be equal to one of the allowed values",params:({schemaCode:s})=>e._`{allowedValues: ${s}}`},i={keyword:"enum",schemaType:"array",$data:!0,error:o,code(s){let{gen:a,data:l,$data:c,schema:u,schemaCode:d,it:f}=s;if(!c&&u.length===0)throw Error("enum must have non-empty array");let p=u.length>=f.opts.loopEnum,m,h=()=>m??(m=(0,n.useFunc)(a,r.default)),g;if(p||c)g=a.let("valid"),s.block$data(g,v);else{if(!Array.isArray(u))throw Error("ajv implementation error");let w=a.const("vSchema",d);g=(0,e.or)(...u.map((_,S)=>y(w,S)))}s.pass(g);function v(){a.assign(g,!1),a.forOf("v",d,w=>a.if(e._`${h()}(${l}, ${w})`,()=>a.assign(g,!0).break()))}function y(w,_){let S=u[_];return typeof S=="object"&&S!==null?e._`${h()}(${l}, ${w}[${_}])`:e._`${l} === ${S}`}}};t.default=i}),$4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=k4n(),n=I4n(),r=P4n(),o=A4n(),i=E4n(),s=M4n(),a=O4n(),l=N4n(),c=R4n(),u=L4n(),d=[e.default,n.default,r.default,o.default,i.default,s.default,a.default,l.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},c.default,u.default];t.default=d}),SNt=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateAdditionalItems=void 0;var e=uo(),n=ni(),r={message:({params:{len:s}})=>e.str`must NOT have more than ${s} items`,params:({params:{len:s}})=>e._`{limit: ${s}}`},o={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:r,code(s){let{parentSchema:a,it:l}=s,{items:c}=a;if(!Array.isArray(c)){(0,n.checkStrictMode)(l,'"additionalItems" is ignored when "items" is not an array of schemas');return}i(s,c)}};function i(s,a){let{gen:l,schema:c,data:u,keyword:d,it:f}=s;f.items=!0;let p=l.const("len",e._`${u}.length`);if(c===!1)s.setParams({len:a.length}),s.pass(e._`${p} <= ${a.length}`);else if(typeof c=="object"&&!(0,n.alwaysValidSchema)(f,c)){let h=l.var("valid",e._`${p} <= ${a.length}`);l.if((0,e.not)(h),()=>m(h)),s.ok(h)}function m(h){l.forRange("i",a.length,p,g=>{s.subschema({keyword:d,dataProp:g,dataPropType:n.Type.Num},h),!f.allErrors&&l.if((0,e.not)(h),()=>l.break())})}}t.validateAdditionalItems=i,t.default=o}),CNt=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateTuple=void 0;var e=uo(),n=ni(),r=ab(),o={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(s){let{schema:a,it:l}=s;if(Array.isArray(a))return i(s,"additionalItems",a);l.items=!0,!(0,n.alwaysValidSchema)(l,a)&&s.ok((0,r.validateArray)(s))}};function i(s,a,l=s.schema){let{gen:c,parentSchema:u,data:d,keyword:f,it:p}=s;g(u),p.opts.unevaluated&&l.length&&p.items!==!0&&(p.items=n.mergeEvaluated.items(c,l.length,p.items));let m=c.name("valid"),h=c.const("len",e._`${d}.length`);l.forEach((v,y)=>{(0,n.alwaysValidSchema)(p,v)||(c.if(e._`${h} > ${y}`,()=>s.subschema({keyword:f,schemaProp:y,dataProp:y},m)),s.ok(m))});function g(v){let{opts:y,errSchemaPath:w}=p,_=l.length,S=_===v.minItems&&(_===v.maxItems||v[a]===!1);if(y.strictTuples&&!S){let I=`"${f}" is ${_}-tuple, but minItems or maxItems/${a} are not specified or different at path "${w}"`;(0,n.checkStrictMode)(p,I,y.strictTuples)}}}t.validateTuple=i,t.default=o}),D4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=CNt(),n={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};t.default=n}),F4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=uo(),n=ni(),r=ab(),o=SNt(),i={message:({params:{len:a}})=>e.str`must NOT have more than ${a} items`,params:({params:{len:a}})=>e._`{limit: ${a}}`},s={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:i,code(a){let{schema:l,parentSchema:c,it:u}=a,{prefixItems:d}=c;u.items=!0,!(0,n.alwaysValidSchema)(u,l)&&(d?(0,o.validateAdditionalItems)(a,d):a.ok((0,r.validateArray)(a)))}};t.default=s}),U4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=uo(),n=ni(),r={message:({params:{min:i,max:s}})=>s===void 0?e.str`must contain at least ${i} valid item(s)`:e.str`must contain at least ${i} and no more than ${s} valid item(s)`,params:({params:{min:i,max:s}})=>s===void 0?e._`{minContains: ${i}}`:e._`{minContains: ${i}, maxContains: ${s}}`},o={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:r,code(i){let{gen:s,schema:a,parentSchema:l,data:c,it:u}=i,d,f,{minContains:p,maxContains:m}=l;u.opts.next?(d=p===void 0?1:p,f=m):d=1;let h=s.const("len",e._`${c}.length`);if(i.setParams({min:d,max:f}),f===void 0&&d===0){(0,n.checkStrictMode)(u,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(f!==void 0&&d>f){(0,n.checkStrictMode)(u,'"minContains" > "maxContains" is always invalid'),i.fail();return}if((0,n.alwaysValidSchema)(u,a)){let _=e._`${h} >= ${d}`;f!==void 0&&(_=e._`${_} && ${h} <= ${f}`),i.pass(_);return}u.items=!0;let g=s.name("valid");f===void 0&&d===1?y(g,()=>s.if(g,()=>s.break())):d===0?(s.let(g,!0),f!==void 0&&s.if(e._`${c}.length > 0`,v)):(s.let(g,!1),v()),i.result(g,()=>i.reset());function v(){let _=s.name("_valid"),S=s.let("count",0);y(_,()=>s.if(_,()=>w(S)))}function y(_,S){s.forRange("i",0,h,I=>{i.subschema({keyword:"contains",dataProp:I,dataPropType:n.Type.Num,compositeRule:!0},_),S()})}function w(_){s.code(e._`${_}++`),f===void 0?s.if(e._`${_} >= ${d}`,()=>s.assign(g,!0).break()):(s.if(e._`${_} > ${f}`,()=>s.assign(g,!1).break()),d===1?s.assign(g,!0):s.if(e._`${_} >= ${d}`,()=>s.assign(g,!0)))}}};t.default=o}),j4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;var e=uo(),n=ni(),r=ab();t.error={message:({params:{property:l,depsCount:c,deps:u}})=>{let d=c===1?"property":"properties";return e.str`must have ${d} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:d}})=>e._`{property: ${l},
missingProperty: ${d},
depsCount: ${c},
deps: ${u}}`};var o={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(l){let[c,u]=i(l);s(l,c),a(l,u)}};function i({schema:l}){let c={},u={};for(let d in l){if(d==="__proto__")continue;let f=Array.isArray(l[d])?c:u;f[d]=l[d]}return[c,u]}function s(l,c=l.schema){let{gen:u,data:d,it:f}=l;if(Object.keys(c).length===0)return;let p=u.let("missing");for(let m in c){let h=c[m];if(h.length===0)continue;let g=(0,r.propertyInData)(u,d,m,f.opts.ownProperties);l.setParams({property:m,depsCount:h.length,deps:h.join(", ")}),f.allErrors?u.if(g,()=>{for(let v of h)(0,r.checkReportMissingProp)(l,v)}):(u.if(e._`${g} && (${(0,r.checkMissingProp)(l,h,p)})`),(0,r.reportMissingProp)(l,p),u.else())}}t.validatePropertyDeps=s;function a(l,c=l.schema){let{gen:u,data:d,keyword:f,it:p}=l,m=u.name("valid");for(let h in c)(0,n.alwaysValidSchema)(p,c[h])||(u.if((0,r.propertyInData)(u,d,h,p.opts.ownProperties),()=>{let g=l.subschema({keyword:f,schemaProp:h},m);l.mergeValidEvaluated(g,m)},()=>u.var(m,!0)),l.ok(m))}t.validateSchemaDeps=a,t.default=o}),B4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=uo(),n=ni(),r={message:"property name must be valid",params:({params:i})=>e._`{propertyName: ${i.propertyName}}`},o={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:r,code(i){let{gen:s,schema:a,data:l,it:c}=i;if((0,n.alwaysValidSchema)(c,a))return;let u=s.name("valid");s.forIn("key",l,d=>{i.setParams({propertyName:d}),i.subschema({keyword:"propertyNames",data:d,dataTypes:["string"],propertyName:d,compositeRule:!0},u),s.if((0,e.not)(u),()=>{i.error(!0),!c.allErrors&&s.break()})}),i.ok(u)}};t.default=o}),kNt=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ab(),n=uo(),r=JP(),o=ni(),i={message:"must NOT have additional properties",params:({params:a})=>n._`{additionalProperty: ${a.additionalProperty}}`},s={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:i,code(a){let{gen:l,schema:c,parentSchema:u,data:d,errsCount:f,it:p}=a;if(!f)throw Error("ajv implementation error");let{allErrors:m,opts:h}=p;if(p.props=!0,h.removeAdditional!=="all"&&(0,o.alwaysValidSchema)(p,c))return;let g=(0,e.allSchemaProperties)(u.properties),v=(0,e.allSchemaProperties)(u.patternProperties);y(),a.ok(n._`${f} === ${r.default.errors}`);function y(){l.forIn("key",d,C=>{!g.length&&!v.length?S(C):l.if(w(C),()=>S(C))})}function w(C){let k;if(g.length>8){let T=(0,o.schemaRefOrVal)(p,u.properties,"properties");k=(0,e.isOwnProperty)(l,T,C)}else g.length?k=(0,n.or)(...g.map(T=>n._`${C} === ${T}`)):k=n.nil;return v.length&&(k=(0,n.or)(k,...v.map(T=>n._`${(0,e.usePattern)(a,T)}.test(${C})`))),(0,n.not)(k)}function _(C){l.code(n._`delete ${d}[${C}]`)}function S(C){if(h.removeAdditional==="all"||h.removeAdditional&&c===!1){_(C);return}if(c===!1){a.setParams({additionalProperty:C}),a.error(),!m&&l.break();return}if(typeof c=="object"&&!(0,o.alwaysValidSchema)(p,c)){let k=l.name("valid");h.removeAdditional==="failing"?(I(C,k,!1),l.if((0,n.not)(k),()=>{a.reset(),_(C)})):(I(C,k),!m&&l.if((0,n.not)(k),()=>l.break()))}}function I(C,k,T){let P={keyword:"additionalProperties",dataProp:C,dataPropType:o.Type.Str};T===!1&&Object.assign(P,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(P,k)}}};t.default=s}),z4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ope(),n=ab(),r=ni(),o=kNt(),i={keyword:"properties",type:"object",schemaType:"object",code(s){let{gen:a,schema:l,parentSchema:c,data:u,it:d}=s;d.opts.removeAdditional==="all"&&c.additionalProperties===void 0&&o.default.code(new e.KeywordCxt(d,o.default,"additionalProperties"));let f=(0,n.allSchemaProperties)(l);for(let v of f)d.definedProperties.add(v);d.opts.unevaluated&&f.length&&d.props!==!0&&(d.props=r.mergeEvaluated.props(a,(0,r.toHash)(f),d.props));let p=f.filter(v=>!(0,r.alwaysValidSchema)(d,l[v]));if(p.length===0)return;let m=a.name("valid");for(let v of p)h(v)?g(v):(a.if((0,n.propertyInData)(a,u,v,d.opts.ownProperties)),g(v),!d.allErrors&&a.else().var(m,!0),a.endIf()),s.it.definedProperties.add(v),s.ok(m);function h(v){return d.opts.useDefaults&&!d.compositeRule&&l[v].default!==void 0}function g(v){s.subschema({keyword:"properties",schemaProp:v,dataProp:v},m)}}};t.default=i}),H4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ab(),n=uo(),r=ni(),o=ni(),i={keyword:"patternProperties",type:"object",schemaType:"object",code(s){let{gen:a,schema:l,data:c,parentSchema:u,it:d}=s,{opts:f}=d,p=(0,e.allSchemaProperties)(l),m=p.filter(S=>(0,r.alwaysValidSchema)(d,l[S]));if(p.length===0||m.length===p.length&&(!d.opts.unevaluated||d.props===!0))return;let h=f.strictSchema&&!f.allowMatchingProperties&&u.properties,g=a.name("valid");d.props!==!0&&!(d.props instanceof n.Name)&&(d.props=(0,o.evaluatedPropsToName)(a,d.props));let{props:v}=d;y();function y(){for(let S of p)h&&w(S),d.allErrors?_(S):(a.var(g,!0),_(S),a.if(g))}function w(S){for(let I in h)new RegExp(S).test(I)&&(0,r.checkStrictMode)(d,`property ${I} matches pattern ${S} (use allowMatchingProperties)`)}function _(S){a.forIn("key",c,I=>{a.if(n._`${(0,e.usePattern)(s,S)}.test(${I})`,()=>{let C=m.includes(S);C||s.subschema({keyword:"patternProperties",schemaProp:S,dataProp:I,dataPropType:o.Type.Str},g),d.opts.unevaluated&&v!==!0?a.assign(n._`${v}[${I}]`,!0):!C&&!d.allErrors&&a.if((0,n.not)(g),()=>a.break())})})}}};t.default=i}),W4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ni(),n={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:o,schema:i,it:s}=r;if((0,e.alwaysValidSchema)(s,i)){r.fail();return}let a=o.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),r.failResult(a,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};t.default=n}),V4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ab(),n={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:e.validateUnion,error:{message:"must match a schema in anyOf"}};t.default=n}),q4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=uo(),n=ni(),r={message:"must match exactly one schema in oneOf",params:({params:i})=>e._`{passingSchemas: ${i.passing}}`},o={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:r,code(i){let{gen:s,schema:a,parentSchema:l,it:c}=i;if(!Array.isArray(a))throw Error("ajv implementation error");if(c.opts.discriminator&&l.discriminator)return;let u=a,d=s.let("valid",!1),f=s.let("passing",null),p=s.name("_valid");i.setParams({passing:f}),s.block(m),i.result(d,()=>i.reset(),()=>i.error(!0));function m(){u.forEach((h,g)=>{let v;(0,n.alwaysValidSchema)(c,h)?s.var(p,!0):v=i.subschema({keyword:"oneOf",schemaProp:g,compositeRule:!0},p),g>0&&s.if(e._`${p} && ${d}`).assign(d,!1).assign(f,e._`[${f}, ${g}]`).else(),s.if(p,()=>{s.assign(d,!0),s.assign(f,g),v&&i.mergeEvaluated(v,e.Name)})})}}};t.default=o}),K4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ni(),n={keyword:"allOf",schemaType:"array",code(r){let{gen:o,schema:i,it:s}=r;if(!Array.isArray(i))throw Error("ajv implementation error");let a=o.name("valid");i.forEach((l,c)=>{if((0,e.alwaysValidSchema)(s,l))return;let u=r.subschema({keyword:"allOf",schemaProp:c},a);r.ok(a),r.mergeEvaluated(u)})}};t.default=n}),G4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=uo(),n=ni(),r={message:({params:s})=>e.str`must match "${s.ifClause}" schema`,params:({params:s})=>e._`{failingKeyword: ${s.ifClause}}`},o={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:r,code(s){let{gen:a,parentSchema:l,it:c}=s;l.then===void 0&&l.else===void 0&&(0,n.checkStrictMode)(c,'"if" without "then" and "else" is ignored');let u=i(c,"then"),d=i(c,"else");if(!u&&!d)return;let f=a.let("valid",!0),p=a.name("_valid");if(m(),s.reset(),u&&d){let g=a.let("ifClause");s.setParams({ifClause:g}),a.if(p,h("then",g),h("else",g))}else u?a.if(p,h("then")):a.if((0,e.not)(p),h("else"));s.pass(f,()=>s.error(!0));function m(){let g=s.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},p);s.mergeEvaluated(g)}function h(g,v){return()=>{let y=s.subschema({keyword:g},p);a.assign(f,p),s.mergeValidEvaluated(y,f),v?a.assign(v,e._`${g}`):s.setParams({ifClause:g})}}}};function i(s,a){let l=s.schema[a];return l!==void 0&&!(0,n.alwaysValidSchema)(s,l)}t.default=o}),Z4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ni(),n={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:o,it:i}){o.if===void 0&&(0,e.checkStrictMode)(i,`"${r}" without "if" is ignored`)}};t.default=n}),Y4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=SNt(),n=D4n(),r=CNt(),o=F4n(),i=U4n(),s=j4n(),a=B4n(),l=kNt(),c=z4n(),u=H4n(),d=W4n(),f=V4n(),p=q4n(),m=K4n(),h=G4n(),g=Z4n();function v(y=!1){let w=[d.default,f.default,p.default,m.default,h.default,g.default,a.default,l.default,s.default,c.default,u.default];return y?w.push(n.default,o.default):w.push(e.default,r.default),w.push(i.default),w}t.default=v}),J4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=uo(),n={message:({schemaCode:o})=>e.str`must match format "${o}"`,params:({schemaCode:o})=>e._`{format: ${o}}`},r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:n,code(o,i){let{gen:s,data:a,$data:l,schema:c,schemaCode:u,it:d}=o,{opts:f,errSchemaPath:p,schemaEnv:m,self:h}=d;if(!f.validateFormats)return;l?g():v();function g(){let y=s.scopeValue("formats",{ref:h.formats,code:f.code.formats}),w=s.const("fDef",e._`${y}[${u}]`),_=s.let("fType"),S=s.let("format");s.if(e._`typeof ${w} == "object" && !(${w} instanceof RegExp)`,()=>s.assign(_,e._`${w}.type || "string"`).assign(S,e._`${w}.validate`),()=>s.assign(_,e._`"string"`).assign(S,w)),o.fail$data((0,e.or)(I(),C()));function I(){return f.strictSchema===!1?e.nil:e._`${u} && !${S}`}function C(){let k=m.$async?e._`(${w}.async ? await ${S}(${a}) : ${S}(${a}))`:e._`${S}(${a})`,T=e._`(typeof ${S} == "function" ? ${k} : ${S}.test(${a}))`;return e._`${S} && ${S} !== true && ${_} === ${i} && !${T}`}}function v(){let y=h.formats[c];if(!y){I();return}if(y===!0)return;let[w,_,S]=C(y);w===i&&o.pass(k());function I(){if(f.strictSchema===!1){h.logger.warn(T());return}throw Error(T());function T(){return`unknown format "${c}" ignored in schema at path "${p}"`}}function C(T){let P=T instanceof RegExp?(0,e.regexpCode)(T):f.code.formats?e._`${f.code.formats}${(0,e.getProperty)(c)}`:void 0,E=s.scopeValue("formats",{key:c,ref:T,code:P});return typeof T=="object"&&!(T instanceof RegExp)?[T.type||"string",T.validate,e._`${E}.validate`]:["string",T,E]}function k(){if(typeof y=="object"&&!(y instanceof RegExp)&&y.async){if(!m.$async)throw Error("async format in sync schema");return e._`await ${S}(${a})`}return typeof _=="function"?e._`${S}(${a})`:e._`${S}.test(${a})`}}}};t.default=r}),X4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=J4n(),n=[e.default];t.default=n}),Q4n=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.contentVocabulary=t.metadataVocabulary=void 0,t.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],t.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]}),eHn=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=C4n(),n=$4n(),r=Y4n(),o=X4n(),i=Q4n(),s=[e.default,n.default,(0,r.default)(),o.default,i.metadataVocabulary,i.contentVocabulary];t.default=s}),tHn=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DiscrError=void 0;var e;(function(n){n.Tag="tag",n.Mapping="mapping"})(e||(t.DiscrError=e={}))}),nHn=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=uo(),n=tHn(),r=sBe(),o=ipe(),i=ni(),s={message:({params:{discrError:l,tagName:c}})=>l===n.DiscrError.Tag?`tag "${c}" must be string`:`value of tag "${c}" must be in oneOf`,params:({params:{discrError:l,tag:c,tagName:u}})=>e._`{error: ${l}, tag: ${u}, tagValue: ${c}}`},a={keyword:"discriminator",type:"object",schemaType:"object",error:s,code(l){let{gen:c,data:u,schema:d,parentSchema:f,it:p}=l,{oneOf:m}=f;if(!p.opts.discriminator)throw Error("discriminator: requires discriminator option");let h=d.propertyName;if(typeof h!="string")throw Error("discriminator: requires propertyName");if(d.mapping)throw Error("discriminator: mapping is not supported");if(!m)throw Error("discriminator: requires oneOf keyword");let g=c.let("valid",!1),v=c.const("tag",e._`${u}${(0,e.getProperty)(h)}`);c.if(e._`typeof ${v} == "string"`,()=>y(),()=>l.error(!1,{discrError:n.DiscrError.Tag,tag:v,tagName:h})),l.ok(g);function y(){let S=_();c.if(!1);for(let I in S)c.elseIf(e._`${v} === ${I}`),c.assign(g,w(S[I]));c.else(),l.error(!1,{discrError:n.DiscrError.Mapping,tag:v,tagName:h}),c.endIf()}function w(S){let I=c.name("valid"),C=l.subschema({keyword:"oneOf",schemaProp:S},I);return l.mergeEvaluated(C,e.Name),I}function _(){var S;let I={},C=T(f),k=!0;for(let O=0;O<m.length;O++){let $=m[O];if($?.$ref&&!(0,i.schemaHasRulesButRef)($,p.self.RULES)){let V=$.$ref;if($=r.resolveRef.call(p.self,p.schemaEnv.root,p.baseId,V),$ instanceof r.SchemaEnv&&($=$.schema),$===void 0)throw new o.default(p.opts.uriResolver,p.baseId,V)}let U=(S=$?.properties)===null||S===void 0?void 0:S[h];if(typeof U!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${h}"`);k=k&&(C||T($)),P(U,O)}if(!k)throw Error(`discriminator: "${h}" must be required`);return I;function T({required:O}){return Array.isArray(O)&&O.includes(h)}function P(O,$){if(O.const)E(O.const,$);else if(O.enum)for(let U of O.enum)E(U,$);else throw Error(`discriminator: "properties/${h}" must have "const" or "enum"`)}function E(O,$){if(typeof O!="string"||O in I)throw Error(`discriminator: "${h}" values must be unique strings`);I[O]=$}}}};t.default=a}),rHn=Le((t,e)=>{e.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}}),INt=Le((t,e)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;var n=_4n(),r=eHn(),o=nHn(),i=rHn(),s=["/properties"],a="http://json-schema.org/draft-07/schema";class l extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(m=>this.addVocabulary(m)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let m=this.opts.$data?this.$dataMetaSchema(i,s):i;this.addMetaSchema(m,a,!1),this.refs["http://json-schema.org/schema"]=a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}}t.Ajv=l,e.exports=t=l,e.exports.Ajv=l,Object.defineProperty(t,"__esModule",{value:!0}),t.default=l;var c=ope();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=uo();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var d=iBe();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=ipe();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return f.default}})}),oHn=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.formatNames=t.fastFormats=t.fullFormats=void 0;function e(E,O){return{validate:E,compare:O}}t.fullFormats={date:e(i,s),time:e(l(!0),c),"date-time":e(f(!0),p),"iso-time":e(l(),u),"iso-date-time":e(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:v,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:P,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:w,int32:{type:"number",validate:I},int64:{type:"number",validate:C},float:{type:"number",validate:k},double:{type:"number",validate:k},password:!0,binary:!0},t.fastFormats={...t.fullFormats,date:e(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,s),time:e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},t.formatNames=Object.keys(t.fullFormats);function n(E){return E%4===0&&(E%100!==0||E%400===0)}var r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function i(E){let O=r.exec(E);if(!O)return!1;let $=+O[1],U=+O[2],V=+O[3];return U>=1&&U<=12&&V>=1&&V<=(U===2&&n($)?29:o[U])}function s(E,O){if(E&&O)return E>O?1:E<O?-1:0}var a=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(E){return function(O){let $=a.exec(O);if(!$)return!1;let U=+$[1],V=+$[2],K=+$[3],se=$[4],le=$[5]==="-"?-1:1,Q=+($[6]||0),ne=+($[7]||0);if(Q>23||ne>59||E&&!se)return!1;if(U<=23&&V<=59&&K<60)return!0;let ee=V-ne*le,ae=U-Q*le-(ee<0?1:0);return(ae===23||ae===-1)&&(ee===59||ee===-1)&&K<61}}function c(E,O){if(!(E&&O))return;let $=new Date("2020-01-01T"+E).valueOf(),U=new Date("2020-01-01T"+O).valueOf();if($&&U)return $-U}function u(E,O){if(!(E&&O))return;let $=a.exec(E),U=a.exec(O);if($&&U)return E=$[1]+$[2]+$[3],O=U[1]+U[2]+U[3],E>O?1:E<O?-1:0}var d=/t|\s/i;function f(E){let O=l(E);return function($){let U=$.split(d);return U.length===2&&i(U[0])&&O(U[1])}}function p(E,O){if(!(E&&O))return;let $=new Date(E).valueOf(),U=new Date(O).valueOf();if($&&U)return $-U}function m(E,O){if(!(E&&O))return;let[$,U]=E.split(d),[V,K]=O.split(d),se=s($,V);if(se!==void 0)return se||c(U,K)}var h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function v(E){return h.test(E)&&g.test(E)}var y=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function w(E){return y.lastIndex=0,y.test(E)}var _=-2147483648,S=2147483647;function I(E){return Number.isInteger(E)&&E<=S&&E>=_}function C(E){return Number.isInteger(E)}function k(){return!0}var T=/[^\\]\\Z/;function P(E){if(T.test(E))return!1;try{return new RegExp(E),!0}catch{return!1}}}),iHn=Le(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.formatLimitDefinition=void 0;var e=INt(),n=uo(),r=n.operators,o={formatMaximum:{okStr:"<=",ok:r.LTE,fail:r.GT},formatMinimum:{okStr:">=",ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:"<",ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:">",ok:r.GT,fail:r.LTE}},i={message:({keyword:a,schemaCode:l})=>n.str`should be ${o[a].okStr} ${l}`,params:({keyword:a,schemaCode:l})=>n._`{comparison: ${o[a].okStr}, limit: ${l}}`};t.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:i,code(a){let{gen:l,data:c,schemaCode:u,keyword:d,it:f}=a,{opts:p,self:m}=f;if(!p.validateFormats)return;let h=new e.KeywordCxt(f,m.RULES.all.format.definition,"format");h.$data?g():v();function g(){let w=l.scopeValue("formats",{ref:m.formats,code:p.code.formats}),_=l.const("fmt",n._`${w}[${h.schemaCode}]`);a.fail$data((0,n.or)(n._`typeof ${_} != "object"`,n._`${_} instanceof RegExp`,n._`typeof ${_}.compare != "function"`,y(_)))}function v(){let w=h.schema,_=m.formats[w];if(!_||_===!0)return;if(typeof _!="object"||_ instanceof RegExp||typeof _.compare!="function")throw Error(`"${d}": format "${w}" does not define "compare" function`);let S=l.scopeValue("formats",{key:w,ref:_,code:p.code.formats?n._`${p.code.formats}${(0,n.getProperty)(w)}`:void 0});a.fail$data(y(S))}function y(w){return n._`${w}.compare(${c}, ${u}) ${o[d].fail} 0`}},dependencies:["format"]};var s=a=>(a.addKeyword(t.formatLimitDefinition),a);t.default=s}),sHn=Le((t,e)=>{Object.defineProperty(t,"__esModule",{value:!0});var n=oHn(),r=iHn(),o=uo(),i=new o.Name("fullFormats"),s=new o.Name("fastFormats"),a=(c,u={keywords:!0})=>{if(Array.isArray(u))return l(c,u,n.fullFormats,i),c;let[d,f]=u.mode==="fast"?[n.fastFormats,s]:[n.fullFormats,i],p=u.formats||n.formatNames;return l(c,p,d,f),u.keywords&&(0,r.default)(c),c};a.get=(c,u="full")=>{let d=(u==="fast"?n.fastFormats:n.fullFormats)[c];if(!d)throw Error(`Unknown format "${c}"`);return d};function l(c,u,d,f){var p,m;(p=(m=c.opts.code).formats)!==null&&p!==void 0||(m.formats=o._`require("ajv-formats/dist/formats").${f}`);for(let h of u)c.addFormat(h,d[h])}e.exports=t=a,Object.defineProperty(t,"__esModule",{value:!0}),t.default=a}),lHn=50;Cuo=new FinalizationRegistry(({parentSignalRef:t,handler:e})=>{t.deref()?.removeEventListener("abort",e)}),cHn="server-fallback-tombstone",kuo=new DOMException(cHn,"AbortError"),uHn="subagent-park",Iuo=new DOMException(uHn,"AbortError");LNt=["PreToolUse","PostToolUse","PostToolUseFailure","PostToolBatch","Notification","UserPromptSubmit","UserPromptExpansion","SessionStart","SessionEnd","Stop","StopFailure","SubagentStart","SubagentStop","PreCompact","PostCompact","PermissionRequest","PermissionDenied","Setup","TeammateIdle","TaskCreated","TaskCompleted","Elicitation","ElicitationResult","ConfigChange","WorktreeCreate","WorktreeRemove","InstructionsLoaded","CwdChanged","FileChanged","MessageDisplay"],Ek=class extends Error{};dMt=globalThis.process?.getBuiltinModule?.("async_hooks"),yHn=dMt?t=>dMt.AsyncResource.bind(t):t=>t;vHn=typeof window=="object"&&window&&window.Object===Object&&window,DNt=vHn,wHn=typeof self=="object"&&self&&self.Object===Object&&self,bHn=DNt||wHn||Function("return this")(),xx=bHn,_Hn=xx.Symbol,vx=_Hn,FNt=Object.prototype,xHn=FNt.hasOwnProperty,SHn=FNt.toString,NZ=vx?vx.toStringTag:void 0;kHn=CHn,IHn=Object.prototype,THn=IHn.toString;AHn=PHn,EHn="[object Null]",MHn="[object Undefined]",fMt=vx?vx.toStringTag:void 0;DR=OHn;Nk=NHn,RHn="[object AsyncFunction]",LHn="[object Function]",$Hn="[object GeneratorFunction]",DHn="[object Proxy]";uBe=FHn,UHn=xx["__core-js_shared__"],OUe=UHn,pMt=function(){var t=/[^.]+$/.exec(OUe&&OUe.keys&&OUe.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();BHn=jHn,zHn=Function.prototype,HHn=zHn.toString;FR=WHn,VHn=/[\\^$.*+?()[\]{}|]/g,qHn=/^\[object .+?Constructor\]$/,KHn=Function.prototype,GHn=Object.prototype,ZHn=KHn.toString,YHn=GHn.hasOwnProperty,JHn=RegExp("^"+ZHn.call(YHn).replace(VHn,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");QHn=XHn;tWn=eWn;UR=nWn,rWn=UR(Object,"create"),d7=rWn;iWn=oWn;aWn=sWn,lWn="__lodash_hash_undefined__",cWn=Object.prototype,uWn=cWn.hasOwnProperty;fWn=dWn,pWn=Object.prototype,mWn=pWn.hasOwnProperty;gWn=hWn,yWn="__lodash_hash_undefined__";wWn=vWn;WB.prototype.clear=iWn;WB.prototype.delete=aWn;WB.prototype.get=fWn;WB.prototype.has=gWn;WB.prototype.set=wWn;mMt=WB;_Wn=bWn;ape=xWn;lpe=SWn,CWn=Array.prototype,kWn=CWn.splice;TWn=IWn;AWn=PWn;MWn=EWn;NWn=OWn;VB.prototype.clear=_Wn;VB.prototype.delete=TWn;VB.prototype.get=AWn;VB.prototype.has=MWn;VB.prototype.set=NWn;cpe=VB,RWn=UR(xx,"Map"),f7=RWn;$Wn=LWn;FWn=DWn;upe=UWn;BWn=jWn;HWn=zWn;VWn=WWn;KWn=qWn;qB.prototype.clear=$Wn;qB.prototype.delete=BWn;qB.prototype.get=HWn;qB.prototype.has=VWn;qB.prototype.set=KWn;dpe=qB,GWn="Expected a function";dBe.Cache=dpe;Za=dBe,A={};_x(A,{xid:()=>E3n,void:()=>J3n,uuidv7:()=>S3n,uuidv6:()=>x3n,uuidv4:()=>_3n,uuid:()=>b3n,url:()=>C3n,uppercase:()=>cze,unknown:()=>ma,union:()=>gs,undefined:()=>Z3n,ulid:()=>A3n,uint64:()=>K3n,uint32:()=>W3n,tuple:()=>tqn,trim:()=>hze,treeifyError:()=>QNt,transform:()=>Zze,toUpperCase:()=>yze,toLowerCase:()=>gze,toJSONSchema:()=>V1t,templateLiteral:()=>uqn,symbol:()=>G3n,superRefine:()=>$$t,success:()=>lqn,stringbool:()=>pqn,stringFormat:()=>j3n,string:()=>ke,strictObject:()=>eqn,startsWith:()=>dze,size:()=>sze,setErrorMap:()=>gqn,set:()=>oqn,safeParseAsync:()=>e$t,safeParse:()=>Q1t,registry:()=>FBe,regexes:()=>CBe,regex:()=>aze,refine:()=>L$t,record:()=>hs,readonly:()=>P$t,property:()=>D1t,promise:()=>dqn,prettifyError:()=>tRt,preprocess:()=>Qze,prefault:()=>_$t,positive:()=>N1t,pipe:()=>afe,partialRecord:()=>nqn,parseAsync:()=>X1t,parse:()=>J1t,overwrite:()=>zR,optional:()=>Js,object:()=>qt,number:()=>xi,nullish:()=>aqn,nullable:()=>sfe,null:()=>Hze,normalize:()=>mze,nonpositive:()=>L1t,nonoptional:()=>x$t,nonnegative:()=>$1t,never:()=>Cpe,negative:()=>R1t,nativeEnum:()=>iqn,nanoid:()=>I3n,nan:()=>cqn,multipleOf:()=>g7,minSize:()=>y7,minLength:()=>SB,mime:()=>pze,maxSize:()=>ype,maxLength:()=>vpe,map:()=>rqn,lte:()=>nb,lt:()=>AR,lowercase:()=>lze,looseObject:()=>vp,locales:()=>DBe,literal:()=>In,length:()=>wpe,lazy:()=>M$t,ksuid:()=>M3n,keyof:()=>Q3n,jwt:()=>U3n,json:()=>mqn,iso:()=>wze,ipv6:()=>N3n,ipv4:()=>O3n,intersection:()=>Ipe,int64:()=>q3n,int32:()=>H3n,int:()=>rje,instanceof:()=>fqn,includes:()=>uze,guid:()=>w3n,gte:()=>qh,gt:()=>ER,globalRegistry:()=>CR,getErrorMap:()=>yqn,function:()=>W1t,formatError:()=>yBe,float64:()=>z3n,float32:()=>B3n,flattenError:()=>gBe,file:()=>sqn,enum:()=>Im,endsWith:()=>fze,emoji:()=>k3n,email:()=>v3n,e164:()=>F3n,discriminatedUnion:()=>qze,date:()=>X3n,custom:()=>R$t,cuid2:()=>P3n,cuid:()=>T3n,core:()=>BNt,config:()=>wp,coerce:()=>D$t,clone:()=>lb,cidrv6:()=>L3n,cidrv4:()=>R3n,check:()=>N$t,catch:()=>k$t,boolean:()=>Fc,bigint:()=>V3n,base64url:()=>D3n,base64:()=>$3n,array:()=>Oo,any:()=>Y3n,_default:()=>w$t,_ZodString:()=>Cze,ZodXID:()=>Oze,ZodVoid:()=>l$t,ZodUnknown:()=>s$t,ZodUnion:()=>Vze,ZodUndefined:()=>r$t,ZodUUID:()=>Ok,ZodURL:()=>Ize,ZodULID:()=>Mze,ZodType:()=>po,ZodTuple:()=>f$t,ZodTransform:()=>Gze,ZodTemplateLiteral:()=>A$t,ZodSymbol:()=>n$t,ZodSuccess:()=>S$t,ZodStringFormat:()=>Qs,ZodString:()=>bpe,ZodSet:()=>m$t,ZodRecord:()=>Kze,ZodRealError:()=>H7,ZodReadonly:()=>T$t,ZodPromise:()=>O$t,ZodPrefault:()=>b$t,ZodPipe:()=>Xze,ZodOptional:()=>Yze,ZodObject:()=>kpe,ZodNumberFormat:()=>KB,ZodNumber:()=>_pe,ZodNullable:()=>y$t,ZodNull:()=>o$t,ZodNonOptional:()=>Jze,ZodNever:()=>a$t,ZodNanoID:()=>Pze,ZodNaN:()=>I$t,ZodMap:()=>p$t,ZodLiteral:()=>h$t,ZodLazy:()=>E$t,ZodKSUID:()=>Nze,ZodJWT:()=>Bze,ZodIssueCode:()=>hqn,ZodIntersection:()=>d$t,ZodISOTime:()=>xze,ZodISODuration:()=>Sze,ZodISODateTime:()=>bze,ZodISODate:()=>_ze,ZodIPv6:()=>Lze,ZodIPv4:()=>Rze,ZodGUID:()=>ife,ZodFile:()=>g$t,ZodError:()=>y3n,ZodEnum:()=>w7,ZodEmoji:()=>Tze,ZodEmail:()=>kze,ZodE164:()=>jze,ZodDiscriminatedUnion:()=>u$t,ZodDefault:()=>v$t,ZodDate:()=>Wze,ZodCustomStringFormat:()=>t$t,ZodCustom:()=>Tpe,ZodCatch:()=>C$t,ZodCUID2:()=>Eze,ZodCUID:()=>Aze,ZodCIDRv6:()=>Dze,ZodCIDRv4:()=>$ze,ZodBoolean:()=>xpe,ZodBigIntFormat:()=>zze,ZodBigInt:()=>Spe,ZodBase64URL:()=>Uze,ZodBase64:()=>Fze,ZodArray:()=>c$t,ZodAny:()=>i$t,TimePrecision:()=>s1t,NEVER:()=>zNt,$output:()=>n1t,$input:()=>r1t,$brand:()=>HNt});BNt={};_x(BNt,{version:()=>XRt,util:()=>Mo,treeifyError:()=>QNt,toJSONSchema:()=>V1t,toDotPath:()=>eRt,safeParseAsync:()=>SBe,safeParse:()=>_Be,registry:()=>FBe,regexes:()=>CBe,prettifyError:()=>tRt,parseAsync:()=>Qde,parse:()=>Xde,locales:()=>DBe,isValidJWT:()=>xLt,isValidBase64URL:()=>wLt,isValidBase64:()=>PBe,globalRegistry:()=>CR,globalConfig:()=>Yde,function:()=>W1t,formatError:()=>yBe,flattenError:()=>gBe,config:()=>wp,clone:()=>lb,_xid:()=>YBe,_void:()=>A1t,_uuidv7:()=>HBe,_uuidv6:()=>zBe,_uuidv4:()=>BBe,_uuid:()=>jBe,_url:()=>WBe,_uppercase:()=>cze,_unknown:()=>rfe,_union:()=>ZVn,_undefined:()=>k1t,_ulid:()=>ZBe,_uint64:()=>S1t,_uint32:()=>y1t,_tuple:()=>F1t,_trim:()=>hze,_transform:()=>o3n,_toUpperCase:()=>yze,_toLowerCase:()=>gze,_templateLiteral:()=>p3n,_symbol:()=>C1t,_success:()=>c3n,_stringbool:()=>z1t,_stringFormat:()=>H1t,_string:()=>o1t,_startsWith:()=>dze,_size:()=>sze,_set:()=>e3n,_safeParseAsync:()=>xBe,_safeParse:()=>bBe,_regex:()=>aze,_refine:()=>B1t,_record:()=>XVn,_readonly:()=>f3n,_property:()=>D1t,_promise:()=>h3n,_positive:()=>N1t,_pipe:()=>d3n,_parseAsync:()=>wBe,_parse:()=>vBe,_overwrite:()=>zR,_optional:()=>i3n,_number:()=>d1t,_nullable:()=>s3n,_null:()=>I1t,_normalize:()=>mze,_nonpositive:()=>L1t,_nonoptional:()=>l3n,_nonnegative:()=>$1t,_never:()=>P1t,_negative:()=>R1t,_nativeEnum:()=>n3n,_nanoid:()=>qBe,_nan:()=>O1t,_multipleOf:()=>g7,_minSize:()=>y7,_minLength:()=>SB,_min:()=>qh,_mime:()=>pze,_maxSize:()=>ype,_maxLength:()=>vpe,_max:()=>nb,_map:()=>QVn,_lte:()=>nb,_lt:()=>AR,_lowercase:()=>lze,_literal:()=>r3n,_length:()=>wpe,_lazy:()=>m3n,_ksuid:()=>JBe,_jwt:()=>ize,_isoTime:()=>c1t,_isoDuration:()=>u1t,_isoDateTime:()=>a1t,_isoDate:()=>l1t,_ipv6:()=>QBe,_ipv4:()=>XBe,_intersection:()=>JVn,_int64:()=>x1t,_int32:()=>g1t,_int:()=>p1t,_includes:()=>uze,_guid:()=>nfe,_gte:()=>qh,_gt:()=>ER,_float64:()=>h1t,_float32:()=>m1t,_file:()=>U1t,_enum:()=>t3n,_endsWith:()=>fze,_emoji:()=>VBe,_email:()=>UBe,_e164:()=>oze,_discriminatedUnion:()=>YVn,_default:()=>a3n,_date:()=>E1t,_custom:()=>j1t,_cuid2:()=>GBe,_cuid:()=>KBe,_coercedString:()=>i1t,_coercedNumber:()=>f1t,_coercedDate:()=>M1t,_coercedBoolean:()=>w1t,_coercedBigint:()=>_1t,_cidrv6:()=>tze,_cidrv4:()=>eze,_catch:()=>u3n,_boolean:()=>v1t,_bigint:()=>b1t,_base64url:()=>rze,_base64:()=>nze,_array:()=>vze,_any:()=>T1t,TimePrecision:()=>s1t,NEVER:()=>zNt,JSONSchemaGenerator:()=>v7,JSONSchema:()=>g3n,Doc:()=>efe,$output:()=>n1t,$input:()=>r1t,$constructor:()=>_e,$brand:()=>HNt,$ZodXID:()=>lLt,$ZodVoid:()=>OLt,$ZodUnknown:()=>tfe,$ZodUnion:()=>RBe,$ZodUndefined:()=>PLt,$ZodUUID:()=>eLt,$ZodURL:()=>nLt,$ZodULID:()=>aLt,$ZodType:()=>Mr,$ZodTuple:()=>gpe,$ZodTransform:()=>LBe,$ZodTemplateLiteral:()=>JLt,$ZodSymbol:()=>TLt,$ZodSuccess:()=>KLt,$ZodStringFormat:()=>Ms,$ZodString:()=>z7,$ZodSet:()=>FLt,$ZodRegistry:()=>h7,$ZodRecord:()=>$Lt,$ZodRealError:()=>j7,$ZodReadonly:()=>YLt,$ZodPromise:()=>XLt,$ZodPrefault:()=>VLt,$ZodPipe:()=>$Be,$ZodOptional:()=>zLt,$ZodObject:()=>NBe,$ZodNumberFormat:()=>kLt,$ZodNumber:()=>ABe,$ZodNullable:()=>HLt,$ZodNull:()=>ALt,$ZodNonOptional:()=>qLt,$ZodNever:()=>MLt,$ZodNanoID:()=>oLt,$ZodNaN:()=>ZLt,$ZodMap:()=>DLt,$ZodLiteral:()=>jLt,$ZodLazy:()=>QLt,$ZodKSUID:()=>cLt,$ZodJWT:()=>SLt,$ZodIntersection:()=>LLt,$ZodISOTime:()=>fLt,$ZodISODuration:()=>pLt,$ZodISODateTime:()=>uLt,$ZodISODate:()=>dLt,$ZodIPv6:()=>hLt,$ZodIPv4:()=>mLt,$ZodGUID:()=>QRt,$ZodFunction:()=>ofe,$ZodFile:()=>BLt,$ZodError:()=>hBe,$ZodEnum:()=>ULt,$ZodEmoji:()=>rLt,$ZodEmail:()=>tLt,$ZodE164:()=>_Lt,$ZodDiscriminatedUnion:()=>RLt,$ZodDefault:()=>WLt,$ZodDate:()=>NLt,$ZodCustomStringFormat:()=>CLt,$ZodCustom:()=>e1t,$ZodCheckUpperCase:()=>VRt,$ZodCheckStringFormat:()=>B7,$ZodCheckStartsWith:()=>KRt,$ZodCheckSizeEquals:()=>URt,$ZodCheckRegex:()=>HRt,$ZodCheckProperty:()=>ZRt,$ZodCheckOverwrite:()=>JRt,$ZodCheckNumberFormat:()=>LRt,$ZodCheckMultipleOf:()=>RRt,$ZodCheckMinSize:()=>FRt,$ZodCheckMinLength:()=>BRt,$ZodCheckMimeType:()=>YRt,$ZodCheckMaxSize:()=>DRt,$ZodCheckMaxLength:()=>jRt,$ZodCheckLowerCase:()=>WRt,$ZodCheckLessThan:()=>IBe,$ZodCheckLengthEquals:()=>zRt,$ZodCheckIncludes:()=>qRt,$ZodCheckGreaterThan:()=>TBe,$ZodCheckEndsWith:()=>GRt,$ZodCheckBigIntFormat:()=>$Rt,$ZodCheck:()=>wl,$ZodCatch:()=>GLt,$ZodCUID2:()=>sLt,$ZodCUID:()=>iLt,$ZodCIDRv6:()=>yLt,$ZodCIDRv4:()=>gLt,$ZodBoolean:()=>EBe,$ZodBigIntFormat:()=>ILt,$ZodBigInt:()=>MBe,$ZodBase64URL:()=>bLt,$ZodBase64:()=>vLt,$ZodAsyncError:()=>GP,$ZodArray:()=>OBe,$ZodAny:()=>ELt});zNt=Object.freeze({status:"aborted"});HNt=Symbol("zod_brand"),GP=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Yde={};Mo={};_x(Mo,{unwrapMessage:()=>QZ,stringifyPrimitive:()=>to,required:()=>d6n,randomString:()=>n6n,propertyKeyTypes:()=>Jde,promiseAllObject:()=>t6n,primitiveTypes:()=>KNt,prefixIssues:()=>Vy,pick:()=>s6n,partial:()=>u6n,optionalKeys:()=>GNt,omit:()=>a6n,numKeys:()=>r6n,nullish:()=>jR,normalizeParams:()=>bt,merge:()=>c6n,jsonStringifyReplacer:()=>WNt,joinValues:()=>Ot,issue:()=>JNt,isPlainObject:()=>m7,isObject:()=>p7,getSizableOrigin:()=>mpe,getParsedType:()=>o6n,getLengthableOrigin:()=>hpe,getEnumValues:()=>fBe,getElementAtPath:()=>e6n,floatSafeRemainder:()=>VNt,finalizeIssue:()=>ob,extend:()=>l6n,escapeRegex:()=>BR,esc:()=>cB,defineLazy:()=>Di,createTransparentProxy:()=>i6n,clone:()=>lb,cleanRegex:()=>ppe,cleanEnum:()=>f6n,captureStackTrace:()=>mBe,cached:()=>fpe,assignProp:()=>pBe,assertNotEqual:()=>YWn,assertNever:()=>XWn,assertIs:()=>JWn,assertEqual:()=>ZWn,assert:()=>QWn,allowsEval:()=>qNt,aborted:()=>mB,NUMBER_FORMAT_RANGES:()=>ZNt,Class:()=>tje,BIGINT_FORMAT_RANGES:()=>YNt});mBe=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};qNt=fpe(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch{return!1}});o6n=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw Error(`Unknown data type: ${e}`)}},Jde=new Set(["string","number","symbol"]),KNt=new Set(["string","number","bigint","boolean","symbol","undefined"]);ZNt={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},YNt={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};tje=class{constructor(...e){}},XNt=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,WNt,2)},enumerable:!0})},hBe=_e("$ZodError",XNt),j7=_e("$ZodError",XNt,{Parent:Error});vBe=t=>(e,n,r,o)=>{let i=r?Object.assign(r,{async:!1}):{async:!1},s=e._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new GP;if(s.issues.length){let a=new(o?.Err??t)(s.issues.map(l=>ob(l,i,wp())));throw mBe(a,o?.callee),a}return s.value},Xde=vBe(j7),wBe=t=>async(e,n,r,o)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},s=e._zod.run({value:n,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??t)(s.issues.map(l=>ob(l,i,wp())));throw mBe(a,o?.callee),a}return s.value},Qde=wBe(j7),bBe=t=>(e,n,r)=>{let o=r?{...r,async:!1}:{async:!1},i=e._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new GP;return i.issues.length?{success:!1,error:new(t??hBe)(i.issues.map(s=>ob(s,o,wp())))}:{success:!0,data:i.value}},_Be=bBe(j7),xBe=t=>async(e,n,r)=>{let o=r?Object.assign(r,{async:!0}):{async:!0},i=e._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new t(i.issues.map(s=>ob(s,o,wp())))}:{success:!0,data:i.value}},SBe=xBe(j7),CBe={};_x(CBe,{xid:()=>iRt,uuid7:()=>g6n,uuid6:()=>h6n,uuid4:()=>m6n,uuid:()=>xB,uppercase:()=>ORt,unicodeEmail:()=>w6n,undefined:()=>ERt,ulid:()=>oRt,time:()=>xRt,string:()=>CRt,rfc5322Email:()=>v6n,number:()=>TRt,null:()=>ARt,nanoid:()=>aRt,lowercase:()=>MRt,ksuid:()=>sRt,ipv6:()=>pRt,ipv4:()=>fRt,integer:()=>IRt,html5Email:()=>y6n,hostname:()=>yRt,guid:()=>cRt,extendedDuration:()=>p6n,emoji:()=>dRt,email:()=>uRt,e164:()=>vRt,duration:()=>lRt,domain:()=>x6n,datetime:()=>SRt,date:()=>bRt,cuid2:()=>rRt,cuid:()=>nRt,cidrv6:()=>hRt,cidrv4:()=>mRt,browserEmail:()=>b6n,boolean:()=>PRt,bigint:()=>kRt,base64url:()=>kBe,base64:()=>gRt,_emoji:()=>_6n});nRt=/^[cC][^\s-]{8,}$/,rRt=/^[0-9a-z]+$/,oRt=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,iRt=/^[0-9a-vA-V]{20}$/,sRt=/^[A-Za-z0-9]{27}$/,aRt=/^[a-zA-Z0-9_-]{21}$/,lRt=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,p6n=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,cRt=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,xB=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,m6n=xB(4),h6n=xB(6),g6n=xB(7),uRt=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,y6n=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,v6n=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,w6n=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,b6n=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,_6n="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";fRt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,pRt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,mRt=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,hRt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,gRt=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,kBe=/^[A-Za-z0-9_-]*$/,yRt=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,x6n=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,vRt=/^\+(?:[0-9]){6,14}[0-9]$/,wRt="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",bRt=new RegExp(`^${wRt}$`);CRt=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},kRt=/^\d+n?$/,IRt=/^\d+$/,TRt=/^-?\d+(?:\.\d+)?/i,PRt=/true|false/i,ARt=/null/i,ERt=/undefined/i,MRt=/^[^A-Z]*$/,ORt=/^[^a-z]*$/,wl=_e("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),NRt={number:"number",bigint:"bigint",object:"date"},IBe=_e("$ZodCheckLessThan",(t,e)=>{wl.init(t,e);let n=NRt[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,i=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<i&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),TBe=_e("$ZodCheckGreaterThan",(t,e)=>{wl.init(t,e);let n=NRt[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,i=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>i&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),RRt=_e("$ZodCheckMultipleOf",(t,e)=>{wl.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):VNt(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),LRt=_e("$ZodCheckNumberFormat",(t,e)=>{wl.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[o,i]=ZNt[e.format];t._zod.onattach.push(s=>{let a=s._zod.bag;a.format=e.format,a.minimum=o,a.maximum=i,n&&(a.pattern=IRt)}),t._zod.check=s=>{let a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:r,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort});return}}a<o&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inst:t})}}),$Rt=_e("$ZodCheckBigIntFormat",(t,e)=>{wl.init(t,e);let[n,r]=YNt[e.format];t._zod.onattach.push(o=>{let i=o._zod.bag;i.format=e.format,i.minimum=n,i.maximum=r}),t._zod.check=o=>{let i=o.value;i<n&&o.issues.push({origin:"bigint",input:i,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!e.abort}),i>r&&o.issues.push({origin:"bigint",input:i,code:"too_big",maximum:r,inst:t})}}),DRt=_e("$ZodCheckMaxSize",(t,e)=>{wl.init(t,e),t._zod.when=n=>{let r=n.value;return!jR(r)&&r.size!==void 0},t._zod.onattach.push(n=>{let r=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<r&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let r=n.value;r.size<=e.maximum||n.issues.push({origin:mpe(r),code:"too_big",maximum:e.maximum,input:r,inst:t,continue:!e.abort})}}),FRt=_e("$ZodCheckMinSize",(t,e)=>{wl.init(t,e),t._zod.when=n=>{let r=n.value;return!jR(r)&&r.size!==void 0},t._zod.onattach.push(n=>{let r=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>r&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let r=n.value;r.size>=e.minimum||n.issues.push({origin:mpe(r),code:"too_small",minimum:e.minimum,input:r,inst:t,continue:!e.abort})}}),URt=_e("$ZodCheckSizeEquals",(t,e)=>{wl.init(t,e),t._zod.when=n=>{let r=n.value;return!jR(r)&&r.size!==void 0},t._zod.onattach.push(n=>{let r=n._zod.bag;r.minimum=e.size,r.maximum=e.size,r.size=e.size}),t._zod.check=n=>{let r=n.value,o=r.size;if(o===e.size)return;let i=o>e.size;n.issues.push({origin:mpe(r),...i?{code:"too_big",maximum:e.size}:{code:"too_small",minimum:e.size},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),jRt=_e("$ZodCheckMaxLength",(t,e)=>{wl.init(t,e),t._zod.when=n=>{let r=n.value;return!jR(r)&&r.length!==void 0},t._zod.onattach.push(n=>{let r=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<r&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let r=n.value;if(r.length<=e.maximum)return;let o=hpe(r);n.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:r,inst:t,continue:!e.abort})}}),BRt=_e("$ZodCheckMinLength",(t,e)=>{wl.init(t,e),t._zod.when=n=>{let r=n.value;return!jR(r)&&r.length!==void 0},t._zod.onattach.push(n=>{let r=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>r&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let r=n.value;if(r.length>=e.minimum)return;let o=hpe(r);n.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:r,inst:t,continue:!e.abort})}}),zRt=_e("$ZodCheckLengthEquals",(t,e)=>{wl.init(t,e),t._zod.when=n=>{let r=n.value;return!jR(r)&&r.length!==void 0},t._zod.onattach.push(n=>{let r=n._zod.bag;r.minimum=e.length,r.maximum=e.length,r.length=e.length}),t._zod.check=n=>{let r=n.value,o=r.length;if(o===e.length)return;let i=hpe(r),s=o>e.length;n.issues.push({origin:i,...s?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),B7=_e("$ZodCheckStringFormat",(t,e)=>{var n,r;wl.init(t,e),t._zod.onattach.push(o=>{let i=o._zod.bag;i.format=e.format,e.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),HRt=_e("$ZodCheckRegex",(t,e)=>{B7.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),WRt=_e("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=MRt),B7.init(t,e)}),VRt=_e("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=ORt),B7.init(t,e)}),qRt=_e("$ZodCheckIncludes",(t,e)=>{wl.init(t,e);let n=BR(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),KRt=_e("$ZodCheckStartsWith",(t,e)=>{wl.init(t,e);let n=new RegExp(`^${BR(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),GRt=_e("$ZodCheckEndsWith",(t,e)=>{wl.init(t,e);let n=new RegExp(`.*${BR(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}});ZRt=_e("$ZodCheckProperty",(t,e)=>{wl.init(t,e),t._zod.check=n=>{let r=e.schema._zod.run({value:n.value[e.property],issues:[]},{});if(r instanceof Promise)return r.then(o=>hMt(o,n,e.property));hMt(r,n,e.property)}}),YRt=_e("$ZodCheckMimeType",(t,e)=>{wl.init(t,e);let n=new Set(e.mime);t._zod.onattach.push(r=>{r._zod.bag.mime=e.mime}),t._zod.check=r=>{n.has(r.value.type)||r.issues.push({code:"invalid_value",values:e.mime,input:r.value.type,inst:t})}}),JRt=_e("$ZodCheckOverwrite",(t,e)=>{wl.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}}),efe=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
`).filter(i=>i),r=Math.min(...n.map(i=>i.length-i.trimStart().length)),o=n.map(i=>i.slice(r)).map(i=>" ".repeat(this.indent*2)+i);for(let i of o)this.content.push(i)}compile(){let e=Function,n=this?.args,r=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...n,r.join(`
`))}},XRt={major:4,minor:0,patch:0},Mr=_e("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=XRt;let r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(let o of r)for(let i of o._zod.onattach)i(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(i,s,a)=>{let l=mB(i),c;for(let u of s){if(u._zod.when){if(!u._zod.when(i))continue}else if(l)continue;let d=i.issues.length,f=u._zod.check(i);if(f instanceof Promise&&a?.async===!1)throw new GP;if(c||f instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await f,i.issues.length!==d&&(l||(l=mB(i,d)))});else{if(i.issues.length===d)continue;l||(l=mB(i,d))}}return c?c.then(()=>i):i};t._zod.run=(i,s)=>{let a=t._zod.parse(i,s);if(a instanceof Promise){if(s.async===!1)throw new GP;return a.then(l=>o(l,r,s))}return o(a,r,s)}}t["~standard"]={validate:o=>{try{let i=_Be(t,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return SBe(t,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),z7=_e("$ZodString",(t,e)=>{Mr.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??CRt(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),Ms=_e("$ZodStringFormat",(t,e)=>{B7.init(t,e),z7.init(t,e)}),QRt=_e("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=cRt),Ms.init(t,e)}),eLt=_e("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=xB(n))}else e.pattern??(e.pattern=xB());Ms.init(t,e)}),tLt=_e("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=uRt),Ms.init(t,e)}),nLt=_e("$ZodURL",(t,e)=>{Ms.init(t,e),t._zod.check=n=>{try{let r=n.value,o=new URL(r),i=o.href;e.hostname&&(e.hostname.lastIndex=0,!e.hostname.test(o.hostname)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:yRt.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,!e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),!r.endsWith("/")&&i.endsWith("/")?n.value=i.slice(0,-1):n.value=i;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),rLt=_e("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=dRt()),Ms.init(t,e)}),oLt=_e("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=aRt),Ms.init(t,e)}),iLt=_e("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=nRt),Ms.init(t,e)}),sLt=_e("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=rRt),Ms.init(t,e)}),aLt=_e("$ZodULID",(t,e)=>{e.pattern??(e.pattern=oRt),Ms.init(t,e)}),lLt=_e("$ZodXID",(t,e)=>{e.pattern??(e.pattern=iRt),Ms.init(t,e)}),cLt=_e("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=sRt),Ms.init(t,e)}),uLt=_e("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=SRt(e)),Ms.init(t,e)}),dLt=_e("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=bRt),Ms.init(t,e)}),fLt=_e("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=xRt(e)),Ms.init(t,e)}),pLt=_e("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=lRt),Ms.init(t,e)}),mLt=_e("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=fRt),Ms.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv4"})}),hLt=_e("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=pRt),Ms.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),gLt=_e("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=mRt),Ms.init(t,e)}),yLt=_e("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=hRt),Ms.init(t,e),t._zod.check=n=>{let[r,o]=n.value.split("/");try{if(!o)throw Error();let i=Number(o);if(`${i}`!==o||i<0||i>128)throw Error();new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});vLt=_e("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=gRt),Ms.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{PBe(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});bLt=_e("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=kBe),Ms.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{wLt(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),_Lt=_e("$ZodE164",(t,e)=>{e.pattern??(e.pattern=vRt),Ms.init(t,e)});SLt=_e("$ZodJWT",(t,e)=>{Ms.init(t,e),t._zod.check=n=>{xLt(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),CLt=_e("$ZodCustomStringFormat",(t,e)=>{Ms.init(t,e),t._zod.check=n=>{e.fn(n.value)||n.issues.push({code:"invalid_format",format:e.format,input:n.value,inst:t,continue:!e.abort})}}),ABe=_e("$ZodNumber",(t,e)=>{Mr.init(t,e),t._zod.pattern=t._zod.bag.pattern??TRt,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}let o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...i?{received:i}:{}}),n}}),kLt=_e("$ZodNumber",(t,e)=>{LRt.init(t,e),ABe.init(t,e)}),EBe=_e("$ZodBoolean",(t,e)=>{Mr.init(t,e),t._zod.pattern=PRt,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}let o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),n}}),MBe=_e("$ZodBigInt",(t,e)=>{Mr.init(t,e),t._zod.pattern=kRt,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=BigInt(n.value)}catch{}return typeof n.value=="bigint"||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:t}),n}}),ILt=_e("$ZodBigInt",(t,e)=>{$Rt.init(t,e),MBe.init(t,e)}),TLt=_e("$ZodSymbol",(t,e)=>{Mr.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;return typeof o=="symbol"||n.issues.push({expected:"symbol",code:"invalid_type",input:o,inst:t}),n}}),PLt=_e("$ZodUndefined",(t,e)=>{Mr.init(t,e),t._zod.pattern=ERt,t._zod.values=new Set([void 0]),t._zod.optin="optional",t._zod.optout="optional",t._zod.parse=(n,r)=>{let o=n.value;return typeof o>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:o,inst:t}),n}}),ALt=_e("$ZodNull",(t,e)=>{Mr.init(t,e),t._zod.pattern=ARt,t._zod.values=new Set([null]),t._zod.parse=(n,r)=>{let o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),n}}),ELt=_e("$ZodAny",(t,e)=>{Mr.init(t,e),t._zod.parse=n=>n}),tfe=_e("$ZodUnknown",(t,e)=>{Mr.init(t,e),t._zod.parse=n=>n}),MLt=_e("$ZodNever",(t,e)=>{Mr.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)}),OLt=_e("$ZodVoid",(t,e)=>{Mr.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;return typeof o>"u"||n.issues.push({expected:"void",code:"invalid_type",input:o,inst:t}),n}}),NLt=_e("$ZodDate",(t,e)=>{Mr.init(t,e),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=new Date(n.value)}catch{}let o=n.value,i=o instanceof Date;return i&&!Number.isNaN(o.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:t}),n}});OBe=_e("$ZodArray",(t,e)=>{Mr.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),n;n.value=Array(o.length);let i=[];for(let s=0;s<o.length;s++){let a=o[s],l=e.element._zod.run({value:a,issues:[]},r);l instanceof Promise?i.push(l.then(c=>gMt(c,n,s))):gMt(l,n,s)}return i.length?Promise.all(i).then(()=>n):n}});NBe=_e("$ZodObject",(t,e)=>{Mr.init(t,e);let n=fpe(()=>{let u=Object.keys(e.shape);for(let f of u)if(!(e.shape[f]instanceof Mr))throw Error(`Invalid element at key "${f}": expected a Zod schema`);let d=GNt(e.shape);return{shape:e.shape,keys:u,keySet:new Set(u),numKeys:u.length,optionalKeys:new Set(d)}});Di(t._zod,"propValues",()=>{let u=e.shape,d={};for(let f in u){let p=u[f]._zod;if(p.values){d[f]??(d[f]=new Set);for(let m of p.values)d[f].add(m)}}return d});let r=u=>{let d=new efe(["shape","payload","ctx"]),f=n.value,p=v=>{let y=cB(v);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};d.write("const input = payload.value;");let m=Object.create(null),h=0;for(let v of f.keys)m[v]=`key_${h++}`;d.write("const newResult = {}");for(let v of f.keys)if(f.optionalKeys.has(v)){let y=m[v];d.write(`const ${y} = ${p(v)};`);let w=cB(v);d.write(`
if (${y}.issues.length) {
if (input[${w}] === undefined) {
if (${w} in input) {
newResult[${w}] = undefined;
}
} else {
payload.issues = payload.issues.concat(
${y}.issues.map((iss) => ({
...iss,
path: iss.path ? [${w}, ...iss.path] : [${w}],
}))
);
}
} else if (${y}.value === undefined) {
if (${w} in input) newResult[${w}] = undefined;
} else {
newResult[${w}] = ${y}.value;
}
`)}else{let y=m[v];d.write(`const ${y} = ${p(v)};`),d.write(`
if (${y}.issues.length) payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
...iss,
path: iss.path ? [${cB(v)}, ...iss.path] : [${cB(v)}]
})));`),d.write(`newResult[${cB(v)}] = ${y}.value`)}d.write("payload.value = newResult;"),d.write("return payload;");let g=d.compile();return(v,y)=>g(u,v,y)},o,i=p7,s=!Yde.jitless,a=s&&qNt.value,l=e.catchall,c;t._zod.parse=(u,d)=>{c??(c=n.value);let f=u.value;if(!i(f))return u.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),u;let p=[];if(s&&a&&d?.async===!1&&d.jitless!==!0)o||(o=r(e.shape)),u=o(u,d);else{u.value={};let y=c.shape;for(let w of c.keys){let _=y[w],S=_._zod.run({value:f[w],issues:[]},d),I=_._zod.optin==="optional"&&_._zod.optout==="optional";S instanceof Promise?p.push(S.then(C=>I?yMt(C,u,w,f):xde(C,u,w))):I?yMt(S,u,w,f):xde(S,u,w)}}if(!l)return p.length?Promise.all(p).then(()=>u):u;let m=[],h=c.keySet,g=l._zod,v=g.def.type;for(let y of Object.keys(f)){if(h.has(y))continue;if(v==="never"){m.push(y);continue}let w=g.run({value:f[y],issues:[]},d);w instanceof Promise?p.push(w.then(_=>xde(_,u,y))):xde(w,u,y)}return m.length&&u.issues.push({code:"unrecognized_keys",keys:m,input:f,inst:t}),p.length?Promise.all(p).then(()=>u):u}});RBe=_e("$ZodUnion",(t,e)=>{Mr.init(t,e),Di(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),Di(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Di(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),Di(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>ppe(r.source)).join("|")})$`)}}),t._zod.parse=(n,r)=>{let o=!1,i=[];for(let s of e.options){let a=s._zod.run({value:n.value,issues:[]},r);if(a instanceof Promise)i.push(a),o=!0;else{if(a.issues.length===0)return a;i.push(a)}}return o?Promise.all(i).then(s=>vMt(s,n,t,r)):vMt(i,n,t,r)}}),RLt=_e("$ZodDiscriminatedUnion",(t,e)=>{RBe.init(t,e);let n=t._zod.parse;Di(t._zod,"propValues",()=>{let o={};for(let i of e.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let[a,l]of Object.entries(s)){o[a]||(o[a]=new Set);for(let c of l)o[a].add(c)}}return o});let r=fpe(()=>{let o=e.options,i=new Map;for(let s of o){let a=s._zod.propValues[e.discriminator];if(!a||a.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let l of a){if(i.has(l))throw Error(`Duplicate discriminator value "${String(l)}"`);i.set(l,s)}}return i});t._zod.parse=(o,i)=>{let s=o.value;if(!p7(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:t}),o;let a=r.value.get(s?.[e.discriminator]);return a?a._zod.run(o,i):e.unionFallback?n(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[e.discriminator],inst:t}),o)}}),LLt=_e("$ZodIntersection",(t,e)=>{Mr.init(t,e),t._zod.parse=(n,r)=>{let o=n.value,i=e.left._zod.run({value:o,issues:[]},r),s=e.right._zod.run({value:o,issues:[]},r);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([a,l])=>wMt(n,a,l)):wMt(n,i,s)}});gpe=_e("$ZodTuple",(t,e)=>{Mr.init(t,e);let n=e.items,r=n.length-[...n].reverse().findIndex(o=>o._zod.optin!=="optional");t._zod.parse=(o,i)=>{let s=o.value;if(!Array.isArray(s))return o.issues.push({input:s,inst:t,expected:"tuple",code:"invalid_type"}),o;o.value=[];let a=[];if(!e.rest){let c=s.length>n.length,u=s.length<r-1;if(c||u)return o.issues.push({input:s,inst:t,origin:"array",...c?{code:"too_big",maximum:n.length}:{code:"too_small",minimum:n.length}}),o}let l=-1;for(let c of n){if(l++,l>=s.length&&l>=r)continue;let u=c._zod.run({value:s[l],issues:[]},i);u instanceof Promise?a.push(u.then(d=>Sde(d,o,l))):Sde(u,o,l)}if(e.rest){let c=s.slice(n.length);for(let u of c){l++;let d=e.rest._zod.run({value:u,issues:[]},i);d instanceof Promise?a.push(d.then(f=>Sde(f,o,l))):Sde(d,o,l)}}return a.length?Promise.all(a).then(()=>o):o}});$Lt=_e("$ZodRecord",(t,e)=>{Mr.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!m7(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let i=[];if(e.keyType._zod.values){let s=e.keyType._zod.values;n.value={};for(let l of s)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){let c=e.valueType._zod.run({value:o[l],issues:[]},r);c instanceof Promise?i.push(c.then(u=>{u.issues.length&&n.issues.push(...Vy(l,u.issues)),n.value[l]=u.value})):(c.issues.length&&n.issues.push(...Vy(l,c.issues)),n.value[l]=c.value)}let a;for(let l in o)s.has(l)||(a=a??[],a.push(l));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{n.value={};for(let s of Reflect.ownKeys(o)){if(s==="__proto__")continue;let a=e.keyType._zod.run({value:s,issues:[]},r);if(a instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(c=>ob(c,r,wp())),input:s,path:[s],inst:t}),n.value[a.value]=a.value;continue}let l=e.valueType._zod.run({value:o[s],issues:[]},r);l instanceof Promise?i.push(l.then(c=>{c.issues.length&&n.issues.push(...Vy(s,c.issues)),n.value[a.value]=c.value})):(l.issues.length&&n.issues.push(...Vy(s,l.issues)),n.value[a.value]=l.value)}}return i.length?Promise.all(i).then(()=>n):n}}),DLt=_e("$ZodMap",(t,e)=>{Mr.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!(o instanceof Map))return n.issues.push({expected:"map",code:"invalid_type",input:o,inst:t}),n;let i=[];n.value=new Map;for(let[s,a]of o){let l=e.keyType._zod.run({value:s,issues:[]},r),c=e.valueType._zod.run({value:a,issues:[]},r);l instanceof Promise||c instanceof Promise?i.push(Promise.all([l,c]).then(([u,d])=>{bMt(u,d,n,s,o,t,r)})):bMt(l,c,n,s,o,t,r)}return i.length?Promise.all(i).then(()=>n):n}});FLt=_e("$ZodSet",(t,e)=>{Mr.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!(o instanceof Set))return n.issues.push({input:o,inst:t,expected:"set",code:"invalid_type"}),n;let i=[];n.value=new Set;for(let s of o){let a=e.valueType._zod.run({value:s,issues:[]},r);a instanceof Promise?i.push(a.then(l=>_Mt(l,n))):_Mt(a,n)}return i.length?Promise.all(i).then(()=>n):n}});ULt=_e("$ZodEnum",(t,e)=>{Mr.init(t,e);let n=fBe(e.entries);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(r=>Jde.has(typeof r)).map(r=>typeof r=="string"?BR(r):r.toString()).join("|")})$`),t._zod.parse=(r,o)=>{let i=r.value;return t._zod.values.has(i)||r.issues.push({code:"invalid_value",values:n,input:i,inst:t}),r}}),jLt=_e("$ZodLiteral",(t,e)=>{Mr.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?BR(n):n?n.toString():String(n)).join("|")})$`),t._zod.parse=(n,r)=>{let o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),n}}),BLt=_e("$ZodFile",(t,e)=>{Mr.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;return o instanceof File||n.issues.push({expected:"file",code:"invalid_type",input:o,inst:t}),n}}),LBe=_e("$ZodTransform",(t,e)=>{Mr.init(t,e),t._zod.parse=(n,r)=>{let o=e.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n));if(o instanceof Promise)throw new GP;return n.value=o,n}}),zLt=_e("$ZodOptional",(t,e)=>{Mr.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Di(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Di(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${ppe(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(n,r):n.value===void 0?n:e.innerType._zod.run(n,r)}),HLt=_e("$ZodNullable",(t,e)=>{Mr.init(t,e),Di(t._zod,"optin",()=>e.innerType._zod.optin),Di(t._zod,"optout",()=>e.innerType._zod.optout),Di(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${ppe(n.source)}|null)$`):void 0}),Di(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),WLt=_e("$ZodDefault",(t,e)=>{Mr.init(t,e),t._zod.optin="optional",Di(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=e.defaultValue,n;let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>xMt(i,e)):xMt(o,e)}});VLt=_e("$ZodPrefault",(t,e)=>{Mr.init(t,e),t._zod.optin="optional",Di(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),qLt=_e("$ZodNonOptional",(t,e)=>{Mr.init(t,e),Di(t._zod,"values",()=>{let n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>SMt(i,t)):SMt(o,t)}});KLt=_e("$ZodSuccess",(t,e)=>{Mr.init(t,e),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>(n.value=i.issues.length===0,n)):(n.value=o.issues.length===0,n)}}),GLt=_e("$ZodCatch",(t,e)=>{Mr.init(t,e),t._zod.optin="optional",Di(t._zod,"optout",()=>e.innerType._zod.optout),Di(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>(n.value=i.value,i.issues.length&&(n.value=e.catchValue({...n,error:{issues:i.issues.map(s=>ob(s,r,wp()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(i=>ob(i,r,wp()))},input:n.value}),n.issues=[]),n)}}),ZLt=_e("$ZodNaN",(t,e)=>{Mr.init(t,e),t._zod.parse=(n,r)=>((typeof n.value!="number"||!Number.isNaN(n.value))&&n.issues.push({input:n.value,inst:t,expected:"nan",code:"invalid_type"}),n)}),$Be=_e("$ZodPipe",(t,e)=>{Mr.init(t,e),Di(t._zod,"values",()=>e.in._zod.values),Di(t._zod,"optin",()=>e.in._zod.optin),Di(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(n,r)=>{let o=e.in._zod.run(n,r);return o instanceof Promise?o.then(i=>CMt(i,e,r)):CMt(o,e,r)}});YLt=_e("$ZodReadonly",(t,e)=>{Mr.init(t,e),Di(t._zod,"propValues",()=>e.innerType._zod.propValues),Di(t._zod,"values",()=>e.innerType._zod.values),Di(t._zod,"optin",()=>e.innerType._zod.optin),Di(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(kMt):kMt(o)}});JLt=_e("$ZodTemplateLiteral",(t,e)=>{Mr.init(t,e);let n=[];for(let r of e.parts)if(r instanceof Mr){if(!r._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...r._zod.traits].shift()}`);let o=r._zod.pattern instanceof RegExp?r._zod.pattern.source:r._zod.pattern;if(!o)throw Error(`Invalid template literal part: ${r._zod.traits}`);let i=o.startsWith("^")?1:0,s=o.endsWith("$")?o.length-1:o.length;n.push(o.slice(i,s))}else if(r===null||KNt.has(typeof r))n.push(BR(`${r}`));else throw Error(`Invalid template literal part: ${r}`);t._zod.pattern=new RegExp(`^${n.join("")}$`),t._zod.parse=(r,o)=>typeof r.value!="string"?(r.issues.push({input:r.value,inst:t,expected:"template_literal",code:"invalid_type"}),r):(t._zod.pattern.lastIndex=0,t._zod.pattern.test(r.value)||r.issues.push({input:r.value,inst:t,code:"invalid_format",format:"template_literal",pattern:t._zod.pattern.source}),r)}),XLt=_e("$ZodPromise",(t,e)=>{Mr.init(t,e),t._zod.parse=(n,r)=>Promise.resolve(n.value).then(o=>e.innerType._zod.run({value:o,issues:[]},r))}),QLt=_e("$ZodLazy",(t,e)=>{Mr.init(t,e),Di(t._zod,"innerType",()=>e.getter()),Di(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),Di(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),Di(t._zod,"optin",()=>t._zod.innerType._zod.optin),Di(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(n,r)=>t._zod.innerType._zod.run(n,r)}),e1t=_e("$ZodCustom",(t,e)=>{wl.init(t,e),Mr.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{let r=n.value,o=e.fn(r);if(o instanceof Promise)return o.then(i=>IMt(i,n,r,t));IMt(o,n,r,t)}});DBe={};_x(DBe,{zhTW:()=>GVn,zhCN:()=>qVn,vi:()=>WVn,ur:()=>zVn,ua:()=>jVn,tr:()=>FVn,th:()=>LVn,ta:()=>NVn,sv:()=>MVn,sl:()=>AVn,ru:()=>TVn,pt:()=>kVn,ps:()=>_Vn,pl:()=>SVn,ota:()=>wVn,no:()=>yVn,nl:()=>hVn,ms:()=>pVn,mk:()=>dVn,ko:()=>cVn,kh:()=>aVn,ja:()=>iVn,it:()=>rVn,id:()=>tVn,hu:()=>Q6n,he:()=>J6n,frCA:()=>Z6n,fr:()=>K6n,fi:()=>V6n,fa:()=>H6n,es:()=>B6n,eo:()=>U6n,en:()=>t1t,de:()=>R6n,cs:()=>O6n,ca:()=>E6n,be:()=>P6n,az:()=>I6n,ar:()=>C6n});S6n=()=>{let t={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"number";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"};return o=>{switch(o.code){case"invalid_type":return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${o.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${to(o.values[0])}`:`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${o.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${i} ${o.maximum.toString()} ${s.unit??"\u0639\u0646\u0635\u0631"}`:`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${o.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${i} ${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${o.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${i} ${o.minimum.toString()} ${s.unit}`:`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${o.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${i} ${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${o.prefix}"`:i.format==="ends_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${i.suffix}"`:i.format==="includes"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${i.includes}"`:i.format==="regex"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${i.pattern}`:`${r[i.format]??o.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${o.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${o.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${o.keys.length>1?"\u0629":""}: ${Ot(o.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${o.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${o.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}};k6n=()=>{let t={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"number";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return o=>{switch(o.code){case"invalid_type":return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${o.expected}, daxil olan ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${to(o.values[0])}`:`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${o.origin??"d\u0259y\u0259r"} ${i}${o.maximum.toString()} ${s.unit??"element"}`:`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${o.origin??"d\u0259y\u0259r"} ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${o.origin} ${i}${o.minimum.toString()} ${s.unit}`:`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${o.origin} ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Yanl\u0131\u015F m\u0259tn: "${i.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`:i.format==="ends_with"?`Yanl\u0131\u015F m\u0259tn: "${i.suffix}" il\u0259 bitm\u0259lidir`:i.format==="includes"?`Yanl\u0131\u015F m\u0259tn: "${i.includes}" daxil olmal\u0131d\u0131r`:i.format==="regex"?`Yanl\u0131\u015F m\u0259tn: ${i.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`:`Yanl\u0131\u015F ${r[i.format]??o.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${o.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${o.keys.length>1?"lar":""}: ${Ot(o.keys,", ")}`;case"invalid_key":return`${o.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${o.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}}};T6n=()=>{let t={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"\u043B\u0456\u043A";case"object":{if(Array.isArray(o))return"\u043C\u0430\u0441\u0456\u045E";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"};return o=>{switch(o.code){case"invalid_type":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${o.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${to(o.values[0])}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);if(s){let a=Number(o.maximum),l=TMt(a,s.unit.one,s.unit.few,s.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${s.verb} ${i}${o.maximum.toString()} ${l}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);if(s){let a=Number(o.minimum),l=TMt(a,s.unit.one,s.unit.few,s.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${o.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${s.verb} ${i}${o.minimum.toString()} ${l}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${o.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${i.prefix}"`:i.format==="ends_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${i.suffix}"`:i.format==="includes"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${i.includes}"`:i.format==="regex"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${i.pattern}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${r[i.format]??o.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${o.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${o.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${Ot(o.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${o.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${o.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}}};A6n=()=>{let t={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"number";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"entrada",email:"adre\xE7a electr\xF2nica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adre\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};return o=>{switch(o.code){case"invalid_type":return`Tipus inv\xE0lid: s'esperava ${o.expected}, s'ha rebut ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Valor inv\xE0lid: s'esperava ${to(o.values[0])}`:`Opci\xF3 inv\xE0lida: s'esperava una de ${Ot(o.values," o ")}`;case"too_big":{let i=o.inclusive?"com a m\xE0xim":"menys de",s=e(o.origin);return s?`Massa gran: s'esperava que ${o.origin??"el valor"} contingu\xE9s ${i} ${o.maximum.toString()} ${s.unit??"elements"}`:`Massa gran: s'esperava que ${o.origin??"el valor"} fos ${i} ${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?"com a m\xEDnim":"m\xE9s de",s=e(o.origin);return s?`Massa petit: s'esperava que ${o.origin} contingu\xE9s ${i} ${o.minimum.toString()} ${s.unit}`:`Massa petit: s'esperava que ${o.origin} fos ${i} ${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Format inv\xE0lid: ha de comen\xE7ar amb "${i.prefix}"`:i.format==="ends_with"?`Format inv\xE0lid: ha d'acabar amb "${i.suffix}"`:i.format==="includes"?`Format inv\xE0lid: ha d'incloure "${i.includes}"`:i.format==="regex"?`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${i.pattern}`:`Format inv\xE0lid per a ${r[i.format]??o.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${o.divisor}`;case"unrecognized_keys":return`Clau${o.keys.length>1?"s":""} no reconeguda${o.keys.length>1?"s":""}: ${Ot(o.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${o.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${o.origin}`;default:return"Entrada inv\xE0lida"}}};M6n=()=>{let t={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"\u010D\xEDslo";case"string":return"\u0159et\u011Bzec";case"boolean":return"boolean";case"bigint":return"bigint";case"function":return"funkce";case"symbol":return"symbol";case"undefined":return"undefined";case"object":{if(Array.isArray(o))return"pole";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"};return o=>{switch(o.code){case"invalid_type":return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${o.expected}, obdr\u017Eeno ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${to(o.values[0])}`:`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${o.origin??"hodnota"} mus\xED m\xEDt ${i}${o.maximum.toString()} ${s.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${o.origin??"hodnota"} mus\xED b\xFDt ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${o.origin??"hodnota"} mus\xED m\xEDt ${i}${o.minimum.toString()} ${s.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${o.origin??"hodnota"} mus\xED b\xFDt ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${i.prefix}"`:i.format==="ends_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${i.suffix}"`:i.format==="includes"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${i.includes}"`:i.format==="regex"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${i.pattern}`:`Neplatn\xFD form\xE1t ${r[i.format]??o.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${o.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${Ot(o.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${o.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${o.origin}`;default:return"Neplatn\xFD vstup"}}};N6n=()=>{let t={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"Zahl";case"object":{if(Array.isArray(o))return"Array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"};return o=>{switch(o.code){case"invalid_type":return`Ung\xFCltige Eingabe: erwartet ${o.expected}, erhalten ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Ung\xFCltige Eingabe: erwartet ${to(o.values[0])}`:`Ung\xFCltige Option: erwartet eine von ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Zu gro\xDF: erwartet, dass ${o.origin??"Wert"} ${i}${o.maximum.toString()} ${s.unit??"Elemente"} hat`:`Zu gro\xDF: erwartet, dass ${o.origin??"Wert"} ${i}${o.maximum.toString()} ist`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Zu klein: erwartet, dass ${o.origin} ${i}${o.minimum.toString()} ${s.unit} hat`:`Zu klein: erwartet, dass ${o.origin} ${i}${o.minimum.toString()} ist`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Ung\xFCltiger String: muss mit "${i.prefix}" beginnen`:i.format==="ends_with"?`Ung\xFCltiger String: muss mit "${i.suffix}" enden`:i.format==="includes"?`Ung\xFCltiger String: muss "${i.includes}" enthalten`:i.format==="regex"?`Ung\xFCltiger String: muss dem Muster ${i.pattern} entsprechen`:`Ung\xFCltig: ${r[i.format]??o.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${o.divisor} sein`;case"unrecognized_keys":return`${o.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${Ot(o.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${o.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${o.origin}`;default:return"Ung\xFCltige Eingabe"}}};L6n=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},$6n=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(r){return t[r]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Invalid input: expected ${r.expected}, received ${L6n(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${to(r.values[0])}`:`Invalid option: expected one of ${Ot(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",i=e(r.origin);return i?`Too big: expected ${r.origin??"value"} to have ${o}${r.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",i=e(r.origin);return i?`Too small: expected ${r.origin} to have ${o}${r.minimum.toString()} ${i.unit}`:`Too small: expected ${r.origin} to be ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${n[o.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${Ot(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};D6n=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"nombro";case"object":{if(Array.isArray(t))return"tabelo";if(t===null)return"senvalora";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},F6n=()=>{let t={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function e(r){return t[r]??null}let n={regex:"enigo",email:"retadreso",url:"URL",emoji:"emo\u011Dio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-da\u016Dro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"};return r=>{switch(r.code){case"invalid_type":return`Nevalida enigo: atendi\u011Dis ${r.expected}, ricevi\u011Dis ${D6n(r.input)}`;case"invalid_value":return r.values.length===1?`Nevalida enigo: atendi\u011Dis ${to(r.values[0])}`:`Nevalida opcio: atendi\u011Dis unu el ${Ot(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",i=e(r.origin);return i?`Tro granda: atendi\u011Dis ke ${r.origin??"valoro"} havu ${o}${r.maximum.toString()} ${i.unit??"elementojn"}`:`Tro granda: atendi\u011Dis ke ${r.origin??"valoro"} havu ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",i=e(r.origin);return i?`Tro malgranda: atendi\u011Dis ke ${r.origin} havu ${o}${r.minimum.toString()} ${i.unit}`:`Tro malgranda: atendi\u011Dis ke ${r.origin} estu ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Nevalida karaktraro: devas komenci\u011Di per "${o.prefix}"`:o.format==="ends_with"?`Nevalida karaktraro: devas fini\u011Di per "${o.suffix}"`:o.format==="includes"?`Nevalida karaktraro: devas inkluzivi "${o.includes}"`:o.format==="regex"?`Nevalida karaktraro: devas kongrui kun la modelo ${o.pattern}`:`Nevalida ${n[o.format]??r.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${r.divisor}`;case"unrecognized_keys":return`Nekonata${r.keys.length>1?"j":""} \u015Dlosilo${r.keys.length>1?"j":""}: ${Ot(r.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${r.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${r.origin}`;default:return"Nevalida enigo"}}};j6n=()=>{let t={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"n\xFAmero";case"object":{if(Array.isArray(o))return"arreglo";if(o===null)return"nulo";if(Object.getPrototypeOf(o)!==Object.prototype)return o.constructor.name}}return i},r={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duraci\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};return o=>{switch(o.code){case"invalid_type":return`Entrada inv\xE1lida: se esperaba ${o.expected}, recibido ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Entrada inv\xE1lida: se esperaba ${to(o.values[0])}`:`Opci\xF3n inv\xE1lida: se esperaba una de ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Demasiado grande: se esperaba que ${o.origin??"valor"} tuviera ${i}${o.maximum.toString()} ${s.unit??"elementos"}`:`Demasiado grande: se esperaba que ${o.origin??"valor"} fuera ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Demasiado peque\xF1o: se esperaba que ${o.origin} tuviera ${i}${o.minimum.toString()} ${s.unit}`:`Demasiado peque\xF1o: se esperaba que ${o.origin} fuera ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Cadena inv\xE1lida: debe comenzar con "${i.prefix}"`:i.format==="ends_with"?`Cadena inv\xE1lida: debe terminar en "${i.suffix}"`:i.format==="includes"?`Cadena inv\xE1lida: debe incluir "${i.includes}"`:i.format==="regex"?`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${i.pattern}`:`Inv\xE1lido ${r[i.format]??o.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${o.divisor}`;case"unrecognized_keys":return`Llave${o.keys.length>1?"s":""} desconocida${o.keys.length>1?"s":""}: ${Ot(o.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${o.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${o.origin}`;default:return"Entrada inv\xE1lida"}}};z6n=()=>{let t={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"\u0639\u062F\u062F";case"object":{if(Array.isArray(o))return"\u0622\u0631\u0627\u06CC\u0647";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"};return o=>{switch(o.code){case"invalid_type":return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${o.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${n(o.input)} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;case"invalid_value":return o.values.length===1?`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${to(o.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`:`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${Ot(o.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${o.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${i}${o.maximum.toString()} ${s.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${o.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${i}${o.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${o.origin} \u0628\u0627\u06CC\u062F ${i}${o.minimum.toString()} ${s.unit} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${o.origin} \u0628\u0627\u06CC\u062F ${i}${o.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${i.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`:i.format==="ends_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${i.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`:i.format==="includes"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${i.includes}" \u0628\u0627\u0634\u062F`:i.format==="regex"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${i.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`:`${r[i.format]??o.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${o.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${o.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${Ot(o.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${o.origin}`;case"invalid_union":return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${o.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}}};W6n=()=>{let t={string:{unit:"merkki\xE4",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"p\xE4iv\xE4m\xE4\xE4r\xE4n"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"number";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"};return o=>{switch(o.code){case"invalid_type":return`Virheellinen tyyppi: odotettiin ${o.expected}, oli ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Virheellinen sy\xF6te: t\xE4ytyy olla ${to(o.values[0])}`:`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Liian suuri: ${s.subject} t\xE4ytyy olla ${i}${o.maximum.toString()} ${s.unit}`.trim():`Liian suuri: arvon t\xE4ytyy olla ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Liian pieni: ${s.subject} t\xE4ytyy olla ${i}${o.minimum.toString()} ${s.unit}`.trim():`Liian pieni: arvon t\xE4ytyy olla ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${i.prefix}"`:i.format==="ends_with"?`Virheellinen sy\xF6te: t\xE4ytyy loppua "${i.suffix}"`:i.format==="includes"?`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${i.includes}"`:i.format==="regex"?`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${i.pattern}`:`Virheellinen ${r[i.format]??o.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${o.divisor} monikerta`;case"unrecognized_keys":return`${o.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${Ot(o.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen sy\xF6te"}}};q6n=()=>{let t={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"nombre";case"object":{if(Array.isArray(o))return"tableau";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"entr\xE9e",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"};return o=>{switch(o.code){case"invalid_type":return`Entr\xE9e invalide : ${o.expected} attendu, ${n(o.input)} re\xE7u`;case"invalid_value":return o.values.length===1?`Entr\xE9e invalide : ${to(o.values[0])} attendu`:`Option invalide : une valeur parmi ${Ot(o.values,"|")} attendue`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Trop grand : ${o.origin??"valeur"} doit ${s.verb} ${i}${o.maximum.toString()} ${s.unit??"\xE9l\xE9ment(s)"}`:`Trop grand : ${o.origin??"valeur"} doit \xEAtre ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Trop petit : ${o.origin} doit ${s.verb} ${i}${o.minimum.toString()} ${s.unit}`:`Trop petit : ${o.origin} doit \xEAtre ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${i.prefix}"`:i.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${i.suffix}"`:i.format==="includes"?`Cha\xEEne invalide : doit inclure "${i.includes}"`:i.format==="regex"?`Cha\xEEne invalide : doit correspondre au mod\xE8le ${i.pattern}`:`${r[i.format]??o.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${o.divisor}`;case"unrecognized_keys":return`Cl\xE9${o.keys.length>1?"s":""} non reconnue${o.keys.length>1?"s":""} : ${Ot(o.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${o.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${o.origin}`;default:return"Entr\xE9e invalide"}}};G6n=()=>{let t={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"number";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"entr\xE9e",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"};return o=>{switch(o.code){case"invalid_type":return`Entr\xE9e invalide : attendu ${o.expected}, re\xE7u ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Entr\xE9e invalide : attendu ${to(o.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"\u2264":"<",s=e(o.origin);return s?`Trop grand : attendu que ${o.origin??"la valeur"} ait ${i}${o.maximum.toString()} ${s.unit}`:`Trop grand : attendu que ${o.origin??"la valeur"} soit ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?"\u2265":">",s=e(o.origin);return s?`Trop petit : attendu que ${o.origin} ait ${i}${o.minimum.toString()} ${s.unit}`:`Trop petit : attendu que ${o.origin} soit ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${i.prefix}"`:i.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${i.suffix}"`:i.format==="includes"?`Cha\xEEne invalide : doit inclure "${i.includes}"`:i.format==="regex"?`Cha\xEEne invalide : doit correspondre au motif ${i.pattern}`:`${r[i.format]??o.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${o.divisor}`;case"unrecognized_keys":return`Cl\xE9${o.keys.length>1?"s":""} non reconnue${o.keys.length>1?"s":""} : ${Ot(o.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${o.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${o.origin}`;default:return"Entr\xE9e invalide"}}};Y6n=()=>{let t={string:{unit:"\u05D0\u05D5\u05EA\u05D9\u05D5\u05EA",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"number";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u05E7\u05DC\u05D8",email:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",url:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",emoji:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",date:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",time:"\u05D6\u05DE\u05DF ISO",duration:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",ipv4:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",ipv6:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",cidrv4:"\u05D8\u05D5\u05D5\u05D7 IPv4",cidrv6:"\u05D8\u05D5\u05D5\u05D7 IPv6",base64:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",base64url:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",json_string:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",e164:"\u05DE\u05E1\u05E4\u05E8 E.164",jwt:"JWT",template_literal:"\u05E7\u05DC\u05D8"};return o=>{switch(o.code){case"invalid_type":return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${o.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${to(o.values[0])}`:`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05D0\u05D7\u05EA \u05DE\u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${o.origin??"value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${i}${o.maximum.toString()} ${s.unit??"elements"}`:`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${o.origin??"value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${o.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${i}${o.minimum.toString()} ${s.unit}`:`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${o.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1"${i.prefix}"`:i.format==="ends_with"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${i.suffix}"`:i.format==="includes"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${i.includes}"`:i.format==="regex"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${i.pattern}`:`${r[i.format]??o.format} \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${o.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${o.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${o.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${Ot(o.keys,", ")}`;case"invalid_key":return`\u05DE\u05E4\u05EA\u05D7 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${o.origin}`;case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${o.origin}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}}};X6n=()=>{let t={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"sz\xE1m";case"object":{if(Array.isArray(o))return"t\xF6mb";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"bemenet",email:"email c\xEDm",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO id\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"};return o=>{switch(o.code){case"invalid_type":return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${o.expected}, a kapott \xE9rt\xE9k ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${to(o.values[0])}`:`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`T\xFAl nagy: ${o.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${i}${o.maximum.toString()} ${s.unit??"elem"}`:`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${o.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${o.origin} m\xE9rete t\xFAl kicsi ${i}${o.minimum.toString()} ${s.unit}`:`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${o.origin} t\xFAl kicsi ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\xC9rv\xE9nytelen string: "${i.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`:i.format==="ends_with"?`\xC9rv\xE9nytelen string: "${i.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`:i.format==="includes"?`\xC9rv\xE9nytelen string: "${i.includes}" \xE9rt\xE9ket kell tartalmaznia`:i.format==="regex"?`\xC9rv\xE9nytelen string: ${i.pattern} mint\xE1nak kell megfelelnie`:`\xC9rv\xE9nytelen ${r[i.format]??o.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${o.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${o.keys.length>1?"s":""}: ${Ot(o.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${o.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${o.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}}};eVn=()=>{let t={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"number";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"};return o=>{switch(o.code){case"invalid_type":return`Input tidak valid: diharapkan ${o.expected}, diterima ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Input tidak valid: diharapkan ${to(o.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Terlalu besar: diharapkan ${o.origin??"value"} memiliki ${i}${o.maximum.toString()} ${s.unit??"elemen"}`:`Terlalu besar: diharapkan ${o.origin??"value"} menjadi ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Terlalu kecil: diharapkan ${o.origin} memiliki ${i}${o.minimum.toString()} ${s.unit}`:`Terlalu kecil: diharapkan ${o.origin} menjadi ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`String tidak valid: harus dimulai dengan "${i.prefix}"`:i.format==="ends_with"?`String tidak valid: harus berakhir dengan "${i.suffix}"`:i.format==="includes"?`String tidak valid: harus menyertakan "${i.includes}"`:i.format==="regex"?`String tidak valid: harus sesuai pola ${i.pattern}`:`${r[i.format]??o.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${o.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${o.keys.length>1?"s":""}: ${Ot(o.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${o.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${o.origin}`;default:return"Input tidak valid"}}};nVn=()=>{let t={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"numero";case"object":{if(Array.isArray(o))return"vettore";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"};return o=>{switch(o.code){case"invalid_type":return`Input non valido: atteso ${o.expected}, ricevuto ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Input non valido: atteso ${to(o.values[0])}`:`Opzione non valida: atteso uno tra ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Troppo grande: ${o.origin??"valore"} deve avere ${i}${o.maximum.toString()} ${s.unit??"elementi"}`:`Troppo grande: ${o.origin??"valore"} deve essere ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Troppo piccolo: ${o.origin} deve avere ${i}${o.minimum.toString()} ${s.unit}`:`Troppo piccolo: ${o.origin} deve essere ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Stringa non valida: deve iniziare con "${i.prefix}"`:i.format==="ends_with"?`Stringa non valida: deve terminare con "${i.suffix}"`:i.format==="includes"?`Stringa non valida: deve includere "${i.includes}"`:i.format==="regex"?`Stringa non valida: deve corrispondere al pattern ${i.pattern}`:`Invalid ${r[i.format]??o.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${o.divisor}`;case"unrecognized_keys":return`Chiav${o.keys.length>1?"i":"e"} non riconosciut${o.keys.length>1?"e":"a"}: ${Ot(o.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${o.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${o.origin}`;default:return"Input non valido"}}};oVn=()=>{let t={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"\u6570\u5024";case"object":{if(Array.isArray(o))return"\u914D\u5217";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"};return o=>{switch(o.code){case"invalid_type":return`\u7121\u52B9\u306A\u5165\u529B: ${o.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${n(o.input)}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;case"invalid_value":return o.values.length===1?`\u7121\u52B9\u306A\u5165\u529B: ${to(o.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`:`\u7121\u52B9\u306A\u9078\u629E: ${Ot(o.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let i=o.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",s=e(o.origin);return s?`\u5927\u304D\u3059\u304E\u308B\u5024: ${o.origin??"\u5024"}\u306F${o.maximum.toString()}${s.unit??"\u8981\u7D20"}${i}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5927\u304D\u3059\u304E\u308B\u5024: ${o.origin??"\u5024"}\u306F${o.maximum.toString()}${i}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let i=o.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",s=e(o.origin);return s?`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${o.origin}\u306F${o.minimum.toString()}${s.unit}${i}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${o.origin}\u306F${o.minimum.toString()}${i}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${i.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:i.format==="ends_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${i.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:i.format==="includes"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${i.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:i.format==="regex"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${i.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u7121\u52B9\u306A${r[i.format]??o.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${o.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${o.keys.length>1?"\u7FA4":""}: ${Ot(o.keys,"\u3001")}`;case"invalid_key":return`${o.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${o.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}}};sVn=()=>{let t={string:{unit:"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},file:{unit:"\u1794\u17C3",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},array:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},set:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"\u1798\u17B7\u1793\u1798\u17C2\u1793\u1787\u17B6\u179B\u17C1\u1781 (NaN)":"\u179B\u17C1\u1781";case"object":{if(Array.isArray(o))return"\u17A2\u17B6\u179A\u17C1 (Array)";if(o===null)return"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",email:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",url:"URL",emoji:"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",date:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",time:"\u1798\u17C9\u17C4\u1784 ISO",duration:"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",ipv4:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",ipv6:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",cidrv4:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",cidrv6:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",base64:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",base64url:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",json_string:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",e164:"\u179B\u17C1\u1781 E.164",jwt:"JWT",template_literal:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"};return o=>{switch(o.code){case"invalid_type":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${to(o.values[0])}`:`\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${i} ${o.maximum.toString()} ${s.unit??"\u1792\u17B6\u178F\u17BB"}`:`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${i} ${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o.origin} ${i} ${o.minimum.toString()} ${s.unit}`:`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o.origin} ${i} ${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${i.prefix}"`:i.format==="ends_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${i.suffix}"`:i.format==="includes"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${i.includes}"`:i.format==="regex"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${i.pattern}`:`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${r[i.format]??o.format}`}case"not_multiple_of":return`\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${o.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${Ot(o.keys,", ")}`;case"invalid_key":return`\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${o.origin}`;case"invalid_union":return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C";case"invalid_element":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${o.origin}`;default:return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C"}}};lVn=()=>{let t={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"number";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"};return o=>{switch(o.code){case"invalid_type":return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${o.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${n(o.input)}\uC785\uB2C8\uB2E4`;case"invalid_value":return o.values.length===1?`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${to(o.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C \uC635\uC158: ${Ot(o.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let i=o.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",s=i==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",a=e(o.origin),l=a?.unit??"\uC694\uC18C";return a?`${o.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${o.maximum.toString()}${l} ${i}${s}`:`${o.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${o.maximum.toString()} ${i}${s}`}case"too_small":{let i=o.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",s=i==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",a=e(o.origin),l=a?.unit??"\uC694\uC18C";return a?`${o.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${o.minimum.toString()}${l} ${i}${s}`:`${o.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${o.minimum.toString()} ${i}${s}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${i.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`:i.format==="ends_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${i.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`:i.format==="includes"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${i.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`:i.format==="regex"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${i.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C ${r[i.format]??o.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${o.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${Ot(o.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${o.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${o.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}}};uVn=()=>{let t={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"\u0431\u0440\u043E\u0458";case"object":{if(Array.isArray(o))return"\u043D\u0438\u0437\u0430";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"};return o=>{switch(o.code){case"invalid_type":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${o.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Invalid input: expected ${to(o.values[0])}`:`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${o.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${i}${o.maximum.toString()} ${s.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${o.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${o.origin} \u0434\u0430 \u0438\u043C\u0430 ${i}${o.minimum.toString()} ${s.unit}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${o.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${i.prefix}"`:i.format==="ends_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${i.suffix}"`:i.format==="includes"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${i.includes}"`:i.format==="regex"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${i.pattern}`:`Invalid ${r[i.format]??o.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${o.divisor}`;case"unrecognized_keys":return`${o.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${Ot(o.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${o.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${o.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}}};fVn=()=>{let t={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"nombor";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"};return o=>{switch(o.code){case"invalid_type":return`Input tidak sah: dijangka ${o.expected}, diterima ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Input tidak sah: dijangka ${to(o.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Terlalu besar: dijangka ${o.origin??"nilai"} ${s.verb} ${i}${o.maximum.toString()} ${s.unit??"elemen"}`:`Terlalu besar: dijangka ${o.origin??"nilai"} adalah ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Terlalu kecil: dijangka ${o.origin} ${s.verb} ${i}${o.minimum.toString()} ${s.unit}`:`Terlalu kecil: dijangka ${o.origin} adalah ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`String tidak sah: mesti bermula dengan "${i.prefix}"`:i.format==="ends_with"?`String tidak sah: mesti berakhir dengan "${i.suffix}"`:i.format==="includes"?`String tidak sah: mesti mengandungi "${i.includes}"`:i.format==="regex"?`String tidak sah: mesti sepadan dengan corak ${i.pattern}`:`${r[i.format]??o.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${o.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${Ot(o.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${o.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${o.origin}`;default:return"Input tidak sah"}}};mVn=()=>{let t={string:{unit:"tekens"},file:{unit:"bytes"},array:{unit:"elementen"},set:{unit:"elementen"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"getal";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"};return o=>{switch(o.code){case"invalid_type":return`Ongeldige invoer: verwacht ${o.expected}, ontving ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Ongeldige invoer: verwacht ${to(o.values[0])}`:`Ongeldige optie: verwacht \xE9\xE9n van ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Te lang: verwacht dat ${o.origin??"waarde"} ${i}${o.maximum.toString()} ${s.unit??"elementen"} bevat`:`Te lang: verwacht dat ${o.origin??"waarde"} ${i}${o.maximum.toString()} is`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Te kort: verwacht dat ${o.origin} ${i}${o.minimum.toString()} ${s.unit} bevat`:`Te kort: verwacht dat ${o.origin} ${i}${o.minimum.toString()} is`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Ongeldige tekst: moet met "${i.prefix}" beginnen`:i.format==="ends_with"?`Ongeldige tekst: moet op "${i.suffix}" eindigen`:i.format==="includes"?`Ongeldige tekst: moet "${i.includes}" bevatten`:i.format==="regex"?`Ongeldige tekst: moet overeenkomen met patroon ${i.pattern}`:`Ongeldig: ${r[i.format]??o.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${o.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${o.keys.length>1?"s":""}: ${Ot(o.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${o.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${o.origin}`;default:return"Ongeldige invoer"}}};gVn=()=>{let t={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"tall";case"object":{if(Array.isArray(o))return"liste";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return o=>{switch(o.code){case"invalid_type":return`Ugyldig input: forventet ${o.expected}, fikk ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Ugyldig verdi: forventet ${to(o.values[0])}`:`Ugyldig valg: forventet en av ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`For stor(t): forventet ${o.origin??"value"} til \xE5 ha ${i}${o.maximum.toString()} ${s.unit??"elementer"}`:`For stor(t): forventet ${o.origin??"value"} til \xE5 ha ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`For lite(n): forventet ${o.origin} til \xE5 ha ${i}${o.minimum.toString()} ${s.unit}`:`For lite(n): forventet ${o.origin} til \xE5 ha ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Ugyldig streng: m\xE5 starte med "${i.prefix}"`:i.format==="ends_with"?`Ugyldig streng: m\xE5 ende med "${i.suffix}"`:i.format==="includes"?`Ugyldig streng: m\xE5 inneholde "${i.includes}"`:i.format==="regex"?`Ugyldig streng: m\xE5 matche m\xF8nsteret ${i.pattern}`:`Ugyldig ${r[i.format]??o.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${o.divisor}`;case"unrecognized_keys":return`${o.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${Ot(o.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${o.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${o.origin}`;default:return"Ugyldig input"}}};vVn=()=>{let t={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"numara";case"object":{if(Array.isArray(o))return"saf";if(o===null)return"gayb";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"giren",email:"epostag\xE2h",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO heng\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"};return o=>{switch(o.code){case"invalid_type":return`F\xE2sit giren: umulan ${o.expected}, al\u0131nan ${n(o.input)}`;case"invalid_value":return o.values.length===1?`F\xE2sit giren: umulan ${to(o.values[0])}`:`F\xE2sit tercih: m\xFBteberler ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Fazla b\xFCy\xFCk: ${o.origin??"value"}, ${i}${o.maximum.toString()} ${s.unit??"elements"} sahip olmal\u0131yd\u0131.`:`Fazla b\xFCy\xFCk: ${o.origin??"value"}, ${i}${o.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Fazla k\xFC\xE7\xFCk: ${o.origin}, ${i}${o.minimum.toString()} ${s.unit} sahip olmal\u0131yd\u0131.`:`Fazla k\xFC\xE7\xFCk: ${o.origin}, ${i}${o.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let i=o;return i.format==="starts_with"?`F\xE2sit metin: "${i.prefix}" ile ba\u015Flamal\u0131.`:i.format==="ends_with"?`F\xE2sit metin: "${i.suffix}" ile bitmeli.`:i.format==="includes"?`F\xE2sit metin: "${i.includes}" ihtiv\xE2 etmeli.`:i.format==="regex"?`F\xE2sit metin: ${i.pattern} nak\u015F\u0131na uymal\u0131.`:`F\xE2sit ${r[i.format]??o.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${o.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${o.keys.length>1?"s":""}: ${Ot(o.keys,", ")}`;case"invalid_key":return`${o.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${o.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}}};bVn=()=>{let t={string:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},file:{unit:"\u0628\u0627\u06CC\u067C\u0633",verb:"\u0648\u0644\u0631\u064A"},array:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},set:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"\u0639\u062F\u062F";case"object":{if(Array.isArray(o))return"\u0627\u0631\u06D0";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0648\u0631\u0648\u062F\u064A",email:"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",url:"\u06CC\u0648 \u0622\u0631 \u0627\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",date:"\u0646\u06D0\u067C\u0647",time:"\u0648\u062E\u062A",duration:"\u0645\u0648\u062F\u0647",ipv4:"\u062F IPv4 \u067E\u062A\u0647",ipv6:"\u062F IPv6 \u067E\u062A\u0647",cidrv4:"\u062F IPv4 \u0633\u0627\u062D\u0647",cidrv6:"\u062F IPv6 \u0633\u0627\u062D\u0647",base64:"base64-encoded \u0645\u062A\u0646",base64url:"base64url-encoded \u0645\u062A\u0646",json_string:"JSON \u0645\u062A\u0646",e164:"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u064A"};return o=>{switch(o.code){case"invalid_type":return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${o.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${n(o.input)} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;case"invalid_value":return o.values.length===1?`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${to(o.values[0])} \u0648\u0627\u06CC`:`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${Ot(o.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${o.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${i}${o.maximum.toString()} ${s.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${o.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${i}${o.maximum.toString()} \u0648\u064A`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${o.origin} \u0628\u0627\u06CC\u062F ${i}${o.minimum.toString()} ${s.unit} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${o.origin} \u0628\u0627\u06CC\u062F ${i}${o.minimum.toString()} \u0648\u064A`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${i.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`:i.format==="ends_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${i.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`:i.format==="includes"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${i.includes}" \u0648\u0644\u0631\u064A`:i.format==="regex"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${i.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`:`${r[i.format]??o.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${o.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${o.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${Ot(o.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${o.origin} \u06A9\u06D0`;case"invalid_union":return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A";case"invalid_element":return`\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${o.origin} \u06A9\u06D0`;default:return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A"}}};xVn=()=>{let t={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"liczba";case"object":{if(Array.isArray(o))return"tablica";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"wyra\u017Cenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ci\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"};return o=>{switch(o.code){case"invalid_type":return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${o.expected}, otrzymano ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${to(o.values[0])}`:`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${o.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${i}${o.maximum.toString()} ${s.unit??"element\xF3w"}`:`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${o.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${o.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${i}${o.minimum.toString()} ${s.unit??"element\xF3w"}`:`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${o.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${i.prefix}"`:i.format==="ends_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${i.suffix}"`:i.format==="includes"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${i.includes}"`:i.format==="regex"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${i.pattern}`:`Nieprawid\u0142ow(y/a/e) ${r[i.format]??o.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${o.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${o.keys.length>1?"s":""}: ${Ot(o.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${o.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${o.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}}};CVn=()=>{let t={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"n\xFAmero";case"object":{if(Array.isArray(o))return"array";if(o===null)return"nulo";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"padr\xE3o",email:"endere\xE7o de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"dura\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};return o=>{switch(o.code){case"invalid_type":return`Tipo inv\xE1lido: esperado ${o.expected}, recebido ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Entrada inv\xE1lida: esperado ${to(o.values[0])}`:`Op\xE7\xE3o inv\xE1lida: esperada uma das ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Muito grande: esperado que ${o.origin??"valor"} tivesse ${i}${o.maximum.toString()} ${s.unit??"elementos"}`:`Muito grande: esperado que ${o.origin??"valor"} fosse ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Muito pequeno: esperado que ${o.origin} tivesse ${i}${o.minimum.toString()} ${s.unit}`:`Muito pequeno: esperado que ${o.origin} fosse ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Texto inv\xE1lido: deve come\xE7ar com "${i.prefix}"`:i.format==="ends_with"?`Texto inv\xE1lido: deve terminar com "${i.suffix}"`:i.format==="includes"?`Texto inv\xE1lido: deve incluir "${i.includes}"`:i.format==="regex"?`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${i.pattern}`:`${r[i.format]??o.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${o.divisor}`;case"unrecognized_keys":return`Chave${o.keys.length>1?"s":""} desconhecida${o.keys.length>1?"s":""}: ${Ot(o.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${o.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${o.origin}`;default:return"Campo inv\xE1lido"}}};IVn=()=>{let t={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"\u0447\u0438\u0441\u043B\u043E";case"object":{if(Array.isArray(o))return"\u043C\u0430\u0441\u0441\u0438\u0432";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"};return o=>{switch(o.code){case"invalid_type":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${o.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${to(o.values[0])}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);if(s){let a=Number(o.maximum),l=PMt(a,s.unit.one,s.unit.few,s.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${i}${o.maximum.toString()} ${l}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);if(s){let a=Number(o.minimum),l=PMt(a,s.unit.one,s.unit.few,s.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${o.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${i}${o.minimum.toString()} ${l}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${o.origin} \u0431\u0443\u0434\u0435\u0442 ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${i.prefix}"`:i.format==="ends_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${i.suffix}"`:i.format==="includes"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${i.includes}"`:i.format==="regex"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${i.pattern}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${r[i.format]??o.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${o.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${o.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${o.keys.length>1?"\u0438":""}: ${Ot(o.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${o.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${o.origin}`;default:return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"}}};PVn=()=>{let t={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"\u0161tevilo";case"object":{if(Array.isArray(o))return"tabela";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"vnos",email:"e-po\u0161tni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in \u010Das",date:"ISO datum",time:"ISO \u010Das",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 \u0161tevilka",jwt:"JWT",template_literal:"vnos"};return o=>{switch(o.code){case"invalid_type":return`Neveljaven vnos: pri\u010Dakovano ${o.expected}, prejeto ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Neveljaven vnos: pri\u010Dakovano ${to(o.values[0])}`:`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Preveliko: pri\u010Dakovano, da bo ${o.origin??"vrednost"} imelo ${i}${o.maximum.toString()} ${s.unit??"elementov"}`:`Preveliko: pri\u010Dakovano, da bo ${o.origin??"vrednost"} ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Premajhno: pri\u010Dakovano, da bo ${o.origin} imelo ${i}${o.minimum.toString()} ${s.unit}`:`Premajhno: pri\u010Dakovano, da bo ${o.origin} ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Neveljaven niz: mora se za\u010Deti z "${i.prefix}"`:i.format==="ends_with"?`Neveljaven niz: mora se kon\u010Dati z "${i.suffix}"`:i.format==="includes"?`Neveljaven niz: mora vsebovati "${i.includes}"`:i.format==="regex"?`Neveljaven niz: mora ustrezati vzorcu ${i.pattern}`:`Neveljaven ${r[i.format]??o.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${o.divisor}`;case"unrecognized_keys":return`Neprepoznan${o.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${Ot(o.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${o.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${o.origin}`;default:return"Neveljaven vnos"}}};EVn=()=>{let t={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att inneh\xE5lla"},set:{unit:"objekt",verb:"att inneh\xE5lla"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"antal";case"object":{if(Array.isArray(o))return"lista";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"regulj\xE4rt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad str\xE4ng",base64url:"base64url-kodad str\xE4ng",json_string:"JSON-str\xE4ng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"};return o=>{switch(o.code){case"invalid_type":return`Ogiltig inmatning: f\xF6rv\xE4ntat ${o.expected}, fick ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Ogiltig inmatning: f\xF6rv\xE4ntat ${to(o.values[0])}`:`Ogiltigt val: f\xF6rv\xE4ntade en av ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`F\xF6r stor(t): f\xF6rv\xE4ntade ${o.origin??"v\xE4rdet"} att ha ${i}${o.maximum.toString()} ${s.unit??"element"}`:`F\xF6r stor(t): f\xF6rv\xE4ntat ${o.origin??"v\xE4rdet"} att ha ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`F\xF6r lite(t): f\xF6rv\xE4ntade ${o.origin??"v\xE4rdet"} att ha ${i}${o.minimum.toString()} ${s.unit}`:`F\xF6r lite(t): f\xF6rv\xE4ntade ${o.origin??"v\xE4rdet"} att ha ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${i.prefix}"`:i.format==="ends_with"?`Ogiltig str\xE4ng: m\xE5ste sluta med "${i.suffix}"`:i.format==="includes"?`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${i.includes}"`:i.format==="regex"?`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${i.pattern}"`:`Ogiltig(t) ${r[i.format]??o.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${o.divisor}`;case"unrecognized_keys":return`${o.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${Ot(o.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${o.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${o.origin??"v\xE4rdet"}`;default:return"Ogiltig input"}}};OVn=()=>{let t={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"\u0B8E\u0BA3\u0BCD \u0B85\u0BB2\u0BCD\u0BB2\u0BBE\u0BA4\u0BA4\u0BC1":"\u0B8E\u0BA3\u0BCD";case"object":{if(Array.isArray(o))return"\u0B85\u0BA3\u0BBF";if(o===null)return"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"};return o=>{switch(o.code){case"invalid_type":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${o.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${to(o.values[0])}`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${Ot(o.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${o.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${i}${o.maximum.toString()} ${s.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${o.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${i}${o.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${o.origin} ${i}${o.minimum.toString()} ${s.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${o.origin} ${i}${o.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${i.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:i.format==="ends_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${i.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:i.format==="includes"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${i.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:i.format==="regex"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${i.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${r[i.format]??o.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${o.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${o.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${Ot(o.keys,", ")}`;case"invalid_key":return`${o.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${o.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"}}};RVn=()=>{let t={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"\u0E44\u0E21\u0E48\u0E43\u0E0A\u0E48\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02 (NaN)":"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02";case"object":{if(Array.isArray(o))return"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)";if(o===null)return"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"};return o=>{switch(o.code){case"invalid_type":return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${o.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${to(o.values[0])}`:`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",s=e(o.origin);return s?`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${o.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${i} ${o.maximum.toString()} ${s.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`:`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${o.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${i} ${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",s=e(o.origin);return s?`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${o.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${i} ${o.minimum.toString()} ${s.unit}`:`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${o.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${i} ${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${i.prefix}"`:i.format==="ends_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${i.suffix}"`:i.format==="includes"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${i.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`:i.format==="regex"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${i.pattern}`:`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${r[i.format]??o.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${o.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${Ot(o.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${o.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${o.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}}};$Vn=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},DVn=()=>{let t={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function e(r){return t[r]??null}let n={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO s\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"};return r=>{switch(r.code){case"invalid_type":return`Ge\xE7ersiz de\u011Fer: beklenen ${r.expected}, al\u0131nan ${$Vn(r.input)}`;case"invalid_value":return r.values.length===1?`Ge\xE7ersiz de\u011Fer: beklenen ${to(r.values[0])}`:`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${Ot(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",i=e(r.origin);return i?`\xC7ok b\xFCy\xFCk: beklenen ${r.origin??"de\u011Fer"} ${o}${r.maximum.toString()} ${i.unit??"\xF6\u011Fe"}`:`\xC7ok b\xFCy\xFCk: beklenen ${r.origin??"de\u011Fer"} ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",i=e(r.origin);return i?`\xC7ok k\xFC\xE7\xFCk: beklenen ${r.origin} ${o}${r.minimum.toString()} ${i.unit}`:`\xC7ok k\xFC\xE7\xFCk: beklenen ${r.origin} ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Ge\xE7ersiz metin: "${o.prefix}" ile ba\u015Flamal\u0131`:o.format==="ends_with"?`Ge\xE7ersiz metin: "${o.suffix}" ile bitmeli`:o.format==="includes"?`Ge\xE7ersiz metin: "${o.includes}" i\xE7ermeli`:o.format==="regex"?`Ge\xE7ersiz metin: ${o.pattern} desenine uymal\u0131`:`Ge\xE7ersiz ${n[o.format]??r.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${r.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${r.keys.length>1?"lar":""}: ${Ot(r.keys,", ")}`;case"invalid_key":return`${r.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${r.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}}};UVn=()=>{let t={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"\u0447\u0438\u0441\u043B\u043E";case"object":{if(Array.isArray(o))return"\u043C\u0430\u0441\u0438\u0432";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"};return o=>{switch(o.code){case"invalid_type":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${o.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${to(o.values[0])}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${s.verb} ${i}${o.maximum.toString()} ${s.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${o.origin} ${s.verb} ${i}${o.minimum.toString()} ${s.unit}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${o.origin} \u0431\u0443\u0434\u0435 ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${i.prefix}"`:i.format==="ends_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${i.suffix}"`:i.format==="includes"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${i.includes}"`:i.format==="regex"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${i.pattern}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${r[i.format]??o.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${o.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${o.keys.length>1?"\u0456":""}: ${Ot(o.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${o.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${o.origin}`;default:return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"}}};BVn=()=>{let t={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"\u0646\u0645\u0628\u0631";case"object":{if(Array.isArray(o))return"\u0622\u0631\u06D2";if(o===null)return"\u0646\u0644";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"};return o=>{switch(o.code){case"invalid_type":return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${o.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${n(o.input)} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;case"invalid_value":return o.values.length===1?`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${to(o.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`:`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${Ot(o.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u0628\u06C1\u062A \u0628\u0691\u0627: ${o.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${i}${o.maximum.toString()} ${s.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0628\u0691\u0627: ${o.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${i}${o.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${o.origin} \u06A9\u06D2 ${i}${o.minimum.toString()} ${s.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${o.origin} \u06A9\u0627 ${i}${o.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${i.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:i.format==="ends_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${i.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:i.format==="includes"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${i.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:i.format==="regex"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${i.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:`\u063A\u0644\u0637 ${r[i.format]??o.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${o.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${o.keys.length>1?"\u0632":""}: ${Ot(o.keys,"\u060C ")}`;case"invalid_key":return`${o.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${o.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}}};HVn=()=>{let t={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"s\u1ED1";case"object":{if(Array.isArray(o))return"m\u1EA3ng";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ng\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"};return o=>{switch(o.code){case"invalid_type":return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${o.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${to(o.values[0])}`:`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${o.origin??"gi\xE1 tr\u1ECB"} ${s.verb} ${i}${o.maximum.toString()} ${s.unit??"ph\u1EA7n t\u1EED"}`:`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${o.origin??"gi\xE1 tr\u1ECB"} ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${o.origin} ${s.verb} ${i}${o.minimum.toString()} ${s.unit}`:`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${o.origin} ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${i.prefix}"`:i.format==="ends_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${i.suffix}"`:i.format==="includes"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${i.includes}"`:i.format==="regex"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${i.pattern}`:`${r[i.format]??o.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${o.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${Ot(o.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${o.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${o.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}}};VVn=()=>{let t={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"\u975E\u6570\u5B57(NaN)":"\u6570\u5B57";case"object":{if(Array.isArray(o))return"\u6570\u7EC4";if(o===null)return"\u7A7A\u503C(null)";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"};return o=>{switch(o.code){case"invalid_type":return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${o.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${to(o.values[0])}`:`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${o.origin??"\u503C"} ${i}${o.maximum.toString()} ${s.unit??"\u4E2A\u5143\u7D20"}`:`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${o.origin??"\u503C"} ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${o.origin} ${i}${o.minimum.toString()} ${s.unit}`:`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${o.origin} ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${i.prefix}" \u5F00\u5934`:i.format==="ends_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${i.suffix}" \u7ED3\u5C3E`:i.format==="includes"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${i.includes}"`:i.format==="regex"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${i.pattern}`:`\u65E0\u6548${r[i.format]??o.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${o.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${Ot(o.keys,", ")}`;case"invalid_key":return`${o.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${o.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}}};KVn=()=>{let t={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"number";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"};return o=>{switch(o.code){case"invalid_type":return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${o.expected}\uFF0C\u4F46\u6536\u5230 ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${to(o.values[0])}`:`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${Ot(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${o.origin??"\u503C"} \u61C9\u70BA ${i}${o.maximum.toString()} ${s.unit??"\u500B\u5143\u7D20"}`:`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${o.origin??"\u503C"} \u61C9\u70BA ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${o.origin} \u61C9\u70BA ${i}${o.minimum.toString()} ${s.unit}`:`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${o.origin} \u61C9\u70BA ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${i.prefix}" \u958B\u982D`:i.format==="ends_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${i.suffix}" \u7D50\u5C3E`:i.format==="includes"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${i.includes}"`:i.format==="regex"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${i.pattern}`:`\u7121\u6548\u7684 ${r[i.format]??o.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${o.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${o.keys.length>1?"\u5011":""}\uFF1A${Ot(o.keys,"\u3001")}`;case"invalid_key":return`${o.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${o.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}}};n1t=Symbol("ZodOutput"),r1t=Symbol("ZodInput"),h7=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...n){let r=n[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}remove(e){return this._map.delete(e),this}get(e){let n=e._zod.parent;if(n){let r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};CR=FBe();s1t={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};ofe=class{constructor(e){this._def=e,this.def=e}implement(e){if(typeof e!="function")throw Error("implement() must be called with a function");let n=(...r)=>{let o=this._def.input?Xde(this._def.input,r,void 0,{callee:n}):r;if(!Array.isArray(o))throw Error("Invalid arguments schema: not an array or tuple schema.");let i=e(...o);return this._def.output?Xde(this._def.output,i,void 0,{callee:n}):i};return n}implementAsync(e){if(typeof e!="function")throw Error("implement() must be called with a function");let n=async(...r)=>{let o=this._def.input?await Qde(this._def.input,r,void 0,{callee:n}):r;if(!Array.isArray(o))throw Error("Invalid arguments schema: not an array or tuple schema.");let i=await e(...o);return this._def.output?Qde(this._def.output,i,void 0,{callee:n}):i};return n}input(...e){let n=this.constructor;return Array.isArray(e[0])?new n({type:"function",input:new gpe({type:"tuple",items:e[0],rest:e[1]}),output:this._def.output}):new n({type:"function",input:e[0],output:this._def.output})}output(e){return new this.constructor({type:"function",input:this._def.input,output:e})}};v7=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??CR,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,n={path:[],schemaPath:[]}){var r;let o=e._zod.def,i={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},s=this.seen.get(e);if(s)return s.count++,n.schemaPath.includes(e)&&(s.cycle=n.path),s.schema;let a={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(e,a);let l=e._zod.toJSONSchema?.();if(l)a.schema=l;else{let u={...n,schemaPath:[...n.schemaPath,e],path:n.path},d=e._zod.parent;if(d)a.ref=d,this.process(d,u),this.seen.get(d).isParent=!0;else{let f=a.schema;switch(o.type){case"string":{let p=f;p.type="string";let{minimum:m,maximum:h,format:g,patterns:v,contentEncoding:y}=e._zod.bag;if(typeof m=="number"&&(p.minLength=m),typeof h=="number"&&(p.maxLength=h),g&&(p.format=i[g]??g,p.format===""&&delete p.format),y&&(p.contentEncoding=y),v&&v.size>0){let w=[...v];w.length===1?p.pattern=w[0].source:w.length>1&&(a.schema.allOf=[...w.map(_=>({...this.target==="draft-7"?{type:"string"}:{},pattern:_.source}))])}break}case"number":{let p=f,{minimum:m,maximum:h,format:g,multipleOf:v,exclusiveMaximum:y,exclusiveMinimum:w}=e._zod.bag;typeof g=="string"&&g.includes("int")?p.type="integer":p.type="number",typeof w=="number"&&(p.exclusiveMinimum=w),typeof m=="number"&&(p.minimum=m,typeof w=="number"&&(w>=m?delete p.minimum:delete p.exclusiveMinimum)),typeof y=="number"&&(p.exclusiveMaximum=y),typeof h=="number"&&(p.maximum=h,typeof y=="number"&&(y<=h?delete p.maximum:delete p.exclusiveMaximum)),typeof v=="number"&&(p.multipleOf=v);break}case"boolean":{let p=f;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema");break}case"null":{f.type="null";break}case"any":break;case"unknown":break;case"undefined":case"never":{f.not={};break}case"void":{if(this.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema");break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let p=f,{minimum:m,maximum:h}=e._zod.bag;typeof m=="number"&&(p.minItems=m),typeof h=="number"&&(p.maxItems=h),p.type="array",p.items=this.process(o.element,{...u,path:[...u.path,"items"]});break}case"object":{let p=f;p.type="object",p.properties={};let m=o.shape;for(let v in m)p.properties[v]=this.process(m[v],{...u,path:[...u.path,"properties",v]});let h=new Set(Object.keys(m)),g=new Set([...h].filter(v=>{let y=o.shape[v]._zod;return this.io==="input"?y.optin===void 0:y.optout===void 0}));g.size>0&&(p.required=Array.from(g)),o.catchall?._zod.def.type==="never"?p.additionalProperties=!1:o.catchall?o.catchall&&(p.additionalProperties=this.process(o.catchall,{...u,path:[...u.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{let p=f;p.anyOf=o.options.map((m,h)=>this.process(m,{...u,path:[...u.path,"anyOf",h]}));break}case"intersection":{let p=f,m=this.process(o.left,{...u,path:[...u.path,"allOf",0]}),h=this.process(o.right,{...u,path:[...u.path,"allOf",1]}),g=y=>"allOf"in y&&Object.keys(y).length===1,v=[...g(m)?m.allOf:[m],...g(h)?h.allOf:[h]];p.allOf=v;break}case"tuple":{let p=f;p.type="array";let m=o.items.map((v,y)=>this.process(v,{...u,path:[...u.path,"prefixItems",y]}));if(this.target==="draft-2020-12"?p.prefixItems=m:p.items=m,o.rest){let v=this.process(o.rest,{...u,path:[...u.path,"items"]});this.target==="draft-2020-12"?p.items=v:p.additionalItems=v}o.rest&&(p.items=this.process(o.rest,{...u,path:[...u.path,"items"]}));let{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(p.minItems=h),typeof g=="number"&&(p.maxItems=g);break}case"record":{let p=f;p.type="object",p.propertyNames=this.process(o.keyType,{...u,path:[...u.path,"propertyNames"]}),p.additionalProperties=this.process(o.valueType,{...u,path:[...u.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let p=f,m=fBe(o.entries);m.every(h=>typeof h=="number")&&(p.type="number"),m.every(h=>typeof h=="string")&&(p.type="string"),p.enum=m;break}case"literal":{let p=f,m=[];for(let h of o.values)if(h===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof h=="bigint"){if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");m.push(Number(h))}else m.push(h);if(m.length!==0)if(m.length===1){let h=m[0];p.type=h===null?"null":typeof h,p.const=h}else m.every(h=>typeof h=="number")&&(p.type="number"),m.every(h=>typeof h=="string")&&(p.type="string"),m.every(h=>typeof h=="boolean")&&(p.type="string"),m.every(h=>h===null)&&(p.type="null"),p.enum=m;break}case"file":{let p=f,m={type:"string",format:"binary",contentEncoding:"binary"},{minimum:h,maximum:g,mime:v}=e._zod.bag;h!==void 0&&(m.minLength=h),g!==void 0&&(m.maxLength=g),v?v.length===1?(m.contentMediaType=v[0],Object.assign(p,m)):p.anyOf=v.map(y=>({...m,contentMediaType:y})):Object.assign(p,m);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let p=this.process(o.innerType,u);f.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,u),a.ref=o.innerType;break}case"success":{let p=f;p.type="boolean";break}case"default":{this.process(o.innerType,u),a.ref=o.innerType,f.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,u),a.ref=o.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,u),a.ref=o.innerType;let p;try{p=o.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}f.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let p=f,m=e._zod.pattern;if(!m)throw Error("Pattern not found in template literal");p.type="string",p.pattern=m.source;break}case"pipe":{let p=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(p,u),a.ref=p;break}case"readonly":{this.process(o.innerType,u),a.ref=o.innerType,f.readOnly=!0;break}case"promise":{this.process(o.innerType,u),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,u),a.ref=o.innerType;break}case"lazy":{let p=e._zod.innerType;this.process(p,u),a.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema");break}default:}}}let c=this.metadataRegistry.get(e);return c&&Object.assign(a.schema,c),this.io==="input"&&Lc(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,n){let r={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0},o=this.seen.get(e);if(!o)throw Error("Unprocessed schema. This is a bug in Zod.");let i=u=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){let m=r.external.registry.get(u[0])?.id;if(m)return{ref:r.external.uri(m)};let h=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=h,{defId:h,ref:`${r.external.uri("__shared")}#/${d}/${h}`}}if(u[1]===o)return{ref:"#"};let f=`#/${d}/`,p=u[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:f+p}},s=u=>{if(u[1].schema.$ref)return;let d=u[1],{ref:f,defId:p}=i(u);d.def={...d.schema},p&&(d.defId=p);let m=d.schema;for(let h in m)delete m[h];m.$ref=f};for(let u of this.seen.entries()){let d=u[1];if(e===u[0]){s(u);continue}if(r.external){let f=r.external.registry.get(u[0])?.id;if(e!==u[0]&&f){s(u);continue}}if(this.metadataRegistry.get(u[0])?.id){s(u);continue}if(d.cycle){if(r.cycles==="throw")throw Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);r.cycles==="ref"&&s(u);continue}if(d.count>1&&r.reused==="ref"){s(u);continue}}let a=(u,d)=>{let f=this.seen.get(u),p=f.def??f.schema,m={...p};if(f.ref===null)return;let h=f.ref;if(f.ref=null,h){a(h,d);let g=this.seen.get(h).schema;g.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(g)):(Object.assign(p,g),Object.assign(p,m))}f.isParent||this.override({zodSchema:u,jsonSchema:p,path:f.path??[]})};for(let u of[...this.seen.entries()].reverse())a(u[0],{target:this.target});let l={};this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),Object.assign(l,o.def);let c=r.external?.defs??{};for(let u of this.seen.entries()){let d=u[1];d.def&&d.defId&&(c[d.defId]=d.def)}!r.external&&Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw Error("Error converting schema to JSON.")}}};g3n={},wze={};_x(wze,{time:()=>G1t,duration:()=>Z1t,datetime:()=>q1t,date:()=>K1t,ZodISOTime:()=>xze,ZodISODuration:()=>Sze,ZodISODateTime:()=>bze,ZodISODate:()=>_ze});bze=_e("ZodISODateTime",(t,e)=>{uLt.init(t,e),Qs.init(t,e)});_ze=_e("ZodISODate",(t,e)=>{dLt.init(t,e),Qs.init(t,e)});xze=_e("ZodISOTime",(t,e)=>{fLt.init(t,e),Qs.init(t,e)});Sze=_e("ZodISODuration",(t,e)=>{pLt.init(t,e),Qs.init(t,e)});Y1t=(t,e)=>{hBe.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>yBe(t,n)},flatten:{value:n=>gBe(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},y3n=_e("ZodError",Y1t),H7=_e("ZodError",Y1t,{Parent:Error}),J1t=vBe(H7),X1t=wBe(H7),Q1t=bBe(H7),e$t=xBe(H7),po=_e("ZodType",(t,e)=>(Mr.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>lb(t,n,r),t.brand=()=>t,t.register=(n,r)=>(n.add(t,r),t),t.parse=(n,r)=>J1t(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Q1t(t,n,r),t.parseAsync=async(n,r)=>X1t(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>e$t(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(L$t(n,r)),t.superRefine=n=>t.check($$t(n)),t.overwrite=n=>t.check(zR(n)),t.optional=()=>Js(t),t.nullable=()=>sfe(t),t.nullish=()=>Js(sfe(t)),t.nonoptional=n=>x$t(t,n),t.array=()=>Oo(t),t.or=n=>gs([t,n]),t.and=n=>Ipe(t,n),t.transform=n=>afe(t,Zze(n)),t.default=n=>w$t(t,n),t.prefault=n=>_$t(t,n),t.catch=n=>k$t(t,n),t.pipe=n=>afe(t,n),t.readonly=()=>P$t(t),t.describe=n=>{let r=t.clone();return CR.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return CR.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return CR.get(t);let r=t.clone();return CR.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Cze=_e("_ZodString",(t,e)=>{z7.init(t,e),po.init(t,e);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(aze(...r)),t.includes=(...r)=>t.check(uze(...r)),t.startsWith=(...r)=>t.check(dze(...r)),t.endsWith=(...r)=>t.check(fze(...r)),t.min=(...r)=>t.check(SB(...r)),t.max=(...r)=>t.check(vpe(...r)),t.length=(...r)=>t.check(wpe(...r)),t.nonempty=(...r)=>t.check(SB(1,...r)),t.lowercase=r=>t.check(lze(r)),t.uppercase=r=>t.check(cze(r)),t.trim=()=>t.check(hze()),t.normalize=(...r)=>t.check(mze(...r)),t.toLowerCase=()=>t.check(gze()),t.toUpperCase=()=>t.check(yze())}),bpe=_e("ZodString",(t,e)=>{z7.init(t,e),Cze.init(t,e),t.email=n=>t.check(UBe(kze,n)),t.url=n=>t.check(WBe(Ize,n)),t.jwt=n=>t.check(ize(Bze,n)),t.emoji=n=>t.check(VBe(Tze,n)),t.guid=n=>t.check(nfe(ife,n)),t.uuid=n=>t.check(jBe(Ok,n)),t.uuidv4=n=>t.check(BBe(Ok,n)),t.uuidv6=n=>t.check(zBe(Ok,n)),t.uuidv7=n=>t.check(HBe(Ok,n)),t.nanoid=n=>t.check(qBe(Pze,n)),t.guid=n=>t.check(nfe(ife,n)),t.cuid=n=>t.check(KBe(Aze,n)),t.cuid2=n=>t.check(GBe(Eze,n)),t.ulid=n=>t.check(ZBe(Mze,n)),t.base64=n=>t.check(nze(Fze,n)),t.base64url=n=>t.check(rze(Uze,n)),t.xid=n=>t.check(YBe(Oze,n)),t.ksuid=n=>t.check(JBe(Nze,n)),t.ipv4=n=>t.check(XBe(Rze,n)),t.ipv6=n=>t.check(QBe(Lze,n)),t.cidrv4=n=>t.check(eze($ze,n)),t.cidrv6=n=>t.check(tze(Dze,n)),t.e164=n=>t.check(oze(jze,n)),t.datetime=n=>t.check(q1t(n)),t.date=n=>t.check(K1t(n)),t.time=n=>t.check(G1t(n)),t.duration=n=>t.check(Z1t(n))});Qs=_e("ZodStringFormat",(t,e)=>{Ms.init(t,e),Cze.init(t,e)}),kze=_e("ZodEmail",(t,e)=>{tLt.init(t,e),Qs.init(t,e)});ife=_e("ZodGUID",(t,e)=>{QRt.init(t,e),Qs.init(t,e)});Ok=_e("ZodUUID",(t,e)=>{eLt.init(t,e),Qs.init(t,e)});Ize=_e("ZodURL",(t,e)=>{nLt.init(t,e),Qs.init(t,e)});Tze=_e("ZodEmoji",(t,e)=>{rLt.init(t,e),Qs.init(t,e)});Pze=_e("ZodNanoID",(t,e)=>{oLt.init(t,e),Qs.init(t,e)});Aze=_e("ZodCUID",(t,e)=>{iLt.init(t,e),Qs.init(t,e)});Eze=_e("ZodCUID2",(t,e)=>{sLt.init(t,e),Qs.init(t,e)});Mze=_e("ZodULID",(t,e)=>{aLt.init(t,e),Qs.init(t,e)});Oze=_e("ZodXID",(t,e)=>{lLt.init(t,e),Qs.init(t,e)});Nze=_e("ZodKSUID",(t,e)=>{cLt.init(t,e),Qs.init(t,e)});Rze=_e("ZodIPv4",(t,e)=>{mLt.init(t,e),Qs.init(t,e)});Lze=_e("ZodIPv6",(t,e)=>{hLt.init(t,e),Qs.init(t,e)});$ze=_e("ZodCIDRv4",(t,e)=>{gLt.init(t,e),Qs.init(t,e)});Dze=_e("ZodCIDRv6",(t,e)=>{yLt.init(t,e),Qs.init(t,e)});Fze=_e("ZodBase64",(t,e)=>{vLt.init(t,e),Qs.init(t,e)});Uze=_e("ZodBase64URL",(t,e)=>{bLt.init(t,e),Qs.init(t,e)});jze=_e("ZodE164",(t,e)=>{_Lt.init(t,e),Qs.init(t,e)});Bze=_e("ZodJWT",(t,e)=>{SLt.init(t,e),Qs.init(t,e)});t$t=_e("ZodCustomStringFormat",(t,e)=>{CLt.init(t,e),Qs.init(t,e)});_pe=_e("ZodNumber",(t,e)=>{ABe.init(t,e),po.init(t,e),t.gt=(r,o)=>t.check(ER(r,o)),t.gte=(r,o)=>t.check(qh(r,o)),t.min=(r,o)=>t.check(qh(r,o)),t.lt=(r,o)=>t.check(AR(r,o)),t.lte=(r,o)=>t.check(nb(r,o)),t.max=(r,o)=>t.check(nb(r,o)),t.int=r=>t.check(rje(r)),t.safe=r=>t.check(rje(r)),t.positive=r=>t.check(ER(0,r)),t.nonnegative=r=>t.check(qh(0,r)),t.negative=r=>t.check(AR(0,r)),t.nonpositive=r=>t.check(nb(0,r)),t.multipleOf=(r,o)=>t.check(g7(r,o)),t.step=(r,o)=>t.check(g7(r,o)),t.finite=()=>t;let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});KB=_e("ZodNumberFormat",(t,e)=>{kLt.init(t,e),_pe.init(t,e)});xpe=_e("ZodBoolean",(t,e)=>{EBe.init(t,e),po.init(t,e)});Spe=_e("ZodBigInt",(t,e)=>{MBe.init(t,e),po.init(t,e),t.gte=(r,o)=>t.check(qh(r,o)),t.min=(r,o)=>t.check(qh(r,o)),t.gt=(r,o)=>t.check(ER(r,o)),t.gte=(r,o)=>t.check(qh(r,o)),t.min=(r,o)=>t.check(qh(r,o)),t.lt=(r,o)=>t.check(AR(r,o)),t.lte=(r,o)=>t.check(nb(r,o)),t.max=(r,o)=>t.check(nb(r,o)),t.positive=r=>t.check(ER(BigInt(0),r)),t.negative=r=>t.check(AR(BigInt(0),r)),t.nonpositive=r=>t.check(nb(BigInt(0),r)),t.nonnegative=r=>t.check(qh(BigInt(0),r)),t.multipleOf=(r,o)=>t.check(g7(r,o));let n=t._zod.bag;t.minValue=n.minimum??null,t.maxValue=n.maximum??null,t.format=n.format??null});zze=_e("ZodBigIntFormat",(t,e)=>{ILt.init(t,e),Spe.init(t,e)});n$t=_e("ZodSymbol",(t,e)=>{TLt.init(t,e),po.init(t,e)});r$t=_e("ZodUndefined",(t,e)=>{PLt.init(t,e),po.init(t,e)});o$t=_e("ZodNull",(t,e)=>{ALt.init(t,e),po.init(t,e)});i$t=_e("ZodAny",(t,e)=>{ELt.init(t,e),po.init(t,e)});s$t=_e("ZodUnknown",(t,e)=>{tfe.init(t,e),po.init(t,e)});a$t=_e("ZodNever",(t,e)=>{MLt.init(t,e),po.init(t,e)});l$t=_e("ZodVoid",(t,e)=>{OLt.init(t,e),po.init(t,e)});Wze=_e("ZodDate",(t,e)=>{NLt.init(t,e),po.init(t,e),t.min=(r,o)=>t.check(qh(r,o)),t.max=(r,o)=>t.check(nb(r,o));let n=t._zod.bag;t.minDate=n.minimum?new Date(n.minimum):null,t.maxDate=n.maximum?new Date(n.maximum):null});c$t=_e("ZodArray",(t,e)=>{OBe.init(t,e),po.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(SB(n,r)),t.nonempty=n=>t.check(SB(1,n)),t.max=(n,r)=>t.check(vpe(n,r)),t.length=(n,r)=>t.check(wpe(n,r)),t.unwrap=()=>t.element});kpe=_e("ZodObject",(t,e)=>{NBe.init(t,e),po.init(t,e),Mo.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Im(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:ma()}),t.loose=()=>t.clone({...t._zod.def,catchall:ma()}),t.strict=()=>t.clone({...t._zod.def,catchall:Cpe()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>Mo.extend(t,n),t.merge=n=>Mo.merge(t,n),t.pick=n=>Mo.pick(t,n),t.omit=n=>Mo.omit(t,n),t.partial=(...n)=>Mo.partial(Yze,t,n[0]),t.required=(...n)=>Mo.required(Jze,t,n[0])});Vze=_e("ZodUnion",(t,e)=>{RBe.init(t,e),po.init(t,e),t.options=e.options});u$t=_e("ZodDiscriminatedUnion",(t,e)=>{Vze.init(t,e),RLt.init(t,e)});d$t=_e("ZodIntersection",(t,e)=>{LLt.init(t,e),po.init(t,e)});f$t=_e("ZodTuple",(t,e)=>{gpe.init(t,e),po.init(t,e),t.rest=n=>t.clone({...t._zod.def,rest:n})});Kze=_e("ZodRecord",(t,e)=>{$Lt.init(t,e),po.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});p$t=_e("ZodMap",(t,e)=>{DLt.init(t,e),po.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});m$t=_e("ZodSet",(t,e)=>{FLt.init(t,e),po.init(t,e),t.min=(...n)=>t.check(y7(...n)),t.nonempty=n=>t.check(y7(1,n)),t.max=(...n)=>t.check(ype(...n)),t.size=(...n)=>t.check(sze(...n))});w7=_e("ZodEnum",(t,e)=>{ULt.init(t,e),po.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{let i={};for(let s of r)if(n.has(s))i[s]=e.entries[s];else throw Error(`Key ${s} not found in enum`);return new w7({...e,checks:[],...Mo.normalizeParams(o),entries:i})},t.exclude=(r,o)=>{let i={...e.entries};for(let s of r)if(n.has(s))delete i[s];else throw Error(`Key ${s} not found in enum`);return new w7({...e,checks:[],...Mo.normalizeParams(o),entries:i})}});h$t=_e("ZodLiteral",(t,e)=>{jLt.init(t,e),po.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});g$t=_e("ZodFile",(t,e)=>{BLt.init(t,e),po.init(t,e),t.min=(n,r)=>t.check(y7(n,r)),t.max=(n,r)=>t.check(ype(n,r)),t.mime=(n,r)=>t.check(pze(Array.isArray(n)?n:[n],r))});Gze=_e("ZodTransform",(t,e)=>{LBe.init(t,e),po.init(t,e),t._zod.parse=(n,r)=>{n.addIssue=i=>{if(typeof i=="string")n.issues.push(Mo.issue(i,n.value,e));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=t),s.continue??(s.continue=!0),n.issues.push(Mo.issue(s))}};let o=e.transform(n.value,n);return o instanceof Promise?o.then(i=>(n.value=i,n)):(n.value=o,n)}});Yze=_e("ZodOptional",(t,e)=>{zLt.init(t,e),po.init(t,e),t.unwrap=()=>t._zod.def.innerType});y$t=_e("ZodNullable",(t,e)=>{HLt.init(t,e),po.init(t,e),t.unwrap=()=>t._zod.def.innerType});v$t=_e("ZodDefault",(t,e)=>{WLt.init(t,e),po.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});b$t=_e("ZodPrefault",(t,e)=>{VLt.init(t,e),po.init(t,e),t.unwrap=()=>t._zod.def.innerType});Jze=_e("ZodNonOptional",(t,e)=>{qLt.init(t,e),po.init(t,e),t.unwrap=()=>t._zod.def.innerType});S$t=_e("ZodSuccess",(t,e)=>{KLt.init(t,e),po.init(t,e),t.unwrap=()=>t._zod.def.innerType});C$t=_e("ZodCatch",(t,e)=>{GLt.init(t,e),po.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});I$t=_e("ZodNaN",(t,e)=>{ZLt.init(t,e),po.init(t,e)});Xze=_e("ZodPipe",(t,e)=>{$Be.init(t,e),po.init(t,e),t.in=e.in,t.out=e.out});T$t=_e("ZodReadonly",(t,e)=>{YLt.init(t,e),po.init(t,e)});A$t=_e("ZodTemplateLiteral",(t,e)=>{JLt.init(t,e),po.init(t,e)});E$t=_e("ZodLazy",(t,e)=>{QLt.init(t,e),po.init(t,e),t.unwrap=()=>t._zod.def.getter()});O$t=_e("ZodPromise",(t,e)=>{XLt.init(t,e),po.init(t,e),t.unwrap=()=>t._zod.def.innerType});Tpe=_e("ZodCustom",(t,e)=>{e1t.init(t,e),po.init(t,e)});pqn=(...t)=>z1t({Pipe:Xze,Boolean:xpe,String:bpe,Transform:Gze},...t);hqn={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};D$t={};_x(D$t,{string:()=>vqn,number:()=>wqn,date:()=>xqn,boolean:()=>bqn,bigint:()=>_qn});wp(t1t());Sqn=A,lfe=Sqn,Cqn={"//":"Hand-maintained baked-in model catalog \u2014 the source of truth for per-model provider IDs and metadata. On model launch add one entry to `models` below; `bun run generate:model-catalog` validates this file against the schema and formats it.",schema_version:1,pricing_tiers:{tier_3_15:{input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,web_search:.01},tier_5_25:{input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5,web_search:.01},tier_15_75:{input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5,web_search:.01},tier_10_50:{input:10,output:50,cache_write_5m:12.5,cache_write_1h:20,cache_read:1,web_search:.01},haiku_35:{input:.8,output:4,cache_write_5m:1,cache_write_1h:1.6,cache_read:.08,web_search:.01},haiku_45:{input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1,web_search:.01}},models:[{id:"claude-3-5-haiku",family:"haiku",display_name:"Haiku 3.5",provider_ids:{first_party:"claude-3-5-haiku-20241022",bedrock:"us.anthropic.claude-3-5-haiku-20241022-v1:0",vertex:"claude-3-5-haiku@20241022",foundry:"claude-3-5-haiku",anthropic_aws:"claude-3-5-haiku-20241022",mantle:null,gateway:"claude-3-5-haiku-20241022"},eager_input_streaming:{vertex:!0},vertex_region_env_var:"VERTEX_REGION_CLAUDE_3_5_HAIKU",max_output_tokens:{default:8192,upper:8192},pricing:"haiku_35",capabilities:[]},{id:"claude-haiku-4-5",family:"haiku",display_name:"Haiku 4.5",knowledge_cutoff:"February 2025",provider_ids:{first_party:"claude-haiku-4-5-20251001",bedrock:"us.anthropic.claude-haiku-4-5-20251001-v1:0",vertex:"claude-haiku-4-5@20251001",foundry:"claude-haiku-4-5",anthropic_aws:"claude-haiku-4-5-20251001",mantle:"anthropic.claude-haiku-4-5",gateway:"claude-haiku-4-5-20251001"},vertex_region_env_var:"VERTEX_REGION_CLAUDE_HAIKU_4_5",context:{window:2e5,supports_1m_suffix:!0},max_output_tokens:{default:32e3,upper:64e3},pricing:"haiku_45",capabilities:["context_management"],advisor_rank:1},{id:"claude-3-5-sonnet",family:"sonnet",display_name:"Sonnet 3.5",provider_ids:{first_party:"claude-3-5-sonnet-20241022",bedrock:"us.anthropic.claude-3-5-sonnet-20241022-v2:0",vertex:"claude-3-5-sonnet-v2@20241022",foundry:"claude-3-5-sonnet",anthropic_aws:"claude-3-5-sonnet-20241022",mantle:null,gateway:"claude-3-5-sonnet-20241022"},vertex_region_env_var:"VERTEX_REGION_CLAUDE_3_5_SONNET",max_output_tokens:{default:8192,upper:8192},pricing:"tier_3_15",capabilities:[]},{id:"claude-3-7-sonnet",family:"sonnet",display_name:"Sonnet 3.7",provider_ids:{first_party:"claude-3-7-sonnet-20250219",bedrock:"us.anthropic.claude-3-7-sonnet-20250219-v1:0",vertex:"claude-3-7-sonnet@20250219",foundry:"claude-3-7-sonnet",anthropic_aws:"claude-3-7-sonnet-20250219",mantle:null,gateway:"claude-3-7-sonnet-20250219"},vertex_region_env_var:"VERTEX_REGION_CLAUDE_3_7_SONNET",max_output_tokens:{default:32e3,upper:64e3},pricing:"tier_3_15",capabilities:[]},{id:"claude-sonnet-4-0",family:"sonnet",display_name:"Sonnet 4",knowledge_cutoff:"January 2025",provider_ids:{first_party:"claude-sonnet-4-20250514",bedrock:"us.anthropic.claude-sonnet-4-20250514-v1:0",vertex:"claude-sonnet-4@20250514",foundry:"claude-sonnet-4",anthropic_aws:"claude-sonnet-4-20250514",mantle:null,gateway:"claude-sonnet-4-20250514"},eager_input_streaming:{vertex:!0},vertex_region_env_var:"VERTEX_REGION_CLAUDE_4_0_SONNET",context:{window:2e5,supports_1m_beta:!0,supports_1m_suffix:!0},max_output_tokens:{default:32e3,upper:64e3},pricing:"tier_3_15",capabilities:["context_management"]},{id:"claude-sonnet-4-5",family:"sonnet",display_name:"Sonnet 4.5",knowledge_cutoff:"January 2025",provider_ids:{first_party:"claude-sonnet-4-5-20250929",bedrock:"us.anthropic.claude-sonnet-4-5-20250929-v1:0",vertex:"claude-sonnet-4-5@20250929",foundry:"claude-sonnet-4-5",anthropic_aws:"claude-sonnet-4-5-20250929",mantle:null,gateway:"claude-sonnet-4-5-20250929"},eager_input_streaming:{vertex:!0},vertex_region_env_var:"VERTEX_REGION_CLAUDE_4_5_SONNET",fallback_3p:"claude-sonnet-4-0",context:{window:2e5,supports_1m_beta:!0,supports_1m_suffix:!0},max_output_tokens:{default:32e3,upper:64e3},pricing:"tier_3_15",capabilities:["context_management"]},{id:"claude-sonnet-4-6",family:"sonnet",display_name:"Sonnet 4.6",knowledge_cutoff:"August 2025",provider_ids:{first_party:"claude-sonnet-4-6",bedrock:"us.anthropic.claude-sonnet-4-6",vertex:"claude-sonnet-4-6",foundry:"claude-sonnet-4-6",anthropic_aws:"claude-sonnet-4-6",mantle:null,gateway:"claude-sonnet-4-6"},eager_input_streaming:{bedrock:!0,vertex:!0},vertex_region_env_var:"VERTEX_REGION_CLAUDE_4_6_SONNET",fallback_3p:"claude-sonnet-4-5",context:{window:2e5,supports_1m_beta:!0,supports_1m_suffix:!0},max_output_tokens:{default:32e3,upper:128e3},pricing:"tier_3_15",capabilities:["effort","max_effort","adaptive_thinking","context_management"],advisor_rank:2},{id:"claude-sonnet-5",family:"sonnet",display_name:"Sonnet 5",knowledge_cutoff:"January 2026",provider_ids:{first_party:"claude-sonnet-5",bedrock:"us.anthropic.claude-sonnet-5",vertex:"claude-sonnet-5",foundry:"claude-sonnet-5",anthropic_aws:"claude-sonnet-5",mantle:"anthropic.claude-sonnet-5",gateway:"claude-sonnet-5"},eager_input_streaming:{bedrock:!0,vertex:!0},vertex_region_env_var:"VERTEX_REGION_CLAUDE_5_SONNET",fallback_3p:"claude-sonnet-4-6",context:{window:1e6,native_1m:!0,native_1m_3p:{bedrock:!0,vertex:!0,foundry:!0},supports_1m_beta:!0},max_output_tokens:{default:64e3,upper:128e3},pricing:"tier_3_15",capabilities:["effort","max_effort","xhigh_effort","adaptive_thinking","mid_conv_system","context_management"],default_effort:"high",image_limits:{maxWidth:2e3,maxHeight:2e3},advisor_rank:3},{id:"claude-opus-4-0",family:"opus",display_name:"Opus 4",knowledge_cutoff:"January 2025",provider_ids:{first_party:"claude-opus-4-20250514",bedrock:"us.anthropic.claude-opus-4-20250514-v1:0",vertex:"claude-opus-4@20250514",foundry:"claude-opus-4",anthropic_aws:"claude-opus-4-20250514",mantle:null,gateway:"claude-opus-4-20250514"},vertex_region_env_var:"VERTEX_REGION_CLAUDE_4_0_OPUS",context:{window:2e5,supports_1m_suffix:!0},max_output_tokens:{default:32e3,upper:32e3},pricing:"tier_15_75",capabilities:["context_management"]},{id:"claude-opus-4-1",family:"opus",display_name:"Opus 4.1",knowledge_cutoff:"January 2025",provider_ids:{first_party:"claude-opus-4-1-20250805",bedrock:"us.anthropic.claude-opus-4-1-20250805-v1:0",vertex:"claude-opus-4-1@20250805",foundry:"claude-opus-4-1",anthropic_aws:"claude-opus-4-1-20250805",mantle:null,gateway:"claude-opus-4-1-20250805"},vertex_region_env_var:"VERTEX_REGION_CLAUDE_4_1_OPUS",context:{window:2e5,supports_1m_suffix:!0},max_output_tokens:{default:32e3,upper:32e3},pricing:"tier_15_75",capabilities:["context_management"]},{id:"claude-opus-4-5",family:"opus",display_name:"Opus 4.5",knowledge_cutoff:"May 2025",provider_ids:{first_party:"claude-opus-4-5-20251101",bedrock:"us.anthropic.claude-opus-4-5-20251101-v1:0",vertex:"claude-opus-4-5@20251101",foundry:"claude-opus-4-5",anthropic_aws:"claude-opus-4-5-20251101",mantle:null,gateway:"claude-opus-4-5-20251101"},eager_input_streaming:{vertex:!0},vertex_region_env_var:"VERTEX_REGION_CLAUDE_4_5_OPUS",fallback_3p:"claude-opus-4-1",context:{window:2e5,supports_1m_suffix:!0},max_output_tokens:{default:32e3,upper:64e3},pricing:"tier_5_25",capabilities:["context_management"]},{id:"claude-opus-4-6",family:"opus",display_name:"Opus 4.6",knowledge_cutoff:"May 2025",provider_ids:{first_party:"claude-opus-4-6",bedrock:"us.anthropic.claude-opus-4-6-v1",vertex:"claude-opus-4-6",foundry:"claude-opus-4-6",anthropic_aws:"claude-opus-4-6",mantle:null,gateway:"claude-opus-4-6"},eager_input_streaming:{vertex:!0},vertex_region_env_var:"VERTEX_REGION_CLAUDE_4_6_OPUS",fallback_3p:"claude-opus-4-5",context:{window:2e5,supports_1m_beta:!0,supports_1m_suffix:!0},max_output_tokens:{default:64e3,upper:128e3},pricing:"tier_5_25",capabilities:["effort","max_effort","adaptive_thinking","context_management"],advisor_rank:3},{id:"claude-opus-4-7",family:"opus",display_name:"Opus 4.7",knowledge_cutoff:"January 2026",provider_ids:{first_party:"claude-opus-4-7",bedrock:"us.anthropic.claude-opus-4-7",vertex:"claude-opus-4-7",foundry:"claude-opus-4-7",anthropic_aws:"claude-opus-4-7",mantle:"anthropic.claude-opus-4-7",gateway:"claude-opus-4-7"},eager_input_streaming:{bedrock:!0,vertex:!0},vertex_region_env_var:"VERTEX_REGION_CLAUDE_4_7_OPUS",fallback_3p:"claude-opus-4-6",context:{window:1e6,native_1m:!0,supports_1m_beta:!0,supports_1m_suffix:!0},max_output_tokens:{default:64e3,upper:128e3},pricing:"tier_5_25",capabilities:["effort","max_effort","xhigh_effort","adaptive_thinking","context_management","fast_mode"],default_effort:"xhigh",image_limits:{maxWidth:2e3,maxHeight:2e3},advisor_rank:4},{id:"claude-opus-4-8",family:"opus",display_name:"Opus 4.8",knowledge_cutoff:"January 2026",provider_ids:{first_party:"claude-opus-4-8",bedrock:"us.anthropic.claude-opus-4-8",vertex:"claude-opus-4-8",foundry:"claude-opus-4-8",anthropic_aws:"claude-opus-4-8",mantle:"anthropic.claude-opus-4-8",gateway:"claude-opus-4-8"},eager_input_streaming:{bedrock:!0,vertex:!0},vertex_region_env_var:"VERTEX_REGION_CLAUDE_4_8_OPUS",fallback_3p:"claude-opus-4-7",context:{window:1e6,native_1m:!0,supports_1m_beta:!0,supports_1m_suffix:!0},max_output_tokens:{default:64e3,upper:128e3},pricing:"tier_5_25",capabilities:["effort","max_effort","xhigh_effort","adaptive_thinking","mid_conv_system","context_management","fast_mode","lean_prompt"],default_effort:"high",image_limits:{maxWidth:2e3,maxHeight:2e3},advisor_rank:4},{id:"claude-fable-5",family:"fable",display_name:"Fable 5",knowledge_cutoff:"January 2026",provider_ids:{first_party:"claude-fable-5",bedrock:"us.anthropic.claude-fable-5",vertex:"claude-fable-5",foundry:"claude-fable-5",anthropic_aws:"claude-fable-5",mantle:"anthropic.claude-fable-5",gateway:"claude-fable-5"},eager_input_streaming:{bedrock:!0,vertex:!0},vertex_region_env_var:"VERTEX_REGION_CLAUDE_FABLE_5",fallback_3p:"claude-opus-4-8",context:{window:1e6,native_1m:!0,supports_1m_beta:!0},max_output_tokens:{default:64e3,upper:128e3},pricing:"tier_10_50",capabilities:["effort","max_effort","xhigh_effort","adaptive_thinking","rejects_disabled_thinking","mid_conv_system","context_management","lean_prompt","fable_5_mitigations"],default_effort:"high",image_limits:{maxWidth:2e3,maxHeight:2e3},advisor_rank:5},{id:"claude-mythos-5",family:"mythos",display_name:"Mythos 5",knowledge_cutoff:"January 2026",provider_ids:{first_party:"claude-mythos-5",bedrock:null,vertex:null,foundry:null,anthropic_aws:null,mantle:null,gateway:null},context:{window:1e6,native_1m:!0,supports_1m_beta:!0},max_output_tokens:{default:64e3,upper:128e3},pricing:"tier_10_50",capabilities:[],image_limits:{maxWidth:2e3,maxHeight:2e3},advisor_rank:5}],aliases:{opus:{default:"claude-opus-4-8",per_provider:{bedrock:"claude-opus-4-6",vertex:"claude-opus-4-6",foundry:"claude-opus-4-6",mantle:"claude-opus-4-7",anthropic_aws:"claude-opus-4-7",gateway:"claude-opus-4-7"}},sonnet:{default:"claude-sonnet-5",per_provider:{bedrock:"claude-sonnet-4-5",vertex:"claude-sonnet-4-5",foundry:"claude-sonnet-4-5",mantle:"claude-sonnet-4-5",anthropic_aws:"claude-sonnet-4-6",gateway:"claude-sonnet-4-6"}},haiku:{default:"claude-haiku-4-5"},fable:{default:"claude-fable-5"}},defaults:{},best:"fable",latest_per_family:{fable:"claude-fable-5",opus:"claude-opus-4-8",sonnet:"claude-sonnet-5",haiku:"claude-haiku-4-5"},alias_migration:{}};kqn=Ze(()=>A.object({first_party:A.string(),bedrock:A.string().nullish(),vertex:A.string().nullish(),foundry:A.string().nullish(),anthropic_aws:A.string().nullish(),mantle:A.string().nullish(),gateway:A.string().nullish()}).loose()),F$t=Ze(()=>A.object({input:A.number(),output:A.number(),cache_write_5m:A.number().optional(),cache_write_1h:A.number().optional(),cache_read:A.number().optional(),web_search:A.number().optional()}).loose()),Iqn=Ze(()=>A.object({id:A.string(),family:A.string(),display_name:A.string(),slogan:A.string().optional(),knowledge_cutoff:A.string().optional(),provider_ids:kqn(),eager_input_streaming:A.object({bedrock:A.literal(!0).optional(),vertex:A.literal(!0).optional()}).loose().optional(),vertex_region_env_var:A.string().optional(),fallback_3p:A.string().optional(),context:A.object({window:A.number(),native_1m:A.boolean().optional(),native_1m_3p:A.object({bedrock:A.literal(!0).optional(),vertex:A.literal(!0).optional(),foundry:A.literal(!0).optional()}).loose().optional(),supports_1m_beta:A.boolean().optional(),supports_1m_suffix:A.boolean().optional()}).loose().optional(),max_output_tokens:A.object({default:A.number(),upper:A.number()}).loose().optional(),pricing:A.union([A.string(),F$t()]).optional(),capabilities:A.array(A.string()).default([]),default_effort:A.enum(["low","medium","high","xhigh","max"]).optional(),image_limits:A.object({maxWidth:A.number().optional(),maxHeight:A.number().optional(),maxBase64Size:A.number().optional()}).loose().optional(),advisor_rank:A.number().optional(),fallback_chain:A.array(A.string()).optional(),picker:A.object({section:A.enum(["main","overflow","deprecated"]).optional(),badge:A.string().optional(),disabled_reason:A.string().optional(),tiers:A.array(A.string()).optional()}).loose().optional(),deprecation:A.object({retirement_dates:A.record(A.string(),A.string()).optional(),remapped_to:A.string().optional()}).loose().optional(),min_cli_version:A.string().optional()}).loose()),Tqn=Ze(()=>A.object({default:A.string(),per_provider:A.record(A.string(),A.string()).optional()}).loose()),Pqn=Ze(()=>A.object({schema_version:A.number(),pricing_tiers:A.record(A.string(),F$t()).default({}),models:A.array(Iqn()),aliases:A.record(A.string(),Tqn()).default({}),defaults:A.record(A.string(),A.string()).default({}),best:A.string().optional(),latest_per_family:A.record(A.string(),A.string()).default({}),alias_migration:A.record(A.string(),A.string()).default({})}).loose()),Aqn={schema_version:0,pricing_tiers:{},models:[],aliases:{},defaults:{},latest_per_family:{},alias_migration:{}},U$t=Za(()=>{let t=Pqn().safeParse(Cqn);return t.success?t.data:Aqn}),j$t=U$t;Tuo=Za(()=>{let t=new Map;for(let e of j$t().models)t.set(e.id,e);return t}),Puo=Za(()=>{let t=new Map;for(let e of j$t().models)for(let n of Object.values(e.provider_ids)){if(typeof n!="string")continue;let r=n.toLowerCase(),o=t.get(r);if(o!==void 0&&o!==e.id)throw Error("model catalog: provider id collision across distinct entries");t.set(r,e.id)}return t}),e4e=Za(()=>(process.env.CLAUDE_CONFIG_DIR??(0,jNt.join)((0,UNt.homedir)(),".claude")).normalize("NFC"),()=>process.env.CLAUDE_CONFIG_DIR),Auo=Za(()=>xm(process.env.CLAUDE_CODE_SUPERVISED)),Euo=Za(()=>U$t().models.flatMap(t=>t.vertex_region_env_var&&/^VERTEX_REGION_[A-Z0-9_]+$/.test(t.vertex_region_env_var)?[[Eqn(t.id),t.vertex_region_env_var]]:[]).sort(([t],[e])=>e.length-t.length||(t<e?-1:t>e?1:0)));B$t=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return B$t=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))};oje=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return Error(JSON.stringify(t))}catch{}}return Error(t)},Vn=class extends Error{},bp=class t extends Vn{constructor(e,n,r,o,i){super(`${t.makeMessage(e,n,r)}`),this.status=e,this.headers=o,this.requestID=o?.get("request-id"),this.error=n,this.type=i??null}static makeMessage(e,n,r){let o=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,n,r,o){if(!e||!o)return new CB({message:r,cause:oje(n)});let i=n,s=i?.error?.type;return e===400?new ufe(e,i,r,o,s):e===401?new dfe(e,i,r,o,s):e===403?new ffe(e,i,r,o,s):e===404?new pfe(e,i,r,o,s):e===409?new mfe(e,i,r,o,s):e===422?new hfe(e,i,r,o,s):e===429?new gfe(e,i,r,o,s):e>=500?new yfe(e,i,r,o,s):new t(e,i,r,o,s)}},Kh=class extends bp{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},CB=class extends bp{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}},cfe=class extends CB{constructor({message:e}={}){super({message:e??"Request timed out."})}},ufe=class extends bp{},dfe=class extends bp{},ffe=class extends bp{},pfe=class extends bp{},mfe=class extends bp{},hfe=class extends bp{},gfe=class extends bp{},yfe=class extends bp{},Mqn=/^[a-z][a-z0-9+.-]*:/i,Oqn=t=>Mqn.test(t),ije=t=>(ije=Array.isArray,ije(t)),AMt=ije;Rqn=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Vn(`${t} must be an integer`);if(e<0)throw new Vn(`${t} must be a positive integer`);return e},z$t=t=>{try{return JSON.parse(t)}catch{return}},Lqn=t=>new Promise(e=>setTimeout(e,t)),HP="0.94.0",$qn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";Fqn=()=>{let t=Dqn();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":HP,"X-Stainless-OS":OMt(Deno.build.os),"X-Stainless-Arch":MMt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":HP,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":HP,"X-Stainless-OS":OMt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":MMt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Uqn();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":HP,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":HP,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};MMt=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",OMt=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),t4e=()=>NMt??(NMt=Fqn());zqn=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});Wqn="urn:ietf:params:oauth:grant-type:jwt-bearer",Vqn="refresh_token",V$t="/v1/oauth/token",vfe="oauth-2025-04-20",qqn="oidc-federation-2026-04-01",Kqn=120,r4e=30,Gqn=5,RMt=1048576;NUe=2e3,Zqn=new Set(["error","error_description","error_uri"]);ms=class extends Vn{constructor(e,n=null,r=null,o=null){super(e),this.statusCode=n,this.body=r,this.requestId=o}};aje=class{constructor(e,n){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=e,this.onAdvisoryRefreshError=n}async getToken(){let e=this.nextForce;this.nextForce=!1;let n=this.cached;if(e||n==null)return(await this.refresh(e)).token;if(n.expiresAt==null)return n.token;let r=n.expiresAt-TR();return r>Kqn?n.token:r>r4e?(this.backgroundRefresh(),n.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(e=!1){return this.pendingRefresh&&!e?this.pendingRefresh:this.doRefresh(e)}backgroundRefresh(){this.pendingRefresh||TR()-this.lastAdvisoryError<Gqn||this.doRefresh().catch(e=>{this.lastAdvisoryError=TR(),this.onAdvisoryRefreshError?.(e)})}doRefresh(e=!1){return this.pendingRefresh=this.provider(e?{forceRefresh:!0}:void 0).then(n=>(this.cached=n,this.pendingRefresh=null,n),n=>{throw this.pendingRefresh=null,n}),this.pendingRefresh}},ps=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0};wfe={off:0,error:200,warn:300,info:400,debug:500},FMt=(t,e,n)=>{if(t){if(Nqn(wfe,t))return t;Mu(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(wfe))}`)}};Xqn={error:e7,warn:e7,info:e7,debug:e7},UMt=new WeakMap;xR=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t),Y$t="1.0",Qqn=/^[A-Za-z0-9_.-]+$/;e5n=async t=>{var e,n;let r=await i4e();if(r===null)return null;let o=t??await X$t();if(o===null)return null;J$t(o);let i=await import("node:fs"),s=(await import("node:path")).join(r,"configs",`${o}.json`),a;try{a=await i.promises.readFile(s,"utf-8")}catch(u){if(u?.code!=="ENOENT")throw Error(`failed to read config file ${s}: ${u}`);a=null}if(a===null){let u=ps("ANTHROPIC_ORGANIZATION_ID"),d=ps("ANTHROPIC_IDENTITY_TOKEN_FILE"),f=ps("ANTHROPIC_FEDERATION_RULE_ID");return f&&u?{fromFile:!1,config:{organization_id:u,workspace_id:ps("ANTHROPIC_WORKSPACE_ID"),base_url:ps("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:f,service_account_id:ps("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:d?{source:"file",path:d}:void 0,scope:ps("ANTHROPIC_SCOPE")}}}:null}let l;try{l=JSON.parse(a)}catch(u){throw Error(`failed to parse config file ${s}: ${u}`)}if(!l.authentication)throw Error(`config file ${s} is missing "authentication"`);let c=l.authentication.type;if(c!=="oidc_federation"&&c!=="user_oauth")throw Error(`authentication.type "${c}" is not a known authentication type`);if(l.organization_id??(l.organization_id=ps("ANTHROPIC_ORGANIZATION_ID")),l.workspace_id??(l.workspace_id=ps("ANTHROPIC_WORKSPACE_ID")),l.base_url??(l.base_url=ps("ANTHROPIC_BASE_URL")),(e=l.authentication).scope??(e.scope=ps("ANTHROPIC_SCOPE")),l.authentication.type==="oidc_federation"){if(!l.authentication.identity_token){let u=ps("ANTHROPIC_IDENTITY_TOKEN_FILE");u&&(l.authentication.identity_token={source:"file",path:u})}l.authentication.federation_rule_id||(l.authentication.federation_rule_id=ps("ANTHROPIC_FEDERATION_RULE_ID")??""),(n=l.authentication).service_account_id??(n.service_account_id=ps("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:l,fromFile:!0}},t5n=async(t,e)=>{if(t?.authentication.credentials_path)return t.authentication.credentials_path;let n=await i4e();if(!n)return null;let r=e??await X$t();return r?(J$t(r),(await import("node:path")).join(n,"credentials",`${r}.json`)):null},i4e=async()=>{if(!n5n())return null;let t=await import("node:path"),e=ps("ANTHROPIC_CONFIG_DIR");if(e)return e;if(t4e()["X-Stainless-OS"]==="Windows"){let o=ps("APPDATA");if(o)return t.join(o,"Anthropic");let i=ps("USERPROFILE");return i?t.join(i,"AppData","Roaming","Anthropic"):null}let n=ps("XDG_CONFIG_HOME");if(n)return t.join(n,"anthropic");let r=ps("HOME");return r?t.join(r,".config","anthropic"):null},n5n=()=>{let t=t4e()["X-Stainless-Runtime"];return t==="node"||t==="deno"},X$t=async()=>{let t=await i4e();if(!t)return null;let e=ps("ANTHROPIC_PROFILE");if(e)return e;let n=await import("node:fs"),r=(await import("node:path")).join(t,"active_config");try{return(await n.promises.readFile(r,"utf-8")).trim()||"default"}catch(o){if(o?.code!=="ENOENT")throw Error(`failed to read ${r}: ${o}`);return"default"}};MR=class{constructor(){jh.set(this,void 0),Bh.set(this,void 0),Ht(this,jh,new Uint8Array,"f"),Ht(this,Bh,null,"f")}decode(e){if(e==null)return[];let n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?o4e(e):e;Ht(this,jh,Jqn([xe(this,jh,"f"),n]),"f");let r=[],o;for(;(o=u5n(xe(this,jh,"f"),xe(this,Bh,"f")))!=null;){if(o.carriage&&xe(this,Bh,"f")==null){Ht(this,Bh,o.index,"f");continue}if(xe(this,Bh,"f")!=null&&(o.index!==xe(this,Bh,"f")+1||o.carriage)){r.push(DMt(xe(this,jh,"f").subarray(0,xe(this,Bh,"f")-1))),Ht(this,jh,xe(this,jh,"f").subarray(xe(this,Bh,"f")),"f"),Ht(this,Bh,null,"f");continue}let i=xe(this,Bh,"f")!==null?o.preceding-1:o.preceding,s=DMt(xe(this,jh,"f").subarray(0,i));r.push(s),Ht(this,jh,xe(this,jh,"f").subarray(o.index),"f"),Ht(this,Bh,null,"f")}return r}flush(){return xe(this,jh,"f").length?this.decode(`
`):[]}};jh=new WeakMap,Bh=new WeakMap;MR.NEWLINE_CHARS=new Set([`
`,"\r"]);MR.NEWLINE_REGEXP=/\r\n|[\n\r]/g;OR=class t{constructor(e,n,r){this.iterator=e,RZ.set(this,void 0),this.controller=n,Ht(this,RZ,r,"f")}static fromSSEResponse(e,n,r){let o=!1,i=r?Mu(r):console;async function*s(){if(o)throw new Vn("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of f5n(e,n)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(c){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),c}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop"||l.event==="message"||l.event==="user.message"||l.event==="user.interrupt"||l.event==="user.tool_confirmation"||l.event==="user.custom_tool_result"||l.event==="agent.message"||l.event==="agent.thinking"||l.event==="agent.tool_use"||l.event==="agent.tool_result"||l.event==="agent.mcp_tool_use"||l.event==="agent.mcp_tool_result"||l.event==="agent.custom_tool_use"||l.event==="agent.thread_context_compacted"||l.event==="session.status_running"||l.event==="session.status_idle"||l.event==="session.status_rescheduled"||l.event==="session.status_terminated"||l.event==="session.error"||l.event==="session.deleted"||l.event==="span.model_request_start"||l.event==="span.model_request_end")try{yield JSON.parse(l.data)}catch(c){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),c}if(l.event!=="ping"&&l.event==="error"){let c=z$t(l.data)??l.data,u=c?.error?.type;throw new bp(void 0,c,void 0,e.headers,u)}}a=!0}catch(l){if(b7(l))return;throw l}finally{a||n.abort()}}return new t(s,n,r)}static fromReadableStream(e,n,r){let o=!1;async function*i(){let a=new MR,l=n4e(e);for await(let c of l)for(let u of a.decode(c))yield u;for(let c of a.flush())yield c}async function*s(){if(o)throw new Vn("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of i())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(b7(l))return;throw l}finally{a||n.abort()}}return new t(s,n,r)}[(RZ=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],n=[],r=this.iterator(),o=i=>({next:()=>{if(i.length===0){let s=r.next();e.push(s),n.push(s)}return i.shift()}});return[new t(()=>o(e),this.controller,xe(this,RZ,"f")),new t(()=>o(n),this.controller,xe(this,RZ,"f"))]}toReadableStream(){let e=this,n;return H$t({async start(){n=e[Symbol.asyncIterator]()},async pull(r){try{let{value:o,done:i}=await n.next();if(i)return r.close();let s=o4e(JSON.stringify(o)+`
`);r.enqueue(s)}catch(o){r.error(o)}},async cancel(){await n.return?.()}})}};lje=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,o]=m5n(e,":");return o.startsWith(" ")&&(o=o.substring(1)),n==="event"?this.event=o:n==="data"&&this.data.push(o),null}};bfe=class t extends Promise{constructor(e,n,r=eDt){super(o=>{o(null)}),this.responsePromise=n,this.parseResponse=r,t7.set(this,void 0),Ht(this,t7,e,"f")}_thenUnwrap(e){return new t(xe(this,t7,"f"),this.responsePromise,async(n,r)=>tDt(e(await this.parseResponse(n,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(xe(this,t7,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};t7=new WeakMap;_fe=class{constructor(e,n,r,o){kde.set(this,void 0),Ht(this,kde,e,"f"),this.options=o,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new Vn("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await xe(this,kde,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(kde=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let n of e.getPaginatedItems())yield n}},cje=class extends bfe{constructor(e,n,r){super(e,n,async(o,i)=>new r(o,i.response,await eDt(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let n of e)yield n}},NR=class extends _fe{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.has_more=r.has_more||!1,this.first_id=r.first_id||null,this.last_id=r.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let n=this.first_id;return n?{...this.options,query:{...sje(this.options.query),before_id:n}}:null}let e=this.last_id;return e?{...this.options,query:{...sje(this.options.query),after_id:e}}:null}},lf=class extends _fe{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.next_page=r.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...sje(this.options.query),page:e}}:null}},nDt=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};rDt=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",s4e=async(t,e,n=!0)=>({...t,body:await g5n(t.body,e,n)}),BMt=new WeakMap;g5n=async(t,e,n=!0)=>{if(!await h5n(e))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(t||{}).map(([o,i])=>uje(r,o,i,n))),r},y5n=t=>t instanceof Blob&&"name"in t,uje=async(t,e,n,r)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response){let o={},i=n.headers.get("Content-Type");i&&(o={type:i}),t.append(e,hB([await n.blob()],Bde(n,r),o))}else if(rDt(n))t.append(e,hB([await new Response(W$t(n)).blob()],Bde(n,r)));else if(y5n(n))t.append(e,hB([n],Bde(n,r),{type:n.type}));else if(Array.isArray(n))await Promise.all(n.map(o=>uje(t,e+"[]",o,r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([o,i])=>uje(t,`${e}[${o}]`,i,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},oDt=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",v5n=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&oDt(t),w5n=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";Xs=class{constructor(e){this._client=e}},iDt=Symbol.for("brand.privateNullableHeaders");lt=t=>{let e=new Headers,n=new Set;for(let r of t){let o=new Set;for(let[i,s]of x5n(r)){let a=i.toLowerCase();o.has(a)||(e.delete(i),o.add(a)),s===null?(e.delete(i),n.add(a)):(e.append(i,s),n.delete(a))}}return{[iDt]:!0,values:e,nulls:n}};zMt=Object.freeze(Object.create(null)),S5n=(t=sDt)=>function(e,...n){if(e.length===1)return e[0];let r=!1,o=[],i=e.reduce((c,u,d)=>{/[?#]/.test(u)&&(r=!0);let f=n[d],p=(r?encodeURIComponent:t)(""+f);return d!==n.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??zMt)??zMt)?.toString)&&(p=f+"",o.push({start:c.length+u.length,length:p.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),c+u+(d===n.length?"":p)},""),s=i.split(/[?#]/,1)[0],a=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=a.exec(s))!==null;)o.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(o.sort((c,u)=>c.start-u.start),o.length>0){let c=0,u=o.reduce((d,f)=>{let p=" ".repeat(f.start-c),m="^".repeat(f.length);return c=f.start+f.length,d+p+m},"");throw new Vn(`Path parameters result in path with invalid segments:
${o.map(d=>d.error).join(`
`)}
${i}
${u}`)}return i},mn=S5n(sDt),xfe=class extends Xs{create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/environments?beta=true",{body:o,...n,headers:lt([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(mn`/v1/environments/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(mn`/v1/environments/${e}?beta=true`,{body:i,...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/environments?beta=true",lf,{query:o,...n,headers:lt([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(mn`/v1/environments/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,n={},r){let{betas:o}=n??{};return this._client.post(mn`/v1/environments/${e}/archive?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}},c7=Symbol("anthropic.sdk.stainlessHelper");Sfe=class extends Xs{list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/files?beta=true",NR,{query:o,...n,headers:lt([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(mn`/v1/files/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString()},r?.headers])})}download(e,n={},r){let{betas:o}=n??{};return this._client.get(mn`/v1/files/${e}/content?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}retrieveMetadata(e,n={},r){let{betas:o}=n??{};return this._client.get(mn`/v1/files/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString()},r?.headers])})}upload(e,n){let{betas:r,...o}=e;return this._client.post("/v1/files?beta=true",s4e({body:o,...n,headers:lt([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},C5n(o.file),n?.headers])},this._client))}},Cfe=class extends Xs{retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(mn`/v1/models/${e}?beta=true`,{...r,headers:lt([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void 0},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/models?beta=true",NR,{query:o,...n,headers:lt([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}},kfe=class extends Xs{create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/user_profiles?beta=true",{body:o,...n,headers:lt([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(mn`/v1/user_profiles/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(mn`/v1/user_profiles/${e}?beta=true`,{body:i,...r,headers:lt([{"anthropic-beta":[...o??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/user_profiles?beta=true",lf,{query:o,...n,headers:lt([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},n?.headers])})}createEnrollmentURL(e,n={},r){let{betas:o}=n??{};return this._client.post(mn`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}},Ife=class extends Xs{list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(mn`/v1/agents/${e}/versions?beta=true`,lf,{query:i,...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}},_7=class extends Xs{constructor(){super(...arguments),this.versions=new Ife(this._client)}create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/agents?beta=true",{body:o,...n,headers:lt([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o,...i}=n??{};return this._client.get(mn`/v1/agents/${e}?beta=true`,{query:i,...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(mn`/v1/agents/${e}?beta=true`,{body:i,...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/agents?beta=true",lf,{query:o,...n,headers:lt([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}archive(e,n={},r){let{betas:o}=n??{};return this._client.post(mn`/v1/agents/${e}/archive?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};_7.Versions=Ife;Tfe=class extends Xs{create(e,n,r){let{view:o,betas:i,...s}=n;return this._client.post(mn`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:o},body:s,...r,headers:lt([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,n,r){let{memory_store_id:o,betas:i,...s}=n;return this._client.get(mn`/v1/memory_stores/${o}/memories/${e}?beta=true`,{query:s,...r,headers:lt([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{memory_store_id:o,view:i,betas:s,...a}=n;return this._client.post(mn`/v1/memory_stores/${o}/memories/${e}?beta=true`,{query:{view:i},body:a,...r,headers:lt([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(mn`/v1/memory_stores/${e}/memories?beta=true`,lf,{query:i,...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,n,r){let{memory_store_id:o,expected_content_sha256:i,betas:s}=n;return this._client.delete(mn`/v1/memory_stores/${o}/memories/${e}?beta=true`,{query:{expected_content_sha256:i},...r,headers:lt([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}},Pfe=class extends Xs{retrieve(e,n,r){let{memory_store_id:o,betas:i,...s}=n;return this._client.get(mn`/v1/memory_stores/${o}/memory_versions/${e}?beta=true`,{query:s,...r,headers:lt([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(mn`/v1/memory_stores/${e}/memory_versions?beta=true`,lf,{query:i,...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}redact(e,n,r){let{memory_store_id:o,betas:i}=n;return this._client.post(mn`/v1/memory_stores/${o}/memory_versions/${e}/redact?beta=true`,{...r,headers:lt([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}},kB=class extends Xs{constructor(){super(...arguments),this.memories=new Tfe(this._client),this.memoryVersions=new Pfe(this._client)}create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/memory_stores?beta=true",{body:o,...n,headers:lt([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(mn`/v1/memory_stores/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(mn`/v1/memory_stores/${e}?beta=true`,{body:i,...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/memory_stores?beta=true",lf,{query:o,...n,headers:lt([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(mn`/v1/memory_stores/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,n={},r){let{betas:o}=n??{};return this._client.post(mn`/v1/memory_stores/${e}/archive?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};kB.Memories=Tfe;kB.MemoryVersions=Pfe;Afe=class t{constructor(e,n){this.iterator=e,this.controller=n}async*decoder(){let e=new MR;for await(let n of this.iterator)for(let r of e.decode(n))yield JSON.parse(r);for(let n of e.flush())yield JSON.parse(n)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,n){if(!e.body)throw n.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Vn("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new Vn("Attempted to iterate over a response with no body");return new t(n4e(e.body),n)}},Efe=class extends Xs{create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/messages/batches?beta=true",{body:o,...n,headers:lt([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(mn`/v1/messages/batches/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",NR,{query:o,...n,headers:lt([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(mn`/v1/messages/batches/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},r?.headers])})}cancel(e,n={},r){let{betas:o}=n??{};return this._client.post(mn`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},r?.headers])})}async results(e,n={},r){let o=await this.retrieve(e);if(!o.results_url)throw new Vn(`No batch \`results_url\`; Has it finished processing? ${o.processing_status} - ${o.id}`);let{betas:i}=n??{};return this._client.get(o.results_url,{...r,headers:lt([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},r?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((s,a)=>Afe.fromResponse(a.response,a.controller))}},cDt={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};I5n=t=>{let e=0,n=[];for(;e<t.length;){let r=t[e];if(r==="\\"){e++;continue}if(r==="{"){n.push({type:"brace",value:"{"}),e++;continue}if(r==="}"){n.push({type:"brace",value:"}"}),e++;continue}if(r==="["){n.push({type:"paren",value:"["}),e++;continue}if(r==="]"){n.push({type:"paren",value:"]"}),e++;continue}if(r===":"){n.push({type:"separator",value:":"}),e++;continue}if(r===","){n.push({type:"delimiter",value:","}),e++;continue}if(r==='"'){let s="",a=!1;for(r=t[++e];r!=='"';){if(e===t.length){a=!0;break}if(r==="\\"){if(e++,e===t.length){a=!0;break}s+=r+t[e],r=t[++e]}else s+=r,r=t[++e]}r=t[++e],!a&&n.push({type:"string",value:s});continue}if(r&&/\s/.test(r)){e++;continue}let o=/[0-9]/;if(r&&o.test(r)||r==="-"||r==="."){let s="";for(r==="-"&&(s+=r,r=t[++e]);r&&o.test(r)||r===".";)s+=r,r=t[++e];n.push({type:"number",value:s});continue}let i=/[a-z]/i;if(r&&i.test(r)){let s="";for(;r&&i.test(r)&&e!==t.length;)s+=r,r=t[++e];if(s=="true"||s=="false"||s==="null")n.push({type:"name",value:s});else{e++;continue}continue}e++}return n},uB=t=>{if(t.length===0)return t;let e=t[t.length-1];switch(e.type){case"separator":return t=t.slice(0,t.length-1),uB(t);case"number":let n=e.value[e.value.length-1];if(n==="."||n==="-")return t=t.slice(0,t.length-1),uB(t);case"string":let r=t[t.length-2];if(r?.type==="delimiter")return t=t.slice(0,t.length-1),uB(t);if(r?.type==="brace"&&r.value==="{")return t=t.slice(0,t.length-1),uB(t);break;case"delimiter":return t=t.slice(0,t.length-1),uB(t)}return t},T5n=t=>{let e=[];return t.map(n=>{n.type==="brace"&&(n.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),n.type==="paren"&&(n.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(n=>{n==="}"?t.push({type:"brace",value:"}"}):n==="]"&&t.push({type:"paren",value:"]"})}),t},P5n=t=>{let e="";return t.map(n=>{switch(n.type){case"string":e+='"'+n.value+'"';break;default:e+=n.value;break}}),e},fDt=t=>JSON.parse(P5n(T5n(uB(I5n(t))))),qMt="__json_buf";fje=class t{constructor(e,n){zy.add(this),this.messages=[],this.receivedMessages=[],LP.set(this,void 0),tB.set(this,null),this.controller=new AbortController,LZ.set(this,void 0),Ide.set(this,()=>{}),$Z.set(this,()=>{}),DZ.set(this,void 0),Tde.set(this,()=>{}),FZ.set(this,()=>{}),kk.set(this,{}),UZ.set(this,!1),Pde.set(this,!1),Ade.set(this,!1),wR.set(this,!1),Ede.set(this,void 0),Mde.set(this,void 0),jZ.set(this,void 0),Ode.set(this,r=>{if(Ht(this,Pde,!0,"f"),b7(r)&&(r=new Kh),r instanceof Kh)return Ht(this,Ade,!0,"f"),this._emit("abort",r);if(r instanceof Vn)return this._emit("error",r);if(r instanceof Error){let o=new Vn(r.message);return o.cause=r,this._emit("error",o)}return this._emit("error",new Vn(String(r)))}),Ht(this,LZ,new Promise((r,o)=>{Ht(this,Ide,r,"f"),Ht(this,$Z,o,"f")}),"f"),Ht(this,DZ,new Promise((r,o)=>{Ht(this,Tde,r,"f"),Ht(this,FZ,o,"f")}),"f"),xe(this,LZ,"f").catch(()=>{}),xe(this,DZ,"f").catch(()=>{}),Ht(this,tB,e,"f"),Ht(this,jZ,n?.logger??console,"f")}get response(){return xe(this,Ede,"f")}get request_id(){return xe(this,Mde,"f")}async withResponse(){Ht(this,wR,!0,"f");let e=await xe(this,LZ,"f");if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let n=new t(null);return n._run(()=>n._fromReadableStream(e)),n}static createMessage(e,n,r,{logger:o}={}){let i=new t(n,{logger:o});for(let s of n.messages)i._addMessageParam(s);return Ht(i,tB,{...n,stream:!0},"f"),i._run(()=>i._createMessage(e,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},xe(this,Ode,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,n=!0){this.receivedMessages.push(e),n&&this._emit("message",e)}async _createMessage(e,n,r){let o=r?.signal,i;o&&(o.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),o.addEventListener("abort",i));try{xe(this,zy,"m",LUe).call(this);let{response:s,data:a}=await e.create({...n,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(s);for await(let l of a)xe(this,zy,"m",$Ue).call(this,l);if(a.controller.signal?.aborted)throw new Kh;xe(this,zy,"m",DUe).call(this)}finally{o&&i&&o.removeEventListener("abort",i)}}_connected(e){this.ended||(Ht(this,Ede,e,"f"),Ht(this,Mde,e?.headers.get("request-id"),"f"),xe(this,Ide,"f").call(this,e),this._emit("connect"))}get ended(){return xe(this,UZ,"f")}get errored(){return xe(this,Pde,"f")}get aborted(){return xe(this,Ade,"f")}abort(){this.controller.abort()}on(e,n){return(xe(this,kk,"f")[e]||(xe(this,kk,"f")[e]=[])).push({listener:n}),this}off(e,n){let r=xe(this,kk,"f")[e];if(!r)return this;let o=r.findIndex(i=>i.listener===n);return o>=0&&r.splice(o,1),this}once(e,n){return(xe(this,kk,"f")[e]||(xe(this,kk,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,r)=>{Ht(this,wR,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,n)})}async done(){Ht(this,wR,!0,"f"),await xe(this,DZ,"f")}get currentMessage(){return xe(this,LP,"f")}async finalMessage(){return await this.done(),xe(this,zy,"m",RUe).call(this)}async finalText(){return await this.done(),xe(this,zy,"m",WMt).call(this)}_emit(e,...n){if(xe(this,UZ,"f"))return;e==="end"&&(Ht(this,UZ,!0,"f"),xe(this,Tde,"f").call(this));let r=xe(this,kk,"f")[e];if(r&&(xe(this,kk,"f")[e]=r.filter(o=>!o.once),r.forEach(({listener:o})=>o(...n))),e==="abort"){let o=n[0];!xe(this,wR,"f")&&!r?.length&&Promise.reject(o),xe(this,$Z,"f").call(this,o),xe(this,FZ,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=n[0];!xe(this,wR,"f")&&!r?.length&&Promise.reject(o),xe(this,$Z,"f").call(this,o),xe(this,FZ,"f").call(this,o),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",xe(this,zy,"m",RUe).call(this))}async _fromReadableStream(e,n){let r=n?.signal,o;r&&(r.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),r.addEventListener("abort",o));try{xe(this,zy,"m",LUe).call(this),this._connected(null);let i=OR.fromReadableStream(e,this.controller);for await(let s of i)xe(this,zy,"m",$Ue).call(this,s);if(i.controller.signal?.aborted)throw new Kh;xe(this,zy,"m",DUe).call(this)}finally{r&&o&&r.removeEventListener("abort",o)}}[(LP=new WeakMap,tB=new WeakMap,LZ=new WeakMap,Ide=new WeakMap,$Z=new WeakMap,DZ=new WeakMap,Tde=new WeakMap,FZ=new WeakMap,kk=new WeakMap,UZ=new WeakMap,Pde=new WeakMap,Ade=new WeakMap,wR=new WeakMap,Ede=new WeakMap,Mde=new WeakMap,jZ=new WeakMap,Ode=new WeakMap,zy=new WeakSet,RUe=function(){if(this.receivedMessages.length===0)throw new Vn("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},WMt=function(){if(this.receivedMessages.length===0)throw new Vn("stream ended without producing a Message with role=assistant");let e=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(e.length===0)throw new Vn("stream ended without producing a content block with type=text");return e.join(" ")},LUe=function(){this.ended||Ht(this,LP,void 0,"f")},$Ue=function(e){if(this.ended)return;let n=xe(this,zy,"m",VMt).call(this,e);switch(this._emit("streamEvent",e,n),e.type){case"content_block_delta":{let r=n.content.at(-1);switch(e.delta.type){case"text_delta":{r.type==="text"&&this._emit("text",e.delta.text,r.text||"");break}case"citations_delta":{r.type==="text"&&this._emit("citation",e.delta.citation,r.citations??[]);break}case"input_json_delta":{KMt(r)&&r.input&&this._emit("inputJson",e.delta.partial_json,r.input);break}case"thinking_delta":{r.type==="thinking"&&this._emit("thinking",e.delta.thinking,r.thinking);break}case"signature_delta":{r.type==="thinking"&&this._emit("signature",r.signature);break}case"compaction_delta":{r.type==="compaction"&&r.content&&this._emit("compaction",r.content);break}default:e.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(HMt(n,xe(this,tB,"f"),{logger:xe(this,jZ,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{Ht(this,LP,n,"f");break}case"content_block_start":case"message_delta":break}},DUe=function(){if(this.ended)throw new Vn("stream has ended, this shouldn't happen");let e=xe(this,LP,"f");if(!e)throw new Vn("request ended without sending any chunks");return Ht(this,LP,void 0,"f"),HMt(e,xe(this,tB,"f"),{logger:xe(this,jZ,"f")})},VMt=function(e){let n=xe(this,LP,"f");if(e.type==="message_start"){if(n)throw new Vn(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!n)throw new Vn(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":return n;case"message_delta":return n.container=e.delta.container,n.stop_reason=e.delta.stop_reason,n.stop_sequence=e.delta.stop_sequence,n.usage.output_tokens=e.usage.output_tokens,n.context_management=e.context_management,e.usage.input_tokens!=null&&(n.usage.input_tokens=e.usage.input_tokens),e.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),e.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),e.usage.server_tool_use!=null&&(n.usage.server_tool_use=e.usage.server_tool_use),e.usage.iterations!=null&&(n.usage.iterations=e.usage.iterations),n;case"content_block_start":return n.content.push(e.content_block),n;case"content_block_delta":{let r=n.content.at(e.index);switch(e.delta.type){case"text_delta":{r?.type==="text"&&(n.content[e.index]={...r,text:(r.text||"")+e.delta.text});break}case"citations_delta":{r?.type==="text"&&(n.content[e.index]={...r,citations:[...r.citations??[],e.delta.citation]});break}case"input_json_delta":{if(r&&KMt(r)){let o=r[qMt]||"";o+=e.delta.partial_json;let i={...r};if(Object.defineProperty(i,qMt,{value:o,enumerable:!1,writable:!0}),o)try{i.input=fDt(o)}catch(s){let a=new Vn(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${s}. JSON: ${o}`);xe(this,Ode,"f").call(this,a)}n.content[e.index]=i}break}case"thinking_delta":{r?.type==="thinking"&&(n.content[e.index]={...r,thinking:r.thinking+e.delta.thinking});break}case"signature_delta":{r?.type==="thinking"&&(n.content[e.index]={...r,signature:e.delta.signature});break}case"compaction_delta":{r?.type==="compaction"&&(n.content[e.index]={...r,content:(r.content||"")+e.delta.content});break}default:e.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],n=[],r=!1;return this.on("streamEvent",o=>{let i=n.shift();i?i.resolve(o):e.push(o)}),this.on("end",()=>{r=!0;for(let o of n)o.resolve(void 0);n.length=0}),this.on("abort",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),this.on("error",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>n.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new OR(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},Mfe=class extends Error{constructor(e){let n=typeof e=="string"?e:e.map(r=>r.type==="text"?r.text:`[${r.type}]`).join(" ");super(n),this.name="ToolError",this.content=e}},A5n=1e5,E5n=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
1. Task Overview
The user's core request and success criteria
Any clarifications or constraints they specified
2. Current State
What has been completed so far
Files created, modified, or analyzed (with paths if relevant)
Key outputs or artifacts produced
3. Important Discoveries
Technical constraints or requirements uncovered
Decisions made and their rationale
Errors encountered and how they were resolved
What approaches were tried that didn't work (and why)
4. Next Steps
Specific actions needed to complete the task
Any blockers or open questions to resolve
Priority order if multiple steps remain
5. Context to Preserve
User preferences or style requirements
Domain-specific details that aren't obvious
Any promises made to the user
Be concise but complete\u2014err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
Wrap your summary in <summary></summary> tags.`;Ofe=class{constructor(e,n,r){BZ.add(this),this.client=e,nB.set(this,!1),bR.set(this,!1),$c.set(this,void 0),_m.set(this,void 0),Uh.set(this,void 0),Mk.set(this,void 0),$P.set(this,void 0),zZ.set(this,0),Ht(this,$c,{params:{...n,messages:structuredClone(n.messages)}},"f");let o=["BetaToolRunner",...aDt(n.tools,n.messages)].join(", ");Ht(this,_m,{...r,headers:lt([{"x-stainless-helper":o},r?.headers])},"f"),Ht(this,$P,ZMt(),"f"),n.compactionControl?.enabled&&console.warn('Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction')}async*[(nB=new WeakMap,bR=new WeakMap,$c=new WeakMap,_m=new WeakMap,Uh=new WeakMap,Mk=new WeakMap,$P=new WeakMap,zZ=new WeakMap,BZ=new WeakSet,GMt=async function(){let e=xe(this,$c,"f").params.compactionControl;if(!e||!e.enabled)return!1;let n=0;if(xe(this,Uh,"f")!==void 0)try{let l=await xe(this,Uh,"f");n=l.usage.input_tokens+(l.usage.cache_creation_input_tokens??0)+(l.usage.cache_read_input_tokens??0)+l.usage.output_tokens}catch{return!1}let r=e.contextTokenThreshold??A5n;if(n<r)return!1;let o=e.model??xe(this,$c,"f").params.model,i=e.summaryPrompt??E5n,s=xe(this,$c,"f").params.messages;if(s[s.length-1].role==="assistant"){let l=s[s.length-1];if(Array.isArray(l.content)){let c=l.content.filter(u=>u.type!=="tool_use");c.length===0?s.pop():l.content=c}}let a=await this.client.beta.messages.create({model:o,messages:[...s,{role:"user",content:[{type:"text",text:i}]}],max_tokens:xe(this,$c,"f").params.max_tokens},{signal:xe(this,_m,"f").signal,headers:lt([xe(this,_m,"f").headers,{"x-stainless-helper":"compaction"}])});if(a.content[0]?.type!=="text")throw new Vn("Expected text response for compaction");return xe(this,$c,"f").params.messages=[{role:"user",content:a.content}],!0},Symbol.asyncIterator)](){var e;if(xe(this,nB,"f"))throw new Vn("Cannot iterate over a consumed stream");Ht(this,nB,!0,"f"),Ht(this,bR,!0,"f"),Ht(this,Mk,void 0,"f");try{for(;;){let n;try{if(xe(this,$c,"f").params.max_iterations&&xe(this,zZ,"f")>=xe(this,$c,"f").params.max_iterations)break;Ht(this,bR,!1,"f"),Ht(this,Mk,void 0,"f"),Ht(this,zZ,(e=xe(this,zZ,"f"),e++,e),"f"),Ht(this,Uh,void 0,"f");let{max_iterations:r,compactionControl:o,...i}=xe(this,$c,"f").params;if(i.stream?(n=this.client.beta.messages.stream({...i},xe(this,_m,"f")),Ht(this,Uh,n.finalMessage(),"f"),xe(this,Uh,"f").catch(()=>{}),yield n):(Ht(this,Uh,this.client.beta.messages.create({...i,stream:!1},xe(this,_m,"f")),"f"),yield xe(this,Uh,"f")),!await xe(this,BZ,"m",GMt).call(this)){if(!xe(this,bR,"f")){let{role:a,content:l}=await xe(this,Uh,"f");xe(this,$c,"f").params.messages.push({role:a,content:l})}let s=await xe(this,BZ,"m",pje).call(this,xe(this,$c,"f").params.messages.at(-1));if(s)xe(this,$c,"f").params.messages.push(s);else if(!xe(this,bR,"f"))break}}finally{n&&n.abort()}}if(!xe(this,Uh,"f"))throw new Vn("ToolRunner concluded without a message from the server");xe(this,$P,"f").resolve(await xe(this,Uh,"f"))}catch(n){throw Ht(this,nB,!1,"f"),xe(this,$P,"f").promise.catch(()=>{}),xe(this,$P,"f").reject(n),Ht(this,$P,ZMt(),"f"),n}}setMessagesParams(e){typeof e=="function"?xe(this,$c,"f").params=e(xe(this,$c,"f").params):xe(this,$c,"f").params=e,Ht(this,bR,!0,"f"),Ht(this,Mk,void 0,"f")}setRequestOptions(e){typeof e=="function"?Ht(this,_m,e(xe(this,_m,"f")),"f"):Ht(this,_m,{...xe(this,_m,"f"),...e},"f")}async generateToolResponse(e=xe(this,_m,"f").signal){let n=await xe(this,Uh,"f")??this.params.messages.at(-1);return n?xe(this,BZ,"m",pje).call(this,n,e):null}done(){return xe(this,$P,"f").promise}async runUntilDone(){if(!xe(this,nB,"f"))for await(let e of this);return this.done()}get params(){return xe(this,$c,"f").params}pushMessages(...e){this.setMessagesParams(n=>({...n,messages:[...n.messages,...e]}))}then(e,n){return this.runUntilDone().then(e,n)}};pje=async function(t,e=xe(this,_m,"f").signal){return xe(this,Mk,"f")!==void 0?xe(this,Mk,"f"):(Ht(this,Mk,M5n(xe(this,$c,"f").params,t,{...xe(this,_m,"f"),signal:e}),"f"),xe(this,Mk,"f"))};YMt={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"},O5n=["claude-mythos-preview","claude-opus-4-6"],RR=class extends Xs{constructor(){super(...arguments),this.batches=new Efe(this._client)}create(e,n){let r=JMt(e),{betas:o,...i}=r;i.model in YMt&&console.warn(`The model '${i.model}' is deprecated and will reach end-of-life on ${YMt[i.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),O5n.includes(i.model)&&i.thinking&&i.thinking.type==="enabled"&&console.warn(`Using Claude with ${i.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let s=this._client._options.timeout;if(!i.stream&&s==null){let l=cDt[i.model]??void 0;s=this._client.calculateNonstreamingTimeout(i.max_tokens,l)}let a=lDt(i.tools,i.messages);return this._client.post("/v1/messages?beta=true",{body:i,timeout:s??6e5,...n,headers:lt([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void 0},a,n?.headers]),stream:r.stream??!1})}parse(e,n){return n={...n,headers:lt([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},n?.headers])},this.create(e,n).then(r=>dDt(r,e,{logger:this._client.logger??console}))}stream(e,n){return fje.createMessage(this,e,n)}countTokens(e,n){let r=JMt(e),{betas:o,...i}=r;return this._client.post("/v1/messages/count_tokens?beta=true",{body:i,...n,headers:lt([{"anthropic-beta":[...o??[],"token-counting-2024-11-01"].toString()},n?.headers])})}toolRunner(e,n){return new Ofe(this._client,e,n)}};RR.Batches=Efe;RR.BetaToolRunner=Ofe;RR.ToolError=Mfe;Nfe=class extends Xs{list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(mn`/v1/sessions/${e}/events?beta=true`,lf,{query:i,...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}send(e,n,r){let{betas:o,...i}=n;return this._client.post(mn`/v1/sessions/${e}/events?beta=true`,{body:i,...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}stream(e,n={},r){let{betas:o}=n??{};return this._client.get(mn`/v1/sessions/${e}/events/stream?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers]),stream:!0})}},Rfe=class extends Xs{retrieve(e,n,r){let{session_id:o,betas:i}=n;return this._client.get(mn`/v1/sessions/${o}/resources/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{session_id:o,betas:i,...s}=n;return this._client.post(mn`/v1/sessions/${o}/resources/${e}?beta=true`,{body:s,...r,headers:lt([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(mn`/v1/sessions/${e}/resources?beta=true`,lf,{query:i,...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,n,r){let{session_id:o,betas:i}=n;return this._client.delete(mn`/v1/sessions/${o}/resources/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}add(e,n,r){let{betas:o,...i}=n;return this._client.post(mn`/v1/sessions/${e}/resources?beta=true`,{body:i,...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}},IB=class extends Xs{constructor(){super(...arguments),this.events=new Nfe(this._client),this.resources=new Rfe(this._client)}create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/sessions?beta=true",{body:o,...n,headers:lt([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(mn`/v1/sessions/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(mn`/v1/sessions/${e}?beta=true`,{body:i,...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/sessions?beta=true",lf,{query:o,...n,headers:lt([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(mn`/v1/sessions/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,n={},r){let{betas:o}=n??{};return this._client.post(mn`/v1/sessions/${e}/archive?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};IB.Events=Nfe;IB.Resources=Rfe;Lfe=class extends Xs{create(e,n={},r){let{betas:o,...i}=n??{};return this._client.post(mn`/v1/skills/${e}/versions?beta=true`,s4e({body:i,...r,headers:lt([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},r?.headers])},this._client))}retrieve(e,n,r){let{skill_id:o,betas:i}=n;return this._client.get(mn`/v1/skills/${o}/versions/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...i??[],"skills-2025-10-02"].toString()},r?.headers])})}list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(mn`/v1/skills/${e}/versions?beta=true`,lf,{query:i,...r,headers:lt([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},r?.headers])})}delete(e,n,r){let{skill_id:o,betas:i}=n;return this._client.delete(mn`/v1/skills/${o}/versions/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...i??[],"skills-2025-10-02"].toString()},r?.headers])})}},x7=class extends Xs{constructor(){super(...arguments),this.versions=new Lfe(this._client)}create(e={},n){let{betas:r,...o}=e??{};return this._client.post("/v1/skills?beta=true",s4e({body:o,...n,headers:lt([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},n?.headers])},this._client,!1))}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(mn`/v1/skills/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/skills?beta=true",lf,{query:o,...n,headers:lt([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(mn`/v1/skills/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},r?.headers])})}};x7.Versions=Lfe;$fe=class extends Xs{create(e,n,r){let{betas:o,...i}=n;return this._client.post(mn`/v1/vaults/${e}/credentials?beta=true`,{body:i,...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,n,r){let{vault_id:o,betas:i}=n;return this._client.get(mn`/v1/vaults/${o}/credentials/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{vault_id:o,betas:i,...s}=n;return this._client.post(mn`/v1/vaults/${o}/credentials/${e}?beta=true`,{body:s,...r,headers:lt([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(mn`/v1/vaults/${e}/credentials?beta=true`,lf,{query:i,...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,n,r){let{vault_id:o,betas:i}=n;return this._client.delete(mn`/v1/vaults/${o}/credentials/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,n,r){let{vault_id:o,betas:i}=n;return this._client.post(mn`/v1/vaults/${o}/credentials/${e}/archive?beta=true`,{...r,headers:lt([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}},S7=class extends Xs{constructor(){super(...arguments),this.credentials=new $fe(this._client)}create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/vaults?beta=true",{body:o,...n,headers:lt([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(mn`/v1/vaults/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(mn`/v1/vaults/${e}?beta=true`,{body:i,...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/vaults?beta=true",lf,{query:o,...n,headers:lt([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(mn`/v1/vaults/${e}?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,n={},r){let{betas:o}=n??{};return this._client.post(mn`/v1/vaults/${e}/archive?beta=true`,{...r,headers:lt([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};S7.Credentials=$fe;Cm=class extends Xs{constructor(){super(...arguments),this.models=new Cfe(this._client),this.messages=new RR(this._client),this.agents=new _7(this._client),this.environments=new xfe(this._client),this.sessions=new IB(this._client),this.vaults=new S7(this._client),this.memoryStores=new kB(this._client),this.files=new Sfe(this._client),this.skills=new x7(this._client),this.userProfiles=new kfe(this._client)}};Cm.Models=Cfe;Cm.Messages=RR;Cm.Agents=_7;Cm.Environments=xfe;Cm.Sessions=IB;Cm.Vaults=S7;Cm.MemoryStores=kB;Cm.Files=Sfe;Cm.Skills=x7;Cm.UserProfiles=kfe;Dfe=class extends Xs{create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/complete",{body:o,timeout:this._client._options.timeout??6e5,...n,headers:lt([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers]),stream:e.stream??!1})}};tOt="__json_buf";mje=class t{constructor(e,n){Hy.add(this),this.messages=[],this.receivedMessages=[],DP.set(this,void 0),rB.set(this,null),this.controller=new AbortController,HZ.set(this,void 0),Nde.set(this,()=>{}),WZ.set(this,()=>{}),VZ.set(this,void 0),Rde.set(this,()=>{}),qZ.set(this,()=>{}),Ik.set(this,{}),KZ.set(this,!1),Lde.set(this,!1),$de.set(this,!1),_R.set(this,!1),Dde.set(this,void 0),Fde.set(this,void 0),GZ.set(this,void 0),UUe.set(this,r=>{if(Ht(this,Lde,!0,"f"),b7(r)&&(r=new Kh),r instanceof Kh)return Ht(this,$de,!0,"f"),this._emit("abort",r);if(r instanceof Vn)return this._emit("error",r);if(r instanceof Error){let o=new Vn(r.message);return o.cause=r,this._emit("error",o)}return this._emit("error",new Vn(String(r)))}),Ht(this,HZ,new Promise((r,o)=>{Ht(this,Nde,r,"f"),Ht(this,WZ,o,"f")}),"f"),Ht(this,VZ,new Promise((r,o)=>{Ht(this,Rde,r,"f"),Ht(this,qZ,o,"f")}),"f"),xe(this,HZ,"f").catch(()=>{}),xe(this,VZ,"f").catch(()=>{}),Ht(this,rB,e,"f"),Ht(this,GZ,n?.logger??console,"f")}get response(){return xe(this,Dde,"f")}get request_id(){return xe(this,Fde,"f")}async withResponse(){Ht(this,_R,!0,"f");let e=await xe(this,HZ,"f");if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let n=new t(null);return n._run(()=>n._fromReadableStream(e)),n}static createMessage(e,n,r,{logger:o}={}){let i=new t(n,{logger:o});for(let s of n.messages)i._addMessageParam(s);return Ht(i,rB,{...n,stream:!0},"f"),i._run(()=>i._createMessage(e,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},xe(this,UUe,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,n=!0){this.receivedMessages.push(e),n&&this._emit("message",e)}async _createMessage(e,n,r){let o=r?.signal,i;o&&(o.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),o.addEventListener("abort",i));try{xe(this,Hy,"m",jUe).call(this);let{response:s,data:a}=await e.create({...n,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(s);for await(let l of a)xe(this,Hy,"m",BUe).call(this,l);if(a.controller.signal?.aborted)throw new Kh;xe(this,Hy,"m",zUe).call(this)}finally{o&&i&&o.removeEventListener("abort",i)}}_connected(e){this.ended||(Ht(this,Dde,e,"f"),Ht(this,Fde,e?.headers.get("request-id"),"f"),xe(this,Nde,"f").call(this,e),this._emit("connect"))}get ended(){return xe(this,KZ,"f")}get errored(){return xe(this,Lde,"f")}get aborted(){return xe(this,$de,"f")}abort(){this.controller.abort()}on(e,n){return(xe(this,Ik,"f")[e]||(xe(this,Ik,"f")[e]=[])).push({listener:n}),this}off(e,n){let r=xe(this,Ik,"f")[e];if(!r)return this;let o=r.findIndex(i=>i.listener===n);return o>=0&&r.splice(o,1),this}once(e,n){return(xe(this,Ik,"f")[e]||(xe(this,Ik,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,r)=>{Ht(this,_R,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,n)})}async done(){Ht(this,_R,!0,"f"),await xe(this,VZ,"f")}get currentMessage(){return xe(this,DP,"f")}async finalMessage(){return await this.done(),xe(this,Hy,"m",FUe).call(this)}async finalText(){return await this.done(),xe(this,Hy,"m",QMt).call(this)}_emit(e,...n){if(xe(this,KZ,"f"))return;e==="end"&&(Ht(this,KZ,!0,"f"),xe(this,Rde,"f").call(this));let r=xe(this,Ik,"f")[e];if(r&&(xe(this,Ik,"f")[e]=r.filter(o=>!o.once),r.forEach(({listener:o})=>o(...n))),e==="abort"){let o=n[0];!xe(this,_R,"f")&&!r?.length&&Promise.reject(o),xe(this,WZ,"f").call(this,o),xe(this,qZ,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=n[0];!xe(this,_R,"f")&&!r?.length&&Promise.reject(o),xe(this,WZ,"f").call(this,o),xe(this,qZ,"f").call(this,o),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",xe(this,Hy,"m",FUe).call(this))}async _fromReadableStream(e,n){let r=n?.signal,o;r&&(r.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),r.addEventListener("abort",o));try{xe(this,Hy,"m",jUe).call(this),this._connected(null);let i=OR.fromReadableStream(e,this.controller);for await(let s of i)xe(this,Hy,"m",BUe).call(this,s);if(i.controller.signal?.aborted)throw new Kh;xe(this,Hy,"m",zUe).call(this)}finally{r&&o&&r.removeEventListener("abort",o)}}[(DP=new WeakMap,rB=new WeakMap,HZ=new WeakMap,Nde=new WeakMap,WZ=new WeakMap,VZ=new WeakMap,Rde=new WeakMap,qZ=new WeakMap,Ik=new WeakMap,KZ=new WeakMap,Lde=new WeakMap,$de=new WeakMap,_R=new WeakMap,Dde=new WeakMap,Fde=new WeakMap,GZ=new WeakMap,UUe=new WeakMap,Hy=new WeakSet,FUe=function(){if(this.receivedMessages.length===0)throw new Vn("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},QMt=function(){if(this.receivedMessages.length===0)throw new Vn("stream ended without producing a Message with role=assistant");let e=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(e.length===0)throw new Vn("stream ended without producing a content block with type=text");return e.join(" ")},jUe=function(){this.ended||Ht(this,DP,void 0,"f")},BUe=function(e){if(this.ended)return;let n=xe(this,Hy,"m",eOt).call(this,e);switch(this._emit("streamEvent",e,n),e.type){case"content_block_delta":{let r=n.content.at(-1);switch(e.delta.type){case"text_delta":{r.type==="text"&&this._emit("text",e.delta.text,r.text||"");break}case"citations_delta":{r.type==="text"&&this._emit("citation",e.delta.citation,r.citations??[]);break}case"input_json_delta":{nOt(r)&&r.input&&this._emit("inputJson",e.delta.partial_json,r.input);break}case"thinking_delta":{r.type==="thinking"&&this._emit("thinking",e.delta.thinking,r.thinking);break}case"signature_delta":{r.type==="thinking"&&this._emit("signature",r.signature);break}default:e.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(XMt(n,xe(this,rB,"f"),{logger:xe(this,GZ,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{Ht(this,DP,n,"f");break}case"content_block_start":case"message_delta":break}},zUe=function(){if(this.ended)throw new Vn("stream has ended, this shouldn't happen");let e=xe(this,DP,"f");if(!e)throw new Vn("request ended without sending any chunks");return Ht(this,DP,void 0,"f"),XMt(e,xe(this,rB,"f"),{logger:xe(this,GZ,"f")})},eOt=function(e){let n=xe(this,DP,"f");if(e.type==="message_start"){if(n)throw new Vn(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!n)throw new Vn(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":return n;case"message_delta":return n.stop_reason=e.delta.stop_reason,n.stop_sequence=e.delta.stop_sequence,n.usage.output_tokens=e.usage.output_tokens,e.usage.input_tokens!=null&&(n.usage.input_tokens=e.usage.input_tokens),e.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),e.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),e.usage.server_tool_use!=null&&(n.usage.server_tool_use=e.usage.server_tool_use),n;case"content_block_start":return n.content.push({...e.content_block}),n;case"content_block_delta":{let r=n.content.at(e.index);switch(e.delta.type){case"text_delta":{r?.type==="text"&&(n.content[e.index]={...r,text:(r.text||"")+e.delta.text});break}case"citations_delta":{r?.type==="text"&&(n.content[e.index]={...r,citations:[...r.citations??[],e.delta.citation]});break}case"input_json_delta":{if(r&&nOt(r)){let o=r[tOt]||"";o+=e.delta.partial_json;let i={...r};Object.defineProperty(i,tOt,{value:o,enumerable:!1,writable:!0}),o&&(i.input=fDt(o)),n.content[e.index]=i}break}case"thinking_delta":{r?.type==="thinking"&&(n.content[e.index]={...r,thinking:r.thinking+e.delta.thinking});break}case"signature_delta":{r?.type==="thinking"&&(n.content[e.index]={...r,signature:e.delta.signature});break}default:e.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],n=[],r=!1;return this.on("streamEvent",o=>{let i=n.shift();i?i.resolve(o):e.push(o)}),this.on("end",()=>{r=!0;for(let o of n)o.resolve(void 0);n.length=0}),this.on("abort",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),this.on("error",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>n.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new OR(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},Ffe=class extends Xs{create(e,n){return this._client.post("/v1/messages/batches",{body:e,...n})}retrieve(e,n){return this._client.get(mn`/v1/messages/batches/${e}`,n)}list(e={},n){return this._client.getAPIList("/v1/messages/batches",NR,{query:e,...n})}delete(e,n){return this._client.delete(mn`/v1/messages/batches/${e}`,n)}cancel(e,n){return this._client.post(mn`/v1/messages/batches/${e}/cancel`,n)}async results(e,n){let r=await this.retrieve(e);if(!r.results_url)throw new Vn(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);return this._client.get(r.results_url,{...n,headers:lt([{Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((o,i)=>Afe.fromResponse(i.response,i.controller))}},C7=class extends Xs{constructor(){super(...arguments),this.batches=new Ffe(this._client)}create(e,n){e.model in rOt&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${rOt[e.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),R5n.includes(e.model)&&e.thinking&&e.thinking.type==="enabled"&&console.warn(`Using Claude with ${e.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let r=this._client._options.timeout;if(!e.stream&&r==null){let i=cDt[e.model]??void 0;r=this._client.calculateNonstreamingTimeout(e.max_tokens,i)}let o=lDt(e.tools,e.messages);return this._client.post("/v1/messages",{body:e,timeout:r??6e5,...n,headers:lt([o,n?.headers]),stream:e.stream??!1})}parse(e,n){return this.create(e,n).then(r=>mDt(r,e,{logger:this._client.logger??console}))}stream(e,n){return mje.createMessage(this,e,n,{logger:this._client.logger??console})}countTokens(e,n){return this._client.post("/v1/messages/count_tokens",{body:e,...n})}},rOt={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026","claude-3-5-haiku-latest":"February 19th, 2026","claude-3-5-haiku-20241022":"February 19th, 2026","claude-opus-4-0":"June 15th, 2026","claude-opus-4-20250514":"June 15th, 2026","claude-sonnet-4-0":"June 15th, 2026","claude-sonnet-4-20250514":"June 15th, 2026"},R5n=["claude-mythos-preview","claude-opus-4-6"];C7.Batches=Ffe;Ufe=class extends Xs{retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(mn`/v1/models/${e}`,{...r,headers:lt([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void 0},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/models",NR,{query:o,...n,headers:lt([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}},L5n="\\n\\nHuman:",$5n="\\n\\nAssistant:",Ga=class{get credentials(){return this._authState.provider}constructor({baseURL:e=ps("ANTHROPIC_BASE_URL"),apiKey:n,authToken:r,...o}={}){if(hje.add(this),this._requestAuthFlags=new WeakMap,Hde.set(this,void 0),n===void 0&&(n=o.profile!=null?null:ps("ANTHROPIC_API_KEY")??null),r===void 0&&(r=o.profile!=null?null:ps("ANTHROPIC_AUTH_TOKEN")??null),o.profile!=null&&(o.credentials!=null||o.config!=null))throw TypeError("Pass at most one of `profile`, `credentials`, or `config`.");let i={apiKey:n,authToken:r,...o,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&$qn())throw new Vn(`It looks like you're running in a browser-like environment.
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
`);this.baseURL=i.baseURL,this._baseURLIsExplicit=o.__baseURLIsExplicit??!!e,this.timeout=i.timeout??a4e.DEFAULT_TIMEOUT,this.logger=i.logger??console;let s="warn";this.logLevel=s,this.logLevel=FMt(i.logLevel,"ClientOptions.logLevel",this)??FMt(ps("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??s,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??jqn(),Ht(this,Hde,zqn,"f");let a=ps("ANTHROPIC_CUSTOM_HEADERS");if(a){let c={};for(let u of a.split(`
`)){let d=u.indexOf(":");d>=0&&(c[u.substring(0,d).trim()]=u.substring(d+1).trim())}i.defaultHeaders={...c,...i.defaultHeaders}}let l=o.__auth;if(delete i.__auth,delete i.__baseURLIsExplicit,this._options=i,this.apiKey=typeof n=="string"?n:null,this.authToken=r,l)this._authState=l,!this._baseURLIsExplicit&&l.baseURL&&(this.baseURL=l.baseURL);else if(this._authState={provider:null,tokenCache:null,resolution:null,error:null,extraHeaders:{}},this.apiKey==null&&this.authToken==null){let c=i.credentials??null;if(c)this._authState.provider=c,this._authState.tokenCache=this._makeTokenCache(c);else if(i.config!=null){let u=Q$t(i.config,this._credentialResolverOptions());this._authState.provider=u.provider,this._authState.tokenCache=this._makeTokenCache(u.provider),this._authState.extraHeaders=u.extraHeaders,this._applyCredentialBaseURL(u.baseURL)}else i.profile!=null?this._authState.resolution=this._resolveDefaultCredentials(i.profile):this._authState.resolution=this._resolveDefaultCredentials()}}_applyCredentialBaseURL(e){if(!e)return;let n=e.replace(/\/+$/,"");this._authState.baseURL=n,!this._baseURLIsExplicit&&(this.baseURL=n)}_credentialResolverOptions(){return{baseURL:this.baseURL,fetch:this.fetch,userAgent:this.getUserAgent(),onCacheWriteError:e=>{Mu(this).debug("credential cache write failed (best-effort)",e)},onSafetyWarning:e=>{Mu(this).warn(e)}}}_makeTokenCache(e){return new aje(e,n=>{Mu(this).debug("advisory token refresh failed; serving cached token",n)})}withOptions(e){let n="credentials"in e||"config"in e||"profile"in e,r="apiKey"in e||"authToken"in e||n,o={...this._options,...this._baseURLIsExplicit?{baseURL:this.baseURL}:{},maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,credentials:this.credentials,...n?{credentials:void 0,config:void 0,profile:void 0}:{},...e,__auth:r?void 0:this._authState,__baseURLIsExplicit:"baseURL"in e?!0:this._baseURLIsExplicit};return new this.constructor(o)}async _resolveDefaultCredentials(e){try{let n=await s5n(this._credentialResolverOptions(),e);if(n)this._authState.provider=n.provider,this._authState.tokenCache=this._makeTokenCache(n.provider),this._authState.extraHeaders=n.extraHeaders,this._applyCredentialBaseURL(n.baseURL);else if(e!=null)throw new Vn(`Profile "${e}" could not be resolved (no <config_dir>/configs/${e}.json found).`)}catch(n){this._authState.error=n}finally{this._authState.resolution=null}}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(!(e.get("x-api-key")||e.get("authorization"))){if(this._authState.error)throw this._authState.error;if(!(this._authState.tokenCache||this._authState.resolution)&&!(this.apiKey&&e.get("x-api-key"))&&!n.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!n.has("authorization"))throw Error('Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}}_authFlags(e){let n=this._requestAuthFlags.get(e);return n||(n={usedTokenCache:!1,didRefreshFor401:!1},this._requestAuthFlags.set(e,n)),n}async authHeaders(e){if(this._authState.resolution&&await this._authState.resolution,!this._authState.error){if(this._authState.tokenCache&&this.apiKey==null){let n=await this._authState.tokenCache.getToken();return this._authFlags(e).usedTokenCache=!0,lt([{Authorization:`Bearer ${n}`}])}return lt([await this.apiKeyAuth(e),await this.bearerAuth(e)])}}async apiKeyAuth(e){if(this.apiKey!=null)return lt([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return lt([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Hqn(e)}getUserAgent(){return`${this.constructor.name}/JS ${HP}`}defaultIdempotencyKey(){return`stainless-node-retry-${B$t()}`}makeStatusError(e,n,r,o){return bp.generate(e,n,r,o)}buildURL(e,n,r){let o=!xe(this,hje,"m",hDt).call(this)&&r||this.baseURL,i=Oqn(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery(),a=Object.fromEntries(i.searchParams);return(!EMt(s)||!EMt(a))&&(n={...a,...s,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(i.search=this.stringifyQuery(n)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new Vn("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 6e5}async prepareOptions(e){}async prepareRequest(e,{url:n,options:r}){if(this._authState.tokenCache&&this.apiKey==null){let o=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[i,s]of Object.entries(this._authState.extraHeaders))o.has(i)||o.set(i,s);o.get("anthropic-beta")?.split(",").map(i=>i.trim())?.includes(vfe)||o.append("anthropic-beta",vfe),e.headers=o}}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(o=>({method:e,path:n,...o})))}request(e,n=null){return new bfe(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){let o=await e,i=o.maxRetries??this.maxRetries;n==null&&(n=i,this._requestAuthFlags.delete(o)),await this.prepareOptions(o);let{req:s,url:a,timeout:l}=await this.buildRequest(o,{retryCount:i-n});await this.prepareRequest(s,{url:a,options:o});let c="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),u=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(Mu(this).debug(`[${c}] sending request`,xR({retryOfRequestLogID:r,method:o.method,url:a,options:o,headers:s.headers})),o.signal?.aborted)throw new Kh;let f=new AbortController,p=await this.fetchWithTimeout(a,s,l,f).catch(oje),m=Date.now();if(p instanceof globalThis.Error){let v=`retrying, ${n} attempts remaining`;if(o.signal?.aborted)throw new Kh;let y=b7(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(n)return Mu(this).info(`[${c}] connection ${y?"timed out":"failed"} - ${v}`),Mu(this).debug(`[${c}] connection ${y?"timed out":"failed"} (${v})`,xR({retryOfRequestLogID:r,url:a,durationMs:m-d,message:p.message})),this.retryRequest(o,n,r??c);throw Mu(this).info(`[${c}] connection ${y?"timed out":"failed"} - error; no more retries left`),Mu(this).debug(`[${c}] connection ${y?"timed out":"failed"} (error; no more retries left)`,xR({retryOfRequestLogID:r,url:a,durationMs:m-d,message:p.message})),y?new cfe:new CB({cause:p})}let h=[...p.headers.entries()].filter(([v])=>v==="request-id").map(([v,y])=>", "+v+": "+JSON.stringify(y)).join(""),g=`[${c}${u}${h}] ${s.method} ${a} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${m-d}ms`;if(!p.ok){let v=await this.shouldRetry(p,o);if(n&&v){let I=`retrying, ${n} attempts remaining`;return await Bqn(p.body),Mu(this).info(`${g} - ${I}`),Mu(this).debug(`[${c}] response error (${I})`,xR({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,durationMs:m-d})),this.retryRequest(o,n,r??c,p.headers)}let y=v?"error; no more retries left":"error; not retryable";Mu(this).info(`${g} - ${y}`);let w=await p.text().catch(I=>oje(I).message),_=z$t(w),S=_?void 0:w;throw Mu(this).debug(`[${c}] response error (${y})`,xR({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,message:S,durationMs:Date.now()-d})),this.makeStatusError(p.status,_,S,p.headers)}return Mu(this).info(g),Mu(this).debug(`[${c}] response start`,xR({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,durationMs:m-d})),{response:p,options:o,controller:f,requestLogID:c,retryOfRequestLogID:r,startTime:d}}getAPIList(e,n,r){return this.requestAPIList(n,r&&"then"in r?r.then(o=>({method:"get",path:e,...o})):{method:"get",path:e,...r})}requestAPIList(e,n){let r=this.makeRequest(n,null,void 0);return new cje(this,r,e)}async fetchWithTimeout(e,n,r,o){let{signal:i,method:s,...a}=n||{},l=this._makeAbort(o);i&&i.addEventListener("abort",l,{once:!0});let c=setTimeout(l,r),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:o.signal,...u?{duplex:"half"}:{},method:"GET",...a};s&&(d.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(c)}}async shouldRetry(e,n){let r=this._authFlags(n);if(e.status===401&&this._authState.tokenCache&&r.usedTokenCache&&!r.didRefreshFor401)return r.didRefreshFor401=!0,this._authState.tokenCache.invalidate(),!0;let o=e.headers.get("x-should-retry");return o==="true"?!0:o==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,r,o){let i,s=o?.get("retry-after-ms");if(s){let l=parseFloat(s);Number.isNaN(l)||(i=l)}let a=o?.get("retry-after");if(a&&!i){let l=parseFloat(a);Number.isNaN(l)?i=Date.parse(a)-Date.now():i=l*1e3}if(i===void 0){let l=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(n,l)}return await Lqn(i),this.makeRequest(e,n-1,r)}calculateDefaultRetryTimeoutMillis(e,n){let r=n-e,o=Math.min(.5*Math.pow(2,r),8),i=1-Math.random()*.25;return o*i*1e3}calculateNonstreamingTimeout(e,n){if(36e5*e/128e3>6e5||n!=null&&e>n)throw new Vn("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:n=0}={}){let r={...e},{method:o,path:i,query:s,defaultBaseURL:a}=r;this._authState.resolution&&await this._authState.resolution,!this._baseURLIsExplicit&&this._authState.baseURL&&this.baseURL!==this._authState.baseURL&&(this.baseURL=this._authState.baseURL);let l=this.buildURL(i,s,a);"timeout"in r&&Rqn("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:c,body:u}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:o,bodyHeaders:c,retryCount:n});return{req:{method:o,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...r.fetchOptions??{}},url:l,timeout:r.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:r,retryCount:o}){let i={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);let s=lt([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...t4e(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(s),s.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=lt([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:W$t(e)}:typeof e=="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:xe(this,Hde,"f").call(this,{body:e,headers:r})}};a4e=Ga,Hde=new WeakMap,hje=new WeakSet,hDt=function(){return this.baseURL!=="https://api.anthropic.com"};Ga.Anthropic=a4e;Ga.HUMAN_PROMPT=L5n;Ga.AI_PROMPT=$5n;Ga.DEFAULT_TIMEOUT=6e5;Ga.AnthropicError=Vn;Ga.APIError=bp;Ga.APIConnectionError=CB;Ga.APIConnectionTimeoutError=cfe;Ga.APIUserAbortError=Kh;Ga.NotFoundError=pfe;Ga.ConflictError=mfe;Ga.RateLimitError=gfe;Ga.BadRequestError=ufe;Ga.AuthenticationError=dfe;Ga.InternalServerError=yfe;Ga.PermissionDeniedError=ffe;Ga.UnprocessableEntityError=hfe;Ga.toFile=b5n;TB=class extends Ga{constructor(){super(...arguments),this.completions=new Dfe(this),this.messages=new C7(this),this.models=new Ufe(this),this.beta=new Cm(this)}};TB.Completions=Dfe;TB.Messages=C7;TB.Models=Ufe;TB.Beta=Cm;gje=class extends Error{constructor(n,r){super(n);M(this,"telemetryMessage");this.name="TelemetrySafeError",this.telemetryMessage=r??n}},D5n=(t,e)=>{try{t!==null&&typeof t=="object"&&!("telemetryMessage"in t)&&Object.isExtensible(t)&&Object.assign(t,{telemetryMessage:e})}catch{}return t};F5n=new Set(["ENOENT","EACCES","EPERM","ENOTDIR","ELOOP","ENAMETOOLONG","EROFS"]);j5n=new Set(["EXDEV","EPERM","EEXIST","EBUSY"]),B5n=new Set(["EPERM","EBUSY","EACCES"]),z5n=4,H5n=50,Muo=new Int32Array(new SharedArrayBuffer(4));q5n=new Set(["ENOSPC","EIO","EDQUOT","EFBIG"]);vje=class{read(e){return(0,Ma.readFile)(e,"utf8")}readBytes(e){return(0,Ma.readFile)(e)}write(e,n,r){return(0,Ma.writeFile)(e,n,{encoding:"utf8",mode:r})}async mkdir(e){try{await(0,Ma.mkdir)(e,{recursive:!0})}catch(n){if(Ky(n)!=="EEXIST")throw n}}atomicWrite(e,n,r){return K5n(e,n,r)}delete(e){return(0,Ma.unlink)(e)}list(e){return(0,Ma.readdir)(e)}append(e,n,r){return(0,Ma.appendFile)(e,n,{encoding:"utf8",mode:r})}writeExclusive(e,n,r){return(0,Ma.writeFile)(e,n,{encoding:"utf8",flag:"wx",mode:r})}writeBytes(e,n){return(0,Ma.writeFile)(e,n)}copy(e,n){return(0,Ma.copyFile)(e,n)}async stat(e){return{mtimeMs:(await(0,Ma.stat)(e)).mtimeMs}}async listEntries(e){return(await(0,Ma.readdir)(e,{withFileTypes:!0})).map(n=>({name:n.name,isDirectory:n.isDirectory(),isFile:n.isFile()}))}async readRange(e,n,r){HUe("readRange","offset",n),HUe("readRange","length",r);let o=await(0,Ma.open)(e,"r");try{return await oOt(o,n,r)}finally{await o.close()}}async readTail(e,n){HUe("readTail","maxBytes",n);let r=await(0,Ma.open)(e,"r");try{let{size:o}=await r.stat(),i=Math.min(n,o);return await oOt(r,o-i,i)}finally{await r.close()}}};G5n=new vDt.AsyncLocalStorage;oB=null;J5n=Y5n;Q5n=X5n;tKn=eKn;rKn=nKn,oKn=200;sKn=iKn;GB.prototype.clear=J5n;GB.prototype.delete=Q5n;GB.prototype.get=tKn;GB.prototype.has=rKn;GB.prototype.set=sKn;aKn=GB,lKn=function(){try{var t=UR(Object,"defineProperty");return t({},"",{}),t}catch{}}(),jfe=lKn;u4e=cKn,uKn=Object.prototype,dKn=uKn.hasOwnProperty;xDt=fKn;mKn=pKn;gKn=hKn;ZB=yKn,vKn="[object Arguments]";iOt=wKn,SDt=Object.prototype,bKn=SDt.hasOwnProperty,_Kn=SDt.propertyIsEnumerable,xKn=iOt(function(){return arguments}())?iOt:function(t){return ZB(t)&&bKn.call(t,"callee")&&!_Kn.call(t,"callee")},k7=xKn,SKn=Array.isArray,ZP=SKn,n7={};_x(n7,{default:()=>d4e});kKn=CKn,CDt=typeof n7=="object"&&n7&&!n7.nodeType&&n7,sOt=CDt&&typeof Pf=="object"&&Pf&&!Pf.nodeType&&Pf,IKn=sOt&&sOt.exports===CDt,aOt=IKn?xx.Buffer:void 0,TKn=aOt?aOt.isBuffer:void 0,PKn=TKn||kKn,d4e=PKn,AKn=9007199254740991,EKn=/^(?:0|[1-9]\d*)$/;Ape=MKn,OKn=9007199254740991;f4e=NKn,RKn="[object Arguments]",LKn="[object Array]",$Kn="[object Boolean]",DKn="[object Date]",FKn="[object Error]",UKn="[object Function]",jKn="[object Map]",BKn="[object Number]",zKn="[object Object]",HKn="[object RegExp]",WKn="[object Set]",VKn="[object String]",qKn="[object WeakMap]",KKn="[object ArrayBuffer]",GKn="[object DataView]",ZKn="[object Float32Array]",YKn="[object Float64Array]",JKn="[object Int8Array]",XKn="[object Int16Array]",QKn="[object Int32Array]",eGn="[object Uint8Array]",tGn="[object Uint8ClampedArray]",nGn="[object Uint16Array]",rGn="[object Uint32Array]",Ys={};Ys[ZKn]=Ys[YKn]=Ys[JKn]=Ys[XKn]=Ys[QKn]=Ys[eGn]=Ys[tGn]=Ys[nGn]=Ys[rGn]=!0;Ys[RKn]=Ys[LKn]=Ys[KKn]=Ys[$Kn]=Ys[GKn]=Ys[DKn]=Ys[FKn]=Ys[UKn]=Ys[jKn]=Ys[BKn]=Ys[zKn]=Ys[HKn]=Ys[WKn]=Ys[VKn]=Ys[qKn]=!1;iGn=oGn;aGn=sGn,r7={};_x(r7,{default:()=>wje});kDt=typeof r7=="object"&&r7&&!r7.nodeType&&r7,u7=kDt&&typeof Af=="object"&&Af&&!Af.nodeType&&Af,lGn=u7&&u7.exports===kDt,WUe=lGn&&DNt.process,cGn=function(){try{var t=u7&&u7.require&&u7.require("util").types;return t||WUe&&WUe.binding&&WUe.binding("util")}catch{}}(),wje=cGn,lOt=wje&&wje.isTypedArray,uGn=lOt?aGn(lOt):iGn,IDt=uGn,dGn=Object.prototype,fGn=dGn.hasOwnProperty;mGn=pGn,hGn=Object.prototype;TDt=gGn;PDt=yGn,Ouo=PDt(Object.keys,Object),vGn=Object.prototype,Nuo=vGn.hasOwnProperty;p4e=wGn;_Gn=bGn,xGn=Object.prototype,SGn=xGn.hasOwnProperty;kGn=CGn;ADt=IGn,o7={};_x(o7,{default:()=>MDt});EDt=typeof o7=="object"&&o7&&!o7.nodeType&&o7,cOt=EDt&&typeof Df=="object"&&Df&&!Df.nodeType&&Df,TGn=cOt&&cOt.exports===EDt,uOt=TGn?xx.Buffer:void 0,dOt=uOt?uOt.allocUnsafe:void 0;MDt=PGn;EGn=AGn,MGn=Object.prototype,Ruo=MGn.propertyIsEnumerable;NGn=OGn,RGn=PDt(Object.getPrototypeOf,Object),ODt=RGn,LGn=UR(xx,"DataView"),bje=LGn,$Gn=UR(xx,"Promise"),_je=$Gn,DGn=UR(xx,"Set"),xje=DGn,FGn=UR(xx,"WeakMap"),Sje=FGn,fOt="[object Map]",UGn="[object Object]",pOt="[object Promise]",mOt="[object Set]",hOt="[object WeakMap]",gOt="[object DataView]",jGn=FR(bje),BGn=FR(f7),zGn=FR(_je),HGn=FR(xje),WGn=FR(Sje),iB=DR;(bje&&iB(new bje(new ArrayBuffer(1)))!=gOt||f7&&iB(new f7)!=fOt||_je&&iB(_je.resolve())!=pOt||xje&&iB(new xje)!=mOt||Sje&&iB(new Sje)!=hOt)&&(iB=function(t){var e=DR(t),n=e==UGn?t.constructor:void 0,r=n?FR(n):"";if(r)switch(r){case jGn:return gOt;case BGn:return fOt;case zGn:return pOt;case HGn:return mOt;case WGn:return hOt}return e});VGn=xx.Uint8Array,yOt=VGn;KGn=qGn;ZGn=GGn,vOt=Object.create,YGn=function(){function t(){}return function(e){if(!Nk(e))return{};if(vOt)return vOt(e);t.prototype=e;var n=new t;return t.prototype=void 0,n}}(),JGn=YGn;QGn=XGn,e9n="__lodash_hash_undefined__";n9n=t9n;o9n=r9n;kje.prototype.add=kje.prototype.push=n9n;kje.prototype.has=o9n;wOt=vx?vx.prototype:void 0,Luo=wOt?wOt.valueOf:void 0,i9n=Object.prototype,$uo=i9n.hasOwnProperty,s9n=Object.prototype,Duo=s9n.hasOwnProperty,a9n="[object Symbol]";m4e=l9n,c9n=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,u9n=/^\w*$/;f9n=d9n,p9n=500;h9n=m9n,g9n=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,y9n=/\\(\\)?/g,v9n=h9n(function(t){var e=[];return t.charCodeAt(0)===46&&e.push(""),t.replace(g9n,function(n,r,o,i){e.push(o?i.replace(y9n,"$1"):r||n)}),e}),w9n=v9n;_9n=b9n,x9n=1/0,bOt=vx?vx.prototype:void 0,_Ot=bOt?bOt.toString:void 0;S9n=NDt;k9n=C9n;Epe=I9n,T9n=1/0;h4e=P9n;E9n=A9n;O9n=M9n;R9n=N9n;$9n=L9n;RDt=D9n,DDt="[\\w-]{1,63}",Uuo=new RegExp(`^${DDt}$`),juo=new RegExp(`^a(?:${DDt}-)?[0-9a-f]{16}$`);U9n="3ab19d7e-9f35-45c2-926e-75e271cc60b3";z9n={renderTarget:"ink",workspace:"local",canDrive:!0,transcriptSource:"local-jsonl",remote:null};W9n=H9n(),V9n=()=>{};q9n=U7(),Buo=q9n.subscribe;K9n=U7(),zuo=K9n.subscribe,G9n=U7(),Huo=G9n.subscribe,Z9n=U7(),Wuo=Z9n.subscribe,Y9n=U7(),Vuo=Y9n.subscribe;zfe=class{constructor(){Rt(this,VP,new Set)}register(e){let n=X9n(e);re(this,VP).add(n);let r=()=>{re(this,VP).delete(n)};return Object.assign(r,{[Symbol.dispose]:r})}async drain(){let e=Array.from(re(this,VP));re(this,VP).clear(),await Promise.all(e.map(async n=>n()))}async[Symbol.asyncDispose](){await this.drain()}get sizeForTesting(){return re(this,VP).size}};VP=new WeakMap;Q9n=new zfe;quo=new zfe,t8n=Za(t=>{if(!t||t.trim()==="")return null;let e=t.split(",").map(i=>i.trim()).filter(Boolean);if(e.length===0)return null;let n=e.some(i=>i.startsWith("!")),r=e.some(i=>!i.startsWith("!"));if(n&&r)return null;let o=e.map(i=>i.replace(/^!/,"").toLowerCase());return{include:n?[]:o,exclude:n?o:[],isExclusive:n}});Ude="\u2192",i8n={cwd(){return process.cwd()},existsSync(t){let e=[];try{let o=gl(e,vl`fs.existsSync(${t})`,0);return Or.existsSync(t)}catch(o){var n=o,r=1}finally{yl(e,n,r)}},async stat(t){return(0,No.stat)(t)},async lstat(t){return(0,No.lstat)(t)},async readdir(t){return(0,No.readdir)(t,{withFileTypes:!0})},async unlink(t){return(0,No.unlink)(t)},async rmdir(t){return(0,No.rmdir)(t)},async rm(t,e){return(0,No.rm)(t,e)},async mkdir(t,e){try{await(0,No.mkdir)(t,{recursive:!0,...e})}catch(n){if(Ky(n)!=="EEXIST")throw n}},async readFile(t,e){return(0,No.readFile)(t,{encoding:e.encoding})},async rename(t,e){return(0,No.rename)(t,e)},async realpath(t){return eje(await(0,No.realpath)(t))},async readlink(t){return(0,No.readlink)(t)},async copyFile(t,e){return(0,No.copyFile)(t,e)},async appendFile(t,e,n){if(n?.mode!==void 0)try{let r=await(0,No.open)(t,"ax",n.mode);try{await r.appendFile(e)}finally{await r.close()}return}catch(r){if(Ky(r)!=="EEXIST")throw r}return(0,No.appendFile)(t,e)},async symlink(t,e,n){return(0,No.symlink)(t,e,n)},async link(t,e){return(0,No.link)(t,e)},async chmod(t,e){return(0,No.chmod)(t,e)},statSync(t){let e=[];try{let o=gl(e,vl`fs.statSync(${t})`,0);return Or.statSync(t)}catch(o){var n=o,r=1}finally{yl(e,n,r)}},lstatSync(t){let e=[];try{let o=gl(e,vl`fs.lstatSync(${t})`,0);return Or.lstatSync(t)}catch(o){var n=o,r=1}finally{yl(e,n,r)}},readFileSync(t,e){let n=[];try{let i=gl(n,vl`fs.readFileSync(${t})`,0);return Or.readFileSync(t,{encoding:e.encoding})}catch(i){var r=i,o=1}finally{yl(n,r,o)}},readFileBytesSync(t){let e=[];try{let o=gl(e,vl`fs.readFileBytesSync(${t})`,0);return Or.readFileSync(t)}catch(o){var n=o,r=1}finally{yl(e,n,r)}},readSync(t,e){let n=[];try{let i=gl(n,vl`fs.readSync(${t}, ${e.length} bytes)`,0),s;try{s=Or.openSync(t,"r");let a=Buffer.alloc(e.length),l=Or.readSync(s,a,0,e.length,0);return{buffer:a,bytesRead:l}}finally{s&&Or.closeSync(s)}}catch(i){var r=i,o=1}finally{yl(n,r,o)}},appendFileSync(t,e,n){let r=[];try{let s=gl(r,vl`fs.appendFileSync(${t}, ${e.length} chars)`,0);if(n?.mode!==void 0)try{let a=Or.openSync(t,"ax",n.mode);try{Or.appendFileSync(a,e)}finally{Or.closeSync(a)}return}catch(a){if(Ky(a)!=="EEXIST")throw a}Or.appendFileSync(t,e)}catch(s){var o=s,i=1}finally{yl(r,o,i)}},copyFileSync(t,e){let n=[];try{let i=gl(n,vl`fs.copyFileSync(${t} ${Ude} ${e})`,0);Or.copyFileSync(t,e)}catch(i){var r=i,o=1}finally{yl(n,r,o)}},unlinkSync(t){let e=[];try{let o=gl(e,vl`fs.unlinkSync(${t})`,0);Or.unlinkSync(t)}catch(o){var n=o,r=1}finally{yl(e,n,r)}},renameSync(t,e){let n=[];try{let i=gl(n,vl`fs.renameSync(${t} ${Ude} ${e})`,0);Or.renameSync(t,e)}catch(i){var r=i,o=1}finally{yl(n,r,o)}},linkSync(t,e){let n=[];try{let i=gl(n,vl`fs.linkSync(${t} ${Ude} ${e})`,0);Or.linkSync(t,e)}catch(i){var r=i,o=1}finally{yl(n,r,o)}},symlinkSync(t,e,n){let r=[];try{let s=gl(r,vl`fs.symlinkSync(${t} ${Ude} ${e})`,0);Or.symlinkSync(t,e,n)}catch(s){var o=s,i=1}finally{yl(r,o,i)}},readlinkSync(t){let e=[];try{let o=gl(e,vl`fs.readlinkSync(${t})`,0);return Or.readlinkSync(t)}catch(o){var n=o,r=1}finally{yl(e,n,r)}},realpathSync(t){let e=[];try{let o=gl(e,vl`fs.realpathSync(${t})`,0);return eje(Or.realpathSync(t))}catch(o){var n=o,r=1}finally{yl(e,n,r)}},mkdirSync(t,e){let n=[];try{let i=gl(n,vl`fs.mkdirSync(${t})`,0),s={recursive:!0};e?.mode!==void 0&&(s.mode=e.mode);try{Or.mkdirSync(t,s)}catch(a){if(Ky(a)!=="EEXIST")throw a}}catch(i){var r=i,o=1}finally{yl(n,r,o)}},readdirSync(t){let e=[];try{let o=gl(e,vl`fs.readdirSync(${t})`,0);return Or.readdirSync(t,{withFileTypes:!0})}catch(o){var n=o,r=1}finally{yl(e,n,r)}},readdirStringSync(t){let e=[];try{let o=gl(e,vl`fs.readdirStringSync(${t})`,0);return Or.readdirSync(t)}catch(o){var n=o,r=1}finally{yl(e,n,r)}},rmdirSync(t){let e=[];try{let o=gl(e,vl`fs.rmdirSync(${t})`,0);Or.rmdirSync(t)}catch(o){var n=o,r=1}finally{yl(e,n,r)}},rmSync(t,e){let n=[];try{let i=gl(n,vl`fs.rmSync(${t})`,0);Or.rmSync(t,e)}catch(i){var r=i,o=1}finally{yl(n,r,o)}},createWriteStream(t){return Or.createWriteStream(t)},async readFileBytes(t,e){if(e===void 0)return(0,No.readFile)(t);let n=await(0,No.open)(t,"r");try{let{size:r}=await n.stat(),o=Math.min(r,e),i=Buffer.allocUnsafe(o),s=0;for(;s<o;){let{bytesRead:a}=await n.read(i,s,o-s,s);if(a===0)break;s+=a}return s<o?i.subarray(0,s):i}finally{await n.close()}}},s8n=i8n;Kuo=typeof String.prototype.isWellFormed=="function"?Function.prototype.call.bind(String.prototype.isWellFormed):void 0,Guo=typeof String.prototype.toWellFormed=="function"?Function.prototype.call.bind(String.prototype.toWellFormed):void 0,u8n=/api[_-]?key|secret|token|password|passwd|credential|bearer|authorization|auth[_-]?header|cookie|session[_-]?(?:id|key)|connection[_-]?string|(?:private|ssh|encryption|signing|access|deploy|master|license)[_-]?key|client[_-]?secret/i,SOt="[^\\s,;&}\\])]+",UDt="-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----[\\s\\S-]{64,}?-----END[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----",d8n=`[^\\s-]{0,4}${UDt}['"\`]?`,COt=`\\[REDACTED\\]|"[^"]*"|'[^']*'|(?:Bearer|Basic)\\s+(?:\\[REDACTED\\]|${SOt})|${d8n}|${SOt}`,f8n=["sk","ant","api"].join("-"),p8n=[{id:"url-userinfo",source:":\\/\\/([^/@\\s]+)@",confidence:"low"},{id:"gcp-service-account",source:"\\b([a-z0-9-]+@[a-z0-9-]+\\.iam\\.gserviceaccount\\.com)\\b",flags:"i",confidence:"low"},{id:"loose-anthropic-key",source:"\\b(sk-ant-?[\\w-]{10,})",confidence:"low"},{id:"http-auth-scheme",source:"\\b(?:Bearer|Basic)\\s+([A-Za-z0-9+/=._~-]{20,})",flags:"i",confidence:"low"},{id:"loose-jwt",source:"\\b(eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,})",confidence:"low"},{id:"sensitive-assign",source:`(?:${u8n.source})[\\w.-]*["']?\\s*[=:]\\s*(${COt})`,flags:"i",confidence:"low"},{id:"cloud-env-var",source:`\\b(?:AWS|GOOGLE|GCP|GCLOUD|AZURE)_\\w+\\s*[=:]\\s*(${COt})`,flags:"i",confidence:"low"},{id:"aws-access-token",source:"\\b((?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z2-7]{16})\\b",confidence:"high"},{id:"gcp-api-key",source:"\\b(AIza[\\w-]{35})(?![\\w-])",confidence:"high"},{id:"google-oauth-client-secret",source:"\\bGOCSPX-[\\w-]{28}(?![\\w-])",confidence:"high"},{id:"azure-ad-client-secret",source:`(?:^|[\\\\'"\\x60\\s>=:(,)])([a-zA-Z0-9_~.]{3}\\dQ~[a-zA-Z0-9_~.-]{31,34})(?:$|[\\\\'"\\x60\\s<),])`,confidence:"high"},{id:"digitalocean-pat",source:`\\b(dop_v1_[a-f0-9]{64})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"digitalocean-access-token",source:`\\b(doo_v1_[a-f0-9]{64})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"anthropic-api-key",source:`\\b(${f8n}03-[a-zA-Z0-9_\\-]{93}AA)(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"anthropic-admin-api-key",source:`\\b(sk-ant-admin01-[a-zA-Z0-9_\\-]{93}AA)(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"openai-api-key",source:"sk-[A-Za-z0-9_-]{8,200}T3BlbkFJ[A-Za-z0-9_-]{8,200}",confidence:"high"},{id:"openai-legacy-api-key",source:"\\bsk-[a-zA-Z0-9]{48}(?![a-zA-Z0-9])",confidence:"high"},{id:"huggingface-access-token",source:`\\b(hf_[a-zA-Z]{34})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"supabase-secret-key",source:"\\bsb_secret_[A-Za-z0-9_-]{20,}",confidence:"high"},{id:"supabase-access-token",source:"\\bsbp_[a-z0-9]{40,}",confidence:"high"},{id:"github-pat",source:"ghp_[0-9a-zA-Z]{36}",confidence:"high"},{id:"github-fine-grained-pat",source:"github_pat_\\w{82}",confidence:"high"},{id:"github-app-token",source:"(?:ghu|ghs)_[0-9a-zA-Z]{36}",confidence:"high"},{id:"github-oauth",source:"gho_[0-9a-zA-Z]{36}",confidence:"high"},{id:"github-refresh-token",source:"ghr_[0-9a-zA-Z]{36}",confidence:"high"},{id:"gitlab-pat",source:"glpat-[\\w-]{20}",confidence:"high"},{id:"gitlab-deploy-token",source:"gldt-[0-9a-zA-Z_\\-]{20}",confidence:"high"},{id:"slack-bot-token",source:"xoxb-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*",confidence:"high"},{id:"slack-user-token",source:"xox[pe](?:-[0-9]{10,13}){3}-[a-zA-Z0-9-]{28,34}",confidence:"high"},{id:"slack-app-token",source:"xapp-\\d-[A-Z0-9]+-\\d+-[a-z0-9]+",flags:"i",confidence:"high"},{id:"twilio-api-key",source:"SK[0-9a-fA-F]{32}",confidence:"high"},{id:"sendgrid-api-token",source:`\\b(SG\\.[a-zA-Z0-9=_\\-.]{66})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"npm-access-token",source:`\\b(npm_[a-zA-Z0-9]{36})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"pypi-upload-token",source:"pypi-AgEIcHlwaS5vcmc[\\w-]{50,1000}",confidence:"high"},{id:"databricks-api-token",source:`\\b(dapi[a-f0-9]{32}(?:-\\d)?)(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"hashicorp-tf-api-token",source:"[a-zA-Z0-9]{14}\\.atlasv1\\.[a-zA-Z0-9\\-_=]{60,70}",confidence:"high"},{id:"pulumi-api-token",source:`\\b(pul-[a-f0-9]{40})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"postman-api-token",source:`\\b(PMAK-[a-fA-F0-9]{24}-[a-fA-F0-9]{34})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"grafana-api-key",source:`\\b(eyJrIjoi[A-Za-z0-9+/]{70,400}={0,3})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"grafana-cloud-api-token",source:`\\b(glc_[A-Za-z0-9+/]{32,400}={0,3})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"grafana-service-account-token",source:`\\b(glsa_[A-Za-z0-9]{32}_[A-Fa-f0-9]{8})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"sentry-user-token",source:`\\b(sntryu_[a-f0-9]{64})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"sentry-org-token",source:"\\bsntrys_eyJpYXQiO[a-zA-Z0-9+/]{10,200}(?:LCJyZWdpb25fdXJs|InJlZ2lvbl91cmwi|cmVnaW9uX3VybCI6)[a-zA-Z0-9+/]{10,200}={0,2}_[a-zA-Z0-9+/]{43}",confidence:"high"},{id:"stripe-access-token",source:`\\b((?:sk|rk)_(?:test|live|prod)_[a-zA-Z0-9]{10,99})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"shopify-access-token",source:"shpat_[a-fA-F0-9]{32}",confidence:"high"},{id:"shopify-shared-secret",source:"shpss_[a-fA-F0-9]{32}",confidence:"high"},{id:"private-key",source:UDt,flags:"i",confidence:"high"}],kOt=null;g8n=512,y8n=512,ZZ=new Map;Ije={verbose:0,debug:1,info:2,warn:3,error:4},w8n=Za(()=>{let t=process.env.CLAUDE_CODE_DEBUG_LOG_LEVEL?.toLowerCase().trim();return t&&Object.hasOwn(Ije,t)?t:"debug"}),b8n=!1;jDt=Za(()=>{let t=Mpe();return b8n||xm(process.env.DEBUG)||xm(process.env.DEBUG_SDK)||t.includes("--debug")||t.includes("-d")||BDt()||t.some(e=>e.startsWith("--debug="))||zDt()!==null}),_8n=Za(()=>{let t=Mpe().find(n=>n.startsWith("--debug="));if(!t)return null;let e=t.substring(8);return t8n(e)}),BDt=Za(()=>{let t=Mpe();return t.includes("--debug-to-stderr")||t.includes("-d2e")}),zDt=Za(()=>{let t=Mpe();for(let e=0;e<t.length;e++){let n=t[e];if(n.startsWith("--debug-file="))return IOt(n.substring(13));if(n==="--debug-file"&&e+1<t.length)return IOt(t[e+1])}return null});S8n=!1,C8n=10485760,YZ=null,VUe=Promise.resolve(),dB=[],i7=null,TOt=null,JZ=-1,qUe=!1,Tje=null;A8n=Za(async()=>{try{let t=Pje(),e=(0,wx.dirname)(t),n=(0,wx.join)(e,"latest");await(0,cf.unlink)(n).catch(()=>{}),await(0,cf.symlink)(t,n)}catch{}}),Zuo=(()=>{let t=process.env.CLAUDE_CODE_SLOW_OPERATION_THRESHOLD_MS;if(t!==void 0){let e=Number(t);if(!Number.isNaN(e)&&e>=0)return e}return 1/0})(),E8n={[Symbol.dispose](){}};vl=M8n;g4e=(t,e)=>{let n=[];try{let i=gl(n,vl`JSON.parse(${t})`,0);return typeof e>"u"?JSON.parse(t):JSON.parse(t,e)}catch(i){var r=i,o=1}finally{yl(n,r,o)}};R8n=2e3,Hfe=new Set,POt=!1;Aje=class{constructor(e){M(this,"options");M(this,"process");M(this,"processStdin");M(this,"processStdout");M(this,"ready",!1);M(this,"abortController");M(this,"exitError");M(this,"exitListeners",[]);M(this,"abortHandler");M(this,"forwardedAbort",QUe());M(this,"pendingWrites",[]);M(this,"pendingEndInput",!1);M(this,"spawnResolve");M(this,"spawnReject");M(this,"spawnPromise");this.options=e,this.abortController=e.abortController||QUe(),e.deferSpawn?(this.spawnPromise=new Promise((n,r)=>{this.spawnResolve=n,this.spawnReject=r}),this.spawnPromise.catch(()=>{})):this.initialize()}spawn(){try{this.initialize()}catch(n){throw this.spawnAbort(Ppe(n)),n}let e=this.pendingWrites;this.pendingWrites=[],this.spawnResolve&&(this.spawnResolve(),this.spawnResolve=void 0,this.spawnReject=void 0);for(let n of e)this.write(n);this.pendingEndInput&&(this.pendingEndInput=!1,this.processStdin?.end())}spawnAbort(e){this.spawnReject&&(this.spawnReject(e),this.spawnReject=void 0,this.spawnResolve=void 0,this.pendingWrites=[])}updateEnv(e){this.options.env?Object.assign(this.options.env,e):this.options.env={...e}}updateResume(e){this.options.resume=e}getDefaultExecutable(){return $Nt()?"bun":"node"}spawnLocalProcess(e){let{command:n,args:r,cwd:o,env:i,signal:s}=e,a=xm(i.DEBUG_CLAUDE_AGENT_SDK)||this.options.stderr?"pipe":"ignore",l=(0,ONt.spawn)(n,r,{cwd:o,stdio:["pipe","pipe",a],signal:s,env:i,windowsHide:!0});return(xm(i.DEBUG_CLAUDE_AGENT_SDK)||this.options.stderr)&&l.stderr.on("data",c=>{let u=c.toString();yx(u),this.options.stderr&&this.options.stderr(u)}),{stdin:l.stdin,stdout:l.stdout,get killed(){return l.killed},get exitCode(){return l.exitCode},kill:l.kill.bind(l),on:l.on.bind(l),once:l.once.bind(l),off:l.off.bind(l)}}initialize(){try{let{additionalDirectories:e=[],agent:n,betas:r,cwd:o,executable:i=this.getDefaultExecutable(),executableArgs:s=[],extraArgs:a={},pathToClaudeCodeExecutable:l,env:c={...process.env},thinkingConfig:u,maxTurns:d,maxBudgetUsd:f,taskBudget:p,model:m,fallbackModel:h,jsonSchema:g,permissionMode:v,allowDangerouslySkipPermissions:y,permissionPromptToolName:w,continueConversation:_,resume:S,settingSources:I,skills:C,disallowedTools:k=[],tools:T,mcpServers:P,strictMcpConfig:E,canUseTool:O,includePartialMessages:$,plugins:U,sandbox:V}=this.options,{allowedTools:K=[]}=this.options;if(C!==void 0){let F=C==="all"?["Skill"]:C.map(N=>`Skill(${N})`),z=new Set(K);K=[...K,...F.filter(N=>!z.has(N))]}let se=["--output-format","stream-json","--verbose","--input-format","stream-json"];if(u){switch(u.type){case"enabled":u.budgetTokens===void 0?se.push("--thinking","adaptive"):se.push("--max-thinking-tokens",u.budgetTokens.toString());break;case"disabled":se.push("--thinking","disabled");break;case"adaptive":se.push("--thinking","adaptive");break}u.type!=="disabled"&&u.display&&se.push("--thinking-display",u.display)}if(this.options.effort&&se.push("--effort",this.options.effort),d&&se.push("--max-turns",d.toString()),f!==void 0&&se.push("--max-budget-usd",f.toString()),p&&se.push("--task-budget",p.total.toString()),m&&se.push("--model",m),n&&se.push("--agent",n),r&&r.length>0&&se.push("--betas",r.join(",")),g&&se.push("--json-schema",yp(g)),this.options.debugFile?se.push("--debug-file",this.options.debugFile):this.options.debug&&se.push("--debug"),!this.options.debugFile&&!this.options.spawnClaudeCodeProcess){let F=Z5n();F&&se.push("--debug-file",F)}if(O){if(w)throw Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");se.push("--permission-prompt-tool","stdio")}else w&&se.push("--permission-prompt-tool",w);if(_&&se.push("--continue"),S&&se.push("--resume",S),this.options.channels&&this.options.channels.length>0&&se.push("--channels",...this.options.channels),K.length>0&&se.push("--allowedTools",K.join(",")),k.length>0&&se.push("--disallowedTools",k.join(",")),T!==void 0&&(Array.isArray(T)?T.length===0?se.push("--tools",""):se.push("--tools",T.join(",")):se.push("--tools","default")),P&&Object.keys(P).length>0&&se.push("--mcp-config",yp({mcpServers:P})),I!==void 0&&se.push(`--setting-sources=${I.join(",")}`),E&&se.push("--strict-mcp-config"),v&&se.push("--permission-mode",v),y&&se.push("--allow-dangerously-skip-permissions"),h){if(m&&h===m)throw Error("Fallback model cannot be the same as the main model. Please specify a different model for fallbackModel option.");se.push("--fallback-model",h)}this.options.includeHookEvents&&se.push("--include-hook-events"),$&&se.push("--include-partial-messages"),this.options.sessionMirror&&se.push("--session-mirror");for(let F of e)se.push("--add-dir",F);if(U&&U.length>0)for(let F of U)if(F.type==="local")se.push(F.skipMcpDiscovery?"--plugin-dir-no-mcp":"--plugin-dir",F.path);else throw Error(`Unsupported plugin type: ${F.type}`);this.options.forkSession&&se.push("--fork-session"),this.options.resumeSessionAt&&se.push("--resume-session-at",this.options.resumeSessionAt),this.options.sessionId&&se.push("--session-id",this.options.sessionId),this.options.persistSession===!1&&se.push("--no-session-persistence"),this.options.managedSettings&&se.push("--managed-settings",this.options.managedSettings);let le={...a??{}};this.options.settings&&(le.settings=this.options.settings);let Q=N8n(le,V);for(let[F,z]of Object.entries(Q))z===null?se.push(`--${F}`):se.push(`--${F}`,z);c.CLAUDE_CODE_ENTRYPOINT||(c.CLAUDE_CODE_ENTRYPOINT="sdk-ts"),delete c.NODE_OPTIONS,xm(c.DEBUG_CLAUDE_AGENT_SDK)?c.DEBUG="1":delete c.DEBUG;let ne=D8n(l),ee=ne?l:i,ae=ne?[...s,...se]:[...s,l,...se],q={command:ee,args:ae,cwd:o,env:c,signal:this.forwardedAbort.signal};this.options.spawnClaudeCodeProcess?(yx(`Spawning Claude Code (custom): ${ee} ${ae.join(" ")}`),this.process=this.options.spawnClaudeCodeProcess(q)):(yx(`Spawning Claude Code: ${ee} ${ae.join(" ")}`),this.process=this.spawnLocalProcess(q)),this.processStdin=this.process.stdin,this.processStdout=this.process.stdout,$8n(this.process),this.abortHandler=()=>this.close(),this.abortController.signal.addEventListener("abort",this.abortHandler),this.abortController.signal.aborted&&this.close(),this.process.on("error",F=>{if(this.ready=!1,this.abortController.signal.aborted)this.exitError=new Ek("Claude Code process aborted by user");else if(U5n(F)){let z=F8n(l,ne);this.exitError=ReferenceError(z),yx(this.exitError.message)}else this.exitError=Error(`Failed to spawn Claude Code process: ${F.message}`),yx(this.exitError.message)}),this.process.on("exit",(F,z)=>{if(this.ready=!1,this.abortController.signal.aborted)this.exitError=new Ek("Claude Code process aborted by user");else{let N=this.getProcessExitError(F,z);N&&(this.exitError=N,yx(N.message))}}),this.ready=!this.abortController.signal.aborted}catch(e){throw this.ready=!1,e}}getProcessExitError(e,n){if(e!==0&&e!==null)return Error(`Claude Code process exited with code ${e}`);if(n)return Error(`Claude Code process terminated by signal ${n}`)}write(e){if(this.abortController.signal.aborted)throw new Ek("Operation aborted");if(this.spawnResolve){this.pendingWrites.push(e);return}if(!this.ready||!this.processStdin)throw Error("ProcessTransport is not ready for writing");if(this.processStdin.writableEnded){yx("[ProcessTransport] Dropping write to ended stdin stream");return}if(this.process?.killed||this.process?.exitCode!==null)throw Error("Cannot write to terminated process");if(this.exitError)throw Error(`Cannot write to process that exited with error: ${this.exitError.message}`);yx(`[ProcessTransport] Writing to stdin: ${e.substring(0,100)}`);try{this.processStdin.write(e)||yx("[ProcessTransport] Write buffer full, data queued")}catch(n){throw this.ready=!1,Error(`Failed to write to process stdin: ${Wde(n)}`)}}[Symbol.dispose](){this.close()}close(){this.spawnAbort(this.abortController.signal.aborted?new Ek("Claude Code process aborted by user"):Error("Query closed before spawn")),this.processStdin&&(this.processStdin.end(),this.processStdin=void 0),this.abortHandler&&(this.abortController.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=void 0);for(let{handler:r}of this.exitListeners)this.process?.off("exit",r);this.exitListeners=[];let e=()=>{this.abortController.signal.aborted&&this.forwardedAbort.abort(this.abortController.signal.reason)},n=this.process;n&&!n.killed&&n.exitCode===null?((t=>{t&&t.unref&&t.unref()})(setTimeout((r,o)=>{if(r.exitCode!==null){o();return}if(process.platform==="win32"){(t=>{t&&t.unref&&t.unref()})(setTimeout((i,s)=>{i.exitCode===null&&i.kill("SIGKILL"),s()},5e3,r,o));return}r.kill("SIGTERM"),(t=>{t&&t.unref&&t.unref()})(setTimeout(i=>{i.exitCode===null&&i.kill("SIGKILL")},5e3,r)),o()},R8n,n,e)),n.once("exit",()=>Hfe.delete(n))):n&&(Hfe.delete(n),e()),this.ready=!1}isReady(){return this.ready}async*readMessages(){if(this.spawnPromise&&(await this.spawnPromise,this.spawnPromise=void 0),!this.processStdout)throw Error("ProcessTransport output stream not available");if(this.exitError)throw this.exitError;let e=(0,RNt.createInterface)({input:this.processStdout}),n=this.process?(()=>{let r=this.process,o=()=>e.close();return r.on("error",o),()=>r.off("error",o)})():void 0;this.exitError&&e.close();try{for await(let r of e)if(r.trim()){let o;try{o=g4e(r)}catch{yx(`Non-JSON stdout: ${r}`);continue}yield o}if(this.exitError)throw this.exitError;await this.waitForExit()}catch(r){throw r}finally{n?.(),e.close()}}endInput(){if(this.spawnResolve){this.pendingEndInput=!0;return}this.processStdin&&this.processStdin.end()}getInputStream(){return this.processStdin}onExit(e){if(!this.process)return()=>{};let n=(r,o)=>{let i=this.getProcessExitError(r,o);e(i)};return this.process.on("exit",n),this.exitListeners.push({callback:e,handler:n}),()=>{this.process&&this.process.off("exit",n);let r=this.exitListeners.findIndex(o=>o.handler===n);r!==-1&&this.exitListeners.splice(r,1)}}async waitForExit(){if(!this.process){if(this.exitError)throw this.exitError;return}if(this.process.exitCode!==null||this.process.killed||this.exitError){if(this.exitError)throw this.exitError;return}return new Promise((e,n)=>{let r=(i,s)=>{if(this.abortController.signal.aborted){n(new Ek("Operation aborted"));return}let a=this.getProcessExitError(i,s);a?n(a):e()};this.process.once("exit",r);let o=i=>{this.process.off("exit",r),n(i)};this.process.once("error",o),this.process.once("exit",()=>{this.process.off("error",o)})})}};sB="@anthropic-ai/claude-agent-sdk";Eje=class{constructor(e){M(this,"returned");M(this,"queue",[]);M(this,"readResolve");M(this,"readReject");M(this,"isDone",!1);M(this,"hasError");M(this,"started",!1);this.returned=e}[Symbol.asyncIterator](){if(this.started)throw Error("Stream can only be iterated once");return this.started=!0,this}next(){return this.queue.length>0?Promise.resolve({done:!1,value:this.queue.shift()}):this.isDone?Promise.resolve({done:!0,value:void 0}):this.hasError?Promise.reject(this.hasError):new Promise((e,n)=>{this.readResolve=e,this.readReject=n})}enqueue(e){if(this.readResolve){let n=this.readResolve;this.readResolve=void 0,this.readReject=void 0,n({done:!1,value:e})}else this.queue.push(e)}done(){if(this.isDone=!0,this.readResolve){let e=this.readResolve;this.readResolve=void 0,this.readReject=void 0,e({done:!0,value:void 0})}}error(e){if(this.hasError=e,this.readReject){let n=this.readReject;this.readResolve=void 0,this.readReject=void 0,n(e)}}return(){return this.isDone=!0,this.returned&&this.returned(),Promise.resolve({done:!0,value:void 0})}};z8n=B8n();Mje=class{constructor(e){M(this,"sendMcpMessage");M(this,"isClosed",!1);M(this,"onclose");M(this,"onerror");M(this,"onmessage");this.sendMcpMessage=e}async start(){}async send(e){if(this.isClosed)throw Error("Transport is closed");this.sendMcpMessage(e)}async close(){this.isClosed||(this.isClosed=!0,this.onclose?.())}},KUe=Symbol("suppressControlResponse"),Qfe=class Qfe{constructor(e,n,r,o,i,s=new Map,a,l,c,u,d,f){M(this,"transport");M(this,"isSingleUserTurn");M(this,"canUseTool");M(this,"hooks");M(this,"abortController");M(this,"jsonSchema");M(this,"initConfig");M(this,"onElicitation");M(this,"getOAuthToken");M(this,"getHostAuthToken");M(this,"onUserDialog");M(this,"pendingControlResponses",new Map);M(this,"unmatchedControlResponses",new Map);M(this,"cleanupPerformed",!1);M(this,"sdkMessages");M(this,"inputStream",new Eje);M(this,"initialization");M(this,"cancelControllers",new Map);M(this,"hookCallbacks",new Map);M(this,"nextCallbackId",0);M(this,"initHooksPayload");M(this,"sdkMcpTransports",new Map);M(this,"sdkMcpServerInstances",new Map);M(this,"pendingMcpResponses",new Map);M(this,"firstResultReceivedResolve");M(this,"firstResultReceived",!1);M(this,"lastErrorResultText");M(this,"transcriptMirrorBatcher");M(this,"cleanupCallbacks",[]);M(this,"cleanupPromise");this.transport=e,this.isSingleUserTurn=n,this.canUseTool=r,this.hooks=o,this.abortController=i,this.jsonSchema=a,this.initConfig=l,this.onElicitation=c,this.getOAuthToken=u,this.getHostAuthToken=d,this.onUserDialog=f;for(let[p,m]of s)this.connectSdkMcpServer(p,m);this.sdkMessages=this.readSdkMessages(),this.readMessages(),this.initialization=this.initialize(),this.initialization.catch(()=>{})}setIsSingleUserTurn(e){this.isSingleUserTurn=e}setTranscriptMirrorBatcher(e){this.transcriptMirrorBatcher=e}reportMirrorError(e,n){let r={type:"system",subtype:"mirror_error",error:n,key:e,uuid:(0,Bfe.randomUUID)(),session_id:e.sessionId};this.inputStream.enqueue(r)}addCleanupCallback(e){this.cleanupPerformed?e():this.cleanupCallbacks.push(e)}isClosed(){return this.cleanupPerformed}hasBidirectionalNeeds(){return this.sdkMcpTransports.size>0||this.hooks!==void 0&&Object.keys(this.hooks).length>0||this.canUseTool!==void 0||this.onElicitation!==void 0||this.onUserDialog!==void 0||this.getOAuthToken!==void 0||this.getHostAuthToken!==void 0}setError(e){this.inputStream.error(e)}async stopTask(e){await this.request({subtype:"stop_task",task_id:e})}async backgroundTasks(e){return(await this.request({subtype:"background_tasks",tool_use_id:e})).response.backgrounded??!0}close(){this.cleanup()}cleanup(e){return this.cleanupPromise?this.cleanupPromise:(this.cleanupPerformed=!0,this.cleanupPromise=this.performCleanup(e),this.cleanupPromise)}async performCleanup(e){for(let n of this.cleanupCallbacks)try{n()}catch{}if(this.cleanupCallbacks=[],this.transcriptMirrorBatcher)try{await this.transcriptMirrorBatcher.flush()}catch{}try{for(let r of this.cancelControllers.values())r.abort();this.cancelControllers.clear(),this.transport.close();let n=e??Error("Query closed before response received");for(let{reject:r}of this.pendingControlResponses.values())r(n);this.pendingControlResponses.clear(),this.unmatchedControlResponses.clear();for(let{reject:r}of this.pendingMcpResponses.values())r(n);this.pendingMcpResponses.clear(),this.hookCallbacks.clear();for(let r of this.sdkMcpTransports.values())r.close().catch(()=>{});this.sdkMcpTransports.clear(),e?this.inputStream.error(e):this.inputStream.done()}catch{}if(this.transport.waitForExit){let n=new AbortController;try{await Promise.race([this.transport.waitForExit(),spe(2e3,n.signal)])}catch{}finally{n.abort()}}}next(...[e]){return this.sdkMessages.next(e)}async return(e){return await this.cleanup(),this.sdkMessages.return(e)}async throw(e){return await this.cleanup(),this.sdkMessages.throw(e)}[Symbol.asyncIterator](){return this.sdkMessages}async[Symbol.asyncDispose](){await this.cleanup()}async readMessages(){try{for await(let e of this.transport.readMessages()){if(e.type==="control_response"){let n=this.pendingControlResponses.get(e.response.request_id);if(n)n.handler(e.response);else{if(this.unmatchedControlResponses.size>=Qfe.UNMATCHED_CONTROL_RESPONSES_MAX){let r=this.unmatchedControlResponses.keys().next().value;r!==void 0&&this.unmatchedControlResponses.delete(r)}this.unmatchedControlResponses.set(e.response.request_id,e.response)}continue}else if(e.type==="control_request"){this.handleControlRequest(e);continue}else if(e.type==="control_cancel_request"){this.handleControlCancelRequest(e);continue}else{if(e.type==="keep_alive")continue;if(e.type==="transcript_mirror"){this.transcriptMirrorBatcher?.enqueue(e.filePath,e.entries);continue}}if(e.type==="system"&&(e.subtype==="post_turn_summary"||e.subtype==="task_summary")){this.inputStream.enqueue(e);continue}if(e.type==="active_goal"){this.inputStream.enqueue(e);continue}e.type==="result"?(this.transcriptMirrorBatcher&&await this.transcriptMirrorBatcher.flush(),this.lastErrorResultText=e.is_error?e.subtype==="success"?e.result:e.errors.join("; "):void 0,this.firstResultReceived=!0,this.firstResultReceivedResolve&&this.firstResultReceivedResolve(),this.isSingleUserTurn&&(Ka("[Query.readMessages] First result received for single-turn query, closing stdin"),this.transport.endInput())):e.type==="system"&&e.subtype==="session_state_changed"||(this.lastErrorResultText=void 0),this.inputStream.enqueue(e)}this.transcriptMirrorBatcher&&await this.transcriptMirrorBatcher.flush(),this.firstResultReceivedResolve&&this.firstResultReceivedResolve(),this.inputStream.done(),this.cleanup()}catch(e){if(this.transcriptMirrorBatcher&&await this.transcriptMirrorBatcher.flush(),this.firstResultReceivedResolve&&this.firstResultReceivedResolve(),this.lastErrorResultText!==void 0&&!(e instanceof Ek)&&e?.name!=="SSEHttpError"){let n=Error(`Claude Code returned an error result: ${this.lastErrorResultText}`);Ka(`[Query.readMessages] Replacing exit error with result text. Original: ${Wde(e)}`),this.inputStream.error(n),this.cleanup(n);return}this.inputStream.error(e),this.cleanup(e)}}async handleControlRequest(e){if(this.cancelControllers.has(e.request_id)){Ka(`[Query.handleControlRequest] Duplicate delivery of in-flight request ${e.request_id} (${e.request.subtype}) \u2014 skipping`);return}let n=new AbortController;this.cancelControllers.set(e.request_id,n);try{let r=await this.processControlRequest(e,n.signal);if(this.cleanupPerformed||r===KUe)return;let o={type:"control_response",response:{subtype:"success",request_id:e.request_id,response:r}};await Promise.resolve(this.transport.write(yp(o)+`
`))}catch(r){if(this.cleanupPerformed)return;let o={type:"control_response",response:{subtype:"error",request_id:e.request_id,error:Wde(r)}};try{await Promise.resolve(this.transport.write(yp(o)+`
`))}catch(i){Ka(`[Query.handleControlRequest] Error-response write failed: ${Wde(i)}`,{level:"error"})}}finally{this.cancelControllers.delete(e.request_id)}}handleControlCancelRequest(e){let n=this.cancelControllers.get(e.request_id);n&&(n.abort(),this.cancelControllers.delete(e.request_id))}async processControlRequest(e,n){if(e.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");let r=await this.canUseTool(e.request.tool_name,e.request.input,{signal:n,suggestions:e.request.permission_suggestions,blockedPath:e.request.blocked_path,decisionReason:e.request.decision_reason,title:e.request.title,displayName:e.request.display_name,description:e.request.description,toolUseID:e.request.tool_use_id,agentID:e.request.agent_id,requestId:e.request_id});return r===null?KUe:{...r,toolUseID:e.request.tool_use_id}}else{if(e.request.subtype==="hook_callback")return await this.handleHookCallbacks(e.request.callback_id,e.request.input,e.request.tool_use_id,n);if(e.request.subtype==="mcp_message"){let r=e.request,o=this.sdkMcpTransports.get(r.server_name);if(!o)throw Error(`SDK MCP server not found: ${r.server_name}`);return"method"in r.message&&"id"in r.message&&r.message.id!==null?{mcp_response:await this.handleMcpControlRequest(r.server_name,r,o)}:(o.onmessage&&o.onmessage(r.message),{mcp_response:{jsonrpc:"2.0",result:{},id:0}})}else if(e.request.subtype==="elicitation"){let r=e.request;return this.onElicitation?await this.onElicitation({serverName:r.mcp_server_name,message:r.message,mode:r.mode,url:r.url,elicitationId:r.elicitation_id,requestedSchema:r.requested_schema,title:r.title,displayName:r.display_name,description:r.description},{signal:n}):{action:"decline"}}else{if(e.request.subtype==="request_user_dialog")return this.onUserDialog?await this.onUserDialog({dialogKind:e.request.dialog_kind,payload:e.request.payload,toolUseID:e.request.tool_use_id},{signal:n}):(Ka(`[Query] No onUserDialog handler for request_user_dialog (kind=${e.request.dialog_kind}) \u2014 staying silent so a capable client (or the worker's park deadline) settles it`),y4e("tengu_request_user_dialog_response_ignored",{shape:l4e("auto_cancel")}),KUe);if(e.request.subtype==="oauth_token_refresh"){if(!this.getOAuthToken)throw Error("getOAuthToken callback is not provided.");return{accessToken:await this.getOAuthToken({signal:n})??null}}else if(e.request.subtype==="host_auth_token_refresh"){if(!this.getHostAuthToken)throw Error("getHostAuthToken callback is not provided.");return{authToken:await this.getHostAuthToken({signal:n})??null}}}}throw Error("Unsupported control request subtype: "+e.request.subtype)}async*readSdkMessages(){try{for await(let e of this.inputStream)yield e}finally{await this.cleanup()}}async initialize(){if(this.hooks&&!this.initHooksPayload){this.initHooksPayload={};for(let[r,o]of Object.entries(this.hooks))o.length>0&&(this.initHooksPayload[r]=o.map(i=>{let s=[];for(let a of i.hooks){let l=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(l,a),s.push(l)}return{matcher:i.matcher,hookCallbackIds:s,timeout:i.timeout}}))}let e=this.sdkMcpTransports.size>0?Array.from(this.sdkMcpTransports.keys()):void 0,n={subtype:"initialize",hooks:this.initHooksPayload,sdkMcpServers:e,jsonSchema:this.jsonSchema,systemPrompt:typeof this.initConfig?.systemPrompt=="string"?[this.initConfig.systemPrompt]:this.initConfig?.systemPrompt,appendSystemPrompt:this.initConfig?.appendSystemPrompt,planModeInstructions:this.initConfig?.planModeInstructions,appendSubagentSystemPrompt:this.initConfig?.appendSubagentSystemPrompt,toolAliases:this.initConfig?.toolAliases,excludeDynamicSections:this.initConfig?.excludeDynamicSections,agents:this.initConfig?.agents,title:this.initConfig?.title,skills:Array.isArray(this.initConfig?.skills)?this.initConfig.skills:void 0,webSearchIsolationExemptMcpServers:this.initConfig?.webSearchIsolationExemptMcpServers,promptSuggestions:this.initConfig?.promptSuggestions,agentProgressSummaries:this.initConfig?.agentProgressSummaries,forwardSubagentText:this.initConfig?.forwardSubagentText,supportedDialogKinds:this.initConfig?.supportedDialogKinds};return(await this.request(n)).response}async interrupt(){return Wy("sdk_interrupt",async()=>{let e=(await this.request({subtype:"interrupt"})).response?.still_queued;return Array.isArray(e)?{still_queued:e.filter(n=>typeof n=="string")}:void 0})}async setPermissionMode(e){await this.request({subtype:"set_permission_mode",mode:e})}async setMcpPermissionModeOverride(e,n){return(await this.request({subtype:"set_mcp_permission_mode_override",serverName:e,mode:n})).response??{}}awaitControlResponse(e){return this.transport.expectControlResponse?.(e),new Promise((n,r)=>{let o=s=>{if(s.subtype==="success"){let{pending_permission_requests:a,pending_user_dialog_requests:l,...c}=s;n(c)}else r(new gje(s.error,"awaitControlResponse: CLI error verdict"));(s.pending_permission_requests||s.pending_user_dialog_requests)&&Ka("[Query] Ignoring prompt-redelivery fields on awaitControlResponse response")};if(this.cleanupPerformed){r(Error("Query closed before response received"));return}let i=this.unmatchedControlResponses.get(e);if(i){this.unmatchedControlResponses.delete(e),o(i);return}this.pendingControlResponses.set(e,{handler:s=>{this.pendingControlResponses.delete(e),o(s)},reject:r})})}async setModel(e){await this.request({subtype:"set_model",model:e})}async setMaxThinkingTokens(e,n){await this.request({subtype:"set_max_thinking_tokens",max_thinking_tokens:e,thinking_display:n})}async applyFlagSettings(e){return Wy("sdk_apply_flag_settings",async()=>{await this.request({subtype:"apply_flag_settings",settings:e})})}async getSettings(){return(await this.request({subtype:"get_settings"})).response}async rewindFiles(e,n){return Wy("sdk_rewind_files",async()=>(await this.request({subtype:"rewind_files",user_message_id:e,dry_run:n?.dryRun})).response)}async cancelAsyncMessage(e){return(await this.request({subtype:"cancel_async_message",message_uuid:e})).response.cancelled}async seedReadState(e,n){await this.request({subtype:"seed_read_state",path:e,mtime:n})}async setCwd(e,n){return Wy("sdk_set_cwd",async()=>(await this.request({subtype:"set_cwd",path:e,...n?.trustAccepted!==void 0&&{trust_accepted:n.trustAccepted},...n?.trustedDirectory!==void 0&&{trusted_directory:n.trustedDirectory}})).response)}async enableRemoteControl(e,n){return(await this.request({subtype:"remote_control",enabled:e,...n!==void 0&&{name:n}})).response}async submitFeedback(e,n){return(await this.request({subtype:"submit_feedback",description:e,surface:n?.surface})).response}async generateSessionTitle(e,n){return Wy("sdk_session_title_generate",async()=>(await this.request({subtype:"generate_session_title",description:e,persist:n?.persist})).response.title)}async askSideQuestion(e){return Wy("sdk_side_question",async()=>{let n=(await this.request({subtype:"side_question",question:e})).response;return n.response===null?null:{response:n.response,synthetic:n.synthetic??!1}})}async launchUltrareview(e,n){return(await this.request({subtype:"ultrareview_launch",args:e,confirm:n?.confirm??!1})).response}async messageRated(e){await this.request({subtype:"message_rated",messageUuid:e.messageUuid,sentiment:e.sentiment,surface:e.surface,cleared:e.cleared??!1})}processPendingPermissionRequests(e){for(let n of e)n.request.subtype==="can_use_tool"&&this.handleControlRequest(n).catch(()=>{})}processPendingUserDialogRequests(e){for(let n of e)n.request.subtype==="request_user_dialog"&&this.handleControlRequest(n).catch(()=>{})}request(e){let n=Math.random().toString(36).substring(2,15);this.transport.expectControlResponse?.(n);let r={request_id:n,type:"control_request",request:e},o=e.subtype==="initialize";return new Promise((i,s)=>{this.pendingControlResponses.set(n,{handler:a=>{this.pendingControlResponses.delete(n),a.subtype==="success"?i(a):s(Error(a.error)),!o&&(a.pending_permission_requests||a.pending_user_dialog_requests)?Ka(`[Query] Ignoring prompt-redelivery fields on non-initialize response (subtype=${e.subtype})`):(a.pending_permission_requests&&this.processPendingPermissionRequests(a.pending_permission_requests),a.pending_user_dialog_requests&&this.processPendingUserDialogRequests(a.pending_user_dialog_requests))},reject:s}),Promise.resolve(this.transport.write(yp(r)+`
`)).catch(a=>{this.pendingControlResponses.delete(n),s(a)})})}initializationResult(){return this.initialization}reinitialize(){return Wy("sdk_reinitialize",()=>this.initialize())}async supportedCommands(){return(await this.initialization).commands}async supportedModels(){return(await this.initialization).models}async supportedAgents(){return(await this.initialization).agents}async reconnectMcpServer(e){await this.request({subtype:"mcp_reconnect",serverName:e})}async toggleMcpServer(e,n){return Wy("sdk_mcp_toggle_server",async()=>{await this.request({subtype:"mcp_toggle",serverName:e,enabled:n})})}async enableChannel(e){return Wy("sdk_mcp_enable_channel",async()=>{await this.request({subtype:"channel_enable",serverName:e})})}async mcpAuthenticate(e,n){return(await this.request({subtype:"mcp_authenticate",serverName:e,redirectUri:n})).response}async mcpClearAuth(e){return(await this.request({subtype:"mcp_clear_auth",serverName:e})).response}async mcpSubmitOAuthCallbackUrl(e,n){return(await this.request({subtype:"mcp_oauth_callback_url",serverName:e,callbackUrl:n})).response}async claudeAuthenticate(e){return(await this.request({subtype:"claude_authenticate",loginWithClaudeAi:e})).response}async claudeOAuthCallback(e,n){return(await this.request({subtype:"claude_oauth_callback",authorizationCode:e,state:n})).response}async claudeOAuthWaitForCompletion(){return(await this.request({subtype:"claude_oauth_wait_for_completion"})).response}async mcpServerStatus(){return(await this.request({subtype:"mcp_status"})).response.mcpServers}async getContextUsage(){return(await this.request({subtype:"get_context_usage"})).response}async usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET(){return(await this.request({subtype:"get_usage"})).response}async readFile(e,n){try{return(await this.request({subtype:"read_file",path:e,max_bytes:n?.maxBytes,encoding:n?.encoding})).response}catch{return null}}async reloadPlugins(){return Wy("sdk_reload_plugins",async()=>(await this.request({subtype:"reload_plugins"})).response)}async reloadSkills(){return Wy("sdk_reload_skills",async()=>(await this.request({subtype:"reload_skills"})).response)}async setMcpServers(e){return Wy("sdk_mcp_set_servers",async()=>{let n={},r={};for(let[a,l]of Object.entries(e))l.type==="sdk"&&"instance"in l?n[a]=l.instance:r[a]=l;let o=new Set(this.sdkMcpServerInstances.keys()),i=new Set(Object.keys(n));for(let a of o)i.has(a)||await this.disconnectSdkMcpServer(a);for(let[a,l]of Object.entries(n))o.has(a)||this.connectSdkMcpServer(a,l);let s={};for(let a of Object.keys(n))s[a]={type:"sdk",name:a};return(await this.request({subtype:"mcp_set_servers",servers:{...r,...s}})).response})}async accountInfo(){return(await this.initialization).account}async streamInput(e){Ka("[Query.streamInput] Starting to process input stream");try{let n=0;for await(let r of e){if(n++,Ka(`[Query.streamInput] Processing message ${n}: ${r.type}`),this.abortController?.signal.aborted)break;await Promise.resolve(this.transport.write(yp(r)+`
`))}Ka(`[Query.streamInput] Finished processing ${n} messages from input stream`),n>0&&this.hasBidirectionalNeeds()&&(Ka("[Query.streamInput] Has bidirectional needs, waiting for first result"),await this.waitForFirstResult()),Ka("[Query] Calling transport.endInput() to close stdin to CLI process"),this.transport.endInput()}catch(n){if(!(n instanceof Ek))throw n}}waitForFirstResult(){return this.firstResultReceived?(Ka("[Query.waitForFirstResult] Result already received, returning immediately"),Promise.resolve()):new Promise(e=>{if(this.abortController?.signal.aborted){e();return}this.abortController?.signal.addEventListener("abort",()=>e(),{once:!0}),this.firstResultReceivedResolve=e})}handleHookCallbacks(e,n,r,o){let i=this.hookCallbacks.get(e);if(!i)throw Error(`No hook callback found for ID: ${e}`);return i(n,r,{signal:o})}connectSdkMcpServer(e,n){let r=new Mje(o=>this.sendMcpServerMessageToCli(e,o));this.sdkMcpTransports.set(e,r),this.sdkMcpServerInstances.set(e,n),n.connect(r).catch(o=>{this.sdkMcpTransports.get(e)===r&&this.sdkMcpTransports.delete(e),this.sdkMcpServerInstances.get(e)===n&&this.sdkMcpServerInstances.delete(e),Ka(`[Query.connectSdkMcpServer] Failed to connect MCP server '${e}': ${o}`,{level:"error"})})}async disconnectSdkMcpServer(e){let n=this.sdkMcpTransports.get(e);n&&(await n.close(),this.sdkMcpTransports.delete(e)),this.sdkMcpServerInstances.delete(e)}sendMcpServerMessageToCli(e,n){if("id"in n&&n.id!==null&&n.id!==void 0){let o=`${e}:${n.id}`,i=this.pendingMcpResponses.get(o);if(i){i.resolve(n),this.pendingMcpResponses.delete(o);return}}let r={type:"control_request",request_id:(0,Bfe.randomUUID)(),request:{subtype:"mcp_message",server_name:e,message:n}};Promise.resolve(this.transport.write(yp(r)+`
`)).catch(o=>{Ka(`[Query.sendMcpServerMessageToCli] Transport write failed: ${o}`,{level:"error"})})}handleMcpControlRequest(e,n,r){let o="id"in n.message?n.message.id:null,i=`${e}:${o}`;return new Promise((s,a)=>{let l=()=>{this.pendingMcpResponses.delete(i)},c=d=>{l(),s(d)},u=d=>{l(),a(d)};if(this.pendingMcpResponses.set(i,{resolve:c,reject:u}),r.onmessage)r.onmessage(n.message);else{l(),a(Error("No message handler registered"));return}})}};M(Qfe,"UNMATCHED_CONTROL_RESPONSES_MAX",1024);Oje=Qfe,qDt=500,KDt=1048576,V8n=[200,800],Nje=class{constructor(e,n=6e4,r,o=qDt,i=KDt,s=V8n){M(this,"send");M(this,"sendTimeoutMs");M(this,"onError");M(this,"maxPendingEntries");M(this,"maxPendingBytes");M(this,"backoffMs");M(this,"pending",[]);M(this,"pendingEntries",0);M(this,"pendingBytes",0);M(this,"flushPromise",null);this.send=e,this.sendTimeoutMs=n,this.onError=r,this.maxPendingEntries=o,this.maxPendingBytes=i,this.backoffMs=s}enqueue(e,n){let r=yp(n).length;this.pending.push({filePath:e,entries:n,bytes:r}),this.pendingEntries+=n.length,this.pendingBytes+=r,(this.pendingEntries>this.maxPendingEntries||this.pendingBytes>this.maxPendingBytes)&&(this.flushPromise=this.drain(),this.flushPromise.catch(()=>{}))}async flush(){let e=this.drain();this.flushPromise=e,await e,this.flushPromise===e&&(this.flushPromise=null)}async drain(){let e=this.flushPromise,n=this.pending.splice(0);this.pendingEntries=0,this.pendingBytes=0,e&&await e,n.length!==0&&await this.doFlush(n)}async doFlush(e){let n=new Map;for(let o of e){let i=n.get(o.filePath);i?i.push(...o.entries):n.set(o.filePath,o.entries.slice())}let r=this.backoffMs.length+1;for(let[o,i]of n){let s=`SessionStore.append() timed out after ${this.sendTimeoutMs}ms for ${o}`,a,l=1;for(;l<=r;l++)try{await l7(this.send(o,i),this.sendTimeoutMs,s),a=void 0;break}catch(c){if(a=Ppe(c),a.message===s)break;let u=this.backoffMs[l-1];if(u===void 0)break;await spe(u)}if(a){Ka(`[TranscriptMirrorBatcher] flush failed for ${o} after ${l} attempt(s): ${a}`,{level:"error"});try{this.onError?.(o,a)}catch(c){Ka(`[TranscriptMirrorBatcher] onError callback threw: ${c}`,{level:"error"})}}}}},AOt=eBe(d4n(),1),Quo=(0,YDt.promisify)(ZDt.execFile);X8n=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;MOt=200;edo=Buffer.from('{"type":"attribution-snapshot"'),tdo=Buffer.from('{"type":"system"'),rZn=10,ndo=Buffer.from([rZn]);dZn="user:inference",rFt="user:profile",fZn="org:create_api_key",pZn=[fZn,rFt],mZn=[rFt,dZn,"user:sessions:claude_code","user:mcp_servers","user:file_upload"],odo=cZn([...pZn,...mZn]),OOt={BASE_API_URL:"https://api.anthropic.com",CONSOLE_AUTHORIZE_URL:"https://platform.claude.com/oauth/authorize",CLAUDE_AI_AUTHORIZE_URL:"https://claude.com/cai/oauth/authorize",CLAUDE_AI_ORIGIN:"https://claude.ai",TOKEN_URL:"https://platform.claude.com/v1/oauth/token",API_KEY_URL:"https://api.anthropic.com/api/oauth/claude_cli/create_api_key",ROLES_URL:"https://api.anthropic.com/api/oauth/claude_cli/roles",CONSOLE_SUCCESS_URL:"https://platform.claude.com/buy_credits?returnUrl=/oauth/code/success%3Fapp%3Dclaude-code",CLAUDEAI_SUCCESS_URL:"https://platform.claude.com/oauth/code/success?app=claude-code",MANUAL_REDIRECT_URL:"https://platform.claude.com/oauth/code/callback",CLIENT_ID:"9d1c250a-e61b-44d9-88ed-5944d1962f5e",DESIGN_CLIENT_ID:"59637612-477b-4836-a601-b0589eda7704",OAUTH_FILE_SUFFIX:"",MCP_PROXY_URL:"https://mcp-proxy.anthropic.com",MCP_PROXY_PATH:"/v1/mcp/{server_id}"},hZn=void 0;yZn=["https://beacon.claude-ai.staging.ant.dev","https://claude.fedstart.com","https://claude-staging.fedstart.com"];wZn="-credentials";_Zn=/^[a-zA-Z0-9._-]+$/;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw Error()}t.assertNever=n,t.arrayToEnum=o=>{let i={};for(let s of o)i[s]=s;return i},t.getValidEnumValues=o=>{let i=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),s={};for(let a of i)s[a]=o[a];return t.objectValues(s)},t.objectValues=o=>t.objectKeys(o).map(function(i){return o[i]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},t.find=(o,i)=>{for(let s of o)if(i(s))return s},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(ti||(ti={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(NOt||(NOt={}));Zt=ti.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),zP=t=>{switch(typeof t){case"undefined":return Zt.undefined;case"string":return Zt.string;case"number":return Number.isNaN(t)?Zt.nan:Zt.number;case"boolean":return Zt.boolean;case"function":return Zt.function;case"bigint":return Zt.bigint;case"symbol":return Zt.symbol;case"object":return Array.isArray(t)?Zt.array:t===null?Zt.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Zt.promise:typeof Map<"u"&&t instanceof Map?Zt.map:typeof Set<"u"&&t instanceof Set?Zt.set:typeof Date<"u"&&t instanceof Date?Zt.date:Zt.object;default:return Zt.unknown}},at=ti.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Zy=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(i){return i.message},r={_errors:[]},o=i=>{for(let s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)r._errors.push(n(s));else{let a=r,l=0;for(;l<s.path.length;){let c=s.path[l];l!==s.path.length-1?a[c]=a[c]||{_errors:[]}:(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(s))),a=a[c],l++}}};return o(this),r}static assert(e){if(!(e instanceof t))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ti.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let i=o.path[0];n[i]=n[i]||[],n[i].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Zy.create=t=>new Zy(t);kZn=(t,e)=>{let n;switch(t.code){case at.invalid_type:t.received===Zt.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case at.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,ti.jsonStringifyReplacer)}`;break;case at.unrecognized_keys:n=`Unrecognized key(s) in object: ${ti.joinValues(t.keys,", ")}`;break;case at.invalid_union:n="Invalid input";break;case at.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ti.joinValues(t.options)}`;break;case at.invalid_enum_value:n=`Invalid enum value. Expected ${ti.joinValues(t.options)}, received '${t.received}'`;break;case at.invalid_arguments:n="Invalid function arguments";break;case at.invalid_return_type:n="Invalid function return type";break;case at.invalid_date:n="Invalid date";break;case at.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:ti.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case at.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case at.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case at.custom:n="Invalid input";break;case at.invalid_intersection_types:n="Intersection results could not be merged";break;case at.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case at.not_finite:n="Number must be finite";break;default:n=e.defaultError,ti.assertNever(t)}return{message:n}},I7=kZn,IZn=I7;$je=t=>{let{data:e,path:n,errorMaps:r,issueData:o}=t,i=[...n,...o.path||[]],s={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let a="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(s,{data:e,defaultError:a}).message;return{...o,path:i,message:a}};_p=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let o of n){if(o.status==="aborted")return yr;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let o of n){let i=await o.key,s=await o.value;r.push({key:i,value:s})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let o of n){let{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return yr;i.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:e.value,value:r}}},yr=Object.freeze({status:"aborted"}),s7=t=>({status:"dirty",value:t}),km=t=>({status:"valid",value:t}),ROt=t=>t.status==="aborted",LOt=t=>t.status==="dirty",PB=t=>t.status==="valid",Wfe=t=>typeof Promise<"u"&&t instanceof Promise;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Sn||(Sn={}));Yy=class{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},$Ot=(t,e)=>{if(PB(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Zy(t.common.issues);return this._error=n,this._error}}};fo=class{get description(){return this._def.description}_getType(e){return zP(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:zP(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new _p,ctx:{common:e.parent.common,data:e.data,parsedType:zP(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Wfe(n))throw Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zP(e)},o=this._parseSync({data:e,path:r.path,parent:r});return $Ot(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zP(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return PB(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>PB(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zP(e)},o=this._parse({data:e,path:r.path,parent:r}),i=await(Wfe(o)?o:Promise.resolve(o));return $Ot(r,i)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{let s=e(o),a=()=>i.addIssue({code:at.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new ib({schema:this,typeName:vr.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return rb.create(this,this._def)}nullable(){return Lk.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return YP.create(this)}promise(){return LR.create(this,this._def)}or(e){return OB.create([this,e],this._def)}and(e){return NB.create(this,e,this._def)}transform(e){return new ib({...Kr(this._def),schema:this,typeName:vr.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new FB({...Kr(this._def),innerType:this,defaultValue:n,typeName:vr.ZodDefault})}brand(){return new Vfe({typeName:vr.ZodBranded,type:this,...Kr(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new UB({...Kr(this._def),innerType:this,catchValue:n,typeName:vr.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return qfe.create(this,e)}readonly(){return jB.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},TZn=/^c[^\s-]{8,}$/i,PZn=/^[0-9a-z]+$/,AZn=/^[0-9A-HJKMNP-TV-Z]{26}$/i,EZn=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,MZn=/^[a-z0-9_-]{21}$/i,OZn=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,NZn=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,RZn=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,LZn="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",$Zn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,DZn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,FZn=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,UZn=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,jZn=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,BZn=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,oFt="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",zZn=new RegExp(`^${oFt}$`);AB=class t extends fo{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Zt.string){let o=this._getOrReturnCtx(e);return Ut(o,{code:at.invalid_type,expected:Zt.string,received:o.parsedType}),yr}let n=new _p,r;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(r=this._getOrReturnCtx(e,r),Ut(r,{code:at.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(r=this._getOrReturnCtx(e,r),Ut(r,{code:at.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let i=e.data.length>o.value,s=e.data.length<o.value;(i||s)&&(r=this._getOrReturnCtx(e,r),i?Ut(r,{code:at.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):s&&Ut(r,{code:at.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")RZn.test(e.data)||(r=this._getOrReturnCtx(e,r),Ut(r,{validation:"email",code:at.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")GUe||(GUe=new RegExp(LZn,"u")),GUe.test(e.data)||(r=this._getOrReturnCtx(e,r),Ut(r,{validation:"emoji",code:at.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")EZn.test(e.data)||(r=this._getOrReturnCtx(e,r),Ut(r,{validation:"uuid",code:at.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")MZn.test(e.data)||(r=this._getOrReturnCtx(e,r),Ut(r,{validation:"nanoid",code:at.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")TZn.test(e.data)||(r=this._getOrReturnCtx(e,r),Ut(r,{validation:"cuid",code:at.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")PZn.test(e.data)||(r=this._getOrReturnCtx(e,r),Ut(r,{validation:"cuid2",code:at.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")AZn.test(e.data)||(r=this._getOrReturnCtx(e,r),Ut(r,{validation:"ulid",code:at.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),Ut(r,{validation:"url",code:at.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,!o.regex.test(e.data)&&(r=this._getOrReturnCtx(e,r),Ut(r,{validation:"regex",code:at.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(r=this._getOrReturnCtx(e,r),Ut(r,{code:at.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(r=this._getOrReturnCtx(e,r),Ut(r,{code:at.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(r=this._getOrReturnCtx(e,r),Ut(r,{code:at.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?WZn(o).test(e.data)||(r=this._getOrReturnCtx(e,r),Ut(r,{code:at.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?zZn.test(e.data)||(r=this._getOrReturnCtx(e,r),Ut(r,{code:at.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?HZn(o).test(e.data)||(r=this._getOrReturnCtx(e,r),Ut(r,{code:at.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?NZn.test(e.data)||(r=this._getOrReturnCtx(e,r),Ut(r,{validation:"duration",code:at.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?VZn(e.data,o.version)||(r=this._getOrReturnCtx(e,r),Ut(r,{validation:"ip",code:at.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?qZn(e.data,o.alg)||(r=this._getOrReturnCtx(e,r),Ut(r,{validation:"jwt",code:at.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?KZn(e.data,o.version)||(r=this._getOrReturnCtx(e,r),Ut(r,{validation:"cidr",code:at.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?jZn.test(e.data)||(r=this._getOrReturnCtx(e,r),Ut(r,{validation:"base64",code:at.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?BZn.test(e.data)||(r=this._getOrReturnCtx(e,r),Ut(r,{validation:"base64url",code:at.invalid_string,message:o.message}),n.dirty()):ti.assertNever(o);return{status:n.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:at.invalid_string,...Sn.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Sn.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Sn.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Sn.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Sn.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Sn.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Sn.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Sn.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Sn.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Sn.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Sn.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Sn.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Sn.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Sn.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Sn.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Sn.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Sn.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...Sn.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...Sn.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...Sn.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...Sn.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...Sn.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...Sn.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...Sn.errToObj(n)})}nonempty(e){return this.min(1,Sn.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};AB.create=t=>new AB({checks:[],typeName:vr.ZodString,coerce:t?.coerce??!1,...Kr(t)});T7=class t extends fo{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Zt.number){let o=this._getOrReturnCtx(e);return Ut(o,{code:at.invalid_type,expected:Zt.number,received:o.parsedType}),yr}let n,r=new _p;for(let o of this._def.checks)o.kind==="int"?ti.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),Ut(n,{code:at.invalid_type,expected:"integer",received:"float",message:o.message}),r.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),Ut(n,{code:at.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),r.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),Ut(n,{code:at.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),r.dirty()):o.kind==="multipleOf"?GZn(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),Ut(n,{code:at.not_multiple_of,multipleOf:o.value,message:o.message}),r.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),Ut(n,{code:at.not_finite,message:o.message}),r.dirty()):ti.assertNever(o);return{status:r.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,Sn.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Sn.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Sn.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Sn.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Sn.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Sn.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Sn.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Sn.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Sn.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Sn.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Sn.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:Sn.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Sn.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Sn.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ti.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};T7.create=t=>new T7({checks:[],typeName:vr.ZodNumber,coerce:t?.coerce||!1,...Kr(t)});P7=class t extends fo{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==Zt.bigint)return this._getInvalidInput(e);let n,r=new _p;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),Ut(n,{code:at.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),r.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),Ut(n,{code:at.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),r.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),Ut(n,{code:at.not_multiple_of,multipleOf:o.value,message:o.message}),r.dirty()):ti.assertNever(o);return{status:r.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return Ut(n,{code:at.invalid_type,expected:Zt.bigint,received:n.parsedType}),yr}gte(e,n){return this.setLimit("min",e,!0,Sn.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Sn.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Sn.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Sn.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Sn.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Sn.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Sn.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Sn.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Sn.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Sn.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};P7.create=t=>new P7({checks:[],typeName:vr.ZodBigInt,coerce:t?.coerce??!1,...Kr(t)});A7=class extends fo{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Zt.boolean){let n=this._getOrReturnCtx(e);return Ut(n,{code:at.invalid_type,expected:Zt.boolean,received:n.parsedType}),yr}return km(e.data)}};A7.create=t=>new A7({typeName:vr.ZodBoolean,coerce:t?.coerce||!1,...Kr(t)});E7=class t extends fo{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Zt.date){let o=this._getOrReturnCtx(e);return Ut(o,{code:at.invalid_type,expected:Zt.date,received:o.parsedType}),yr}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return Ut(o,{code:at.invalid_date}),yr}let n=new _p,r;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(r=this._getOrReturnCtx(e,r),Ut(r,{code:at.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(r=this._getOrReturnCtx(e,r),Ut(r,{code:at.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):ti.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:Sn.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:Sn.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};E7.create=t=>new E7({checks:[],coerce:t?.coerce||!1,typeName:vr.ZodDate,...Kr(t)});M7=class extends fo{_parse(e){if(this._getType(e)!==Zt.symbol){let n=this._getOrReturnCtx(e);return Ut(n,{code:at.invalid_type,expected:Zt.symbol,received:n.parsedType}),yr}return km(e.data)}};M7.create=t=>new M7({typeName:vr.ZodSymbol,...Kr(t)});EB=class extends fo{_parse(e){if(this._getType(e)!==Zt.undefined){let n=this._getOrReturnCtx(e);return Ut(n,{code:at.invalid_type,expected:Zt.undefined,received:n.parsedType}),yr}return km(e.data)}};EB.create=t=>new EB({typeName:vr.ZodUndefined,...Kr(t)});MB=class extends fo{_parse(e){if(this._getType(e)!==Zt.null){let n=this._getOrReturnCtx(e);return Ut(n,{code:at.invalid_type,expected:Zt.null,received:n.parsedType}),yr}return km(e.data)}};MB.create=t=>new MB({typeName:vr.ZodNull,...Kr(t)});O7=class extends fo{constructor(){super(...arguments),this._any=!0}_parse(e){return km(e.data)}};O7.create=t=>new O7({typeName:vr.ZodAny,...Kr(t)});KP=class extends fo{constructor(){super(...arguments),this._unknown=!0}_parse(e){return km(e.data)}};KP.create=t=>new KP({typeName:vr.ZodUnknown,...Kr(t)});bx=class extends fo{_parse(e){let n=this._getOrReturnCtx(e);return Ut(n,{code:at.invalid_type,expected:Zt.never,received:n.parsedType}),yr}};bx.create=t=>new bx({typeName:vr.ZodNever,...Kr(t)});N7=class extends fo{_parse(e){if(this._getType(e)!==Zt.undefined){let n=this._getOrReturnCtx(e);return Ut(n,{code:at.invalid_type,expected:Zt.void,received:n.parsedType}),yr}return km(e.data)}};N7.create=t=>new N7({typeName:vr.ZodVoid,...Kr(t)});YP=class t extends fo{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==Zt.array)return Ut(n,{code:at.invalid_type,expected:Zt.array,received:n.parsedType}),yr;if(o.exactLength!==null){let s=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(s||a)&&(Ut(n,{code:s?at.too_big:at.too_small,minimum:a?o.exactLength.value:void 0,maximum:s?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(Ut(n,{code:at.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(Ut(n,{code:at.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,a)=>o.type._parseAsync(new Yy(n,s,n.path,a)))).then(s=>_p.mergeArray(r,s));let i=[...n.data].map((s,a)=>o.type._parseSync(new Yy(n,s,n.path,a)));return _p.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:Sn.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:Sn.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:Sn.toString(n)}})}nonempty(e){return this.min(1,e)}};YP.create=(t,e)=>new YP({type:t,minLength:null,maxLength:null,exactLength:null,typeName:vr.ZodArray,...Kr(e)});Gh=class t extends fo{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=ti.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==Zt.object){let l=this._getOrReturnCtx(e);return Ut(l,{code:at.invalid_type,expected:Zt.object,received:l.parsedType}),yr}let{status:n,ctx:r}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof bx&&this._def.unknownKeys==="strip"))for(let l in r.data)i.includes(l)||s.push(l);let a=[];for(let l of i){let c=o[l],u=r.data[l];a.push({key:{status:"valid",value:l},value:c._parse(new Yy(r,u,r.path,l)),alwaysSet:l in r.data})}if(this._def.catchall instanceof bx){let l=this._def.unknownKeys;if(l==="passthrough")for(let c of s)a.push({key:{status:"valid",value:c},value:{status:"valid",value:r.data[c]}});else if(l==="strict")s.length>0&&(Ut(r,{code:at.unrecognized_keys,keys:s}),n.dirty());else if(l!=="strip")throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let c of s){let u=r.data[c];a.push({key:{status:"valid",value:c},value:l._parse(new Yy(r,u,r.path,c)),alwaysSet:c in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let l=[];for(let c of a){let u=await c.key,d=await c.value;l.push({key:u,value:d,alwaysSet:c.alwaysSet})}return l}).then(l=>_p.mergeObjectSync(n,l)):_p.mergeObjectSync(n,a)}get shape(){return this._def.shape()}strict(e){return Sn.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:Sn.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:vr.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of ti.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of ti.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return fB(this)}partial(e){let n={};for(let r of ti.objectKeys(this.shape)){let o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of ti.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof rb;)o=o._def.innerType;n[r]=o}return new t({...this._def,shape:()=>n})}keyof(){return sFt(ti.objectKeys(this.shape))}};Gh.create=(t,e)=>new Gh({shape:()=>t,unknownKeys:"strip",catchall:bx.create(),typeName:vr.ZodObject,...Kr(e)});Gh.strictCreate=(t,e)=>new Gh({shape:()=>t,unknownKeys:"strict",catchall:bx.create(),typeName:vr.ZodObject,...Kr(e)});Gh.lazycreate=(t,e)=>new Gh({shape:t,unknownKeys:"strip",catchall:bx.create(),typeName:vr.ZodObject,...Kr(e)});OB=class extends fo{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function o(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let s=i.map(a=>new Zy(a.ctx.common.issues));return Ut(n,{code:at.invalid_union,unionErrors:s}),yr}if(n.common.async)return Promise.all(r.map(async i=>{let s={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(o);{let i,s=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:c}),c.common.issues.length&&s.push(c.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map(l=>new Zy(l));return Ut(n,{code:at.invalid_union,unionErrors:a}),yr}}get options(){return this._def.options}};OB.create=(t,e)=>new OB({options:t,typeName:vr.ZodUnion,...Kr(e)});Tk=t=>t instanceof RB?Tk(t.schema):t instanceof ib?Tk(t.innerType()):t instanceof LB?[t.value]:t instanceof $B?t.options:t instanceof DB?ti.objectValues(t.enum):t instanceof FB?Tk(t._def.innerType):t instanceof EB?[void 0]:t instanceof MB?[null]:t instanceof rb?[void 0,...Tk(t.unwrap())]:t instanceof Lk?[null,...Tk(t.unwrap())]:t instanceof Vfe||t instanceof jB?Tk(t.unwrap()):t instanceof UB?Tk(t._def.innerType):[],Dje=class t extends fo{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==Zt.object)return Ut(n,{code:at.invalid_type,expected:Zt.object,received:n.parsedType}),yr;let r=this.discriminator,o=n.data[r],i=this.optionsMap.get(o);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(Ut(n,{code:at.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),yr)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let o=new Map;for(let i of n){let s=Tk(i.shape[e]);if(!s.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(o.has(a))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,i)}}return new t({typeName:vr.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...Kr(r)})}};NB=class extends fo{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(i,s)=>{if(ROt(i)||ROt(s))return yr;let a=Fje(i.value,s.value);return a.valid?((LOt(i)||LOt(s))&&n.dirty(),{status:n.value,value:a.data}):(Ut(r,{code:at.invalid_intersection_types}),yr)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,s])=>o(i,s)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};NB.create=(t,e,n)=>new NB({left:t,right:e,typeName:vr.ZodIntersection,...Kr(n)});Rk=class t extends fo{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Zt.array)return Ut(r,{code:at.invalid_type,expected:Zt.array,received:r.parsedType}),yr;if(r.data.length<this._def.items.length)return Ut(r,{code:at.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),yr;!this._def.rest&&r.data.length>this._def.items.length&&(Ut(r,{code:at.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((i,s)=>{let a=this._def.items[s]||this._def.rest;return a?a._parse(new Yy(r,i,r.path,s)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>_p.mergeArray(n,i)):_p.mergeArray(n,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Rk.create=(t,e)=>{if(!Array.isArray(t))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Rk({items:t,typeName:vr.ZodTuple,rest:null,...Kr(e)})};Uje=class t extends fo{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Zt.object)return Ut(r,{code:at.invalid_type,expected:Zt.object,received:r.parsedType}),yr;let o=[],i=this._def.keyType,s=this._def.valueType;for(let a in r.data)o.push({key:i._parse(new Yy(r,a,r.path,a)),value:s._parse(new Yy(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?_p.mergeObjectAsync(n,o):_p.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof fo?new t({keyType:e,valueType:n,typeName:vr.ZodRecord,...Kr(r)}):new t({keyType:AB.create(),valueType:e,typeName:vr.ZodRecord,...Kr(n)})}},R7=class extends fo{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Zt.map)return Ut(r,{code:at.invalid_type,expected:Zt.map,received:r.parsedType}),yr;let o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([a,l],c)=>({key:o._parse(new Yy(r,a,r.path,[c,"key"])),value:i._parse(new Yy(r,l,r.path,[c,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of s){let c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return yr;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let l of s){let{key:c,value:u}=l;if(c.status==="aborted"||u.status==="aborted")return yr;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}}}};R7.create=(t,e,n)=>new R7({valueType:e,keyType:t,typeName:vr.ZodMap,...Kr(n)});L7=class t extends fo{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Zt.set)return Ut(r,{code:at.invalid_type,expected:Zt.set,received:r.parsedType}),yr;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(Ut(r,{code:at.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(Ut(r,{code:at.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let i=this._def.valueType;function s(l){let c=new Set;for(let u of l){if(u.status==="aborted")return yr;u.status==="dirty"&&n.dirty(),c.add(u.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>i._parse(new Yy(r,l,r.path,c)));return r.common.async?Promise.all(a).then(l=>s(l)):s(a)}min(e,n){return new t({...this._def,minSize:{value:e,message:Sn.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:Sn.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};L7.create=(t,e)=>new L7({valueType:t,minSize:null,maxSize:null,typeName:vr.ZodSet,...Kr(e)});jje=class t extends fo{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==Zt.function)return Ut(n,{code:at.invalid_type,expected:Zt.function,received:n.parsedType}),yr;function r(a,l){return $je({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Lje(),I7].filter(c=>!!c),issueData:{code:at.invalid_arguments,argumentsError:l}})}function o(a,l){return $je({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Lje(),I7].filter(c=>!!c),issueData:{code:at.invalid_return_type,returnTypeError:l}})}let i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof LR){let a=this;return km(async function(...l){let c=new Zy([]),u=await a._def.args.parseAsync(l,i).catch(f=>{throw c.addIssue(r(l,f)),c}),d=await Reflect.apply(s,this,u);return await a._def.returns._def.type.parseAsync(d,i).catch(f=>{throw c.addIssue(o(d,f)),c})})}else{let a=this;return km(function(...l){let c=a._def.args.safeParse(l,i);if(!c.success)throw new Zy([r(l,c.error)]);let u=Reflect.apply(s,this,c.data),d=a._def.returns.safeParse(u,i);if(!d.success)throw new Zy([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Rk.create(e).rest(KP.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||Rk.create([]).rest(KP.create()),returns:n||KP.create(),typeName:vr.ZodFunction,...Kr(r)})}},RB=class extends fo{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};RB.create=(t,e)=>new RB({getter:t,typeName:vr.ZodLazy,...Kr(e)});LB=class extends fo{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return Ut(n,{received:n.data,code:at.invalid_literal,expected:this._def.value}),yr}return{status:"valid",value:e.data}}get value(){return this._def.value}};LB.create=(t,e)=>new LB({value:t,typeName:vr.ZodLiteral,...Kr(e)});$B=class t extends fo{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return Ut(n,{expected:ti.joinValues(r),received:n.parsedType,code:at.invalid_type}),yr}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return Ut(n,{received:n.data,code:at.invalid_enum_value,options:r}),yr}return km(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};$B.create=sFt;DB=class extends fo{_parse(e){let n=ti.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==Zt.string&&r.parsedType!==Zt.number){let o=ti.objectValues(n);return Ut(r,{expected:ti.joinValues(o),received:r.parsedType,code:at.invalid_type}),yr}if(this._cache||(this._cache=new Set(ti.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ti.objectValues(n);return Ut(r,{received:r.data,code:at.invalid_enum_value,options:o}),yr}return km(e.data)}get enum(){return this._def.values}};DB.create=(t,e)=>new DB({values:t,typeName:vr.ZodNativeEnum,...Kr(e)});LR=class extends fo{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==Zt.promise&&n.common.async===!1)return Ut(n,{code:at.invalid_type,expected:Zt.promise,received:n.parsedType}),yr;let r=n.parsedType===Zt.promise?n.data:Promise.resolve(n.data);return km(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};LR.create=(t,e)=>new LR({type:t,typeName:vr.ZodPromise,...Kr(e)});ib=class extends fo{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===vr.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,i={addIssue:s=>{Ut(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){let s=o.transform(r.data,i);if(r.common.async)return Promise.resolve(s).then(async a=>{if(n.value==="aborted")return yr;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?yr:l.status==="dirty"||n.value==="dirty"?s7(l.value):l});{if(n.value==="aborted")return yr;let a=this._def.schema._parseSync({data:s,path:r.path,parent:r});return a.status==="aborted"?yr:a.status==="dirty"||n.value==="dirty"?s7(a.value):a}}if(o.type==="refinement"){let s=a=>{let l=o.refinement(a,i);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?yr:(a.status==="dirty"&&n.dirty(),s(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?yr:(a.status==="dirty"&&n.dirty(),s(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!PB(s))return yr;let a=o.transform(s.value,i);if(a instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>PB(s)?Promise.resolve(o.transform(s.value,i)).then(a=>({status:n.value,value:a})):yr);ti.assertNever(o)}};ib.create=(t,e,n)=>new ib({schema:t,typeName:vr.ZodEffects,effect:e,...Kr(n)});ib.createWithPreprocess=(t,e,n)=>new ib({schema:e,effect:{type:"preprocess",transform:t},typeName:vr.ZodEffects,...Kr(n)});rb=class extends fo{_parse(e){return this._getType(e)===Zt.undefined?km(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};rb.create=(t,e)=>new rb({innerType:t,typeName:vr.ZodOptional,...Kr(e)});Lk=class extends fo{_parse(e){return this._getType(e)===Zt.null?km(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Lk.create=(t,e)=>new Lk({innerType:t,typeName:vr.ZodNullable,...Kr(e)});FB=class extends fo{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===Zt.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};FB.create=(t,e)=>new FB({innerType:t,typeName:vr.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Kr(e)});UB=class extends fo{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Wfe(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Zy(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Zy(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};UB.create=(t,e)=>new UB({innerType:t,typeName:vr.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Kr(e)});$7=class extends fo{_parse(e){if(this._getType(e)!==Zt.nan){let n=this._getOrReturnCtx(e);return Ut(n,{code:at.invalid_type,expected:Zt.nan,received:n.parsedType}),yr}return{status:"valid",value:e.data}}};$7.create=t=>new $7({typeName:vr.ZodNaN,...Kr(t)});ido=Symbol("zod_brand"),Vfe=class extends fo{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},qfe=class t extends fo{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?yr:o.status==="dirty"?(n.dirty(),s7(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?yr:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:vr.ZodPipeline})}},jB=class extends fo{_parse(e){let n=this._def.innerType._parse(e),r=o=>(PB(o)&&(o.value=Object.freeze(o.value)),o);return Wfe(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};jB.create=(t,e)=>new jB({innerType:t,typeName:vr.ZodReadonly,...Kr(e)});sdo={object:Gh.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(vr||(vr={}));ado=AB.create,ldo=T7.create,cdo=$7.create,udo=P7.create,ddo=A7.create,fdo=E7.create,pdo=M7.create,mdo=EB.create,hdo=MB.create,gdo=O7.create,ydo=KP.create,vdo=bx.create,wdo=N7.create,bdo=YP.create,_do=Gh.create,xdo=Gh.strictCreate,Sdo=OB.create,Cdo=Dje.create,kdo=NB.create,Ido=Rk.create,Tdo=Uje.create,Pdo=R7.create,Ado=L7.create,Edo=jje.create,Mdo=RB.create,Odo=LB.create,Ndo=$B.create,Rdo=DB.create,Ldo=LR.create,$do=ib.create,Ddo=rb.create,Fdo=Lk.create,Udo=ib.createWithPreprocess,jdo=qfe.create,ZZn=_e("ZodMiniType",(t,e)=>{if(!t._zod)throw Error("Uninitialized schema in ZodMiniType.");Mr.init(t,e),t.def=e,t.parse=(n,r)=>Xde(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>_Be(t,n,r),t.parseAsync=async(n,r)=>Qde(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>SBe(t,n,r),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>lb(t,n,r),t.brand=()=>t,t.register=(n,r)=>(n.add(t,r),t)}),Bdo=_e("ZodMiniObject",(t,e)=>{NBe.init(t,e),ZZn.init(t,e),Mo.defineLazy(t,"shape",()=>e.shape)}),YZn="io.modelcontextprotocol/related-task",Rpe="2.0",Uc=R$t(t=>t!==null&&(typeof t=="object"||typeof t=="function")),aFt=gs([ke(),xi().int()]),lFt=ke(),zdo=vp({ttl:xi().optional(),pollInterval:xi().optional()}),JZn=qt({ttl:xi().optional()}),XZn=qt({taskId:ke()}),v4e=vp({progressToken:aFt.optional(),[YZn]:XZn.optional()}),Zh=qt({_meta:v4e.optional()}),Lpe=Zh.extend({task:JZn.optional()}),hd=qt({method:ke(),params:Zh.loose().optional()}),Jy=qt({_meta:v4e.optional()}),Xy=qt({method:ke(),params:Jy.loose().optional()}),gd=vp({_meta:v4e.optional()}),$pe=gs([ke(),xi().int()]),QZn=qt({jsonrpc:In(Rpe),id:$pe,...hd.shape}).strict(),e7n=qt({jsonrpc:In(Rpe),...Xy.shape}).strict(),cFt=qt({jsonrpc:In(Rpe),id:$pe,result:gd}).strict();(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(DOt||(DOt={}));uFt=qt({jsonrpc:In(Rpe),id:$pe.optional(),error:qt({code:xi().int(),message:ke(),data:ma().optional()})}).strict(),Hdo=gs([QZn,e7n,cFt,uFt]),Wdo=gs([cFt,uFt]),dFt=gd.strict(),t7n=Jy.extend({requestId:$pe.optional(),reason:ke().optional()}),fFt=Xy.extend({method:In("notifications/cancelled"),params:t7n}),n7n=qt({src:ke(),mimeType:ke().optional(),sizes:Oo(ke()).optional(),theme:Im(["light","dark"]).optional()}),V7=qt({icons:Oo(n7n).optional()}),BB=qt({name:ke(),title:ke().optional()}),pFt=BB.extend({...BB.shape,...V7.shape,version:ke(),websiteUrl:ke().optional(),description:ke().optional()}),r7n=Ipe(qt({applyDefaults:Fc().optional()}),hs(ke(),ma())),o7n=Qze(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Ipe(qt({form:r7n.optional(),url:Uc.optional()}),hs(ke(),ma()).optional())),i7n=vp({list:Uc.optional(),cancel:Uc.optional(),requests:vp({sampling:vp({createMessage:Uc.optional()}).optional(),elicitation:vp({create:Uc.optional()}).optional()}).optional()}),s7n=vp({list:Uc.optional(),cancel:Uc.optional(),requests:vp({tools:vp({call:Uc.optional()}).optional()}).optional()}),a7n=qt({experimental:hs(ke(),Uc).optional(),sampling:qt({context:Uc.optional(),tools:Uc.optional()}).optional(),elicitation:o7n.optional(),roots:qt({listChanged:Fc().optional()}).optional(),tasks:i7n.optional(),extensions:hs(ke(),Uc).optional()}),l7n=Zh.extend({protocolVersion:ke(),capabilities:a7n,clientInfo:pFt}),c7n=hd.extend({method:In("initialize"),params:l7n}),u7n=qt({experimental:hs(ke(),Uc).optional(),logging:Uc.optional(),completions:Uc.optional(),prompts:qt({listChanged:Fc().optional()}).optional(),resources:qt({subscribe:Fc().optional(),listChanged:Fc().optional()}).optional(),tools:qt({listChanged:Fc().optional()}).optional(),tasks:s7n.optional(),extensions:hs(ke(),Uc).optional()}),d7n=gd.extend({protocolVersion:ke(),capabilities:u7n,serverInfo:pFt,instructions:ke().optional()}),f7n=Xy.extend({method:In("notifications/initialized"),params:Jy.optional()}),mFt=hd.extend({method:In("ping"),params:Zh.optional()}),p7n=qt({progress:xi(),total:Js(xi()),message:Js(ke())}),m7n=qt({...Jy.shape,...p7n.shape,progressToken:aFt}),hFt=Xy.extend({method:In("notifications/progress"),params:m7n}),h7n=Zh.extend({cursor:lFt.optional()}),q7=hd.extend({params:h7n.optional()}),K7=gd.extend({nextCursor:lFt.optional()}),g7n=Im(["working","input_required","completed","failed","cancelled"]),G7=qt({taskId:ke(),status:g7n,ttl:gs([xi(),Hze()]),createdAt:ke(),lastUpdatedAt:ke(),pollInterval:Js(xi()),statusMessage:Js(ke())}),gFt=gd.extend({task:G7}),y7n=Jy.merge(G7),yFt=Xy.extend({method:In("notifications/tasks/status"),params:y7n}),vFt=hd.extend({method:In("tasks/get"),params:Zh.extend({taskId:ke()})}),wFt=gd.merge(G7),bFt=hd.extend({method:In("tasks/result"),params:Zh.extend({taskId:ke()})}),Vdo=gd.loose(),_Ft=q7.extend({method:In("tasks/list")}),xFt=K7.extend({tasks:Oo(G7)}),SFt=hd.extend({method:In("tasks/cancel"),params:Zh.extend({taskId:ke()})}),qdo=gd.merge(G7),CFt=qt({uri:ke(),mimeType:Js(ke()),_meta:hs(ke(),ma()).optional()}),kFt=CFt.extend({text:ke()}),w4e=ke().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),IFt=CFt.extend({blob:w4e}),Z7=Im(["user","assistant"]),YB=qt({audience:Oo(Z7).optional(),priority:xi().min(0).max(1).optional(),lastModified:wze.datetime({offset:!0}).optional()}),TFt=qt({...BB.shape,...V7.shape,uri:ke(),description:Js(ke()),mimeType:Js(ke()),size:Js(xi()),annotations:YB.optional(),_meta:Js(vp({}))}),v7n=qt({...BB.shape,...V7.shape,uriTemplate:ke(),description:Js(ke()),mimeType:Js(ke()),annotations:YB.optional(),_meta:Js(vp({}))}),w7n=q7.extend({method:In("resources/list")}),b7n=K7.extend({resources:Oo(TFt)}),_7n=q7.extend({method:In("resources/templates/list")}),x7n=K7.extend({resourceTemplates:Oo(v7n)}),b4e=Zh.extend({uri:ke()}),S7n=b4e,C7n=hd.extend({method:In("resources/read"),params:S7n}),k7n=gd.extend({contents:Oo(gs([kFt,IFt]))}),I7n=Xy.extend({method:In("notifications/resources/list_changed"),params:Jy.optional()}),T7n=b4e,P7n=hd.extend({method:In("resources/subscribe"),params:T7n}),A7n=b4e,E7n=hd.extend({method:In("resources/unsubscribe"),params:A7n}),M7n=Jy.extend({uri:ke()}),O7n=Xy.extend({method:In("notifications/resources/updated"),params:M7n}),N7n=qt({name:ke(),description:Js(ke()),required:Js(Fc())}),R7n=qt({...BB.shape,...V7.shape,description:Js(ke()),arguments:Js(Oo(N7n)),_meta:Js(vp({}))}),L7n=q7.extend({method:In("prompts/list")}),$7n=K7.extend({prompts:Oo(R7n)}),D7n=Zh.extend({name:ke(),arguments:hs(ke(),ke()).optional()}),F7n=hd.extend({method:In("prompts/get"),params:D7n}),_4e=qt({type:In("text"),text:ke(),annotations:YB.optional(),_meta:hs(ke(),ma()).optional()}),x4e=qt({type:In("image"),data:w4e,mimeType:ke(),annotations:YB.optional(),_meta:hs(ke(),ma()).optional()}),S4e=qt({type:In("audio"),data:w4e,mimeType:ke(),annotations:YB.optional(),_meta:hs(ke(),ma()).optional()}),U7n=qt({type:In("tool_use"),name:ke(),id:ke(),input:hs(ke(),ma()),_meta:hs(ke(),ma()).optional()}),j7n=qt({type:In("resource"),resource:gs([kFt,IFt]),annotations:YB.optional(),_meta:hs(ke(),ma()).optional()}),B7n=TFt.extend({type:In("resource_link")}),C4e=gs([_4e,x4e,S4e,B7n,j7n]),z7n=qt({role:Z7,content:C4e}),H7n=gd.extend({description:ke().optional(),messages:Oo(z7n)}),W7n=Xy.extend({method:In("notifications/prompts/list_changed"),params:Jy.optional()}),V7n=qt({title:ke().optional(),readOnlyHint:Fc().optional(),destructiveHint:Fc().optional(),idempotentHint:Fc().optional(),openWorldHint:Fc().optional()}),q7n=qt({taskSupport:Im(["required","optional","forbidden"]).optional()}),PFt=qt({...BB.shape,...V7.shape,description:ke().optional(),inputSchema:qt({type:In("object"),properties:hs(ke(),Uc).optional(),required:Oo(ke()).optional()}).catchall(ma()),outputSchema:qt({type:In("object"),properties:hs(ke(),Uc).optional(),required:Oo(ke()).optional()}).catchall(ma()).optional(),annotations:V7n.optional(),execution:q7n.optional(),_meta:hs(ke(),ma()).optional()}),K7n=q7.extend({method:In("tools/list")}),G7n=K7.extend({tools:Oo(PFt)}),AFt=gd.extend({content:Oo(C4e).default([]),structuredContent:hs(ke(),ma()).optional(),isError:Fc().optional()}),Kdo=AFt.or(gd.extend({toolResult:ma()})),Z7n=Lpe.extend({name:ke(),arguments:hs(ke(),ma()).optional()}),Y7n=hd.extend({method:In("tools/call"),params:Z7n}),J7n=Xy.extend({method:In("notifications/tools/list_changed"),params:Jy.optional()}),Gdo=qt({autoRefresh:Fc().default(!0),debounceMs:xi().int().nonnegative().default(300)}),EFt=Im(["debug","info","notice","warning","error","critical","alert","emergency"]),X7n=Zh.extend({level:EFt}),Q7n=hd.extend({method:In("logging/setLevel"),params:X7n}),eYn=Jy.extend({level:EFt,logger:ke().optional(),data:ma()}),tYn=Xy.extend({method:In("notifications/message"),params:eYn}),nYn=qt({name:ke().optional()}),rYn=qt({hints:Oo(nYn).optional(),costPriority:xi().min(0).max(1).optional(),speedPriority:xi().min(0).max(1).optional(),intelligencePriority:xi().min(0).max(1).optional()}),oYn=qt({mode:Im(["auto","required","none"]).optional()}),iYn=qt({type:In("tool_result"),toolUseId:ke().describe("The unique identifier for the corresponding tool call."),content:Oo(C4e).default([]),structuredContent:qt({}).loose().optional(),isError:Fc().optional(),_meta:hs(ke(),ma()).optional()}),sYn=qze("type",[_4e,x4e,S4e]),Kfe=qze("type",[_4e,x4e,S4e,U7n,iYn]),aYn=qt({role:Z7,content:gs([Kfe,Oo(Kfe)]),_meta:hs(ke(),ma()).optional()}),lYn=Lpe.extend({messages:Oo(aYn),modelPreferences:rYn.optional(),systemPrompt:ke().optional(),includeContext:Im(["none","thisServer","allServers"]).optional(),temperature:xi().optional(),maxTokens:xi().int(),stopSequences:Oo(ke()).optional(),metadata:Uc.optional(),tools:Oo(PFt).optional(),toolChoice:oYn.optional()}),cYn=hd.extend({method:In("sampling/createMessage"),params:lYn}),uYn=gd.extend({model:ke(),stopReason:Js(Im(["endTurn","stopSequence","maxTokens"]).or(ke())),role:Z7,content:sYn}),dYn=gd.extend({model:ke(),stopReason:Js(Im(["endTurn","stopSequence","maxTokens","toolUse"]).or(ke())),role:Z7,content:gs([Kfe,Oo(Kfe)])}),fYn=qt({type:In("boolean"),title:ke().optional(),description:ke().optional(),default:Fc().optional()}),pYn=qt({type:In("string"),title:ke().optional(),description:ke().optional(),minLength:xi().optional(),maxLength:xi().optional(),format:Im(["email","uri","date","date-time"]).optional(),default:ke().optional()}),mYn=qt({type:Im(["number","integer"]),title:ke().optional(),description:ke().optional(),minimum:xi().optional(),maximum:xi().optional(),default:xi().optional()}),hYn=qt({type:In("string"),title:ke().optional(),description:ke().optional(),enum:Oo(ke()),default:ke().optional()}),gYn=qt({type:In("string"),title:ke().optional(),description:ke().optional(),oneOf:Oo(qt({const:ke(),title:ke()})),default:ke().optional()}),yYn=qt({type:In("string"),title:ke().optional(),description:ke().optional(),enum:Oo(ke()),enumNames:Oo(ke()).optional(),default:ke().optional()}),vYn=gs([hYn,gYn]),wYn=qt({type:In("array"),title:ke().optional(),description:ke().optional(),minItems:xi().optional(),maxItems:xi().optional(),items:qt({type:In("string"),enum:Oo(ke())}),default:Oo(ke()).optional()}),bYn=qt({type:In("array"),title:ke().optional(),description:ke().optional(),minItems:xi().optional(),maxItems:xi().optional(),items:qt({anyOf:Oo(qt({const:ke(),title:ke()}))}),default:Oo(ke()).optional()}),_Yn=gs([wYn,bYn]),xYn=gs([yYn,vYn,_Yn]),SYn=gs([xYn,fYn,pYn,mYn]),CYn=Lpe.extend({mode:In("form").optional(),message:ke(),requestedSchema:qt({type:In("object"),properties:hs(ke(),SYn),required:Oo(ke()).optional()})}),kYn=Lpe.extend({mode:In("url"),message:ke(),elicitationId:ke(),url:ke().url()}),IYn=gs([CYn,kYn]),TYn=hd.extend({method:In("elicitation/create"),params:IYn}),PYn=Jy.extend({elicitationId:ke()}),AYn=Xy.extend({method:In("notifications/elicitation/complete"),params:PYn}),EYn=gd.extend({action:Im(["accept","decline","cancel"]),content:Qze(t=>t===null?void 0:t,hs(ke(),gs([ke(),xi(),Fc(),Oo(ke())])).optional())}),MYn=qt({type:In("ref/resource"),uri:ke()}),OYn=qt({type:In("ref/prompt"),name:ke()}),NYn=Zh.extend({ref:gs([OYn,MYn]),argument:qt({name:ke(),value:ke()}),context:qt({arguments:hs(ke(),ke()).optional()}).optional()}),RYn=hd.extend({method:In("completion/complete"),params:NYn}),LYn=gd.extend({completion:vp({values:Oo(ke()).max(100),total:Js(xi().int()),hasMore:Js(Fc())})}),$Yn=qt({uri:ke().startsWith("file://"),name:ke().optional(),_meta:hs(ke(),ma()).optional()}),DYn=hd.extend({method:In("roots/list"),params:Zh.optional()}),FYn=gd.extend({roots:Oo($Yn)}),UYn=Xy.extend({method:In("notifications/roots/list_changed"),params:Jy.optional()}),Zdo=gs([mFt,c7n,RYn,Q7n,F7n,L7n,w7n,_7n,C7n,P7n,E7n,Y7n,K7n,vFt,bFt,_Ft,SFt]),Ydo=gs([fFt,hFt,f7n,UYn,yFt]),Jdo=gs([dFt,uYn,dYn,EYn,FYn,wFt,xFt,gFt]),Xdo=gs([mFt,cYn,TYn,DYn,vFt,bFt,_Ft,SFt]),Qdo=gs([fFt,hFt,tYn,O7n,I7n,J7n,W7n,yFt,AYn]),efo=gs([dFt,d7n,LYn,H7n,$7n,b7n,x7n,k7n,AFt,G7n,wFt,xFt,gFt]),tfo=Symbol("Let zodToJsonSchema decide on which parser to use"),nfo=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"),rfo=eBe(INt(),1),ofo=eBe(sHn(),1),ifo=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(FOt||(FOt={}));sfo=Ze(()=>A.object({session_id:A.string(),ws_url:A.string(),work_dir:A.string().optional(),session_key:A.string().optional()})),afo=Promise.resolve();(function(t){t[t.lineFeed=10]="lineFeed",t[t.carriageReturn=13]="carriageReturn",t[t.space=32]="space",t[t._0=48]="_0",t[t._1=49]="_1",t[t._2=50]="_2",t[t._3=51]="_3",t[t._4=52]="_4",t[t._5=53]="_5",t[t._6=54]="_6",t[t._7=55]="_7",t[t._8=56]="_8",t[t._9=57]="_9",t[t.a=97]="a",t[t.b=98]="b",t[t.c=99]="c",t[t.d=100]="d",t[t.e=101]="e",t[t.f=102]="f",t[t.g=103]="g",t[t.h=104]="h",t[t.i=105]="i",t[t.j=106]="j",t[t.k=107]="k",t[t.l=108]="l",t[t.m=109]="m",t[t.n=110]="n",t[t.o=111]="o",t[t.p=112]="p",t[t.q=113]="q",t[t.r=114]="r",t[t.s=115]="s",t[t.t=116]="t",t[t.u=117]="u",t[t.v=118]="v",t[t.w=119]="w",t[t.x=120]="x",t[t.y=121]="y",t[t.z=122]="z",t[t.A=65]="A",t[t.B=66]="B",t[t.C=67]="C",t[t.D=68]="D",t[t.E=69]="E",t[t.F=70]="F",t[t.G=71]="G",t[t.H=72]="H",t[t.I=73]="I",t[t.J=74]="J",t[t.K=75]="K",t[t.L=76]="L",t[t.M=77]="M",t[t.N=78]="N",t[t.O=79]="O",t[t.P=80]="P",t[t.Q=81]="Q",t[t.R=82]="R",t[t.S=83]="S",t[t.T=84]="T",t[t.U=85]="U",t[t.V=86]="V",t[t.W=87]="W",t[t.X=88]="X",t[t.Y=89]="Y",t[t.Z=90]="Z",t[t.asterisk=42]="asterisk",t[t.backslash=92]="backslash",t[t.closeBrace=125]="closeBrace",t[t.closeBracket=93]="closeBracket",t[t.colon=58]="colon",t[t.comma=44]="comma",t[t.dot=46]="dot",t[t.doubleQuote=34]="doubleQuote",t[t.minus=45]="minus",t[t.openBrace=123]="openBrace",t[t.openBracket=91]="openBracket",t[t.plus=43]="plus",t[t.slash=47]="slash",t[t.formFeed=12]="formFeed",t[t.tab=9]="tab"})(UOt||(UOt={}));lfo=Array(20).fill(0).map((t,e)=>" ".repeat(e)),cfo={" ":{"\n":Array(200).fill(0).map((t,e)=>`
`+" ".repeat(e)),"\r":Array(200).fill(0).map((t,e)=>"\r"+" ".repeat(e)),"\r\n":Array(200).fill(0).map((t,e)=>`\r
`+" ".repeat(e))}," ":{"\n":Array(200).fill(0).map((t,e)=>`
`+" ".repeat(e)),"\r":Array(200).fill(0).map((t,e)=>"\r"+" ".repeat(e)),"\r\n":Array(200).fill(0).map((t,e)=>`\r
`+" ".repeat(e))}};(function(t){t.DEFAULT={allowTrailingComma:!1}})(jOt||(jOt={}));(function(t){t[t.None=0]="None",t[t.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",t[t.UnexpectedEndOfString=2]="UnexpectedEndOfString",t[t.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",t[t.InvalidUnicode=4]="InvalidUnicode",t[t.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",t[t.InvalidCharacter=6]="InvalidCharacter"})(BOt||(BOt={}));(function(t){t[t.OpenBraceToken=1]="OpenBraceToken",t[t.CloseBraceToken=2]="CloseBraceToken",t[t.OpenBracketToken=3]="OpenBracketToken",t[t.CloseBracketToken=4]="CloseBracketToken",t[t.CommaToken=5]="CommaToken",t[t.ColonToken=6]="ColonToken",t[t.NullKeyword=7]="NullKeyword",t[t.TrueKeyword=8]="TrueKeyword",t[t.FalseKeyword=9]="FalseKeyword",t[t.StringLiteral=10]="StringLiteral",t[t.NumericLiteral=11]="NumericLiteral",t[t.LineCommentTrivia=12]="LineCommentTrivia",t[t.BlockCommentTrivia=13]="BlockCommentTrivia",t[t.LineBreakTrivia=14]="LineBreakTrivia",t[t.Trivia=15]="Trivia",t[t.Unknown=16]="Unknown",t[t.EOF=17]="EOF"})(zOt||(zOt={}));(function(t){t[t.InvalidSymbol=1]="InvalidSymbol",t[t.InvalidNumberFormat=2]="InvalidNumberFormat",t[t.PropertyNameExpected=3]="PropertyNameExpected",t[t.ValueExpected=4]="ValueExpected",t[t.ColonExpected=5]="ColonExpected",t[t.CommaExpected=6]="CommaExpected",t[t.CloseBraceExpected=7]="CloseBraceExpected",t[t.CloseBracketExpected=8]="CloseBracketExpected",t[t.EndOfFileExpected=9]="EndOfFileExpected",t[t.InvalidCommentToken=10]="InvalidCommentToken",t[t.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",t[t.UnexpectedEndOfString=12]="UnexpectedEndOfString",t[t.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",t[t.InvalidUnicode=14]="InvalidUnicode",t[t.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",t[t.InvalidCharacter=16]="InvalidCharacter"})(HOt||(HOt={}));WP=k4e.default.homedir(),I4e=k4e.default.tmpdir(),{env:pB}=Gfe.default,WYn=t=>{let e=pa.default.join(WP,"Library");return{data:pa.default.join(e,"Application Support",t),config:pa.default.join(e,"Preferences",t),cache:pa.default.join(e,"Caches",t),log:pa.default.join(e,"Logs",t),temp:pa.default.join(I4e,t)}},VYn=t=>{let e=pB.APPDATA||pa.default.join(WP,"AppData","Roaming"),n=pB.LOCALAPPDATA||pa.default.join(WP,"AppData","Local");return{data:pa.default.join(n,t,"Data"),config:pa.default.join(e,t,"Config"),cache:pa.default.join(n,t,"Cache"),log:pa.default.join(n,t,"Log"),temp:pa.default.join(I4e,t)}},qYn=t=>{let e=pa.default.basename(WP);return{data:pa.default.join(pB.XDG_DATA_HOME||pa.default.join(WP,".local","share"),t),config:pa.default.join(pB.XDG_CONFIG_HOME||pa.default.join(WP,".config"),t),cache:pa.default.join(pB.XDG_CACHE_HOME||pa.default.join(WP,".cache"),t),log:pa.default.join(pB.XDG_STATE_HOME||pa.default.join(WP,".local","state"),t),temp:pa.default.join(I4e,e,t)}};ufo=KYn("claude-cli");YYn=100,ZUe=[];XYn=[],WOt=null,dfo=Za(()=>process.argv.includes("--hard-fail"));aB=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,OFt=new Set,Bje=typeof process=="object"&&process?process:{},NFt=(t,e,n,r)=>{typeof Bje.emitWarning=="function"?Bje.emitWarning(t,e,n,r):console.error(`[${n}] ${e}: ${t}`)},Zfe=globalThis.AbortController,VOt=globalThis.AbortSignal;if(typeof Zfe>"u"){VOt=class{constructor(){M(this,"onabort");M(this,"_onabort",[]);M(this,"reason");M(this,"aborted",!1)}addEventListener(n,r){this._onabort.push(r)}},Zfe=class{constructor(){M(this,"signal",new VOt);e()}abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let r of this.signal._onabort)r(n);this.signal.onabort?.(n)}}};let t=Bje.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,NFt("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}QYn=t=>!OFt.has(t),ffo=Symbol("type"),FP=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),RFt=t=>FP(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?gB:null:null,gB=class extends Array{constructor(e){super(e),this.fill(0)}},SR=class SR{constructor(e,n){M(this,"heap");M(this,"length");if(!re(SR,yB))throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new n(e),this.length=0}static create(e){let n=RFt(e);if(!n)return[];Et(SR,yB,!0);let r=new SR(e,n);return Et(SR,yB,!1),r}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}};yB=new WeakMap,Rt(SR,yB,!1);zje=SR,N4e=class N4e{constructor(e){Rt(this,Nt);Rt(this,Gw);Rt(this,zh);Rt(this,Zw);Rt(this,Yw);Rt(this,vB);Rt(this,wB);M(this,"ttl");M(this,"ttlResolution");M(this,"ttlAutopurge");M(this,"updateAgeOnGet");M(this,"updateAgeOnHas");M(this,"allowStale");M(this,"noDisposeOnSet");M(this,"noUpdateTTL");M(this,"maxEntrySize");M(this,"sizeCalculation");M(this,"noDeleteOnFetchRejection");M(this,"noDeleteOnStaleGet");M(this,"allowStaleOnFetchAbort");M(this,"allowStaleOnFetchRejection");M(this,"ignoreFetchAbort");Rt(this,Dc);Rt(this,Jw);Rt(this,Vl);Rt(this,Zs);Rt(this,Rr);Rt(this,hp);Rt(this,Hh);Rt(this,af);Rt(this,Au);Rt(this,Xw);Rt(this,Eu);Rt(this,Qw);Rt(this,eb);Rt(this,Wh);Rt(this,tb);Rt(this,qP);Rt(this,gp);Rt(this,kR,()=>{});Rt(this,Ak,()=>{});Rt(this,D7,()=>{});Rt(this,Vh,()=>!1);Rt(this,IR,e=>{});Rt(this,bB,(e,n,r)=>{});Rt(this,F7,(e,n,r,o)=>{if(r||o)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0});M(this,aNt,"LRUCache");let{max:n=0,ttl:r,ttlResolution:o=1,ttlAutopurge:i,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:l,dispose:c,disposeAfter:u,noDisposeOnSet:d,noUpdateTTL:f,maxSize:p=0,maxEntrySize:m=0,sizeCalculation:h,fetchMethod:g,memoMethod:v,noDeleteOnFetchRejection:y,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:_,allowStaleOnFetchAbort:S,ignoreFetchAbort:I}=e;if(n!==0&&!FP(n))throw TypeError("max option must be a nonnegative integer");let C=n?RFt(n):Array;if(!C)throw Error("invalid max value: "+n);if(Et(this,Gw,n),Et(this,zh,p),this.maxEntrySize=m||re(this,zh),this.sizeCalculation=h,this.sizeCalculation){if(!re(this,zh)&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw TypeError("sizeCalculation set to non-function")}if(v!==void 0&&typeof v!="function")throw TypeError("memoMethod must be a function if defined");if(Et(this,wB,v),g!==void 0&&typeof g!="function")throw TypeError("fetchMethod must be a function if specified");if(Et(this,vB,g),Et(this,qP,!!g),Et(this,Vl,new Map),Et(this,Zs,Array(n).fill(void 0)),Et(this,Rr,Array(n).fill(void 0)),Et(this,hp,new C(n)),Et(this,Hh,new C(n)),Et(this,af,0),Et(this,Au,0),Et(this,Xw,zje.create(n)),Et(this,Dc,0),Et(this,Jw,0),typeof c=="function"&&Et(this,Zw,c),typeof u=="function"?(Et(this,Yw,u),Et(this,Eu,[])):(Et(this,Yw,void 0),Et(this,Eu,void 0)),Et(this,tb,!!re(this,Zw)),Et(this,gp,!!re(this,Yw)),this.noDisposeOnSet=!!d,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!y,this.allowStaleOnFetchRejection=!!_,this.allowStaleOnFetchAbort=!!S,this.ignoreFetchAbort=!!I,this.maxEntrySize!==0){if(re(this,zh)!==0&&!FP(re(this,zh)))throw TypeError("maxSize must be a positive integer if specified");if(!FP(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");Je(this,Nt,LFt).call(this)}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=FP(o)||o===0?o:1,this.ttlAutopurge=!!i,this.ttl=r||0,this.ttl){if(!FP(this.ttl))throw TypeError("ttl must be a positive integer if specified");Je(this,Nt,Wje).call(this)}if(re(this,Gw)===0&&this.ttl===0&&re(this,zh)===0)throw TypeError("At least one of max, maxSize, or ttl is required");!this.ttlAutopurge&&!re(this,Gw)&&!re(this,zh)&&QYn("LRU_CACHE_UNBOUNDED")&&(OFt.add("LRU_CACHE_UNBOUNDED"),NFt("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",N4e))}static unsafeExposeInternals(e){return{starts:re(e,eb),ttls:re(e,Wh),sizes:re(e,Qw),keyMap:re(e,Vl),keyList:re(e,Zs),valList:re(e,Rr),next:re(e,hp),prev:re(e,Hh),get head(){return re(e,af)},get tail(){return re(e,Au)},free:re(e,Xw),isBackgroundFetch:n=>{var r;return Je(r=e,Nt,Gs).call(r,n)},backgroundFetch:(n,r,o,i)=>{var s;return Je(s=e,Nt,Kde).call(s,n,r,o,i)},moveToTail:n=>{var r;return Je(r=e,Nt,a7).call(r,n)},indexes:n=>{var r;return Je(r=e,Nt,UP).call(r,n)},rindexes:n=>{var r;return Je(r=e,Nt,jP).call(r,n)},isStale:n=>{var r;return re(r=e,Vh).call(r,n)}}}get max(){return re(this,Gw)}get maxSize(){return re(this,zh)}get calculatedSize(){return re(this,Jw)}get size(){return re(this,Dc)}get fetchMethod(){return re(this,vB)}get memoMethod(){return re(this,wB)}get dispose(){return re(this,Zw)}get disposeAfter(){return re(this,Yw)}getRemainingTTL(e){return re(this,Vl).has(e)?1/0:0}*entries(){for(let e of Je(this,Nt,UP).call(this))re(this,Rr)[e]!==void 0&&re(this,Zs)[e]!==void 0&&!Je(this,Nt,Gs).call(this,re(this,Rr)[e])&&(yield[re(this,Zs)[e],re(this,Rr)[e]])}*rentries(){for(let e of Je(this,Nt,jP).call(this))re(this,Rr)[e]!==void 0&&re(this,Zs)[e]!==void 0&&!Je(this,Nt,Gs).call(this,re(this,Rr)[e])&&(yield[re(this,Zs)[e],re(this,Rr)[e]])}*keys(){for(let e of Je(this,Nt,UP).call(this)){let n=re(this,Zs)[e];n!==void 0&&!Je(this,Nt,Gs).call(this,re(this,Rr)[e])&&(yield n)}}*rkeys(){for(let e of Je(this,Nt,jP).call(this)){let n=re(this,Zs)[e];n!==void 0&&!Je(this,Nt,Gs).call(this,re(this,Rr)[e])&&(yield n)}}*values(){for(let e of Je(this,Nt,UP).call(this))re(this,Rr)[e]!==void 0&&!Je(this,Nt,Gs).call(this,re(this,Rr)[e])&&(yield re(this,Rr)[e])}*rvalues(){for(let e of Je(this,Nt,jP).call(this))re(this,Rr)[e]!==void 0&&!Je(this,Nt,Gs).call(this,re(this,Rr)[e])&&(yield re(this,Rr)[e])}[(lNt=Symbol.iterator,aNt=Symbol.toStringTag,lNt)](){return this.entries()}find(e,n={}){for(let r of Je(this,Nt,UP).call(this)){let o=re(this,Rr)[r],i=Je(this,Nt,Gs).call(this,o)?o.__staleWhileFetching:o;if(i!==void 0&&e(i,re(this,Zs)[r],this))return this.get(re(this,Zs)[r],n)}}forEach(e,n=this){for(let r of Je(this,Nt,UP).call(this)){let o=re(this,Rr)[r],i=Je(this,Nt,Gs).call(this,o)?o.__staleWhileFetching:o;i!==void 0&&e.call(n,i,re(this,Zs)[r],this)}}rforEach(e,n=this){for(let r of Je(this,Nt,jP).call(this)){let o=re(this,Rr)[r],i=Je(this,Nt,Gs).call(this,o)?o.__staleWhileFetching:o;i!==void 0&&e.call(n,i,re(this,Zs)[r],this)}}purgeStale(){let e=!1;for(let n of Je(this,Nt,jP).call(this,{allowStale:!0}))re(this,Vh).call(this,n)&&(Je(this,Nt,BP).call(this,re(this,Zs)[n],"expire"),e=!0);return e}info(e){let n=re(this,Vl).get(e);if(n===void 0)return;let r=re(this,Rr)[n],o=Je(this,Nt,Gs).call(this,r)?r.__staleWhileFetching:r;if(o===void 0)return;let i={value:o};if(re(this,Wh)&&re(this,eb)){let s=re(this,Wh)[n],a=re(this,eb)[n];if(s&&a){let l=s-(aB.now()-a);i.ttl=l,i.start=Date.now()}}return re(this,Qw)&&(i.size=re(this,Qw)[n]),i}dump(){let e=[];for(let n of Je(this,Nt,UP).call(this,{allowStale:!0})){let r=re(this,Zs)[n],o=re(this,Rr)[n],i=Je(this,Nt,Gs).call(this,o)?o.__staleWhileFetching:o;if(i===void 0||r===void 0)continue;let s={value:i};if(re(this,Wh)&&re(this,eb)){s.ttl=re(this,Wh)[n];let a=aB.now()-re(this,eb)[n];s.start=Math.floor(Date.now()-a)}re(this,Qw)&&(s.size=re(this,Qw)[n]),e.unshift([r,s])}return e}load(e){this.clear();for(let[n,r]of e){if(r.start){let o=Date.now()-r.start;r.start=aB.now()-o}this.set(n,r.value,r)}}set(e,n,r={}){var f,p,m;if(n===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:i,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=r,{noUpdateTTL:c=this.noUpdateTTL}=r,u=re(this,F7).call(this,e,n,r.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),Je(this,Nt,BP).call(this,e,"set"),this;let d=re(this,Dc)===0?void 0:re(this,Vl).get(e);if(d===void 0)d=re(this,Dc)===0?re(this,Au):re(this,Xw).length!==0?re(this,Xw).pop():re(this,Dc)===re(this,Gw)?Je(this,Nt,qde).call(this,!1):re(this,Dc),re(this,Zs)[d]=e,re(this,Rr)[d]=n,re(this,Vl).set(e,d),re(this,hp)[re(this,Au)]=d,re(this,Hh)[d]=re(this,Au),Et(this,Au,d),Hoe(this,Dc)._++,re(this,bB).call(this,d,u,l),l&&(l.set="add"),c=!1;else{Je(this,Nt,a7).call(this,d);let h=re(this,Rr)[d];if(n!==h){if(re(this,qP)&&Je(this,Nt,Gs).call(this,h)){h.__abortController.abort(Error("replaced"));let{__staleWhileFetching:g}=h;g!==void 0&&!s&&(re(this,tb)&&((f=re(this,Zw))==null||f.call(this,g,e,"set")),re(this,gp)&&re(this,Eu)?.push([g,e,"set"]))}else s||(re(this,tb)&&((p=re(this,Zw))==null||p.call(this,h,e,"set")),re(this,gp)&&re(this,Eu)?.push([h,e,"set"]));if(re(this,IR).call(this,d),re(this,bB).call(this,d,u,l),re(this,Rr)[d]=n,l){l.set="replace";let g=h&&Je(this,Nt,Gs).call(this,h)?h.__staleWhileFetching:h;g!==void 0&&(l.oldValue=g)}}else l&&(l.set="update")}if(o!==0&&!re(this,Wh)&&Je(this,Nt,Wje).call(this),re(this,Wh)&&(c||re(this,D7).call(this,d,o,i),l&&re(this,Ak).call(this,l,d)),!s&&re(this,gp)&&re(this,Eu)){let h=re(this,Eu),g;for(;g=h?.shift();)(m=re(this,Yw))==null||m.call(this,...g)}return this}pop(){var e;try{for(;re(this,Dc);){let n=re(this,Rr)[re(this,af)];if(Je(this,Nt,qde).call(this,!0),Je(this,Nt,Gs).call(this,n)){if(n.__staleWhileFetching)return n.__staleWhileFetching}else if(n!==void 0)return n}}finally{if(re(this,gp)&&re(this,Eu)){let n=re(this,Eu),r;for(;r=n?.shift();)(e=re(this,Yw))==null||e.call(this,...r)}}}has(e,n={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:o}=n,i=re(this,Vl).get(e);if(i!==void 0){let s=re(this,Rr)[i];if(Je(this,Nt,Gs).call(this,s)&&s.__staleWhileFetching===void 0)return!1;if(re(this,Vh).call(this,i))o&&(o.has="stale",re(this,Ak).call(this,o,i));else return r&&re(this,kR).call(this,i),o&&(o.has="hit",re(this,Ak).call(this,o,i)),!0}else o&&(o.has="miss");return!1}peek(e,n={}){let{allowStale:r=this.allowStale}=n,o=re(this,Vl).get(e);if(o===void 0||!r&&re(this,Vh).call(this,o))return;let i=re(this,Rr)[o];return Je(this,Nt,Gs).call(this,i)?i.__staleWhileFetching:i}async fetch(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:f=this.allowStaleOnFetchRejection,ignoreFetchAbort:p=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:h,forceRefresh:g=!1,status:v,signal:y}=n;if(!re(this,qP))return v&&(v.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:i,status:v});let w={allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:i,ttl:s,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:m,ignoreFetchAbort:p,status:v,signal:y},_=re(this,Vl).get(e);if(_===void 0){v&&(v.fetch="miss");let S=Je(this,Nt,Kde).call(this,e,_,w,h);return S.__returned=S}else{let S=re(this,Rr)[_];if(Je(this,Nt,Gs).call(this,S)){let T=r&&S.__staleWhileFetching!==void 0;return v&&(v.fetch="inflight",T&&(v.returnedStale=!0)),T?S.__staleWhileFetching:S.__returned=S}let I=re(this,Vh).call(this,_);if(!g&&!I)return v&&(v.fetch="hit"),Je(this,Nt,a7).call(this,_),o&&re(this,kR).call(this,_),v&&re(this,Ak).call(this,v,_),S;let C=Je(this,Nt,Kde).call(this,e,_,w,h),k=C.__staleWhileFetching!==void 0&&r;return v&&(v.fetch=I?"stale":"refresh",k&&I&&(v.returnedStale=!0)),k?C.__staleWhileFetching:C.__returned=C}}async forceFetch(e,n={}){let r=await this.fetch(e,n);if(r===void 0)throw Error("fetch() returned undefined");return r}memo(e,n={}){let r=re(this,wB);if(!r)throw Error("no memoMethod provided to constructor");let{context:o,forceRefresh:i,...s}=n,a=this.get(e,s);if(!i&&a!==void 0)return a;let l=r(e,a,{options:s,context:o});return this.set(e,l,s),l}get(e,n={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:s}=n,a=re(this,Vl).get(e);if(a!==void 0){let l=re(this,Rr)[a],c=Je(this,Nt,Gs).call(this,l);return s&&re(this,Ak).call(this,s,a),re(this,Vh).call(this,a)?(s&&(s.get="stale"),c?(s&&r&&l.__staleWhileFetching!==void 0&&(s.returnedStale=!0),r?l.__staleWhileFetching:void 0):(i||Je(this,Nt,BP).call(this,e,"expire"),s&&r&&(s.returnedStale=!0),r?l:void 0)):(s&&(s.get="hit"),c?l.__staleWhileFetching:(Je(this,Nt,a7).call(this,a),o&&re(this,kR).call(this,a),l))}else s&&(s.get="miss")}delete(e){return Je(this,Nt,BP).call(this,e,"delete")}clear(){return Je(this,Nt,Kje).call(this,"delete")}};Gw=new WeakMap,zh=new WeakMap,Zw=new WeakMap,Yw=new WeakMap,vB=new WeakMap,wB=new WeakMap,Dc=new WeakMap,Jw=new WeakMap,Vl=new WeakMap,Zs=new WeakMap,Rr=new WeakMap,hp=new WeakMap,Hh=new WeakMap,af=new WeakMap,Au=new WeakMap,Xw=new WeakMap,Eu=new WeakMap,Qw=new WeakMap,eb=new WeakMap,Wh=new WeakMap,tb=new WeakMap,qP=new WeakMap,gp=new WeakMap,Nt=new WeakSet,Wje=function(){let e=new gB(re(this,Gw)),n=new gB(re(this,Gw));Et(this,Wh,e),Et(this,eb,n),Et(this,D7,(i,s,a=aB.now())=>{if(n[i]=s!==0?a:0,e[i]=s,s!==0&&this.ttlAutopurge){let l=setTimeout(()=>{re(this,Vh).call(this,i)&&Je(this,Nt,BP).call(this,re(this,Zs)[i],"expire")},s+1);l.unref&&l.unref()}}),Et(this,kR,i=>{n[i]=e[i]!==0?aB.now():0}),Et(this,Ak,(i,s)=>{if(e[s]){let a=e[s],l=n[s];if(!a||!l)return;i.ttl=a,i.start=l,i.now=r||o();let c=i.now-l;i.remainingTTL=a-c}});let r=0,o=()=>{let i=aB.now();if(this.ttlResolution>0){r=i;let s=setTimeout(()=>r=0,this.ttlResolution);s.unref&&s.unref()}return i};this.getRemainingTTL=i=>{let s=re(this,Vl).get(i);if(s===void 0)return 0;let a=e[s],l=n[s];if(!a||!l)return 1/0;let c=(r||o())-l;return a-c},Et(this,Vh,i=>{let s=n[i],a=e[i];return!!a&&!!s&&(r||o())-s>a})},kR=new WeakMap,Ak=new WeakMap,D7=new WeakMap,Vh=new WeakMap,LFt=function(){let e=new gB(re(this,Gw));Et(this,Jw,0),Et(this,Qw,e),Et(this,IR,n=>{Et(this,Jw,re(this,Jw)-e[n]),e[n]=0}),Et(this,F7,(n,r,o,i)=>{if(Je(this,Nt,Gs).call(this,r))return 0;if(!FP(o))if(i){if(typeof i!="function")throw TypeError("sizeCalculation must be a function");if(o=i(r,n),!FP(o))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o}),Et(this,bB,(n,r,o)=>{if(e[n]=r,re(this,zh)){let i=re(this,zh)-e[n];for(;re(this,Jw)>i;)Je(this,Nt,qde).call(this,!0)}Et(this,Jw,re(this,Jw)+e[n]),o&&(o.entrySize=r,o.totalCalculatedSize=re(this,Jw))})},IR=new WeakMap,bB=new WeakMap,F7=new WeakMap,UP=function*({allowStale:e=this.allowStale}={}){if(re(this,Dc))for(let n=re(this,Au);!(!Je(this,Nt,Vje).call(this,n)||((e||!re(this,Vh).call(this,n))&&(yield n),n===re(this,af)));)n=re(this,Hh)[n]},jP=function*({allowStale:e=this.allowStale}={}){if(re(this,Dc))for(let n=re(this,af);!(!Je(this,Nt,Vje).call(this,n)||((e||!re(this,Vh).call(this,n))&&(yield n),n===re(this,Au)));)n=re(this,hp)[n]},Vje=function(e){return e!==void 0&&re(this,Vl).get(re(this,Zs)[e])===e},qde=function(e){var i;let n=re(this,af),r=re(this,Zs)[n],o=re(this,Rr)[n];return re(this,qP)&&Je(this,Nt,Gs).call(this,o)?o.__abortController.abort(Error("evicted")):(re(this,tb)||re(this,gp))&&(re(this,tb)&&((i=re(this,Zw))==null||i.call(this,o,r,"evict")),re(this,gp)&&re(this,Eu)?.push([o,r,"evict"])),re(this,IR).call(this,n),e&&(re(this,Zs)[n]=void 0,re(this,Rr)[n]=void 0,re(this,Xw).push(n)),re(this,Dc)===1?(Et(this,af,Et(this,Au,0)),re(this,Xw).length=0):Et(this,af,re(this,hp)[n]),re(this,Vl).delete(r),Hoe(this,Dc)._--,n},Kde=function(e,n,r,o){let i=n===void 0?void 0:re(this,Rr)[n];if(Je(this,Nt,Gs).call(this,i))return i;let s=new Zfe,{signal:a}=r;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let l={signal:s.signal,options:r,context:o},c=(h,g=!1)=>{let{aborted:v}=s.signal,y=r.ignoreFetchAbort&&h!==void 0;if(r.status&&(v&&!g?(r.status.fetchAborted=!0,r.status.fetchError=s.signal.reason,y&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),v&&!y&&!g)return d(s.signal.reason);let w=p;return re(this,Rr)[n]===p&&(h===void 0?w.__staleWhileFetching?re(this,Rr)[n]=w.__staleWhileFetching:Je(this,Nt,BP).call(this,e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,h,l.options))),h},u=h=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=h),d(h)),d=h=>{let{aborted:g}=s.signal,v=g&&r.allowStaleOnFetchAbort,y=v||r.allowStaleOnFetchRejection,w=y||r.noDeleteOnFetchRejection,_=p;if(re(this,Rr)[n]===p&&(!w||_.__staleWhileFetching===void 0?Je(this,Nt,BP).call(this,e,"fetch"):v||(re(this,Rr)[n]=_.__staleWhileFetching)),y)return r.status&&_.__staleWhileFetching!==void 0&&(r.status.returnedStale=!0),_.__staleWhileFetching;if(_.__returned===_)throw h},f=(h,g)=>{var y;let v=(y=re(this,vB))==null?void 0:y.call(this,e,i,l);v&&v instanceof Promise&&v.then(w=>h(w===void 0?void 0:w),g),s.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(h(void 0),r.allowStaleOnFetchAbort&&(h=w=>c(w,!0)))})};r.status&&(r.status.fetchDispatched=!0);let p=new Promise(f).then(c,u),m=Object.assign(p,{__abortController:s,__staleWhileFetching:i,__returned:void 0});return n===void 0?(this.set(e,m,{...l.options,status:void 0}),n=re(this,Vl).get(e)):re(this,Rr)[n]=m,m},Gs=function(e){if(!re(this,qP))return!1;let n=e;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof Zfe},qje=function(e,n){re(this,Hh)[n]=e,re(this,hp)[e]=n},a7=function(e){e!==re(this,Au)&&(e===re(this,af)?Et(this,af,re(this,hp)[e]):Je(this,Nt,qje).call(this,re(this,Hh)[e],re(this,hp)[e]),Je(this,Nt,qje).call(this,re(this,Au),e),Et(this,Au,e))},BP=function(e,n){var o,i;let r=!1;if(re(this,Dc)!==0){let s=re(this,Vl).get(e);if(s!==void 0)if(r=!0,re(this,Dc)===1)Je(this,Nt,Kje).call(this,n);else{re(this,IR).call(this,s);let a=re(this,Rr)[s];if(Je(this,Nt,Gs).call(this,a)?a.__abortController.abort(Error("deleted")):(re(this,tb)||re(this,gp))&&(re(this,tb)&&((o=re(this,Zw))==null||o.call(this,a,e,n)),re(this,gp)&&re(this,Eu)?.push([a,e,n])),re(this,Vl).delete(e),re(this,Zs)[s]=void 0,re(this,Rr)[s]=void 0,s===re(this,Au))Et(this,Au,re(this,Hh)[s]);else if(s===re(this,af))Et(this,af,re(this,hp)[s]);else{let l=re(this,Hh)[s];re(this,hp)[l]=re(this,hp)[s];let c=re(this,hp)[s];re(this,Hh)[c]=re(this,Hh)[s]}Hoe(this,Dc)._--,re(this,Xw).push(s)}}if(re(this,gp)&&re(this,Eu)?.length){let s=re(this,Eu),a;for(;a=s?.shift();)(i=re(this,Yw))==null||i.call(this,...a)}return r},Kje=function(e){var n,r;for(let o of Je(this,Nt,jP).call(this,{allowStale:!0})){let i=re(this,Rr)[o];if(Je(this,Nt,Gs).call(this,i))i.__abortController.abort(Error("deleted"));else{let s=re(this,Zs)[o];re(this,tb)&&((n=re(this,Zw))==null||n.call(this,i,s,e)),re(this,gp)&&re(this,Eu)?.push([i,s,e])}}if(re(this,Vl).clear(),re(this,Rr).fill(void 0),re(this,Zs).fill(void 0),re(this,Wh)&&re(this,eb)&&(re(this,Wh).fill(0),re(this,eb).fill(0)),re(this,Qw)&&re(this,Qw).fill(0),Et(this,af,0),Et(this,Au,0),re(this,Xw).length=0,Et(this,Jw,0),Et(this,Dc,0),re(this,gp)&&re(this,Eu)){let o=re(this,Eu),i;for(;i=o?.shift();)(r=re(this,Yw))==null||r.call(this,...i)}};Hje=N4e;tJn=8192;qOt=eJn($Ft,t=>t,50),pfo=Object.assign(function(t,e=!0){if(!t)return null;let n=t.length>tJn?$Ft(t,e):qOt(t,e);return n.ok?n.value:null},{cache:qOt.cache}),UFt=Za(()=>{try{return Vde().readFileSync("/proc/version",{encoding:"utf8"}).toLowerCase()}catch{return}}),BFt=Za(()=>{try{if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";if(process.platform==="linux"){if(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP)return"wsl";let t=jFt??UFt();return t!==void 0&&(t.includes("microsoft")||t.includes("wsl"))?"wsl":"linux"}return"unknown"}catch(t){return MFt(t),"unknown"}}),hfo=Za(()=>{if(process.platform!=="linux")return;let t=jFt??UFt();if(t===void 0)return;let e=t.match(/wsl(\d+)/);if(e&&e[1])return e[1];if(t.includes("microsoft"))return"1"}),gfo=Za(async()=>{if(process.platform!=="linux")return;let t={linuxKernel:(0,T4e.release)()};try{let e=await(0,FFt.readFile)("/etc/os-release","utf8");for(let n of e.split(`
`)){let r=n.match(/^(ID|VERSION_ID)=(.*)$/);if(r&&r[1]&&r[2]){let o=r[2].replace(/^"|"$/g,"");r[1]==="ID"?t.linuxDistroId=o:t.linuxDistroVersion=o}}}catch{}return t}),yfo=Za(()=>{if(process.platform!=="darwin")return;let t=(0,T4e.release)().match(/^(\d+)\./);if(!(!t||!t[1]))return parseInt(t[1],10)-9}),nJn=Za(function(){switch(BFt()){case"macos":return"/Library/Application Support/ClaudeCode";case"windows":return"C:\\Program Files\\ClaudeCode";default:return"/etc/claude-code"}}),vfo=Za(function(){return(0,DFt.join)(nJn(),"managed-settings.d")});Gje=rJn;iJn=oJn,sJn=iJn(),aJn=sJn;cJn=lJn,uJn="[object Object]",dJn=Function.prototype,fJn=Object.prototype,zFt=dJn.toString,pJn=fJn.hasOwnProperty,mJn=zFt.call(Object);gJn=hJn;Zje=yJn;wJn=vJn;_Jn=bJn;xJn=HFt;CJn=SJn,KOt=Math.max;WFt=kJn;TJn=IJn,PJn=jfe?function(t,e){return jfe(t,"toString",{configurable:!0,enumerable:!1,value:TJn(e),writable:!0})}:RDt,AJn=PJn,EJn=800,MJn=16,OJn=Date.now;RJn=NJn,LJn=RJn(AJn),VFt=LJn;DJn=$Jn;UJn=FJn;BJn=jJn,wfo=BJn(function(t,e,n,r){xJn(t,e,n,r)});HJn=zJn;VJn=WJn;KJn=qJn,GOt=vx?vx.isConcatSpreadable:void 0;ZJn=GJn;YJn=qFt;XJn=JJn;eXn=QJn,bfo=eXn(function(t,e){return t==null?{}:KJn(t,e)}),KFt=["CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_ANTHROPIC_AWS","CLAUDE_CODE_USE_MANTLE","CLAUDE_CODE_USE_GATEWAY","ANTHROPIC_FOUNDRY_RESOURCE","ANTHROPIC_VERTEX_PROJECT_ID","ANTHROPIC_AWS_WORKSPACE_ID","CLOUD_ML_REGION"],GFt=["ANTHROPIC_BASE_URL","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL","ANTHROPIC_BEDROCK_BASE_URL","ANTHROPIC_VERTEX_BASE_URL","ANTHROPIC_FOUNDRY_BASE_URL","ANTHROPIC_AWS_BASE_URL","ANTHROPIC_BEDROCK_MANTLE_BASE_URL","CLAUDE_CODE_ARTIFACTS_API_BASE_URL"],ZFt=["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","AWS_BEARER_TOKEN_BEDROCK","ANTHROPIC_FOUNDRY_API_KEY","ANTHROPIC_FOUNDRY_AUTH_TOKEN","ANTHROPIC_AWS_API_KEY","ANTHROPIC_BEDROCK_MANTLE_API_KEY"],nXn=["CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH","CLAUDE_CODE_SKIP_MANTLE_AUTH"],rXn=["ANTHROPIC_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_FABLE_MODEL_NAME","ANTHROPIC_DEFAULT_FABLE_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_HAIKU_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME","ANTHROPIC_DEFAULT_HAIKU_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_OPUS_MODEL_NAME","ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_SONNET_MODEL_NAME","ANTHROPIC_DEFAULT_SONNET_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_SMALL_FAST_MODEL","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","CLAUDE_CODE_SUBAGENT_MODEL"],oXn=["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN"],iXn=[...oXn,"AWS_PROFILE","AWS_CONFIG_FILE","AWS_SHARED_CREDENTIALS_FILE","GOOGLE_APPLICATION_CREDENTIALS","GOOGLE_CLOUD_PROJECT"],_fo=new Set(["CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST",...KFt,...GFt,...ZFt,...nXn,"CLAUDE_CODE_HOST_AUTH_ENV_VAR","CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH","CLAUDE_CODE_HOST_AUTH_REFRESH_TIMEOUT_MS","CLAUDE_CODE_HOST_CREDS_FILE",...iXn,"GCLOUD_PROJECT","GOOGLE_CLOUD_QUOTA_PROJECT","GCE_METADATA_HOST","GCE_METADATA_IP","METADATA_SERVER_DETECTION","AWS_CONTAINER_CREDENTIALS_FULL_URI","AWS_CONTAINER_CREDENTIALS_RELATIVE_URI","AWS_CONTAINER_AUTHORIZATION_TOKEN","AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE","AWS_EC2_METADATA_SERVICE_ENDPOINT","AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE","AWS_REGION","AWS_DEFAULT_REGION",...rXn,"ANTHROPIC_BEDROCK_SERVICE_TIER","CLAUDE_CODE_CERT_STORE","DISABLE_GROWTHBOOK"]),xfo=new Set(["HTTPS_PROXY","HTTP_PROXY","NO_PROXY","CLAUDE_CODE_PROXY_RESOLVES_HOSTS","CLAUDE_CODE_ENABLE_PROXY_AUTH_HELPER","CLAUDE_CODE_PROXY_AUTH_HELPER_TTL_MS","API_FORCE_IDLE_TIMEOUT","ANTHROPIC_UNIX_SOCKET","NODE_EXTRA_CA_CERTS","CLAUDE_CODE_CERT_STORE","CLAUDE_CODE_CLIENT_CERT","CLAUDE_CODE_CLIENT_KEY","CLAUDE_CODE_CLIENT_KEY_PASSPHRASE","ALL_PROXY","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED",...KFt,...GFt,"CLAUDE_CODE_CUSTOM_OAUTH_URL",...ZFt,"ANTHROPIC_CUSTOM_HEADERS","CLAUDE_CODE_HOST_CREDS_FILE","CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST","CLAUDE_CODE_HOST_AUTH_ENV_VAR","CLAUDE_CONFIG_DIR","CLAUDE_SECURESTORAGE_CONFIG_DIR","CLAUDE_CODE_REMOTE_SETTINGS_PATH","CLAUDE_CODE_MOCK_REMOTE_SETTINGS","USE_LOCAL_OAUTH","USE_STAGING_OAUTH","CLAUDE_LOCAL_OAUTH_API_BASE"].map(t=>t.toUpperCase())),aXn=Ze(()=>A.object({allowedDomains:A.array(A.string()).optional(),deniedDomains:A.array(A.string()).optional().describe("Domains that are always blocked, even if matched by allowedDomains. Supports the same wildcard syntax as allowedDomains. Merged from all settings sources regardless of allowManagedDomainsOnly."),allowManagedDomainsOnly:A.boolean().optional().describe("When true (and set in managed settings), only allowedDomains and WebFetch(domain:...) allow rules from managed settings are respected. User, project, local, and flag settings domains are ignored. Denied domains are still respected from all sources."),allowUnixSockets:A.array(A.string()).optional().describe("macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path)."),allowAllUnixSockets:A.boolean().optional().describe("If true, allow all Unix sockets (disables blocking on both platforms)."),allowLocalBinding:A.boolean().optional(),allowMachLookup:A.array(A.string().refine(t=>!(t.endsWith("*")?t.slice(0,-1):t).includes("*"),{message:'Wildcards are only allowed as a single trailing "*" (e.g., "com.example.*" or "*" for all services).'})).optional().describe('macOS only: Additional XPC/Mach service names to allow looking up. Supports trailing-wildcard prefix matching (e.g., "com.apple.coresimulator.*"). Needed for tools that communicate via XPC such as the iOS Simulator or Playwright.'),httpProxyPort:A.number().optional(),socksProxyPort:A.number().optional(),tlsTerminate:A.object({caCertPath:A.string().min(1).optional(),caKeyPath:A.string().min(1).optional()}).optional().describe("[EXPERIMENTAL] Enable in-process TLS termination so the per-request filter can see HTTPS request bodies. Provide a CA cert+key, or omit both to have sandbox-runtime generate an ephemeral one for the session. Only honored from user, managed/policy, or CLI (`--settings`) settings \u2014 project settings (.claude/settings.json and .claude/settings.local.json) are ignored.")}).optional()),lXn=Ze(()=>A.object({allowWrite:A.array(A.string()).optional().describe("Additional paths to allow writing within the sandbox. Merged with paths from Edit(...) allow permission rules."),denyWrite:A.array(A.string()).optional().describe("Additional paths to deny writing within the sandbox. Merged with paths from Edit(...) deny permission rules."),denyRead:A.array(A.string()).optional().describe("Additional paths to deny reading within the sandbox. Merged with paths from Read(...) deny permission rules."),allowRead:A.array(A.string()).optional().describe("Paths to re-allow reading within denyRead regions. Takes precedence over denyRead for matching paths."),allowManagedReadPathsOnly:A.boolean().optional().describe("When true (set in managed settings), only allowRead paths from policySettings are used.")}).optional()),cXn=Ze(()=>A.object({path:A.string().min(1).describe("Path to a credential file or directory. Same resolution as sandbox.filesystem.* paths: absolute, ~ expanded, or relative to the settings file root (project root for project settings, ~/.claude for user settings)."),mode:A.literal("deny").describe("Access mode for this path. Only `deny` is supported.")})),uXn=Ze(()=>A.object({name:A.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/,"Environment variable name must start with a letter or underscore and contain only letters, digits, and underscores").describe("Environment variable name."),mode:A.enum(["deny","mask"]).describe("Access mode for this environment variable. `deny` unsets the variable for sandboxed commands; `mask` shows sandboxed commands a sentinel value and the host proxy swaps sentinel\u2192real on egress to `injectHosts`."),injectHosts:A.array(A.string()).optional().describe("Optional narrowing of where the proxy substitutes this credential. Only meaningful when mode is `mask`; accepted but ignored for `deny`. If unset, defaults to `network.allowedDomains` \u2014 the credential is injected at every reachable host. Each entry must be reachable via `network.allowedDomains` (sandbox-runtime validates this).")})),dXn=Ze(()=>A.object({files:A.array(cXn()).optional().describe("Credential files or directories to protect. `deny` blocks reads inside the sandbox."),envVars:A.array(uXn()).optional().describe("Environment variables to protect. `deny` unsets the variable for sandboxed commands; `mask` substitutes a sentinel inside the sandbox and injects the real value at the proxy."),allowPlaintextInject:A.boolean().optional().describe("Allow sentinel\u2192real substitution on the plain-HTTP proxy path. Defaults to false: without TLS termination the upstream identity is unverified and the credential travels in cleartext. Set only for trusted-network test fixtures. Only honored from user, managed/policy, or CLI (`--settings`) settings \u2014 project settings (.claude/settings.json and .claude/settings.local.json) are ignored.")}).optional()),fXn=Ze(()=>A.object({enabled:A.boolean().optional(),failIfUnavailable:A.boolean().optional().describe("Exit with an error at startup if sandbox.enabled is true but the sandbox cannot start (missing dependencies or unsupported platform). When false (default), a warning is shown and commands run unsandboxed. Intended for managed-settings deployments that require sandboxing as a hard gate."),autoAllowBashIfSandboxed:A.boolean().optional(),allowUnsandboxedCommands:A.boolean().optional().describe("Allow commands to run outside the sandbox via the dangerouslyDisableSandbox parameter. When false, the dangerouslyDisableSandbox parameter is completely ignored and all commands must run sandboxed. Default: true."),network:aXn(),filesystem:lXn(),credentials:dXn(),ignoreViolations:A.record(A.string(),A.array(A.string())).optional(),enableWeakerNestedSandbox:A.boolean().optional(),enableWeakerNetworkIsolation:A.boolean().optional().describe("macOS only: Allow access to com.apple.trustd.agent in the sandbox. Needed for Go-based CLI tools (gh, gcloud, terraform, etc.) to verify TLS certificates when using httpProxyPort with a MITM proxy and custom CA. **Reduces security** \u2014 opens a potential data exfiltration vector through the trustd service. Default: false"),allowAppleEvents:A.boolean().optional().describe("macOS only: Allow sandboxed commands to send Apple Events (and look up the appleeventsd Mach service). Needed for `open`, `osascript`, and browser-based auth flows that open URLs. **Removes code-execution isolation** \u2014 sandboxed commands can launch other applications unsandboxed with no user prompt, and can script running apps (e.g. Terminal) subject to the user's per-app TCC automation consent. Only honored from user, managed/policy, or CLI (--settings) settings \u2014 project settings (.claude/settings.json and .claude/settings.local.json) are ignored. Default: false"),excludedCommands:A.array(A.string()).optional(),ripgrep:A.object({command:A.string(),args:A.array(A.string()).optional()}).optional().describe("Custom ripgrep configuration for bundled ripgrep support"),bwrapPath:A.preprocess(t=>typeof t=="string"&&(0,Yje.isAbsolute)(t)?t:void 0,A.string()).optional().catch(void 0).describe("Linux/WSL only: Absolute path to the bwrap (bubblewrap) binary. Overrides auto-detection via PATH. Only honored from admin-controlled managed settings."),socatPath:A.preprocess(t=>typeof t=="string"&&(0,Yje.isAbsolute)(t)?t:void 0,A.string()).optional().catch(void 0).describe("Linux/WSL only: Absolute path to the socat binary used for the sandbox network proxy. Overrides auto-detection via PATH. Only honored from admin-controlled managed settings.")}).passthrough()),A4e=["acceptEdits","auto","bypassPermissions","default","dontAsk","plan"],pXn=[...A4e,"bubble"],mXn=pXn;hXn=["auto","iterm2","iterm2_with_bell","terminal_bell","kitty","ghostty","notifications_disabled"],gXn=["normal","vim"],yXn=["auto","tmux","iterm2","in-process"],vXn=["dark","light","light-daltonized","dark-daltonized","light-ansi","dark-ansi"],wXn=["auto",...vXn],Sfo=BFt()==="macos"?"\u23FA":"\u25CF",Cfo=Ze(()=>lfe.preprocess(E4e,lfe.enum(mXn))),kfo=Ze(()=>lfe.preprocess(E4e,lfe.enum(A4e))),bXn=["bash","powershell"],XZ=Ze(()=>A.string().optional().describe('Permission rule syntax to filter when this hook runs (e.g., "Bash(git *)"). Only runs if the tool call matches the pattern. Avoids spawning hooks for non-matching commands.'));xXn=Ze(()=>{let{BashCommandHookSchema:t,PromptHookSchema:e,AgentHookSchema:n,HttpHookSchema:r,McpToolHookSchema:o}=_Xn();return A.discriminatedUnion("type",[t,e,n,r,o])}),SXn=Ze(()=>A.object({matcher:A.string().optional().describe('String pattern to match (e.g. tool names like "Write")'),hooks:A.array(xXn()).describe("List of hooks to execute when the matcher matches")})),Yfe=Ze(()=>A.partialRecord(A.enum(LNt),A.array(SXn()))),Ifo=Ze(()=>A.enum(["local","user","project","dynamic","enterprise","claudeai","managed","agent"])),Tfo=Ze(()=>A.enum(["stdio","sse","sse-ide","http","ws","sdk"])),JB=Ze(()=>A.literal("comms").optional().catch(void 0)),XP=Ze(()=>A.number().int().positive()),CXn=3e5,YFt=Ze(()=>A.number().int().positive().optional().catch(void 0).describe("@internal CCR backend wire hint; folded into timeout at parse."));kXn=Ze(()=>A.object({type:A.literal("stdio").optional(),command:A.string().min(1,"Command cannot be empty"),args:A.array(A.string()).default([]),env:A.record(A.string(),A.string()).optional(),timeout:XP().optional(),alwaysLoad:A.boolean().optional(),role:JB()})),IXn=Ze(()=>A.boolean()),XFt=Ze(()=>A.object({clientId:A.string().optional(),callbackPort:A.number().int().positive().optional(),authServerMetadataUrl:A.string().url().startsWith("https://",{message:"authServerMetadataUrl must use https://"}).optional(),scopes:A.string().min(1).optional(),xaa:IXn().optional()})),QFt=Ze(()=>A.object({name:A.string(),permission_policy:A.enum(["always_allow","always_ask","always_deny"]).optional()})),TXn=Ze(()=>A.object({type:A.literal("sse"),url:A.string(),headers:A.record(A.string(),A.string()).optional(),headersHelper:A.string().optional(),oauth:XFt().optional(),timeout:XP().optional(),request_timeout_ms:YFt(),tools:A.array(QFt()).optional(),alwaysLoad:A.boolean().optional(),role:JB(),toolPermissions:A.record(A.string(),M4e()).optional()}).transform(JFt)),PXn=Ze(()=>A.object({type:A.literal("sse-ide"),url:A.string(),ideName:A.string(),ideRunningInWindows:A.boolean().optional(),timeout:XP().optional(),alwaysLoad:A.boolean().optional(),role:JB()})),AXn=Ze(()=>A.object({type:A.literal("ws-ide"),url:A.string(),ideName:A.string(),authToken:A.string().optional(),ideRunningInWindows:A.boolean().optional(),timeout:XP().optional(),alwaysLoad:A.boolean().optional(),role:JB()})),EXn=Ze(()=>A.object({type:A.enum(["http","streamable-http"]).transform(()=>"http"),url:A.string(),headers:A.record(A.string(),A.string()).optional(),headersHelper:A.string().optional(),oauth:XFt().optional(),timeout:XP().optional(),request_timeout_ms:YFt(),tools:A.array(QFt()).optional(),alwaysLoad:A.boolean().optional(),role:JB(),toolPermissions:A.record(A.string(),M4e()).optional()}).transform(JFt)),MXn=Ze(()=>A.object({type:A.literal("ws"),url:A.string(),headers:A.record(A.string(),A.string()).optional(),headersHelper:A.string().optional(),timeout:XP().optional(),alwaysLoad:A.boolean().optional(),role:JB()})),OXn=Ze(()=>A.object({type:A.literal("sdk"),name:A.string(),timeout:XP().optional(),alwaysLoad:A.boolean().optional()})),M4e=Ze(()=>A.enum(["allow","ask","blocked"])),NXn=Ze(()=>A.object({type:A.literal("claudeai-proxy"),url:A.string(),id:A.string(),displayName:A.string().optional(),iconUrl:A.string().optional(),timeout:XP().optional(),alwaysLoad:A.boolean().optional(),toolPermissions:A.record(A.string(),M4e()).optional(),stateless:A.boolean().optional(),cachedInitResponse:A.record(A.string(),A.unknown()).nullish()})),Jje=Ze(()=>A.union([kXn(),TXn(),PXn(),AXn(),EXn(),MXn(),OXn(),NXn()])),Pfo=Ze(()=>A.object({mcpServers:A.record(A.string(),Jje())})),RXn=new Set(["claude-community","claude-plugins-community","healthcare"]),LXn=new Set(["claude-code-marketplace","claude-code-plugins","claude-plugins-official","anthropic-marketplace","anthropic-plugins","agent-skills","anthropic-agent-skills","life-sciences","knowledge-work-plugins","claude-for-legal","claude-for-financial-services","financial-services-plugins","first-party-plugins"]),e2t=new Set([...LXn,...RXn]),$Xn=/(?:official[^a-z0-9]*(anthropic|claude)|(?:anthropic|claude)[^a-z0-9]*official|^(?:anthropic|claude)[^a-z0-9]*(marketplace|plugins|official))/i,DXn=/[^\u0020-\u007E]/;sb=Ze(()=>A.string().startsWith("./")),$R=Ze(()=>sb().endsWith(".json")),ZOt=Ze(()=>A.union([sb().refine(t=>t.endsWith(".mcpb")||t.endsWith(".dxt"),{message:"MCPB file path must end with .mcpb or .dxt"}).describe("Path to MCPB file relative to plugin root"),A.string().url().refine(t=>t.endsWith(".mcpb")||t.endsWith(".dxt"),{message:"MCPB URL must end with .mcpb or .dxt"}).describe("URL to MCPB file")])),Xje=Ze(()=>sb().endsWith(".md")),Qje=Ze(()=>A.union([Xje(),sb()])),t2t=Ze(()=>A.string().min(1,"Marketplace must have a name").refine(t=>!t.includes(" "),{message:'Marketplace name cannot contain spaces. Use kebab-case (e.g., "my-marketplace")'}).refine(t=>!t.includes("/")&&!t.includes("\\")&&!t.includes("..")&&t!==".",{message:'Marketplace name cannot contain path separators (/ or \\), ".." sequences, or be "."'}).refine(t=>!FXn(t),{message:"Marketplace name impersonates an official Anthropic/Claude marketplace"}).refine(t=>t.toLowerCase()!=="inline",{message:'Marketplace name "inline" is reserved for --plugin-dir session plugins'}).refine(t=>t.toLowerCase()!=="builtin",{message:'Marketplace name "builtin" is reserved for built-in plugins'}).refine(t=>t.toLowerCase()!=="skills-dir",{message:'Marketplace name "skills-dir" is reserved for plugins auto-loaded from .claude/skills/'})),O4e=Ze(()=>A.object({name:A.string().min(1,"Author name cannot be empty").describe("Display name of the plugin author or organization"),email:A.string().optional().describe("Contact email for support or feedback"),url:A.string().optional().describe("Website, GitHub profile, or organization URL")})),UXn=Ze(()=>A.object({$schema:A.string().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:A.string().min(1,"Plugin name cannot be empty").refine(t=>!t.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Unique identifier for the plugin, used for namespacing (prefer kebab-case)"),displayName:A.string().optional().describe('Human-readable name shown in UI (e.g., "GitHub Utils"). Falls back to `name` when omitted. Unlike `name`, may contain spaces and any casing; not used for namespacing or lookup.'),version:A.string().optional().describe("Semantic version (e.g., 1.2.3) following semver.org specification"),description:A.string().optional().describe("Brief, user-facing explanation of what the plugin provides"),author:O4e().optional().describe("Information about the plugin creator or maintainer"),homepage:A.string().url().optional().describe("Plugin homepage or documentation URL"),repository:A.string().optional().describe("Source code repository URL"),license:A.string().optional().describe("SPDX license identifier (e.g., MIT, Apache-2.0)"),keywords:A.array(A.string()).optional().describe("Tags for plugin discovery and categorization"),defaultEnabled:A.boolean().optional().describe("Whether the plugin starts enabled when the user has no explicit enabled/disabled setting for it (default: true). Explicit enabledPlugins values always win, and a plugin required by an enabled dependent is enabled regardless of this value."),dependencies:A.array(wQn()).optional().describe(`Plugins that must be enabled for this plugin to function. Bare names (no "@marketplace") are resolved against the declaring plugin's own marketplace.`)})),Afo=Ze(()=>A.object({description:A.string().optional().describe("Brief, user-facing explanation of what these hooks provide"),hooks:A.lazy(()=>Yfe()).describe("The hooks provided by the plugin, in the same format as the one used for settings")})),jXn=Ze(()=>A.object({hooks:A.union([$R().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),A.lazy(()=>Yfe()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)"),A.array(A.union([$R().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),A.lazy(()=>Yfe()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)")]))])})),BXn=Ze(()=>A.object({source:Qje().optional().describe("Path to command markdown file, relative to plugin root"),content:A.string().optional().describe("Inline markdown content for the command"),description:A.string().optional().describe("Command description override"),argumentHint:A.string().optional().describe('Hint for command arguments (e.g., "[file]")'),model:A.string().optional().describe("Default model for this command"),allowedTools:A.array(A.string()).optional().describe("Tools allowed when command runs")}).refine(t=>t.source&&!t.content||!t.source&&t.content,{message:'Command must have either "source" (file path) or "content" (inline markdown), but not both'})),zXn=Ze(()=>A.object({commands:A.union([Qje().describe("Path to a command file or skill directory, relative to the plugin root. When set, the commands/ directory is not auto-loaded \u2014 list its files here if you want both."),A.array(Qje().describe("Path to a command file or skill directory, relative to the plugin root. When set, the commands/ directory is not auto-loaded \u2014 list its files here if you want both.")).describe("List of command file or skill directory paths. When set, the commands/ directory is not auto-loaded."),A.record(A.string(),BXn()).describe('Object mapping of command names to their metadata and source files. Command name becomes the slash command name (e.g., "about" \u2192 "/plugin:about")')])})),HXn=Ze(()=>A.object({agents:A.union([Xje().describe("Path to an agent file, relative to the plugin root. When set, the agents/ directory is not auto-loaded \u2014 list its files here if you want both."),A.array(Xje().describe("Path to an agent file, relative to the plugin root. When set, the agents/ directory is not auto-loaded \u2014 list its files here if you want both.")).describe("List of agent file paths. When set, the agents/ directory is not auto-loaded.")])})),WXn=Ze(()=>A.object({skills:A.union([sb().describe("Path to a skill directory, relative to the plugin root. Loaded in addition to the skills/ directory (except: for a marketplace entry whose source resolves to the marketplace root, declaring a specific subdirectory replaces the skills/ scan)."),A.array(sb().describe("Path to a skill directory, relative to the plugin root.")).describe("List of skill directory paths, loaded in addition to the skills/ directory (except: for a marketplace entry whose source resolves to the marketplace root, declaring specific subdirectories replaces the skills/ scan).")])})),n2t=Ze(()=>A.object({outputStyles:A.union([sb().describe("Path to an output-styles directory or file, relative to the plugin root. When set, the output-styles/ directory is not auto-loaded \u2014 list its files here if you want both."),A.array(sb().describe("Path to an output-styles directory or file, relative to the plugin root. When set, the output-styles/ directory is not auto-loaded \u2014 list its files here if you want both.")).describe("List of output-style directory or file paths. When set, the output-styles/ directory is not auto-loaded.")])})),VXn=Ze(()=>A.string().max(64).regex(/^[a-z][a-z0-9_-]*$/,"must match ^[a-z][a-z0-9_-]*$")),qXn=16,KXn=Ze(()=>A.object({id:VXn(),remote:A.string().max(256).regex(/^(npm:[@a-z0-9/._-]+(@[a-z0-9._+-]+)?|github:[\w.-]+\/[\w.-]+@[\w./-]+#.+\.js)$/,"must be npm:<pkg>[@ver] or github:<owner>/<repo>@<ref>#<path>.js").optional(),integrity:A.string().max(512).regex(/^sha(256|384|512)-[A-Za-z0-9+/=]+$/,"must be SRI form: sha256-, sha384-, or sha512-<base64>").optional()}).strict()),GXn=Ze(()=>A.object({syntaxHighlighting:A.object({hljsLanguages:A.array(KXn()).max(qXn)}).strict()})),r2t=Ze(()=>A.object({themes:A.union([sb().describe("Path to a themes directory or file, relative to the plugin root. When set, the themes/ directory is not auto-loaded \u2014 list its files here if you want both."),A.array(sb().describe("Path to a themes directory or file, relative to the plugin root. When set, the themes/ directory is not auto-loaded \u2014 list its files here if you want both.")).describe("List of theme directory or file paths. When set, the themes/ directory is not auto-loaded.")])})),ZXn=Ze(()=>A.object({})),YOt=Ze(()=>A.string().min(1)),YXn=Ze(()=>A.string().min(2).refine(t=>t.startsWith("."),{message:'File extensions must start with dot (e.g., ".ts", not "ts")'})),JXn=Ze(()=>A.object({mcpServers:A.union([$R().describe("MCP servers to include in the plugin (in addition to those in the .mcp.json file, if it exists)"),ZOt().describe("Path or URL to MCPB file containing MCP server configuration"),A.record(A.string(),Jje()).describe("MCP server configurations keyed by server name"),A.array(A.union([$R().describe("Path to MCP servers configuration file"),ZOt().describe("Path or URL to MCPB file"),A.record(A.string(),Jje()).describe("Inline MCP server configurations")])).describe("Array of MCP server configurations (paths, MCPB files, or inline definitions)")])})),o2t=Ze(()=>A.object({type:A.enum(["string","number","boolean","directory","file"]).describe("Type of the configuration value"),title:A.string().describe("Human-readable label shown in the config dialog"),description:A.string().describe("Help text shown beneath the field in the config dialog"),required:A.boolean().optional().describe("If true, validation fails when this field is empty"),default:A.union([A.string(),A.number(),A.boolean(),A.array(A.string())]).optional().describe("Default value used when the user provides nothing"),multiple:A.boolean().optional().describe("For string type: allow an array of strings"),sensitive:A.boolean().optional().describe("If true, masks dialog input and stores value in secure storage (keychain/credentials file) instead of settings.json"),min:A.number().optional().describe("Minimum value (number type only)"),max:A.number().optional().describe("Maximum value (number type only)")}).strict()),XXn=Ze(()=>A.object({userConfig:A.record(A.string().regex(/^[A-Za-z_]\w*$/,"Option keys must be valid identifiers (letters, digits, underscore; no leading digit) \u2014 they become CLAUDE_PLUGIN_OPTION_<KEY> env vars in hooks"),o2t()).optional().describe("User-configurable values this plugin needs. Prompted at enable time. Non-sensitive values saved to settings.json; sensitive values to secure storage. Available as ${user_config.KEY} in MCP/LSP server config, hook commands, and (non-sensitive only) skill/agent content. Keep sensitive value counts small.")})),QXn=Ze(()=>A.object({channels:A.array(A.object({server:A.string().min(1).describe("Name of the MCP server this channel binds to. Must match a key in this plugin's mcpServers."),displayName:A.string().optional().describe('Human-readable name shown in the config dialog title (e.g., "Telegram"). Defaults to the server name.'),userConfig:A.record(A.string(),o2t()).optional().describe("Fields to prompt the user for when enabling this plugin in assistant mode. Saved values are substituted into ${user_config.KEY} references in the mcpServers env.")}).strict()).describe("Channels this plugin provides. Each entry declares an MCP server as a message channel and optionally specifies user configuration to prompt for at enable time.")})),JOt=Ze(()=>A.strictObject({command:A.string().min(1).refine(t=>!(t.includes(" ")&&!t.startsWith("/")),{message:"Command should not contain spaces. Use args array for arguments."}).describe('Command to execute the LSP server (e.g., "typescript-language-server")'),args:A.array(YOt()).optional().describe("Command-line arguments to pass to the server"),extensionToLanguage:A.record(YXn(),YOt()).refine(t=>Object.keys(t).length>0,{message:"extensionToLanguage must have at least one mapping"}).describe("Mapping from file extension to LSP language ID. File extensions and languages are derived from this mapping."),transport:A.enum(["stdio","socket"]).default("stdio").describe("Communication transport mechanism"),env:A.record(A.string(),A.string()).optional().describe("Environment variables to set when starting the server"),initializationOptions:A.unknown().optional().describe("Initialization options passed to the server during initialization"),settings:A.unknown().optional().describe("Settings passed to the server via workspace/didChangeConfiguration"),workspaceFolder:A.string().optional().describe("Workspace folder path to use for the server"),startupTimeout:A.number().int().positive().optional().describe("Maximum time to wait for server startup (milliseconds)"),shutdownTimeout:A.number().int().positive().optional().describe("Maximum time to wait for graceful shutdown (milliseconds)"),restartOnCrash:A.boolean().optional().describe("Whether to restart the server if it crashes"),maxRestarts:A.number().int().nonnegative().optional().describe("Maximum number of restart attempts before giving up"),diagnostics:A.boolean().optional().describe("Whether to push publishDiagnostics into the agent context after edits. Set to false to keep LSP navigation (goToDefinition, hover, etc.) but suppress automatic diagnostic injection. Defaults to true.")})),eQn=Ze(()=>A.strictObject({name:A.string().min(1).describe("Identifier for this monitor, unique within the plugin. Used to dedupe so re-arming (plugin reload, repeat skill invoke) does not spawn duplicates."),command:A.string().min(1).describe('Shell command to run as a persistent background monitor. Each stdout line is delivered to the model as a <task_notification> event; the process runs for the session lifetime. ${CLAUDE_PLUGIN_ROOT}, ${CLAUDE_PLUGIN_DATA}, ${CLAUDE_PROJECT_DIR}, ${user_config.*}, and ${ENV_VAR} are substituted. Runs in the session cwd \u2014 prefix with `cd "${CLAUDE_PLUGIN_ROOT}" && ` if the script needs its own directory.'),description:A.string().min(1).describe("Short human-readable description of what is being monitored (shown in task panel and notification summary)."),when:A.union([A.literal("always"),A.string().startsWith("on-skill-invoke:").refine(t=>t.length>16,{message:"on-skill-invoke: must specify a skill name"})]).default("always").describe('Arm trigger. "always" arms at session start and on plugin reload. "on-skill-invoke:<skill>" arms the first time that skill is dispatched (via Skill tool or slash command).')})),tQn=Ze(()=>A.array(eQn()).refine(t=>new Set(t.map(e=>e.name)).size===t.length,{message:"Monitor names must be unique within a plugin"})),i2t=Ze(()=>A.object({monitors:A.union([$R().describe("Path to a JSON file containing the monitors array, relative to the plugin root"),tQn()]).describe("Background watch scripts the host arms as persistent Monitor tasks (unsandboxed, same trust tier as hooks) so plugins need not instruct the model to arm them. When omitted, monitors/monitors.json at the plugin root is loaded if present.")})),nQn=Ze(()=>A.object({lspServers:A.union([$R().describe("Path to .lsp.json configuration file relative to plugin root"),A.record(A.string(),JOt()).describe("LSP server configurations keyed by server name"),A.array(A.union([$R().describe("Path to LSP configuration file"),A.record(A.string(),JOt()).describe("Inline LSP server configurations")])).describe("Array of LSP server configurations (paths or inline definitions)")])})),s2t=Ze(()=>A.string().refine(t=>!t.includes("..")&&!t.includes("//"),"Package name cannot contain path traversal patterns").refine(t=>{let e=/^@[a-z0-9][a-z0-9-._]*\/[a-z0-9][a-z0-9-._]*$/,n=/^[a-z0-9][a-z0-9-._]*$/;return e.test(t)||n.test(t)},"Invalid npm package name format")),rQn=/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9_-])?$/,oQn=/^[0-9a-f]{64}$/,iQn=64,sQn=Ze(()=>A.object({sha256:A.string().regex(oQn)}));lQn=Ze(()=>A.object({binaries:A.unknown().transform(aQn).describe("sha256-pinned files to fetch into bin/ at install time, keyed by basename (target triple encoded in the name)")})),cQn=Ze(()=>A.object({settings:A.record(A.string(),A.unknown()).optional().describe("Settings to merge into the user settings while this plugin is enabled. Only the documented allowlisted keys are applied.")})),uQn=Ze(()=>A.object({experimental:A.preprocess(t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0,A.object({...r2t().partial().shape,...GXn().partial().shape,...i2t().partial().shape,...n2t().partial().shape,evals:A.union([A.string(),A.array(A.string())]).optional().describe("Path(s) to evaluation query files for `claude plugin eval`. Defaults to `evals/`.")}).passthrough().optional().describe("Components whose manifest shape may change without a deprecation cycle. Move a key out of here once it is promoted to stable."))})),dQn=Ze(()=>A.object({...UXn().shape,...jXn().partial().shape,...zXn().partial().shape,...HXn().partial().shape,...WXn().partial().shape,...n2t().partial().shape,...r2t().partial().shape,...ZXn().shape,...QXn().partial().shape,...JXn().partial().shape,...nQn().partial().shape,...i2t().partial().shape,...cQn().partial().shape,...XXn().partial().shape,...lQn().partial().shape,...uQn().partial().shape})),Jfe=Ze(()=>A.discriminatedUnion("source",[A.object({source:A.literal("url"),url:A.string().url().describe("Direct URL to marketplace.json file"),headers:A.record(A.string(),A.string()).optional().describe("Custom HTTP headers (e.g., for authentication)")}),A.object({source:A.literal("github"),repo:A.string().describe("GitHub repository in owner/repo format"),ref:A.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:A.string().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:A.array(A.string()).optional().describe('Directories to include via git sparse-checkout (cone mode). Use for monorepos where the marketplace lives in a subdirectory. Example: [".claude-plugin", "plugins"]. If omitted, the full repository is cloned.'),skipLfs:A.boolean().optional().describe("Skip Git LFS smudge during clone and update (sets GIT_LFS_SKIP_SMUDGE=1) so LFS pointer files stay as pointers instead of downloading their content. Use for marketplaces hosted in repos with large LFS objects.")}),A.object({source:A.literal("git"),url:A.string().describe("Full git repository URL"),ref:A.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:A.string().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:A.array(A.string()).optional().describe('Directories to include via git sparse-checkout (cone mode). Use for monorepos where the marketplace lives in a subdirectory. Example: [".claude-plugin", "plugins"]. If omitted, the full repository is cloned.'),skipLfs:A.boolean().optional().describe("Skip Git LFS smudge during clone and update (sets GIT_LFS_SKIP_SMUDGE=1) so LFS pointer files stay as pointers instead of downloading their content. Use for marketplaces hosted in repos with large LFS objects.")}),A.object({source:A.literal("npm"),package:s2t().describe("NPM package containing marketplace.json")}),A.object({source:A.literal("file"),path:A.string().describe("Local file path to marketplace.json")}),A.object({source:A.literal("directory"),path:A.string().describe("Local directory containing .claude-plugin/marketplace.json")}),A.object({source:A.literal("skills-dir")}).describe("Policy-list sentinel for the ~/.claude/skills/ auto-load (@skills-dir plugins). In strictKnownMarketplaces: opt the scan back IN (by default any allowlist blocks it). In blockedMarketplaces: turn the scan OFF without otherwise restricting marketplaces. Only meaningful in those two managed-settings lists (areLocalPluginDirsAllowedByPolicy); known_marketplaces.json / marketplace add etc. ignore it."),A.object({source:A.literal("hostPattern"),hostPattern:A.string().describe('Regex pattern to match the host/domain extracted from any marketplace source type. For github sources, matches against github.com. For git sources (SSH or HTTPS), extracts the hostname from the URL. Use in strictKnownMarketplaces to allow all marketplaces from a specific host (e.g., "^github\\.mycompany\\.com$").')}),A.object({source:A.literal("pathPattern"),pathPattern:A.string().describe('Regex pattern matched against the .path field of file and directory sources. Use in strictKnownMarketplaces to allow filesystem-based marketplaces alongside hostPattern restrictions for network sources. Use ".*" to allow all filesystem paths, or a narrower pattern (e.g., "^/opt/approved/") to restrict to specific directories.')}),A.object({source:A.literal("settings"),name:t2t().refine(t=>!e2t.has(t.toLowerCase()),{message:"Reserved marketplace names cannot be used with settings sources. validateOfficialNameSource only accepts github/git sources from anthropics/* for these names; a settings source would be rejected after loadAndCacheMarketplace has already written to disk with cleanupNeeded=false."}).describe("Marketplace name. Must match the extraKnownMarketplaces key (enforced); the synthetic manifest is written under this name. Same validation as PluginMarketplaceSchema plus reserved-name rejection \u2014 validateOfficialNameSource runs after the disk write, too late to clean up."),plugins:A.array(fQn()).describe("Plugin entries declared inline in settings.json"),owner:O4e().optional()}).describe("Inline marketplace manifest defined directly in settings.json. The reconciler writes a synthetic marketplace.json to the cache; diffMarketplaces detects edits via isEqual on the stored source (the plugins array is inside this object, so edits surface as sourceChanged).")])),YUe=Ze(()=>A.string().length(40).regex(/^[a-f0-9]{40}$/,"Must be a full 40-character lowercase git commit SHA")),a2t=Ze(()=>A.union([A.preprocess(t=>t==="."?"./":t,sb()).describe("Path to the plugin root, relative to the marketplace root (the directory containing .claude-plugin/, not .claude-plugin/ itself)"),A.object({source:A.literal("npm"),package:s2t().or(A.string().refine(t=>/^(?:file|https?|git(?:\+https?|\+ssh)?|ssh|github|gitlab|bitbucket):/i.test(t)||!t.includes(".."),'Package reference cannot contain ".." path segments')).describe("Package name (or url, or local path, or anything else that can be passed to `npm` as a package)"),version:A.string().optional().describe("Specific version or version range (e.g., ^1.0.0, ~2.1.0)"),registry:A.string().url().optional().describe("Custom NPM registry URL (defaults to using system default, likely npmjs.org)")}).describe("NPM package as plugin source"),A.object({source:A.literal("url"),url:A.string().describe("Full git repository URL (https:// or git@)"),ref:A.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:YUe().optional().describe("Specific commit SHA to use")}),A.object({source:A.literal("github"),repo:A.string().describe("GitHub repository in owner/repo format"),ref:A.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:YUe().optional().describe("Specific commit SHA to use")}),A.object({source:A.literal("git-subdir"),url:A.string().describe("Git repository: GitHub owner/repo shorthand, https://, or git@ URL"),path:A.string().min(1).describe('Subdirectory within the repo containing the plugin (e.g., "tools/claude-plugin"). Cloned sparsely using partial clone (--filter=tree:0) to minimize bandwidth for monorepos.'),ref:A.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:YUe().optional().describe("Specific commit SHA to use")}).describe("Plugin located in a subdirectory of a larger repository (monorepo). Only the specified subdirectory is materialized; the rest of the repo is not downloaded."),A.object({source:A.literal("unsupported")}).describe('Placeholder for source types this Claude Code version does not recognize. Never authored by hand \u2014 PluginMarketplaceSchema rewrites unparseable sources to this so the entry remains in marketplace.plugins (detectDelistedPlugins must not see it as removed). Install attempts fail at cachePlugin with a clear "update Claude Code" message.')])),fQn=Ze(()=>A.object({name:A.string().min(1,"Plugin name cannot be empty").refine(t=>!t.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Plugin name as it appears in the target repository"),source:a2t().describe("Where to fetch the plugin from. Must be a remote source \u2014 relative paths have no marketplace repository to resolve against."),description:A.string().optional(),version:A.string().optional(),strict:A.boolean().optional()}).refine(t=>typeof t.source!="string",{message:'Plugins in a settings-sourced marketplace must use remote sources (github, git-subdir, npm, url). Relative-path sources like "./foo" have no marketplace repository to resolve against.'}).refine(t=>typeof t.source=="string"||t.source.source!=="unsupported",{message:"source.source: 'unsupported' is a parse-time placeholder and cannot be authored. Use a remote source (github, git-subdir, npm, url)."})),pQn=Ze(()=>A.object({cli:A.array(A.string().max(64)).max(10).optional().describe('First command tokens (e.g. ["stripe"]) \u2014 exact match against commands run this session.'),hosts:A.array(A.string().max(128)).max(20).optional().describe('Hostnames (e.g. ["api.stripe.com"]) \u2014 exact, case-insensitive match against hostnames seen in https?:// URLs in bash commands run this session. Bare hostname only: lowercase, no scheme, no port, no path.'),filesRead:A.array(A.string().max(256)).max(10).optional().describe('Glob patterns (e.g. ["**/*.tf"]) \u2014 the plugin is relevant when a file Claude has read this session matches any pattern. Matched against read-file paths, forward-slash normalized, case-insensitive.'),manifestDeps:A.array(A.object({file:A.string().max(256),pattern:A.string().max(256)})).max(10).optional().describe("Dependency declared in a package manifest. Each {file, pattern} is a pair of RegExp sources: `file` matches the manifest filename (package.json, go.mod, requirements.txt, \u2026); `pattern` matches the dependency declaration inside that file. Evaluated against files read this session."),cwd:A.array(A.string().max(256)).max(10).optional().describe(`Glob patterns (e.g. ["Engine/Source/Runtime/Renderer/**"]) \u2014 the plugin is relevant when the session's working directory is at or under a directory matching the pattern. Matched against the cwd both relative to the enclosing git repo root and as an absolute path, forward-slash normalized, case-insensitive. A bare directory (no glob characters) means "cwd is at or under this directory". Known at session start, so this signal can surface a suggestion before the first turn.`)})),mQn=Ze(()=>A.object({topic:A.string().max(64).optional().describe('What the user is working with when this plugin is relevant \u2014 fills "Working with {topic}?". Often the product name (e.g. "Stripe"); use a domain (e.g. "design") when the plugin name does not read naturally as a topic. Defaults to the plugin name with each hyphen-segment capitalized.'),signals:pQn().optional().describe("Matchers that determine when the plugin is relevant.")})),hQn=Ze(()=>dQn().partial().extend({name:A.string().min(1,"Plugin name cannot be empty").refine(t=>!t.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Unique identifier matching the plugin name"),source:a2t().describe("Where to fetch the plugin from"),category:A.string().optional().describe('Category for organizing plugins (e.g., "productivity", "development")'),tags:A.array(A.string()).optional().describe("Tags for searchability and discovery"),strict:A.boolean().optional().default(!0).describe("Require the plugin manifest to be present in the plugin folder. If false, the marketplace entry provides the manifest."),relevance:A.preprocess(t=>typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0,mQn().optional()).describe(`Declares when this plugin is relevant to the user's work. Consumed by the spinner tip ("Working with {topic}?"), session-start auto-suggest, and marketplace browse ranking.`)})),gQn=Ze(()=>A.object({name:A.string().min(1).refine(t=>!t.includes(" "))}));Efo=Ze(()=>A.object({$schema:A.string().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:t2t(),version:A.string().optional().describe("Marketplace manifest version"),description:A.string().optional().describe("Human-readable description of this marketplace"),owner:O4e().describe("Marketplace maintainer or curator information"),plugins:A.array(A.unknown()).transform(yQn).describe("Collection of available plugins in this marketplace"),forceRemoveDeletedPlugins:A.boolean().optional().describe("When true, plugins removed from this marketplace will be automatically uninstalled and flagged for users"),metadata:A.object({pluginRoot:A.string().optional().describe("Base path for relative plugin sources"),version:A.string().optional().describe("Marketplace version"),description:A.string().optional().describe("Marketplace description")}).optional().describe("Optional marketplace metadata"),allowCrossMarketplaceDependenciesOn:A.array(A.string()).optional().describe("Marketplace names whose plugins may be auto-installed as dependencies. Only the root marketplace's allowlist applies \u2014 no transitive trust."),renames:A.record(A.string(),A.string().nullable()).optional().catch(void 0).describe("Append-only map of old plugin name \u2192 current name (or null when removed). The loader follows this on plugin-not-found and migrates user settings to the new name.")})),l2t=Ze(()=>A.string().regex(/^[A-Za-z0-9][-A-Za-z0-9._]*@[A-Za-z0-9][-A-Za-z0-9._]*$/,"Plugin ID must be in format: plugin@marketplace")),vQn=/^[A-Za-z0-9][-A-Za-z0-9._]*(@[A-Za-z0-9][-A-Za-z0-9._]*)?(@\^[^@]*)?$/,wQn=Ze(()=>A.union([A.string().regex(vQn,"Dependency must be a plugin name, optionally qualified with @marketplace").transform(t=>t.replace(/@\^[^@]*$/,"")),A.object({name:A.string().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/),marketplace:A.string().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/).optional()}).loose().transform(t=>t.marketplace?`${t.name}@${t.marketplace}`:t.name)])),bQn=Ze(()=>A.object({version:A.string().describe("Currently installed version"),installedAt:A.string().describe("ISO 8601 timestamp of installation"),lastUpdated:A.string().optional().describe("ISO 8601 timestamp of last update"),installPath:A.string().describe("Absolute path to the installed plugin directory"),gitCommitSha:A.string().optional().describe("Git commit SHA for git-based plugins (for version tracking)"),resolvedVersion:A.string().optional().describe("Tag-derived semver this install resolved to (when fetched via a version constraint). Used by verifyAndDemote in preference to manifest.version, since the upstream may have forgotten to bump plugin.json."),auto:A.boolean().optional().describe("True when this plugin was pulled in as a dependency rather than installed explicitly. Auto-installed plugins are eligible for removal by the orphan sweep when nothing depends on them. Absent = manual (preserves pre-flag installs).")})),_Qn=Ze(()=>A.object({version:A.literal(1).describe("Schema version 1"),plugins:A.record(l2t(),bQn()).describe("Map of plugin IDs to their installation metadata")})),xQn=Ze(()=>A.enum(["managed","user","project","local"])),SQn=Ze(()=>A.object({scope:xQn().describe("Installation scope"),projectPath:A.string().optional().describe("Project path (required for project/local scopes)"),installPath:A.string().describe("Absolute path to the versioned plugin directory"),version:A.string().optional().describe("Currently installed version"),installedAt:A.string().optional().describe("ISO 8601 timestamp of installation"),lastUpdated:A.string().optional().describe("ISO 8601 timestamp of last update"),gitCommitSha:A.string().optional().describe("Git commit SHA for git-based plugins"),resolvedVersion:A.string().optional().describe("Tag-derived semver this install resolved to"),auto:A.boolean().optional().describe("True when pulled in as a dependency. Eligible for orphan sweep.")})),CQn=Ze(()=>A.object({version:A.literal(2).describe("Schema version 2"),plugins:A.record(l2t(),A.array(SQn())).describe("Map of plugin IDs to arrays of installation entries")})),Mfo=Ze(()=>A.union([_Qn(),CQn()])),kQn=Ze(()=>A.object({source:Jfe().describe("Where to fetch the marketplace from"),installLocation:A.string().describe("Local cache path where marketplace manifest is stored"),lastUpdated:A.string().describe("ISO 8601 timestamp of last marketplace refresh"),autoUpdate:A.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),Ofo=Ze(()=>A.record(A.string(),kQn())),IQn=["autoMode","deepLink","voice","briefView","screenReader"],jde={},Dpe={autoMode:{buildGate:()=>!1,shape:()=>jde,permissionsShape:()=>jde,permissionModes:()=>[]},deepLink:{buildGate:()=>!0,shape:()=>({disableDeepLinkRegistration:A.enum(["disable"]).optional().describe("Prevent claude-cli:// protocol handler registration with the OS")})},voice:{buildGate:()=>!1,shape:()=>jde},briefView:{buildGate:()=>!0,shape:()=>({defaultView:A.enum(["chat","transcript"]).optional().describe("Default transcript view: chat (SendUserMessage checkpoints only) or transcript (full)")})},screenReader:{buildGate:()=>!1,shape:()=>jde}};XOt={Task:"Agent",KillShell:"TaskStop",KillBash:"TaskStop",AgentOutputTool:"TaskOutput",BashOutputTool:"TaskOutput",AgentOutput:"TaskOutput",BashOutput:"TaskOutput",ListPeers:"ListAgents",Brief:"SendUserMessage",ListMcpResources:"ListMcpResourcesTool",ReadMcpResource:"ReadMcpResourceTool",ReadMcpResourceDir:"ReadMcpResourceDirTool"};d2t="workspace",Nfo=`mcp__${d2t}__bash`,Rfo=`mcp__${d2t}__web_fetch`;Xfe={filePatternTools:["Read","Write","Edit","Glob","NotebookRead","NotebookEdit","Cd"],bashPrefixTools:["Bash"],customValidation:{WebSearch:t=>t.includes("*")||t.includes("?")?{valid:!1,error:"WebSearch does not support wildcards",suggestion:"Use exact search terms without * or ?",examples:["WebSearch(claude ai)","WebSearch(typescript tutorial)"]}:{valid:!0},WebFetch:t=>t.includes("://")||t.startsWith("http")?{valid:!1,error:"WebFetch permissions use domain format, not URLs",suggestion:'Use "domain:hostname" format',examples:["WebFetch(domain:example.com)","WebFetch(domain:github.com)"]}:t.startsWith("domain:")?{valid:!0}:{valid:!1,error:'WebFetch permissions must use "domain:" prefix',suggestion:'Use "domain:hostname" format',examples:["WebFetch(domain:example.com)","WebFetch(domain:*.google.com)"]}}};tNt=Ze(()=>p2t()),UQn=Ze(()=>p2t("allow"));jQn=Ze(()=>A.record(A.string(),A.coerce.string()));Lfo=Ze(()=>m2t(c2t())),BQn=Ze(()=>A.object({source:Jfe().describe("Where to fetch the marketplace from"),installLocation:A.string().optional().describe("Local cache path where marketplace manifest is stored (auto-generated if not provided)"),autoUpdate:A.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),zQn=Ze(()=>A.object({serverName:A.string().regex(/^[a-zA-Z0-9_-]+$/,"Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that users are allowed to configure"),serverCommand:A.array(A.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for allowed stdio servers"),serverUrl:A.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for allowed remote MCP servers')}).refine(t=>nFt([t.serverName!==void 0,t.serverCommand!==void 0,t.serverUrl!==void 0],Boolean)===1,{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),HQn=Ze(()=>A.object({serverName:A.string().min(1,"Server name must be non-empty").refine(t=>t.trim().length>0,{message:"Server name must not be whitespace-only"}).refine(t=>t===t.trim(),{message:"Server name has leading or trailing whitespace and will never match (names are compared verbatim)"}).optional().describe("Name of the MCP server that is explicitly blocked"),serverCommand:A.array(A.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for blocked stdio servers"),serverUrl:A.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for blocked remote MCP servers')}).refine(t=>nFt([t.serverName!==void 0,t.serverCommand!==void 0,t.serverUrl!==void 0],Boolean)===1,{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),WQn=Ze(()=>A.object({path:A.string().describe("Absolute path to the helper executable"),timeoutMs:A.number().int().min(1e3).optional(),refreshIntervalMs:A.union([A.literal(0),A.number().int().min(6e4)]).optional()})),nNt=["skills","agents","hooks","mcp"],rNt=Object.freeze({type:"invalid-entry-stripped"}),VQn=Ze(()=>A.union([A.object({type:A.literal("regex").describe('Config variant. This client understands "regex": matches turn output and builds a URL from named capture groups. Entries with other variants are preserved but skipped at runtime.'),pattern:A.string().describe("Regex matched against turn output (tool results and assistant text)"),url:A.string().describe("Link target. {name} placeholders are filled from named regex capture groups, e.g. (?<id>...) -> {id}. Values are URL-encoded; the origin must be literal in the template. The scheme must be https, http, or a recognized editor or workspace deep-link scheme: vscode, vscode-insiders, cursor, windsurf, zed, jetbrains, idea, slack, linear, notion, figma."),label:A.string().optional().describe("Badge text. {name} placeholders filled from named capture groups; defaults to the full match.")}).passthrough(),A.object({type:A.string().describe("Config variant discriminator for entries this client does not understand; the entry is preserved as-is and skipped at runtime.")}).passthrough()]));KQn=Ze(()=>qQn(c2t())),$fo=Object.freeze({serverName:"invalid-entry-stripped"}),Pk="https://code.claude.com/docs/en",Dfo=[{matches:t=>t.path==="permissions.defaultMode"&&t.code==="invalid_value",tip:{suggestion:'Valid modes: "acceptEdits" (ask before file changes), "plan" (analysis only), "bypassPermissions" (auto-accept all), or "default" (standard behavior)',docLink:`${Pk}/iam#permission-modes`}},{matches:t=>t.path==="apiKeyHelper"&&t.code==="invalid_type",tip:{suggestion:'Provide a shell command that outputs your API key to stdout. The script should output only the API key. Example: "/bin/generate_temp_api_key.sh"'}},{matches:t=>t.path==="cleanupPeriodDays"&&t.code==="too_small",tip:{suggestion:'cleanupPeriodDays must be at least 1. To keep transcripts for a long time, set a large number (e.g. 3650 for ~10 years). To disable transcript writes entirely, remove this setting and use the --no-session-persistence CLI flag or the SDK persistSession:false option instead. (0 is rejected because it previously silently disabled all transcript writes, which users setting it to mean "never clean up" did not expect.)'}},{matches:t=>t.path.startsWith("env.")&&t.code==="invalid_type",tip:{suggestion:'Environment variables must be strings. Wrap numbers and booleans in quotes. Example: "DEBUG": "true", "PORT": "3000"',docLink:`${Pk}/settings#environment-variables`}},{matches:t=>(t.path==="permissions.allow"||t.path==="permissions.deny")&&t.code==="invalid_type"&&t.expected==="array",tip:{suggestion:'Permission rules must be in an array. Format: ["Tool(specifier)"]. Examples: ["Bash(npm run build)", "Edit(docs/**)", "Read(~/.zshrc)"]. Use * for wildcards.'}},{matches:t=>t.path.startsWith("hooks.")&&t.code==="invalid_key",tip:{suggestion:"Not a recognized hook event. Common events: PreToolUse, PostToolUse, UserPromptSubmit, SessionStart, SessionEnd, Stop. Check spelling and capitalization.",docLink:`${Pk}/hooks`}},{matches:t=>/\.hooks\.\d+\.command$/.test(t.path)&&t.code==="invalid_type"&&t.received==="undefined",tip:{suggestion:'Command hooks require `command`. For exec form (no shell), set `command` to the executable and `args` to its arguments: {"type": "command", "command": "echo", "args": ["hi"]}. For shell form, set `command` to the full shell string: {"type": "command", "command": "echo hi"}.',docLink:`${Pk}/hooks#exec-form-and-shell-form`}},{matches:t=>t.path.includes("hooks")&&t.code==="invalid_type",tip:{suggestion:'Hooks use a matcher + hooks array. The matcher is a string: a tool name ("Bash"), pipe-separated list ("Edit|Write"), or empty to match all. Example: {"PostToolUse": [{"matcher": "Edit|Write", "hooks": [{"type": "command", "command": "echo Done"}]}]}'}},{matches:t=>t.code==="invalid_type"&&t.expected==="boolean",tip:{suggestion:'Use true or false without quotes. Example: "includeCoAuthoredBy": true'}},{matches:t=>t.code==="unrecognized_keys",tip:{suggestion:"Check for typos or refer to the documentation for valid fields",docLink:`${Pk}/settings`}},{matches:t=>t.code==="invalid_value"&&t.enumValues!==void 0,tip:{suggestion:void 0}},{matches:t=>t.code==="invalid_type"&&t.expected==="object"&&t.received===null&&t.path==="",tip:{suggestion:"Check for missing commas, unmatched brackets, or trailing commas. Use a JSON validator to identify the exact syntax error."}},{matches:t=>t.path==="permissions.additionalDirectories"&&t.code==="invalid_type",tip:{suggestion:'Must be an array of directory paths. Example: ["~/projects", "/tmp/workspace"]. You can also use --add-dir flag or /add-dir command',docLink:`${Pk}/iam#working-directories`}}],Ffo={permissions:`${Pk}/iam#configuring-permissions`,env:`${Pk}/settings#environment-variables`,hooks:`${Pk}/hooks`},Ufo=Ze(()=>KQn().strict()),jfo=new Set(LNt),Bfo=Object.freeze({settings:{},errors:[]});process.env.NoDefaultCurrentDirectoryInExePath="1";eer=new Set(["EBUSY","EMFILE","ENFILE","ENOTEMPTY","EPERM"])});function Upe(t,e){return{model:oer(t,e),mode:cer(t,e)}}function oer(t,e){let n=t.models?null:ier(t.configOptions),r=t.models??n?.state??null;if(!r)return null;let o=n?ser(t.configOptions):null,i=n?{kind:"setConfigOption",configId:n.configId,...o?{effortConfigId:o.id}:{}}:{kind:"setModel"},s=[],a=new Map;for(let p of r.availableModels){let m=e.wire.decode(p.modelId),h=m.selection.baseModelId,v=a.get(h)??(()=>{let y={baseModelId:h,provider:m.provider,name:p.name,description:p.description??void 0,variants:[]};return a.set(h,y),s.push(y),y})();v.variants.some(y=>y.effort===m.selection.effort)||v.variants.push({effort:m.selection.effort,wireId:p.modelId})}let l=s.map(p=>({baseModelId:p.baseModelId,name:y2t(p.variants.length>=2?fer(p.name,p.variants):p.name,e),description:e.showModelDescriptions?p.description:void 0,provider:p.provider,effortOptions:aer(p,e)})),c=e.wire.decode(r.currentModelId),u=c.selection.baseModelId,d=l.find(p=>p.baseModelId===u);if(!d){let p=e.wire.effortConfigFor?L4e(e.wire.effortConfigFor(u)):[];d={baseModelId:u,name:y2t(u,e),provider:c.provider,effortOptions:p},l.push(d)}return o&&(d.effortOptions=L4e(o)),{current:{baseModelId:d.baseModelId,effort:ler(c.selection.effort,d,e,t.configOptions,o)},availableModels:l,apply:i}}function ier(t){if(!t)return null;let e=t.find(r=>r.category==="model"&&r.type==="select");if(!e||e.type!=="select")return null;let n=[];for(let r of e.options)if("options"in r)for(let o of r.options)n.push({modelId:o.value,name:o.name,description:o.description});else n.push({modelId:r.value,name:r.name,description:r.description});return n.length===0?null:{state:{currentModelId:String(e.currentValue),availableModels:n},configId:e.id}}function ser(t){return t?.find(e=>e.category==="thought_level"&&e.type==="select")??null}function aer(t,e){if(t.variants.length>=2){let n=[];t.variants.some(o=>o.effort===null)&&n.push({value:null,label:"default"});for(let o of t.variants)o.effort!==null&&n.push({value:o.effort,label:o.effort.toLowerCase()});return n}if(e.wire.effortConfigFor){let n=e.wire.effortConfigFor(t.baseModelId);return L4e(n)}return[]}function L4e(t){if(!t||t.type!=="select")return[];let e=[];for(let n of t.options)if("options"in n)for(let r of n.options)e.push({value:r.value,name:r.name});else e.push({value:n.value,name:n.name});return e.map(n=>({value:n.value,label:(n.name||n.value).toLowerCase()}))}function ler(t,e,n,r,o=null){let i=t;if(i===null&&o?.type==="select"&&(i=String(o.currentValue)),i===null&&n.wire.effortConfigFor){let s=n.wire.effortConfigFor(e.baseModelId);if(s&&s.type==="select"){let a=r?.find(c=>c.id===s.id);i=(a&&a.type==="select"?String(a.currentValue):null)??(s.currentValue!=null?String(s.currentValue):null)}}return i===null?(e.effortOptions.some(s=>s.value===null),null):e.effortOptions.some(s=>s.value===i)?i:null}function cer(t,e){let n=e.getModeMapping?.(t.modes,t.configOptions);return n?n.kind==="setMode"?uer(n,t.modes):der(n,t.configOptions):null}function uer(t,e){if(!e)return null;let n=new Set(e.availableModes.map(s=>s.id)),r=[],o={};for(let s of $4e){let a=t.canonical[s];!a||!n.has(a)||(r.push({value:s,label:v2t[s]}),o[s]={kind:"setMode",nativeId:a})}return r.length===0?null:{current:w2t(t.canonical,e.currentModeId,r),options:r,apply:o}}function der(t,e){if(!t.configId||!e)return null;let n=e.find(a=>a.id===t.configId);if(!n||n.type!=="select")return null;let r=new Set;for(let a of n.options)if("options"in a)for(let l of a.options)r.add(l.value);else r.add(a.value);let o=[],i={};for(let a of $4e){let l=t.canonical[a];!l||!r.has(l)||(o.push({value:a,label:v2t[a]}),i[a]={kind:"setConfigOption",configId:n.id,value:l})}return o.length===0?null:{current:w2t(t.canonical,String(n.currentValue),o),options:o,apply:i}}function w2t(t,e,n){let r=new Set(n.map(o=>o.value));for(let o of $4e)if(r.has(o)&&t[o]===e)return o;return null}function y2t(t,e){return e.normalizeModelName?.(t)??t}function fer(t,e){let n=t.match(/^(.*?)\s*\(([^()]+)\)\s*$/);return!n||!new Set(e.flatMap(o=>o.effort?[o.effort.toLowerCase()]:[])).has(n[2].toLowerCase())?t:n[1].trim()}function b2t(t){let e=t?.model;if(!e)return"";let n=e.apply.kind==="setConfigOption"?`setConfigOption:${e.apply.configId}:${e.apply.effortConfigId??""}`:e.apply.kind;return[e.current.baseModelId,e.current.effort??"",n,e.availableModels.map(r=>`${r.baseModelId}:${r.provider??""}:${r.effortOptions.map(o=>o.value??"_").join("|")}`).join(",")].join("/")}function _2t(t){return t?JSON.stringify(t.availableModels):""}function x2t(t){let e=t?.mode;if(!e)return"";let n=e.options.map(r=>`${r.value}:${e.apply[r.value]?.kind??""}`).join(",");return`${e.current??""}|${n}`}var $4e,v2t,XB=b(()=>{$4e=["default","plan","auto"],v2t={default:"Default",plan:"Plan",auto:"Auto"}});function Y7(t){let e=t.lastIndexOf(per),n=e===-1?-1:t.lastIndexOf(S2t,e);return n===-1||e<=n?t:t.slice(n+S2t.length,e).replace(/^\n/,"").replace(/\n$/,"")}var S2t,per,D4e=b(()=>{S2t="<user-message>",per="</user-message>"});function k2t(t){let e=[],n=t.split(/\r?\n/);for(let r of n){if(!r.trim())continue;let o;try{o=JSON.parse(r)}catch{continue}if(o.isMeta===!0||o.isSidechain===!0)continue;let i=o.message?.content,s=null,a="";o.type==="user"&&typeof i=="string"?(s=ar,a=Y7(i).trim()):o.type==="user"&&Array.isArray(i)?i.some(l=>l?.type==="tool_result")||(s=ar,a=Y7(C2t(i)).trim()):o.type==="assistant"&&Array.isArray(i)&&(s=pl,a=C2t(i)),!(!s||!a)&&e.push({id:`claude-loaded-${e.length}`,sender:s,message:a,isVisible:!0,timestamp:mer(o.timestamp)})}return e}function C2t(t){return t.filter(e=>e?.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
`).trim()}function mer(t){if(typeof t!="string")return null;let e=new Date(t);return Number.isNaN(e.getTime())?null:Cs(e)}var I2t=b(()=>{gt();ut();D4e()});function QB(t){return typeof t!="number"||!Number.isFinite(t)?null:Math.max(0,t)}function ez(t,e=Date.now()){return t.length===0?{kind:"unavailable"}:{kind:"usage",planUsage:{windows:t,updatedAt:e}}}function QP(t,e=Date.now()){let n=t.windows.filter(r=>r.resetsAt===void 0||r.resetsAt>e);return n.length===0?null:n.length===t.windows.length?t:{...t,windows:n}}var HR=b(()=>{});function yer(t){if(typeof t!="string")return;let e=Date.parse(t);return Number.isFinite(e)?e:void 0}function T2t(t,e,n){if(!n)return null;let r=QB(n.utilization);return r===null?null:{id:t,label:e,percent:r,resetsAt:yer(n.resets_at)}}function ver(t,e=Date.now()){if(t?.rate_limits_available===!1)return{kind:"none"};let n=t?.rate_limits;if(!n)return{kind:"unavailable"};let r=[];for(let[o,i]of ger){let s=T2t(o,i,n[o]);s&&r.push(s)}for(let o of n.model_scoped??[]){let i=typeof o?.display_name=="string"?o.display_name.trim():"";if(!i)continue;let s=T2t(`model_scoped:${i}`,`Weekly (${i})`,o);s&&r.push(s)}return ez(r,e)}async function P2t(t){let e=t?.[her];if(typeof e!="function")return j("[AgentMode] Claude SDK exposes no usage API; plan caps unavailable"),{kind:"unavailable"};try{let n=await e.call(t),r=ver(n);return j(r.kind==="usage"?`[AgentMode] read ${r.planUsage.windows.length} plan cap window(s)`:`[AgentMode] usage read reported ${r.kind==="none"?"no plan caps":"nothing usable"}`),r}catch(n){return j("[AgentMode] Claude SDK usage read failed; plan caps unavailable",n),{kind:"unavailable"}}}var her,ger,A2t=b(()=>{HR();pe();her="usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET",ger=[["five_hour","5h"],["seven_day","Weekly"],["seven_day_oauth_apps","Weekly (OAuth apps)"],["seven_day_opus","Weekly (Opus)"],["seven_day_sonnet","Weekly (Sonnet)"]]});function E2t(t){return wer.includes(t)?t:null}function X7(){return{pendingCreatesByToolUseId:new Map,tasksById:new Map,nextOrder:0,lastSignature:null}}function N2t(t,e,n,r){let o=J7(r)?r:null;switch(n){case"TodoWrite":{let i=o?.todos;if(!Array.isArray(i))return null;let s=[];for(let a of i){if(!J7(a))continue;let l=E2t(a.status);typeof a.content!="string"||a.content.length===0||!l||s.push({content:a.content,status:l,priority:"medium"})}return s.length===0&&i.length>0?null:jpe(t,s)}case"TaskCreate":{let i=typeof o?.subject=="string"?o.subject.trim():"";return i&&t.pendingCreatesByToolUseId.set(e,{subject:i}),null}case"TaskUpdate":{let i=typeof o?.taskId=="string"?o.taskId:"";if(!i)return null;if(o?.status==="deleted")return t.tasksById.delete(i)?jpe(t,U4e(t)):null;let s=E2t(o?.status),a=t.tasksById.get(i);return!a||!s||a.status===s?null:(a.status=s,jpe(t,U4e(t)))}default:return null}}function R2t(t,e,n){let r=t.pendingCreatesByToolUseId.get(e);if(!r)return null;t.pendingCreatesByToolUseId.delete(e);let o=_er(n);return o?(ber(t)&&(t.tasksById.clear(),t.nextOrder=0),t.tasksById.set(o.id,{subject:o.subject??r.subject,status:"pending",order:t.nextOrder++}),jpe(t,U4e(t))):null}function ber(t){if(t.tasksById.size===0)return!1;for(let e of t.tasksById.values())if(e.status!=="completed")return!1;return!0}function U4e(t){return Array.from(t.tasksById.values()).sort((e,n)=>e.order-n.order).map(e=>({content:e.subject,status:e.status,priority:"medium"}))}function jpe(t,e){let n=JSON.stringify(e);return n===t.lastSignature?null:(t.lastSignature=n,{sessionUpdate:"plan",entries:e})}function _er(t){let e=F4e(t);if(e)return e;if(typeof t=="string")return F4e(O2t(t))??M2t(t);if(Array.isArray(t))for(let n of t){if(!J7(n)||n.type!=="text"||typeof n.text!="string")continue;let r=F4e(O2t(n.text))??M2t(n.text);if(r)return r}return null}function M2t(t){let e=xer.exec(t.trim());return e?{id:e[1]}:null}function F4e(t){if(!J7(t)||!J7(t.task))return null;let{id:e,subject:n}=t.task;return typeof e!="string"||e.length===0?null:{id:e,subject:typeof n=="string"?n:void 0}}function O2t(t){try{return JSON.parse(t)}catch{return null}}function J7(t){return typeof t=="object"&&t!==null}var wer,xer,j4e=b(()=>{wer=["pending","in_progress","completed"];xer=/^Task #(\d+) created successfully\b/});function Ser(t){if(t.kind==="tool_snapshot")return t.nativeToolName==="Agent"||t.nativeToolName==="Task"?{kind:"launch_observed",toolCallId:t.toolCallId}:void 0;let e=t.message;if(e.type==="user")return{kind:"result_batch",results:ker(e),asyncLaunchTaskId:Ter(e)};if(e.type!=="system")return;let n=e;if(n.subtype==="task_updated"){let a=Sx(n.task_id),l=Q7(n.patch),c=D2t(l?.status);return!a||!c?void 0:{kind:"task_terminal",taskId:a,status:c,output:Sx(l?.error)}}if(n.subtype!=="task_started"&&n.subtype!=="task_progress"&&n.subtype!=="task_notification")return;let r=Sx(n.task_id),o=Sx(n.tool_use_id);if(!r||n.tool_use_id!==void 0&&!o)return;let i=Ier(n);if(n.subtype!=="task_notification")return{kind:"task_active",toolCallId:o,taskId:r,...n.subtype==="task_progress"&&i?{progress:i}:{}};let s=D2t(n.status);return s?{kind:"task_terminal",toolCallId:o,taskId:r,status:s,output:Sx(n.summary),...i?{progress:i}:{}}:{kind:"task_active",toolCallId:o,taskId:r,...i?{progress:i}:{}}}function L2t(t){return{updates:[t],resultActions:U2t}}function Cer(t){return t.phase==="terminal"}function Q7(t){return typeof t=="object"&&t!==null?t:void 0}function Sx(t){return typeof t=="string"&&t.trim().length>0?t:void 0}function B4e(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function ker(t){let e=Q7(t.message)?.content;if(!Array.isArray(e))return[];let n=[];for(let r of e){let o=Q7(r);if(o?.type!=="tool_result")continue;let i=Sx(o.tool_use_id);i&&n.push({toolCallId:i,status:o.is_error===!0?"failed":"completed"})}return n}function Ier(t){let e=Q7(t.usage),n=Sx(t.description),r=Sx(t.last_tool_name),o=B4e(e?.tool_uses),i=B4e(e?.duration_ms),s=B4e(e?.total_tokens);if(!(n===void 0&&r===void 0&&o===void 0&&i===void 0&&s===void 0))return{...n?{description:n}:{},...r?{toolName:r}:{},...o!==void 0?{toolUses:o}:{},...i!==void 0?{durationMs:i}:{},...s!==void 0?{totalTokens:s}:{}}}function $2t(t){return[{type:"content",content:{type:"text",text:t}}]}function Ter(t){let e=Q7(t.tool_use_result);if(!(!e||!(e.isAsync===!0||Sx(e.status)==="async_launched")))return Sx(e.agentId)}function D2t(t){switch(t){case"completed":return"completed";case"failed":case"stopped":case"killed":return"failed";default:return}}var F2t,U2t,tz,WR,z4e=b(()=>{F2t=Object.freeze([]),U2t=new Map,tz=Object.freeze({updates:F2t,resultActions:U2t}),WR=class{constructor(){this.launchesByToolCallId=new Map;this.launchToolCallIdByTaskId=new Map;this.pendingTerminalsByTaskId=new Map;this.replayedUpdates=[]}accept(e){let n=Ser(e);if(!n)return tz;let r=this.transition(n);return this.replayedUpdates.length===0?r:{updates:[...this.replayedUpdates.splice(0),...r.updates],resultActions:r.resultActions}}transition(e){switch(e.kind){case"launch_observed":return this.launchesByToolCallId.has(e.toolCallId)||this.launchesByToolCallId.set(e.toolCallId,{phase:"awaiting_identity",toolCallId:e.toolCallId}),tz;case"task_active":return this.transitionActiveTask(e);case"task_terminal":return this.transitionTerminalTask(e);case"result_batch":return this.transitionResultBatch(e)}}transitionActiveTask(e){let n=this.resolveLaunch(e.toolCallId,e.taskId);return!n||Cer(n)?tz:L2t({toolCallId:n.toolCallId,status:"in_progress",...e.progress?{progress:e.progress}:{}})}transitionTerminalTask(e){let n=this.resolveLaunch(e.toolCallId,e.taskId);if(!n){if(e.toolCallId===void 0){let o=this.pendingTerminalsByTaskId.get(e.taskId);this.pendingTerminalsByTaskId.set(e.taskId,{status:o?.status??e.status,output:o?.output??e.output,progress:o?.progress&&e.progress?{...o.progress,...e.progress}:o?.progress??e.progress})}return tz}let r=this.mergeTerminal(n,e.status,e.output,e.progress);return r?L2t(r):tz}transitionResultBatch(e){let n=new Map,r=e.asyncLaunchTaskId?this.launchAckOwner(e.asyncLaunchTaskId,e.results):void 0;r&&n.set(r,{kind:"omit"});let o=e.asyncLaunchTaskId&&!r&&!this.launchToolCallIdByTaskId.has(e.asyncLaunchTaskId)&&e.results.filter(({toolCallId:i})=>this.launchesByToolCallId.get(i)?.phase==="awaiting_identity").length>1?e.asyncLaunchTaskId:void 0;for(let{toolCallId:i,status:s}of e.results){let a=this.launchesByToolCallId.get(i);a&&i!==r&&(a.phase==="awaiting_identity"&&o?this.launchesByToolCallId.set(i,{...a,candidateTaskId:o}):(a.phase==="terminal"&&n.set(i,{kind:"preserve_status",status:a.terminalStatus}),this.markForegroundResult(a,s)))}return n.size===0?tz:{updates:F2t,resultActions:n}}bindLaunch(e,n){let r=this.launchesByToolCallId.get(e);if(!r||r.phase==="active"&&r.taskId!==n||r.phase==="terminal"&&r.taskId&&r.taskId!==n)return;let o=this.launchToolCallIdByTaskId.get(n);if(o&&o!==e)return;if(r.phase==="awaiting_identity"&&r.candidateTaskId!==void 0){if(r.candidateTaskId!==n)return;this.pruneAmbiguousCandidates(n,e)}let i;r.phase==="awaiting_identity"?i={phase:"active",toolCallId:e,taskId:n}:r.phase==="terminal"?i={...r,taskId:n}:i=r,this.launchesByToolCallId.set(e,i),this.launchToolCallIdByTaskId.set(n,e);let s=this.pendingTerminalsByTaskId.get(n);if(!s)return i;this.pendingTerminalsByTaskId.delete(n);let a=this.mergeTerminal(i,s.status,s.output,s.progress);return a&&this.replayedUpdates.push(a),this.launchesByToolCallId.get(e)}resolveLaunch(e,n){let r=e??this.launchToolCallIdByTaskId.get(n);return r?this.bindLaunch(r,n):void 0}launchAckOwner(e,n){let r=this.launchToolCallIdByTaskId.get(e);if(r)return n.some(({toolCallId:i})=>i===r)?r:void 0;let o=n.filter(({toolCallId:i})=>this.launchesByToolCallId.get(i)?.phase==="awaiting_identity");if(o.length===1)return this.bindLaunch(o[0].toolCallId,e)?.toolCallId}pruneAmbiguousCandidates(e,n){for(let[r,o]of this.launchesByToolCallId)r!==n&&o.phase==="awaiting_identity"&&o.candidateTaskId===e&&this.launchesByToolCallId.delete(r)}markForegroundResult(e,n){if(e.phase==="terminal"){e.outputAvailable||this.launchesByToolCallId.set(e.toolCallId,{...e,outputAvailable:!0});return}this.launchesByToolCallId.set(e.toolCallId,{phase:"terminal",toolCallId:e.toolCallId,...e.phase==="active"?{taskId:e.taskId}:{},terminalStatus:n,outputAvailable:!0})}mergeTerminal(e,n,r,o){return e.phase==="terminal"?!r||e.outputAvailable?void 0:(this.launchesByToolCallId.set(e.toolCallId,{...e,outputAvailable:!0}),{toolCallId:e.toolCallId,status:e.terminalStatus,content:$2t(r),...o?{progress:o}:{}}):(this.launchesByToolCallId.set(e.toolCallId,{phase:"terminal",toolCallId:e.toolCallId,taskId:e.taskId,terminalStatus:n,outputAvailable:r!==void 0}),{toolCallId:e.toolCallId,status:n,...r?{content:$2t(r)}:{},...o?{progress:o}:{}})}}});function Per(t){let e=/^mcp__(.+?)__(.+)$/.exec(t);return e?{server:e[1],tool:e[2]}:null}function cb(t){let e=Per(t);return e?{tool:e.tool,mcpServer:e.server}:{tool:t}}var Bpe=b(()=>{});function nz(t,e,n){let r={vendorToolName:t};return e&&(r.parentToolCallId=e),!n&&t==="ExitPlanMode"&&(r.isPlanProposal=!0),r}function eY(t,e){if(!e&&(t==="ExitPlanMode"||t==="EnterPlanMode"))return"switch_mode";let n=t.toLowerCase();return n==="read"||n==="glob"||n==="grep"||n==="ls"?"read":n==="write"||n==="edit"||n==="multiedit"||n==="notebookedit"?"edit":n==="bash"?"execute":n==="websearch"||n==="webfetch"?"fetch":n==="todowrite"||n==="task"||n==="agent"?"think":"other"}function zpe(t,e,n){if(typeof n=="string"&&n.length>0)return n;let r=e;if(r&&typeof r=="object"){if(typeof r.path=="string")return`${t} ${r.path}`;if(typeof r.file_path=="string")return`${t} ${r.file_path}`;if(typeof r.command=="string")return`${t}: ${j2t(r.command,60)}`;if(typeof r.pattern=="string")return`${t} ${j2t(r.pattern,60)}`;if(typeof r.url=="string")return`${t} ${r.url}`}return t}function j2t(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}var H4e=b(()=>{});function H2t(t,e){return{toolUseBlocks:new Map,emittedToolUseIds:new Set,backgroundTasks:e??new WR,claudeTasks:t??X7()}}function Qy(t,e){return{sessionId:t,update:e}}function W2t(t,e,n){switch(t.type){case"stream_event":return Oer(t,e,n);case"assistant":return Ner(t,e,n);case"user":return Ler(t,e,n);case"system":return Mer(t,e,n);case"result":return Aer(t,e,n);default:return[]}}function Aer(t,e,n){let r=n.lastAssistantUsage;if(!r)return[];let o={usedTokens:r.usedTokens,contextWindow:Eer(t.modelUsage,r.model),inputTokens:r.inputTokens,outputTokens:r.outputTokens,cacheReadTokens:r.cacheReadTokens,cacheWriteTokens:r.cacheWriteTokens,updatedAt:Date.now()};return[Qy(e,{sessionUpdate:"usage_update",usage:o})]}function Eer(t,e){let n=Object.entries(t);if(n.length===0)return;if(e){let o=t[e];if(o)return o.contextWindow;let i=n.find(([s])=>s.startsWith(e));if(i)return i[1].contextWindow}return n.reduce((o,i)=>B2t(i[1])>B2t(o[1])?i:o)[1].contextWindow}function B2t(t){return t.inputTokens+t.outputTokens+t.cacheReadInputTokens+t.cacheCreationInputTokens}function Mer(t,e,n){let r=n.backgroundTasks.accept({kind:"sdk_message",message:t});return G2t(e,r.updates)}function V2t(t){return t.subtype==="success"?"end_turn":"cancelled"}function Oer(t,e,n){let r=t.parent_tool_use_id??void 0,o=t.event;switch(o.type){case"message_start":return n.toolUseBlocks.clear(),[];case"content_block_start":{let i=o.content_block;if(i.type==="tool_use"){let{tool:s,mcpServer:a}=cb(i.name);K2t(n,i.id,s,a),n.toolUseBlocks.set(o.index,{id:i.id,name:s,mcpServer:a,inputJsonAcc:"",lastParsedInput:i.input??{}}),n.emittedToolUseIds.add(i.id);let l=[Qy(e,q2t(i.id,i.name,i.input??{},r))];return!a&&s==="EnterPlanMode"&&l.push(Qy(e,{sessionUpdate:"current_mode_update",currentModeId:"plan"})),l.push(...Hpe(e,n,i.id,s,a,r,i.input??{})),l}return[]}case"content_block_delta":{let i=o.delta;if(i.type==="text_delta")return[Qy(e,{sessionUpdate:"agent_message_chunk",content:{type:"text",text:i.text}})];if(i.type==="thinking_delta")return[Qy(e,{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:i.thinking}})];if(i.type==="input_json_delta"){let s=n.toolUseBlocks.get(o.index);if(!s)return[];if(s.inputJsonAcc+=i.partial_json,!Der(s.inputJsonAcc))return[];let a=z2t(s.inputJsonAcc);return a.ok?(s.lastParsedInput=a.value,[Qy(e,{sessionUpdate:"tool_call_update",toolCallId:s.id,rawInput:a.value,...nz(s.name,r,s.mcpServer)}),...Hpe(e,n,s.id,s.name,s.mcpServer,r,a.value)]):[]}return[]}case"content_block_stop":{let i=n.toolUseBlocks.get(o.index);if(!i)return[];let s=z2t(i.inputJsonAcc),a=s.ok?s.value:i.lastParsedInput;return i.lastParsedInput=a,[Qy(e,{sessionUpdate:"tool_call_update",toolCallId:i.id,rawInput:a,status:"in_progress",...nz(i.name,r,i.mcpServer)}),...Hpe(e,n,i.id,i.name,i.mcpServer,r,a)]}case"message_delta":case"message_stop":default:return[]}}function Ner(t,e,n){let r=[],o=t.message,i=t.parent_tool_use_id??void 0;i===void 0&&o.usage&&(n.lastAssistantUsage=Rer(o.usage,o.model));let s=o.content;if(!Array.isArray(s))return r;for(let a of s){let l=a;if(l.type!=="tool_use"||!l.id||!l.name)continue;let{tool:c,mcpServer:u}=cb(l.name);K2t(n,l.id,c,u),!n.emittedToolUseIds.has(l.id)&&(n.emittedToolUseIds.add(l.id),r.push(Qy(e,q2t(l.id,l.name,l.input??{},i))),r.push(...Hpe(e,n,l.id,c,u,i,l.input??{})))}return r}function Rer(t,e){let n=t.input_tokens??0,r=t.output_tokens??0,o=t.cache_read_input_tokens??0,i=t.cache_creation_input_tokens??0;return{usedTokens:n+o+i+r,inputTokens:n,outputTokens:r,cacheReadTokens:o,cacheWriteTokens:i,model:e??""}}function Hpe(t,e,n,r,o,i,s){if(o||i)return[];let a=N2t(e.claudeTasks,n,r,s);return a?[Qy(t,a)]:[]}function Ler(t,e,n){let r=t.message.content;if(!Array.isArray(r))return[];let o=n.backgroundTasks.accept({kind:"sdk_message",message:t}),i=[];for(let s of r){let a=s;if(a.type!=="tool_result"||!a.tool_use_id)continue;let l=o.resultActions.get(a.tool_use_id);if(l?.kind==="omit")continue;let c;l?.kind==="preserve_status"?c=l.status:c=a.is_error?"failed":"completed";let u=$er(a.content);i.push(Qy(e,{sessionUpdate:"tool_call_update",toolCallId:a.tool_use_id,status:c,content:u}));let d=R2t(n.claudeTasks,a.tool_use_id,a.is_error?null:a.content);!a.is_error&&d&&i.push(Qy(e,d))}return i.push(...G2t(e,o.updates)),i}function q2t(t,e,n,r){let{tool:o,mcpServer:i}=cb(e);return{sessionUpdate:"tool_call",toolCallId:t,title:zpe(o,n),kind:eY(o,i),status:"in_progress",rawInput:n,mcpServer:i,...nz(o,r,i)}}function K2t(t,e,n,r){t.backgroundTasks.accept({kind:"tool_snapshot",toolCallId:e,nativeToolName:r?void 0:n})}function G2t(t,e){return e.map(n=>Qy(t,{sessionUpdate:"tool_call_update",...n}))}function $er(t){if(typeof t=="string")return[{type:"content",content:{type:"text",text:t}}];if(!Array.isArray(t))return;let e=[];for(let n of t){let r=n;r.type==="text"&&typeof r.text=="string"&&e.push({type:"content",content:{type:"text",text:r.text}})}return e.length>0?e:void 0}function z2t(t){if(t.trim().length===0)return{ok:!0,value:{}};try{return{ok:!0,value:JSON.parse(t)}}catch{return{ok:!1}}}function Der(t){let e=t.length-1;for(;e>=0;){let n=t.charCodeAt(e);if(n===32||n===9||n===10||n===13){e--;continue}return n===125||n===93||n===34||n===101||n===108||n>=48&&n<=57}return!1}var Z2t=b(()=>{Bpe();j4e();H4e();z4e()});var eA,Wpe,tY,rz=b(()=>{eA=["allow_once","allow_always","reject_once","reject_always"],Wpe=["allow_once","allow_always"],tY=["reject_once","reject_always"]});function Si(t){return typeof t!="string"?"":t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Y2t(t){return typeof t!="string"?"":t.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&")}var nY=b(()=>{});function oz(t){return t.sourceType==="web"}function iz(t){return t.sourceType==="note"}var rY=b(()=>{});function qpe(t){return t===void 0?!0:Fer.has(t)}function rUt(t){let e={};for(let n of Object.keys(t.answers))e[n]={...t.answers[n]};return{answers:e,summary:{...t.summary}}}function iUt(t){return t.length===0?null:`<prior_turns>
Earlier in this conversation you ran the following multi-agent turn(s). Each shows the user's question and the summary that was already shown to the user. Treat these as conversation history for continuity; do not redo or re-answer them.
${t.map(n=>`<multi_agent_turn>
<question>
${Si(n.question)}
</question>
<summary>
${Si(n.summary)}
</summary>
</multi_agent_turn>`).join(`
`)}
</prior_turns>`}function q4e(t,e,n){return t.length<=e?t:`${t.slice(0,e)}
${n}`}function zer(t){if(!t)return 0;let e=0;for(let n of t){if(typeof n!="object"||n===null)continue;let r=n.type;(r==="image"||r==="image_url")&&(e+=1)}return e}function Her(t){if(!t)return[];let e=[];for(let r of t.selectedTextContexts??[]){let o=iz(r)?r.noteTitle:oz(r)?r.title||r.url:"selection",i=q4e(r.content.trim(),Ber,aUt);e.push(`[selected from ${o}]
${i}`)}let n=(t.notes??[]).map(r=>r.path);if(n.length>0&&e.push(`[notes: ${n.join(", ")}]`),t.folders&&t.folders.length>0&&e.push(`[folders: ${t.folders.join(", ")}]`),t.urls&&t.urls.length>0&&e.push(`[urls: ${t.urls.join(", ")}]`),t.tags&&t.tags.length>0&&e.push(`[tags: ${t.tags.join(", ")}]`),t.webTabs&&t.webTabs.length>0){let r=t.webTabs.map(o=>o.title?`${o.title} (${o.url})`:o.url).join(", ");e.push(`[web tabs: ${r}]`)}return e.length===0?[]:[`[context]
${e.join(`
`)}`]}function Wer(t){let e=t.fanout??K4e(t.message);return e?oY(e,n=>n):t.message}function Ver(t){let e=[],n=Wer(t).trim();n.length>0&&e.push(n);let r=zer(t.content);if(r>0){let o=r===1?"image attachment":"image attachments";e.push(`[${r} ${o} omitted from history; existed in this turn]`)}return e.push(...Her(t.context)),e.length===0?null:e.join(`
`)}function lUt(t,e){let n=[];for(let a of t){let l=Ver(a);if(l===null)continue;let c=a.sender===ar?"user":"assistant";n.push(`<turn role="${c}">
${Si(l)}
</turn>`)}if(n.length===0)return null;let r=n.reduce((a,l)=>a+l.length+1,-1),o=!1;for(;n.length>1&&r>e;)r-=n.shift().length+1,o=!0;let i=n.join(`
`);i.length>e&&(i=q4e(i,e,aUt),o=!0);let s="Earlier in this conversation the following was said. Treat this as read-only context to inform your answer; do NOT redo or re-answer these earlier turns. Answer only the current question that follows.";return o&&(i=`${jer}
${i}`),`<conversation_history>
${s}
${i}
</conversation_history>`}function Kpe(t){let e=[],n=[];for(let r of Object.keys(t.answers)){let o=t.answers[r],i=o.text.trim();o.status==="done"&&i.length>0?e.push({backendId:r,text:i}):n.push(r)}return{succeeded:e,failed:n}}function cUt(t,e,n){if(e.succeeded.length===0)return null;let r=e.succeeded.map(({backendId:i,text:s})=>`### ${n(i)}
${q4e(s,qer,Ker)}`);return[{type:"text",text:[Uer,`## Question
${t.trim()}`,`## Agent answers
${r.join(`
`)}`].join(`
`)}]}function W4e(t){return t.split(Gpe).join(fUt).split(pUt).join(mUt)}function Qer(t){return t.split(mUt).join(pUt).split(fUt).join(Gpe)}function X2t(t){return t.length<=J2t?t:`${t.slice(0,J2t)}
${Ger}`}function Zpe(t,e){let{succeeded:n}=Kpe(t),r=new Set(n.map(s=>s.backendId)),o=t.summary.text.trim(),i=[Yer,dUt,"### Summary"];o.length>0&&i.push(W4e(o));for(let s of Object.keys(t.answers)){let a=e(s),l=` name="${sz(a)}"`,c=t.answers[s];if(r.has(s))i.push(`<!--copilot:agent id="${sz(s)}"${l} status="done"-->`,`### ${a}`,W4e(X2t(c.text.trim())));else{let u=c.status==="error"&&c.error?` error="${sz(c.error)}"`:"",d=` status="${sz(c.status)}"`,f=c.text.trim();f.length>0?i.push(`<!--copilot:agent id="${sz(s)}"${l}${d}${u}-->`,`### ${a}`,W4e(X2t(f))):i.push(`<!--copilot:agent id="${sz(s)}"${l}${d}${u} note="${hUt}"-->`)}}return i.push(uUt),i.join(`
`)}function oY(t,e){let{succeeded:n}=Kpe(t),r=new Set(n.map(s=>s.backendId)),o=[],i=t.summary.text.trim();o.push(i.length>0?`### Summary
${i}`:"### Summary");for(let s of Object.keys(t.answers)){let a=e(s),l=t.answers[s];if(r.has(s))o.push(`### ${a}
${l.text.trim()}`);else{let c=l.text.trim();o.push(c.length>0?`### ${a}
${c}`:`### ${a}
_${hUt}_`)}}return o.join(`
`)}function sz(t){return t.replace(/--/g,"\u2014").replace(/"/g,"'").replace(/>/g,"\u203A")}function Vpe(t,e){let n=t.match(new RegExp(`${e}="([^"]*)"`));return n?n[1]:void 0}function etr(t){return t==="done"||t==="error"||t==="cancelled"?t:"error"}function K4e(t){if(!Jer.test(t)||!t.includes(uUt))return null;let e={},n="",r=/<!--copilot:(summary|agent[^>]*|multi-agent(?:-end)?[^>]*)-->/g,o=[],i,s=null,a=0;for(;(i=r.exec(t))!==null;)s!==null&&o.push({marker:s,body:t.slice(a,i.index)}),s=i[0],a=r.lastIndex;s!==null&&o.push({marker:s,body:t.slice(a)});for(let l of o){if(l.marker.startsWith("<!--copilot:multi-agent"))continue;let c=ttr(Qer(l.body)).trim();if(l.marker===dUt){n=c;continue}let u=Vpe(l.marker,"id");if(!u)continue;let d=etr(Vpe(l.marker,"status")),f=Vpe(l.marker,"note"),p=Vpe(l.marker,"error");e[u]={backendId:u,status:d,text:f!==void 0?"":c,...p!==void 0?{error:p}:{}}}return n.length===0&&Object.keys(e).length===0?null:{answers:e,summary:{status:"done",text:n}}}function ttr(t){let e=t.split(`
`),n=0;for(;n<e.length&&e[n].trim()==="";)n+=1;return n<e.length&&/^#{1,6}\s/.test(e[n].trim())?e.slice(n+1).join(`
`):t}var V4e,Q2t,eUt,tUt,nUt,Fer,Uer,oUt,ypo,sUt,jer,aUt,Ber,qer,Ker,J2t,Ger,Zer,Yer,Jer,uUt,dUt,Gpe,fUt,Xer,pUt,mUt,hUt,tA=b(()=>{gt();nY();rY();V4e="You are answering a read-only question. Do NOT modify any files, run any commands that change state, or execute write/shell tools \u2014 answer only. You may freely read, search, grep, and fetch to inform your answer. Respond with your analysis directly.",Q2t=5*60*1e3,eUt="Timed out waiting for this agent to answer.",tUt=3*1e3,nUt=500,Fer=new Set(["edit","delete","move"]);Uer=`You are a neutral synthesizer. The labeled blocks below are what SEVERAL DIFFERENT AI agents each produced in response to the user's request. Write a synthesis for the user ABOUT their outputs \u2014 you are reporting on what the agents produced, not doing the task yourself.
VOICE (always):
- Third person, attributing each point to the agent by name (convert the agents' "I/my" into "<agent> \u2026"). NEVER write in the first person or as if the request were made of you; no sentence may begin with "I".
- Use ONLY the outputs shown; ignore any environment scaffolding (tool lists, available skills/agents, boilerplate). Do not mention how many agents there were, who did not respond, or anything missing.
FORMAT (always): clean, scannable Markdown, and be concise. Lead with the bottom line in one or two sentences, THEN the sections below as \`###\` subheadings \u2014 each on its own line, preceded by a blank line, with one or two short paragraphs under it. Do NOT pack points into dense bullet lists; prefer short paragraphs and whitespace, and use a bullet list only for 3+ genuinely parallel items, one line each, never nested.
FIRST pick the MODE from the request and the outputs:
- ANSWER mode \u2014 the agents answered a question or analyzed something (facts, explanation, a recommendation, identity); there is a best answer to converge on.
- DELIVERABLE mode \u2014 the agents each produced an ALTERNATIVE ARTIFACT the user will choose from or use (a rewrite, draft, message, translation, code, plan, design); these are options, not competing claims.
If only ONE agent responded (either mode): one to three sentences on its answer or approach, attributed, no headings.
TWO OR MORE in ANSWER mode \u2014 lead with the bottom line, then these \`###\` sections, omitting any that would be empty:
### Each agent
A short attributed paragraph for each agent's take.
### Agreements
The points the agents share.
### Disagreements
Where they differ, naming the sides.
TWO OR MORE in DELIVERABLE mode \u2014 lead with the bottom line, then help the user CHOOSE or MERGE (NOT agreements/disagreements), as \`###\` sections:
### Options
A short attributed paragraph per agent on what is DISTINCTIVE about its take \u2014 the angle, tone, structure, or tradeoff that would make someone pick it, and who it suits.
### Recommendation
Name the best option for the likely goal and why; if a combination is clearly better, say which parts of which to merge.
Do NOT reproduce the artifacts (the user already has each in its own tab); describe the approach only.
Do NOT modify any files or run write/shell tools.`,oUt="All agents failed to answer; no summary could be generated.",ypo=Object.freeze([]);sUt=48e3,jer="[earlier conversation truncated]",aUt="[turn truncated]",Ber=2e3;qer=12e3,Ker="[answer truncated]";J2t=24e3,Ger="[answer truncated]",Zer=1,Yer=`<!--copilot:multi-agent v=${Zer}-->`,Jer=/<!--copilot:multi-agent v=\d+-->/,uUt="<!--copilot:multi-agent-end-->",dUt="<!--copilot:summary-->",Gpe="\uE000",fUt=`${Gpe}0`,Xer=`${Gpe}1`,pUt="<!--copilot:",mUt=`<!--copilot${Xer}`;hUt="did not answer"});function yUt(t){gUt=t}function dtr(t,e){let n=mtr(t),r=e.join(e.tmpdir(),...itr,n);return{dirPath:r,logPath:e.join(r,ntr),rotatedPath:e.join(r,rtr)}}function ftr(){try{let t=Pe("fs/promises"),e=Pe("os"),n=Pe("path"),r=require("electron"),o=r.shell??r.remote?.shell;return{tmpdir:()=>e.tmpdir(),join:(...i)=>n.join(...i),dirname:i=>n.dirname(i),mkdir:async(i,s)=>{await t.mkdir(i,s)},appendFile:t.appendFile,writeFile:t.writeFile,rm:t.rm,stat:t.stat,rename:t.rename,openPath:o?.openPath?.bind(o),showItemInFolder:o?.showItemInFolder?.bind(o)}}catch{return null}}async function ptr(t,e){try{await t.stat(e)}catch{await t.writeFile(e,"","utf8")}}async function Z4e(t,e){try{await t.rm(e,{force:!0})}catch{}}function mtr(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619);return(e>>>0).toString(16).padStart(8,"0")}function htr(t){if(!t||typeof t!="object")return String(t);let e=t,n=e.update,r=[];return typeof e.method=="string"&&r.push(`method=${e.method}`),n&&typeof n.sessionUpdate=="string"&&(r.push(`sessionUpdate=${n.sessionUpdate}`),typeof n.toolCallId=="string"&&r.push(`toolCallId=${n.toolCallId}`)),r.join(" ")||"<no summary>"}function VR(t){if(t===void 0)return"";let e;try{e=JSON.stringify(t)}catch{e=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?String(t):Object.prototype.toString.call(t)}return e.length<=G4e?e:e.slice(0,G4e)+`\u2026(+${e.length-G4e})`}var ntr,rtr,otr,itr,str,atr,ltr,ctr,utr,G4e,gUt,Y4e,$k,iY=b(()=>{$n();ntr="acp-frames.ndjson",rtr="acp-frames.old.ndjson",otr="(Agent Mode frame logs are desktop-only)",itr=["obsidian-copilot","acp-frames"],str=50*1024*1024,atr=64*1024,ltr=32,ctr=8*1024*1024,utr=25,G4e=400,gUt=null;Y4e=class{constructor(e={}){this.options=e;this.writeChain=Promise.resolve();this.ensuredDirPath=null;this.writeCount=0;this.pendingFrames=0;this.pendingBytes=0;this.droppedSinceLastWrite=0}getPath(){return this.resolvePaths()?.logPath??otr}append(e){let n=this.resolvePaths();if(!n)return;let r=this.toLine(e);if(this.pendingFrames>=ltr||this.pendingBytes+r.length>ctr){this.droppedSinceLastWrite++;return}let o=r.length;this.pendingFrames++,this.pendingBytes+=o,this.writeChain=this.writeChain.then(()=>this.doAppend(n,r)).then(()=>{this.pendingFrames--,this.pendingBytes-=o},()=>{this.pendingFrames--,this.pendingBytes-=o})}async clear(){let e=this.writeChain.then(async()=>{let n=this.resolvePaths();if(!n)return;let r=this.getRuntime();r&&(await Z4e(r,n.logPath),await Z4e(r,n.rotatedPath))});return this.writeChain=e.catch(()=>{}),e}async open(){let e=this.writeChain.then(async()=>{let o=this.resolvePaths();if(!o)return;let i=this.getRuntime();i&&(await this.ensureFolder(i,o.dirPath),await ptr(i,o.logPath))});this.writeChain=e.catch(()=>{}),await e;let n=this.resolvePaths();if(!n)return;let r=this.getRuntime();if(r){if(r.openPath){let o=await r.openPath(n.logPath);if(typeof o=="string"&&o.length>0)throw new Error(o);return}if(r.showItemInFolder){r.showItemInFolder(n.logPath);return}throw new Error("No OS file opener is available.")}}async flush(){await this.writeChain}resolvePaths(){let e=this.getRuntime();if(!e)return null;let n=this.options.vaultBasePath??gUt;return n?dtr(n,e):null}getRuntime(){return this.options.runtime??ftr()}async ensureFolder(e,n){this.ensuredDirPath!==n&&(await e.mkdir(n,{recursive:!0}),this.ensuredDirPath=n)}toLine(e){let n;try{n=JSON.stringify(e)+`
`}catch{return JSON.stringify({...e,payload:{__unserializable:!0}})+`
`}if(n.length<=atr)return n;let r=0;try{r=JSON.stringify(e.payload).length}catch{r=0}return JSON.stringify({...e,payload:{__truncated:!0,originalBytes:r,summary:htr(e.payload)}})+`
`}async doAppend(e,n){let r=this.getRuntime();if(!r)return;let o=n;if(this.droppedSinceLastWrite>0){let i=this.droppedSinceLastWrite;this.droppedSinceLastWrite=0,o=JSON.stringify({ts:new Date().toISOString(),dir:"\u2192",tag:"frameSink",kind:"raw",method:"frameSink.dropped",id:null,payload:{dropped:i}})+`
`+n}try{await this.ensureFolder(r,e.dirPath),await r.appendFile(e.logPath,o,"utf8")}catch{try{await r.mkdir(r.dirname(e.logPath),{recursive:!0}),await r.writeFile(e.logPath,o,"utf8")}catch{return}}this.writeCount++,this.writeCount%utr===0&&await this.maybeRotate(r,e)}async maybeRotate(e,n){try{if((await e.stat(n.logPath)).size<str)return;await Z4e(e,n.rotatedPath),await e.rename(n.logPath,n.rotatedPath)}catch{}}};$k=new Y4e});function Ype(t,e=$k){let n=t.id??null,r=n!==null?`#${n}`:t.kind==="notif"?"(notif)":"(no-id)";j(`[ACP ${t.dir}][${vUt}] ${t.method} ${r} ${VR(t.payload)}`),Y().agentMode?.debugFullFrames&&e.append({ts:new Date().toISOString(),dir:t.dir,tag:vUt,kind:t.kind??(t.dir==="\u2192"?"request":"notif"),method:t.method,id:n,payload:t.payload})}function Yh(t,e,n,r){Ype({dir:"\u2192",method:t,id:n,payload:e,kind:"request"},r)}function Jpe(t,e,n,r){Ype({dir:"\u2192",method:t,id:n,payload:e,kind:"result"},r)}function sY(t,e,n,r){Ype({dir:"\u2190",method:t,id:n,payload:e,kind:"notif"},r)}function az(t,e,n,r,o){Ype({dir:t,method:e,id:r,payload:n,kind:"error"},o)}function wUt(t){let e=t;if(!e||typeof e.type!="string")return"(unknown)";if(e.type==="stream_event"){let n=e.event&&typeof e.event=="object"?e.event:null;return`stream_event:${n&&typeof n.type=="string"?n.type:"?"}`}return e.type==="result"&&typeof e.subtype=="string"?`result:${e.subtype}`:e.type}var vUt,J4e=b(()=>{pe();Se();iY();vUt="claude-sdk"});function wtr(t,e,n,r){let{tool:o,mcpServer:i}=cb(t);return{sessionId:n,toolCall:{toolCallId:r.toolUseID,kind:eY(o,i),status:"pending",title:zpe(o,e,typeof r.title=="string"?r.title:void 0),rawInput:e,mcpServer:i,...nz(o,void 0,i)},options:ytr}}function btr(t,e,n){if(t.outcome.outcome==="cancelled")return{behavior:"deny",message:"User cancelled"};switch(vtr.has(t.outcome.optionId)?t.outcome.optionId:"reject_once"){case"allow_once":return{behavior:"allow",updatedInput:n};case"allow_always":return{behavior:"allow",updatedInput:n,updatedPermissions:e??[]};case"reject_once":case"reject_always":return{behavior:"deny",message:t.denyMessage??"User declined"}}}var Xpe,gtr,ytr,vtr,bUt=b(()=>{rz();Bpe();tA();ut();J4e();H4e();Xpe=class{constructor(e){this.opts=e;this.currentSessionId=null;this.canUseTool=async(e,n,r)=>{if(e==="AskUserQuestion")return this.handleAskUserQuestion(n,r);let o=this.currentSessionId;sY("canUseTool:request",{toolName:e,input:n,suggestions:r.suggestions},o);let i=this.opts.getIsReadOnlySession?.();if(o&&i?.(o)){let{tool:u,mcpServer:d}=cb(e),f=eY(u,d),p=!!d&&f==="other";if(qpe(f)||p)return this.deny("canUseTool:response","Read-only QA turn: vault-write tools are disabled.",o)}if(e==="Write"){let u=typeof n.file_path=="string"?n.file_path:null;if(u&&this.opts.isPlanModePlanFilePath?.(u)){let d={behavior:"allow",updatedInput:n};return Yh("canUseTool:response:auto-allow-plan",d,o),d}}let s=this.opts.getPrompter();if(!s)return this.deny("canUseTool:response","No permission prompter available",o);if(!o)return this.deny("canUseTool:response","Permission requested outside a session",o);let a=wtr(e,n,o,r),l=await s(a),c=btr(l,r.suggestions,n);return Yh("canUseTool:response",c,o),c}}setSessionContext(e){this.currentSessionId=e}clearSessionContext(){this.currentSessionId=null}async handleAskUserQuestion(e,n){let r=this.currentSessionId;sY("askUserQuestion:request",e,r);let o=this.opts.getAskUserQuestionPrompter?.()??null;if(!o||!r)return this.deny("askUserQuestion:response","AskUserQuestion is not yet supported",r);try{let i=await o({sessionId:r,requestId:n.toolUseID,questions:e.questions});if(Object.keys(i).length===0)return this.deny("askUserQuestion:response","User cancelled the question",r);let s={behavior:"allow",updatedInput:{questions:e.questions,answers:i}};return Yh("askUserQuestion:response",s,r),s}catch(i){return this.deny("askUserQuestion:response",`AskUserQuestion failed: ${kt(i)}`,r)}}deny(e,n,r){let o={behavior:"deny",message:n};return Yh(e,o,r),o}},gtr={allow_once:"Allow once",allow_always:"Allow always",reject_once:"Deny once",reject_always:"Deny always"},ytr=eA.map(t=>({optionId:t,name:gtr[t],kind:t})),vtr=new Set(eA)});function Qpe(t,e){let n=t?.supportsEffort?t.supportedEffortLevels??[]:[];return n.length===0?null:{id:"effort",type:"select",category:"thought_level",name:"Effort",currentValue:e&&n.includes(e)?e:n[0],options:n.map(o=>({value:o,name:o}))}}function Q4e(t,e){return e&&t.some(n=>n.value===e)?e:(e&&W(`[AgentMode] persisted Claude model "${e}" not in live catalog; falling back to default`),t[0]?.value)}function _Ut(t){let e=Object.entries(t??{}).sort(([n],[r])=>n.localeCompare(r));return JSON.stringify(e)}function eme(t){return X4e?.key===_Ut(t)?X4e.models:null}async function xUt(t,e){let n=async function*(){await new Promise(()=>{})}(),r={pathToClaudeCodeExecutable:t};e&&Object.keys(e).length>0&&(r.env={...process.env,...e});let o=Fpe({prompt:n,options:r});try{let i=await o.initializationResult();return i.models.length>0&&(X4e={key:_Ut(e),models:i.models}),i.models}catch(i){return W("[AgentMode] Claude SDK init probe failed",i),[]}finally{try{await o.interrupt()}catch{}}}var X4e,eHe=b(()=>{R4e();pe();X4e=null});function xtr(t){if(t.type!=="stream_event")return null;let e=t.event?.type;return typeof e=="string"?e:null}function Str(t){return t==="content_block_start"||t==="content_block_delta"||t==="content_block_stop"}async function*SUt(t,{abortController:e,timeoutMs:n=6e4,onStall:r}){let o=!1,i=!1,s,a=()=>{s!==void 0&&(window.clearTimeout(s),s=void 0)};try{for await(let l of t){a();let c=xtr(l);Str(c)&&(i=!0),c==="message_stop"&&(i=!1),i&&c!=="message_stop"&&(s=window.setTimeout(()=>{o=!0,r?.(n),e.abort()},n)),yield l}}catch(l){if(!o)throw l}finally{a()}if(o)throw new Error(_tr)}var _tr,CUt=b(()=>{_tr="Claude stopped responding \u2014 the response stream stalled mid-reply (no output for 60s) and the turn was ended. Send your message again to continue."});function Ttr(t){let e=t.toLowerCase();return e==="image/jpg"?"image/jpeg":e==="image/jpeg"||e==="image/png"||e==="image/gif"||e==="image/webp"?e:null}function Ptr(t){if(!t.prompt.some(r=>r.type!=="text")){let r=[];for(let o of t.prompt)o.type==="text"&&o.text.length>0&&r.push(o.text);return r.join(`
`)}let n=[];for(let r of t.prompt)if(r.type==="text")r.text.length>0&&n.push({type:"text",text:r.text});else if(r.type==="image"){let o=Ttr(r.mimeType);if(!o){W(`[AgentMode] unsupported image media type for Claude SDK: ${r.mimeType}`),n.push({type:"text",text:`[Unsupported image attachment omitted: ${r.mimeType}]`});continue}n.push({type:"image",source:{type:"base64",media_type:o,data:r.data}})}else n.push({type:"text",text:`[Attached resource: ${r.name??r.uri}]`});return n}function Atr(t){return typeof t=="string"?t:t.map(e=>e.type==="image"?{type:"image",media_type:e.source.media_type,dataLength:e.source.data.length}:e)}async function*Etr(t,e){yield{type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:e}}function Mtr(t){switch(t){case"default":case"acceptEdits":case"auto":case"bypassPermissions":case"plan":return t;default:return null}}var Ctr,ktr,Itr,tHe,nme,tme,kUt=b(()=>{pe();ut();R4e();Gf();XB();I2t();A2t();HR();ok();$n();j4e();z4e();Z2t();bUt();eHe();J4e();CUt();Ctr=new Set(["Agent","Task","Bash"]),ktr="Remote-isolated agents require background execution, which is temporarily unavailable in Copilot v4.",Itr=async t=>{if(t.hook_event_name!=="PreToolUse"||!Ctr.has(t.tool_name))return{};let e=typeof t.tool_input=="object"&&t.tool_input!==null&&!Array.isArray(t.tool_input)?t.tool_input:{};return(t.tool_name==="Agent"||t.tool_name==="Task")&&e.isolation==="remote"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:ktr}}:{hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{...e,run_in_background:!1}}}},tHe={currentModeId:"default",availableModes:[{id:"default",name:"Default"},{id:"plan",name:"Plan"},{id:"acceptEdits",name:"Accept Edits"},{id:"auto",name:"Auto"},{id:"bypassPermissions",name:"Bypass Permissions"}]},nme=class nme{constructor(e){this.opts=e;this.sessionHandlers=new Map;this.pendingUpdates=new Map;this.lastPlanUsage=null;this.sessions=new Map;this.permissionPrompter=null;this.askUserQuestionPrompter=null;this.isReadOnlySession=null;this.exitListeners=new Set;this.shuttingDown=!1;this.cachedModels=null;this.cachedModelsProbe=null;this.authConfirmed=!1;this.compatibilityConfirmed=!1;this.compatibilityProbe=null;this.resolvedConfigDir=null;this.bridge=new Xpe({getPrompter:()=>this.permissionPrompter,getAskUserQuestionPrompter:()=>this.askUserQuestionPrompter,isPlanModePlanFilePath:e.isPlanModePlanFilePath,getIsReadOnlySession:()=>this.isReadOnlySession}),j(`[AgentMode] ClaudeSdkBackendProcess constructed (claude=${e.pathToClaudeCodeExecutable})`)}isRunning(){return!this.shuttingDown}onExit(e){return this.exitListeners.add(e),()=>this.exitListeners.delete(e)}setPermissionPrompter(e){this.permissionPrompter=e}setReadOnlySessionPredicate(e){this.isReadOnlySession=e}setAskUserQuestionPrompter(e){this.askUserQuestionPrompter=e}resolveSystemPromptAppend(){return this.opts.getSystemPromptAppend?.()??""}registerSessionHandler(e,n){this.sessionHandlers.set(e,n);let r=this.pendingUpdates.get(e);if(r){this.pendingUpdates.delete(e);for(let o of r)try{n(o)}catch(i){W(`[AgentMode] replay of buffered SDK event threw for ${e}`,i)}}if(this.lastPlanUsage=this.lastPlanUsage&&QP(this.lastPlanUsage),this.lastPlanUsage)try{n({sessionId:e,update:{sessionUpdate:"plan_usage_update",planUsage:this.lastPlanUsage}})}catch(o){W(`[AgentMode] replay of plan usage threw for ${e}`,o)}return()=>{this.sessionHandlers.get(e)===n&&this.sessionHandlers.delete(e)}}async newSession(e){Yh("newSession",{cwd:e.cwd,projectId:e.projectId??null}),await this.ensureCompatible();let n=Co(),r=e.cwd??null,o=await this.ensureModelCatalog(),i=this.opts.getDefaultModelId?.(),s=Q4e(o,i);this.sessions.set(n,{cwd:r,projectId:e.projectId,firstPromptStarted:!1,model:s,additionalDirectories:e.additionalDirectories,systemPromptAppend:this.resolveSystemPromptAppend(),claudeTaskPlan:X7(),backgroundTasks:new WR});let a=this.computeState(n);return Jpe("newSession",{sessionId:n,currentModelId:s??null,hasEffort:a.model!==null},n),{sessionId:n,state:a}}async prompt(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`Unknown session ${e.sessionId}`);if(this.opts.checkAuth&&!this.authConfirmed)if(await this.opts.checkAuth())this.authConfirmed=!0;else throw new Oae("You're not signed in to Claude. Use the Sign in button above the chat box to continue.");let r=Ptr(e),o=Etr(r,e.sessionId);this.bridge.setSessionContext(e.sessionId);let i={pathToClaudeCodeExecutable:this.opts.pathToClaudeCodeExecutable,cwd:n.cwd??void 0,includePartialMessages:!0,allowedTools:["Read","Write","Edit","Glob","Grep","LS"],disallowedTools:["TaskOutput","Workflow","Monitor"],canUseTool:this.bridge.canUseTool};i.systemPrompt={type:"preset",preset:"claude_code",excludeDynamicSections:!0,append:n.systemPromptAppend||void 0},n.firstPromptStarted?i.resume=e.sessionId:i.sessionId=e.sessionId,n.model&&(i.model=n.model),n.permissionMode&&(i.permissionMode=n.permissionMode),n.effort&&(i.effort=n.effort),n.additionalDirectories?.length&&(i.additionalDirectories=n.additionalDirectories),i.thinking=this.opts.getEnableThinking?.()?{type:"adaptive",display:"summarized"}:{type:"disabled"};let s=this.opts.getEnvOverrides?.(),l={...await this.opts.getManagedEnv?.()??{},...s};Object.keys(l).length>0&&(i.env={...process.env,...l}),i.hooks={PreToolUse:[{hooks:[Itr]}]},Yh("prompt",{prompt:Atr(r),resume:i.resume??null,sessionIdSeed:i.sessionId??null,model:i.model??null,permissionMode:i.permissionMode??null,effort:i.effort??null,allowedTools:i.allowedTools,disallowedTools:i.disallowedTools},e.sessionId);let c=new AbortController;i.abortController=c;let u=Fpe({prompt:o,options:i});n.active=u,n.firstPromptStarted=!0;let d=SUt(u,{abortController:c,onStall:h=>az("\u2190","stream:stalled",{idleMs:h},e.sessionId)}),f=H2t(n.claudeTaskPlan,n.backgroundTasks),p="end_turn",m=null;try{let h=!1;for await(let g of d){if(this.shuttingDown)break;sY(wUt(g),g,e.sessionId),h||(h=!0,this.refreshPlanUsage(u));let v=W2t(g,e.sessionId,f);for(let y of v)this.dispatchEvent(y);if(g.type==="result"){if(p=V2t(g),g.subtype==="success"&&g.is_error&&g.result.trim())m=g.result;else if(p!=="end_turn"&&g.subtype!=="success"){let y="errors"in g?g.errors:void 0;y&&y.length>0?m=y.join("; "):this.authConfirmed=!1}break}}}finally{n.active===u&&(n.active=void 0),this.bridge.clearSessionContext()}if(m)throw az("\u2192","prompt",{error:m},e.sessionId),new Error(m);return Jpe("prompt",{stopReason:p},e.sessionId),{stopReason:p}}async cancel(e){Yh("cancel",{},e.sessionId);let n=this.sessions.get(e.sessionId);if(n?.active)try{await n.active.interrupt()}catch(r){W("[AgentMode] SDK query.interrupt() threw",r),az("\u2192","interrupt",{error:kt(r)},e.sessionId)}}async setSessionModel(e){Yh("setSessionModel",{modelId:e.modelId},e.sessionId);let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`Unknown session ${e.sessionId}`);if(n.model=e.modelId,this.cachedModels&&n.effort){let i=this.cachedModels.find(s=>s.value===e.modelId)?.supportedEffortLevels??[];i.includes(n.effort)||(n.effort=i[0])}if(n.active)try{await n.active.setModel(e.modelId)}catch(o){W("[AgentMode] SDK query.setModel() threw (will apply on next turn)",o),az("\u2192","setModel",{error:kt(o)},e.sessionId)}let r=this.computeState(e.sessionId);return this.dispatchStateChanged(e.sessionId,r),r}isSetSessionModelSupported(){return!0}async setSessionMode(e){Yh("setSessionMode",{modeId:e.modeId},e.sessionId);let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`Unknown session ${e.sessionId}`);let r=Mtr(e.modeId);if(!r)throw new Error(`Unsupported mode ${e.modeId}`);if(n.permissionMode=r,n.active)try{await n.active.setPermissionMode(r)}catch(i){W("[AgentMode] SDK query.setPermissionMode() threw (will apply on next turn)",i),az("\u2192","setPermissionMode",{error:kt(i)},e.sessionId)}let o=this.computeState(e.sessionId);return this.dispatchStateChanged(e.sessionId,o),o}isSetSessionModeSupported(){return!0}async setSessionConfigOption(e){if(Yh("setSessionConfigOption",{configId:e.configId,value:e.value},e.sessionId),e.configId!=="effort")throw new da("session/set_config_option");let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`Unknown session ${e.sessionId}`);if(!((await this.ensureModelCatalog()).find(a=>a.value===n.model)?.supportedEffortLevels??[]).includes(e.value))throw new Error(`Effort '${e.value}' not supported by ${n.model??"default model"}`);n.effort=e.value;let s=this.computeState(e.sessionId);return this.dispatchStateChanged(e.sessionId,s),s}isSetSessionConfigOptionSupported(){return!0}async listSessions(e){throw new da("session/list")}async readPersistedTranscript(e){try{let{readFile:n}=Pe("fs/promises"),r=await this.claudeTranscriptPath(e.sessionId,e.cwd),o=await n(r,"utf8");return k2t(o)}catch(n){return W(`[AgentMode] could not read Claude transcript for ${e.sessionId}`,n),[]}}async sessionExistsLocally(e){try{let{access:n}=Pe("fs/promises");return await n(await this.claudeTranscriptPath(e.sessionId,e.cwd)),!0}catch{return!1}}async claudeTranscriptPath(e,n){let r=Pe("path"),o=(await this.resolveClaudeConfigDir()).trim(),i=n.replace(/[^a-zA-Z0-9]/g,"-");return r.join(o,"projects",i,`${e}.jsonl`)}async resolveClaudeConfigDir(){if(this.resolvedConfigDir!==null)return this.resolvedConfigDir;let e=Pe("os"),n=Pe("path"),r=this.opts.getEnvOverrides?.()??{},o=await this.opts.getManagedEnv?.()??{};return this.resolvedConfigDir=r.CLAUDE_CONFIG_DIR||o.CLAUDE_CONFIG_DIR||process.env.CLAUDE_CONFIG_DIR||n.join(e.homedir(),".claude"),this.resolvedConfigDir}async resumeSession(e){Yh("resumeSession",{cwd:e.cwd,projectId:e.projectId??null},e.sessionId),await this.ensureCompatible();let n=e.cwd??null,r=await this.ensureModelCatalog(),o=this.opts.getDefaultModelId?.(),i=Q4e(r,o);this.sessions.set(e.sessionId,{cwd:n,projectId:e.projectId,firstPromptStarted:!0,model:i,additionalDirectories:e.additionalDirectories,systemPromptAppend:this.resolveSystemPromptAppend(),claudeTaskPlan:X7(),backgroundTasks:new WR});let s=this.computeState(e.sessionId);return Jpe("resumeSession",{currentModelId:i??null,hasEffort:s.model!==null},e.sessionId),{sessionId:e.sessionId,state:s}}async loadSession(e){throw new da("session/load")}supportsAdditionalDirectories(){return!0}async shutdown(){this.shuttingDown=!0;for(let e of this.sessions.values()){let n=e.active;if(n)try{await n.interrupt()}catch(r){W("[AgentMode] interrupt during shutdown threw",r)}}this.sessions.clear(),this.sessionHandlers.clear(),this.pendingUpdates.clear();for(let e of this.exitListeners)try{e()}catch(n){W("[AgentMode] SDK exit listener threw",n)}this.exitListeners.clear()}ensureModelCatalog(){if(this.cachedModels)return Promise.resolve(this.cachedModels);let e=this.opts.getEnvOverrides?.(),n=eme(e);if(n&&n.length>0)return this.cachedModels=n,Promise.resolve(n);if(this.cachedModelsProbe)return this.cachedModelsProbe;let r=xUt(this.opts.pathToClaudeCodeExecutable,e).then(o=>(o.length>0?this.cachedModels=o:this.cachedModelsProbe=null,o));return this.cachedModelsProbe=r,r}ensureCompatible(){if(this.compatibilityConfirmed||!this.opts.checkCompatibility)return Promise.resolve();if(this.compatibilityProbe)return this.compatibilityProbe;let e=this.opts.checkCompatibility().then(()=>{this.compatibilityConfirmed=!0,this.compatibilityProbe=null},n=>{throw this.compatibilityProbe=null,n});return this.compatibilityProbe=e,e}computeState(e){let n=this.sessions.get(e),r=this.cachedModels??[],o=n?.model,i=r.length>0&&o?{currentModelId:o,availableModels:r.map(u=>({modelId:u.value,name:u.displayName,description:u.description}))}:null,s={...tHe,currentModeId:n?.permissionMode??tHe.currentModeId,availableModes:[...tHe.availableModes]},a=o?r.find(u=>u.value===o):void 0,l=Qpe(a,n?.effort);return Upe({models:i,modes:s,configOptions:l?[l]:null},this.opts.descriptor)}dispatchStateChanged(e,n){this.dispatchEvent({sessionId:e,update:{sessionUpdate:"state_changed",state:n}})}async refreshPlanUsage(e){let n=await P2t(e);if(!(this.shuttingDown||n.kind==="unavailable")){this.lastPlanUsage=n.kind==="usage"?n.planUsage:null;for(let r of this.sessionHandlers.keys())this.dispatchEvent({sessionId:r,update:{sessionUpdate:"plan_usage_update",planUsage:this.lastPlanUsage}})}}dispatchEvent(e){let n=this.sessionHandlers.get(e.sessionId);if(!n){let r=this.pendingUpdates.get(e.sessionId);if(r||(r=[],this.pendingUpdates.set(e.sessionId,r)),r.length>=nme.PENDING_UPDATE_LIMIT){let o=e.update.sessionUpdate;W(`[AgentMode] dropping SDK event for ${e.sessionId}: pending buffer full (${r.length}, kind=${o})`);return}r.push(e);return}try{n(e)}catch(r){H(`[AgentMode] SDK event handler threw for ${e.sessionId}`,r)}}};nme.PENDING_UPDATE_LIMIT=32;tme=nme});var rme,IUt=b(()=>{pe();Se();ut();$n();rme=class t{constructor(){this.cachedBaseUrl=null}static getInstance(){return t.instance||(t.instance=new t),t.instance}async resolveBaseUrl(e={}){let n=(e.overrideUrl||"").trim();if(n.length>0)return this.normalizeBaseUrl(n);if(this.cachedBaseUrl&&!e.forceRefresh)return this.cachedBaseUrl;if(!Ln())return null;let r=await this.readServiceConfig();if(r==="missing"){let i=this.getDefaultBaseUrl();return this.cachedBaseUrl=null,Y().debug&&j(`Miyo service discovery file missing; using fallback ${i}`),i}if(!r)return this.cachedBaseUrl=null,null;let o=this.normalizeBaseUrl(`http://${r.host}:${r.port}`);return this.cachedBaseUrl=o,o}normalizeBaseUrl(e){return e.trim().replace(/\/+$/,"")}getDefaultBaseUrl(){return this.normalizeBaseUrl("http://127.0.0.1:8742")}getServiceFilePaths(){let e=this.getNodeRequire();if(!e)return[];let n=e("os"),r=e("process"),o=e("path"),i=n.homedir(),s=n.platform(),a=r.env||{};if(s==="win32"){let l=(a.LOCALAPPDATA||"").trim(),c=(a.APPDATA||"").trim();return[l,o.join(i,"AppData","Local"),c,o.join(i,"AppData","Roaming")].filter((d,f,p)=>d.length>0&&p.indexOf(d)===f).map(d=>o.join(d,"Miyo","service.json"))}return s==="linux"?[o.join(i,".config","Miyo","service.json")]:s==="darwin"?[o.join(i,"Library","Application Support","Miyo","service.json")]:(W(`Miyo service discovery unsupported platform: ${s}`),[])}async readServiceConfig(){let e=this.getServiceFilePaths();if(e.length===0)return null;let n=this.getNodeRequire();if(!n)return null;let r=n("fs"),o=!1;for(let i of e)try{let s=await r.promises.readFile(i,"utf8"),a=JSON.parse(s);return!a.host||typeof a.host!="string"?(W("Miyo service discovery missing host"),null):typeof a.port!="number"||Number.isNaN(a.port)?(W("Miyo service discovery missing port"),null):(Y().debug&&j(`Miyo service discovery resolved host=${a.host} port=${a.port}`),a)}catch(s){if(this.isMissingFileError(s)){o=!0;continue}return Y().debug&&W(`Miyo service discovery failed: ${kt(s)}`),null}return o?"missing":null}isMissingFileError(e){return e?.code==="ENOENT"}getNodeRequire(){let e=window?.require;return typeof e=="function"?e:null}}});var aY,ome,jc,nA=b(()=>{pe();IUt();Se();ut();aY=require("obsidian"),ome=class ome{constructor(e){this.authSnapshot=e,this.discovery=rme.getInstance()}async resolveBaseUrl(e){let n=await this.discovery.resolveBaseUrl({overrideUrl:e});if(!n)throw new Error("Miyo base URL not available");return n}async fetchHealth(e){try{return await Bie(async()=>{let n=await this.resolveBaseUrl(e);return this.requestJson(n,"/v0/health",{method:"GET"})},ome.HEALTH_TIMEOUT_MS,"Miyo health probe")}catch(n){return W(`Miyo health fetch failed: ${kt(n)}`),null}}async isBackendAvailable(e){let n=await this.fetchHealth(e);return n?n.status!=="ok"?(W(`Miyo health check failed: status="${n.status??"unknown"}"`),!1):!0:!1}async addFolder(e,n,r){let o;try{let a=await this.resolveBaseUrl(n),l=new URL("/v0/folder",a),c=await this.buildHeaders(),u=JSON.stringify(e);r?.(),j("Miyo request:",{method:"POST",url:l.toString(),hasBody:!0,hasAuthorizationHeader:!!c.Authorization,...Y().debug?{postBody:e}:{}}),o=await(0,aY.requestUrl)({url:l.toString(),method:"POST",headers:c,contentType:"application/json",body:u,throw:!1})}catch(a){throw W(`Miyo add-folder request failed: ${kt(a)}`),a}if(o.status===409)return j("Miyo folder already registered; treating as success"),null;if(o.status===201)return this.parseResponseJson(o.json,o.text);let s=this.parseResponseJson(o.json,o.text)?.detail||o.text||"";throw W(`Miyo add-folder failed (${o.status}): ${s}`),new Error(s?`Miyo add-folder failed with status ${o.status}: ${s}`:`Miyo add-folder failed with status ${o.status}`)}async getFolder(e,n){return this.requestJson(e,"/v0/folder",{method:"GET",query:{path:n}})}async deleteFolder(e,n,r){let o=await this.resolveBaseUrl(n),i=await this.buildHeaders(),s=new URL("/v0/folder",o);r?.(),j("Miyo request:",{method:"DELETE",url:s.toString(),hasBody:!0,hasAuthorizationHeader:!!i.Authorization});let a=await(0,aY.requestUrl)({url:s.toString(),method:"DELETE",headers:i,contentType:"application/json",body:JSON.stringify({path:e}),throw:!1});if(a.status===404){j("Miyo folder already unregistered; delete is a no-op");return}if(a.status>=400){let l=this.parseResponseJson(a.json,a.text)?.detail||a.text||"";throw new Error(l?`Miyo delete-folder failed with status ${a.status}: ${l}`:`Miyo delete-folder failed with status ${a.status}`)}}async checkFolderRegistration(e,n){try{let r=await this.resolveBaseUrl(n);if(!r)return"error";let o=new URL("/v0/folder",r);o.searchParams.set("path",e);let i=await(0,aY.requestUrl)({url:o.toString(),method:"GET",headers:await this.buildHeaders(),throw:!1});return i.status===200?"registered":i.status===404?"unregistered":(W(`Miyo folder registration check failed: status=${i.status}`),"error")}catch(r){return W(`Miyo folder registration check failed: ${kt(r)}`),"error"}}async scanFolder(e,n,r=!1){return this.requestJson(e,"/v0/scan",{method:"POST",body:{path:n,force:r}})}async listFolderFiles(e,n){return this.requestJson(e,"/v0/folder/files",{method:"GET",query:{folder_name:n.folderName,title:n.title,file_path:n.filePath,mtime_after:n.mtimeAfter,mtime_before:n.mtimeBefore,offset:n.offset,limit:n.limit,order_by:n.orderBy}})}async getDocumentsByPath(e,n,r){return this.requestJson(e,"/v0/folder/documents",{method:"GET",query:{path:r,folder_name:n}})}async search(e,n,r,o,i){let s={query:r,...n?{folder_name:n}:{},limit:o,...i&&i.length>0?{filters:i}:{}};return Y().debug&&j("Miyo search request:",{baseUrl:e,payload:s}),this.requestJson(e,"/v0/search",{method:"POST",body:s})}async searchRelated(e,n,r){let o={file_path:n,...r?.folderName?{folder_name:r.folderName}:{},...typeof r?.limit=="number"?{limit:r.limit}:{},...r?.filters&&r.filters.length>0?{filters:r.filters}:{}};return this.requestJson(e,"/v0/search/related",{method:"POST",body:o})}async parseDoc(e,n,r){return this.requestJson(e,"/v0/parse-doc",{method:"POST",body:{folder_name:n,path:r}})}async buildHeaders(){let e=this.authSnapshot??Y(),n={},r=e.plusLicenseKey;return r&&(n.Authorization=`Bearer ${r}`),n}async requestJson(e,n,r){let o=new URL(n,e);r.query&&Object.entries(r.query).forEach(([c,u])=>{u!=null&&o.searchParams.set(c,String(u))});let i=r.body?JSON.stringify(r.body):void 0,s=await this.buildHeaders();j("Miyo request:",{method:r.method,url:o.toString(),hasBody:!!i,hasAuthorizationHeader:!!s.Authorization,...Y().debug&&r.method==="POST"?{postBody:r.body}:{}});let a=await(0,aY.requestUrl)({url:o.toString(),method:r.method,headers:s,contentType:i?"application/json":void 0,body:i,throw:!1});if(a.status>=400){let u=this.parseResponseJson(a.json,a.text)?.detail||a.text||"";throw W(`Miyo request failed (${a.status}): ${u}`),new Error(u?`Miyo request failed with status ${a.status}: ${u}`:`Miyo request failed with status ${a.status}`)}let l=this.parseResponseJson(a.json,a.text);return Y().debug&&j(`Miyo request ${r.method} ${o.toString()} succeeded`),l}parseResponseJson(e,n){if(typeof e=="string")try{return JSON.parse(e)}catch(r){return H(`Failed to parse Miyo JSON response: ${kt(r)}`),{}}if(e!=null)return e;if(n)try{return JSON.parse(n)}catch(r){return H(`Failed to parse Miyo text response: ${kt(r)}`),{}}return{}}};ome.HEALTH_TIMEOUT_MS=8e3;jc=ome});function Ci(t){return(t.miyoServerUrl||"").trim()}function lz(t){return t.enableMiyo?!TUt.Platform.isMobile||!!Ci(t):!1}var TUt,ime=b(()=>{TUt=require("obsidian")});function lY(){return ql.checkedAt===null||Date.now()-ql.checkedAt<=Ntr?ql:(cme===ql&&uz||(cme=ql,uz=Object.freeze({...ql,backend:sme(ql.backend),connector:sme(ql.connector),chatSync:sme(ql.chatSync),documentProcessor:sme(ql.documentProcessor)})),uz)}function AUt(t){return lY()[t]==="available"}function ume(t={}){if(Ltr(),!lz(Y()))return EUt(),Promise.resolve(ql);if(!t.force&&Btr())return Promise.resolve(ql);if(cz)return cz;let e=$tr().finally(()=>{cz===e&&(cz=null)});return cz=e,e}function EUt(){lme+=1,cz=null,ql!==nHe&&(ql=nHe,cme=null,uz=null,ame.forEach(t=>t()))}function MUt(t){return ame.add(t),()=>{ame.delete(t)}}function Ltr(){PUt||(PUt=!0,zr((t,e)=>{(t.enableMiyo!==e.enableMiyo||Ci(t)!==Ci(e))&&EUt()}))}async function $tr(){let t=lme,e=Ci(Y())||void 0,n=null;try{n=await Rtr.fetchHealth(e)}catch(r){W(`Miyo status refresh failed: ${kt(r)}`),n=null}return lme!==t||ztr(Dtr(n,Date.now())),ql}function Dtr(t,e){return!t||t.status!=="ok"?Object.freeze({backend:"unavailable",connector:"unknown",chatSync:"unknown",documentProcessor:"unknown",checkedAt:e,source:"fresh"}):Object.freeze({backend:"available",connector:Ftr(t.relay),chatSync:Utr(t.chat_sync),documentProcessor:"available",checkedAt:e,source:"fresh"})}function Ftr(t){return!t||!t.status||t.status==="unknown"?"unknown":t.status==="connected"?"available":"unavailable"}function Utr(t){return t?jtr(t.platforms)?"syncing":t.configured===!0?"available":"unavailable":"unknown"}function jtr(t){return t?Object.values(t).some(e=>e?.syncing===!0):!1}function Btr(){return ql.checkedAt!==null&&Date.now()-ql.checkedAt<=Otr}function sme(t){return t==="available"?"stale":t}function ztr(t){ql=t,lme+=1,cme=null,uz=null,ame.forEach(e=>e())}var Otr,Ntr,nHe,Rtr,ame,ql,cz,PUt,lme,cme,uz,dme=b(()=>{pe();nA();ime();Se();ut();Otr=1e4,Ntr=6e4,nHe=Object.freeze({backend:"unknown",connector:"unknown",chatSync:"unknown",documentProcessor:"unknown",checkedAt:null,source:"none"}),Rtr=new jc,ame=new Set,ql=nHe,cz=null,PUt=!1,lme=0,cme=null,uz=null});var NUt={};sr(NUt,{hasCaseInsensitiveFilesystem:()=>dz,isFileAlreadyExistsError:()=>KR,isInVaultCache:()=>xp,isNameTooLongError:()=>cY,listMarkdownFiles:()=>qR,patchFrontmatter:()=>kx,readFrontmatterViaAdapter:()=>uf,resolveFileByPath:()=>Dk,trashFile:()=>Bc});function dz(){return Cx.Platform.isWin||Cx.Platform.isMacOS||Cx.Platform.isIosApp}async function Bc(t,e){await t.fileManager.trashFile(e)}async function Dk(t,e){let n=t.vault.getAbstractFileByPath(e);return n instanceof Cx.TFile?n:await t.vault.adapter.exists(e)?OUt(t,e):null}function xp(t,e){return t.vault.getAbstractFileByPath(e)!=null}async function qR(t,e){let n=t.vault.getAbstractFileByPath(e);if(n instanceof Cx.TFolder)return t.vault.getMarkdownFiles().filter(r=>r.path.startsWith(n.path));if(await t.vault.adapter.exists(e)){let o=(await t.vault.adapter.list(e)).files.filter(s=>s.endsWith(".md")),i=[];for(let s of o)i.push(await OUt(t,s));return i}return[]}async function kx(t,e,n){let r=t.vault.getAbstractFileByPath(e);if(r instanceof Cx.TFile&&t.fileManager?.processFrontMatter){await t.fileManager.processFrontMatter(r,a=>{for(let[l,c]of Object.entries(n))a[l]=c});return}if(!await t.vault.adapter.exists(e))return;let o=await t.vault.adapter.read(e),i=o.includes(`\r
`)?`\r
`:`
`,s=o.replace(/^(\uFEFF?---\r?\n[\s\S]*?\r?\n)(---)/,(a,l,c)=>{let u=l;for(let[d,f]of Object.entries(n)){let p=typeof f=="string"?`"${f.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:String(f),m=new RegExp(`^${d}:\\s*.+`,"m");m.test(u)?u=u.replace(m,`${d}: ${p}`):u+=`${d}: ${p}${i}`}return u+c});s!==o&&await t.vault.adapter.write(e,s)}async function uf(t,e){let o=(await t.vault.adapter.read(e)).replace(/^\uFEFF/,"").match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];if(!o)return null;let i={};for(let s of o.split(/\r?\n/)){let a=s.match(/^([\w-]+):\s*(.+)/);a&&(i[a[1]]=a[2].trim().replace(/^["']|["']$/g,""))}return i}function KR(t){return t?(t instanceof Error?t.message:typeof t=="string"?t:JSON.stringify(t)).toLowerCase().includes("already exists"):!1}function cY(t){if(!t)return!1;let n=(t instanceof Error?t.message:typeof t=="string"?t:JSON.stringify(t)).toLowerCase();return n.includes("enametoolong")||n.includes("name too long")}async function OUt(t,e){let n=await t.vault.adapter.stat(e),r=e.split("/").pop()??"",o=Object.create(Cx.TFile.prototype);return Object.assign(o,{path:e,name:r,basename:r.replace(/\.md$/,""),extension:"md",stat:n??{ctime:Date.now(),mtime:Date.now(),size:0},vault:t.vault,parent:null}),o}var Cx,Jh=b(()=>{Cx=require("obsidian")});function FUt(t){return t.split(/\r?\n/).every(e=>e.trim().length===0||DUt.test(e))}async function pme(t,e){let n=ub(e,df),r=await Ix(t,n);return r?fme.test(await rA(t,r)):!0}async function mme(t,e){let n=ub(e,df),r=await Ix(t,n);return r?(await rA(t,r)).replace(fme,"$1"):""}async function hme(t,e,n){let r=ub(e,df);if(!await Ix(t,r)&&!n.trim())return;let o=await uY(t,e,n);await rA(t,o)!==n&&await vme(t,o,n)}async function UUt(t,e){try{let n=await Ix(t,ub(e,df));if(!n||!fme.test(await rA(t,n)))return;await zUt(t,n)}catch(n){W(`[Instructions] Failed to remove the generated ${df} in "${e}"`,n)}}async function jUt(t,e){return{agents:await LUt(t,ub(e,df)),claude:await LUt(t,ub(e,fz))}}async function BUt(t,e,n){try{await $Ut(t,ub(e,df),n.agents),await $Ut(t,ub(e,fz),n.claude)}catch(r){W(`[Instructions] Failed to restore instruction files in "${e}"`,r)}}async function LUt(t,e){let n=await Ix(t,e);return n?await rA(t,n):null}async function $Ut(t,e,n){let r=await Ix(t,e);if(n===null){r&&await zUt(t,r);return}if(!r){await rHe(t,e,n);return}await rA(t,r)!==n&&await vme(t,r,n)}async function zUt(t,e){xp(t,e.path)?await Bc(t,e):await t.vault.adapter.remove(e.path)}async function uY(t,e,n){let r=ub(e,df),o=await rHe(t,r,n);return await Wtr(t,o,n),await Htr(t,ub(e,fz)),o}async function gme(t,e,n){try{let r=ub(e,df);if(!await Ix(t,r)&&!n.trim())return;await uY(t,e,n)}catch(r){W(`[Instructions] Failed to ensure AGENTS.md for "${e||"<vault root>"}"`,r)}}async function yme(t,e,n,r){let o=await uY(t,e,n);if(!xp(t,o.path))throw new Error(`${o.path} is in a hidden folder Obsidian cannot open. Edit it externally.`);await t.workspace.getLeaf(r).openFile(o)}function ub(t,e){return(0,Tx.normalizePath)(t?`${t}/${e}`:e)}async function Ix(t,e){let n=t.vault.getAbstractFileByPath(e);if(n instanceof Tx.TFile)return n;let r=await Dk(t,e);return r?WUt(t,e)??r:null}function HUt(t,e){let n=t.vault.getAbstractFileByPath(e);return n instanceof Tx.TFile?n:WUt(t,e)}function WUt(t,e){if(!dz())return null;let n=e.lastIndexOf("/"),r=n===-1?"":e.slice(0,n),o=(n===-1?e:e.slice(n+1)).toLowerCase(),i=r?t.vault.getAbstractFileByPath(r):t.vault.getRoot();return i instanceof Tx.TFolder?i.children.find(s=>s instanceof Tx.TFile&&s.name.toLowerCase()===o)??null:null}async function rA(t,e){return xp(t,e.path)?await t.vault.read(e):await t.vault.adapter.read(e.path)}async function vme(t,e,n){xp(t,e.path)?await t.vault.modify(e,n):await t.vault.adapter.write(e.path,n)}async function rHe(t,e,n){let r=await Ix(t,e);if(r)return r;let o=(0,Tx.normalizePath)(e.split("/").slice(0,-1).join("/")),i=o?t.vault.getAbstractFileByPath(o):null;if(!o||i instanceof Tx.TFolder)return await t.vault.create(e,n);await t.vault.adapter.write(e,n);let s=await Ix(t,e);if(!s)throw new Error(`Failed to create ${e}`);return s}async function Htr(t,e){let n=await Ix(t,e);if(!n){await rHe(t,e,`${RUt}
`);return}let r=await rA(t,n);if(DUt.test(r))return;let o=r.length===0?"":r.endsWith(`
`)?`
`:`
`;await vme(t,n,`${r}${o}${RUt}
`)}async function Wtr(t,e,n){let r=await rA(t,e),o=r.match(fme);if(!o)return;let i=n?`${o[1]}${n}`:`${o[1]}${r.slice(o[0].length)}`;await vme(t,e,i)}var Tx,df,fz,RUt,DUt,fme,db=b(()=>{pe();Jh();Tx=require("obsidian"),df="AGENTS.md",fz="CLAUDE.md",RUt="@AGENTS.md",DUt=/^[ \t>-]*@\.?\/?AGENTS\.md[ \t]*$/im;fme=/^(\uFEFF?)<!-- copilot:generated-agents-mirror [^\r\n]* -->\r?\n\r?\n/});var VUt,Tm,GR,ZR,YR,oA,iA,JR,fb,XR,QR,eL,tL,Xh,ff,sA=b(()=>{VUt={id:"",name:"",description:"",systemPrompt:"",projectModelKey:"",modelConfigs:{},contextSource:{},created:0,UsageTimestamps:0},Tm="copilot-project-id",GR="copilot-project-name",ZR="copilot-project-description",YR="copilot-project-model-key",oA="copilot-project-temperature",iA="copilot-project-max-tokens",JR="copilot-project-created",fb="copilot-project-last-used",XR="copilot-project-inclusions",QR="copilot-project-exclusions",eL="copilot-project-web-urls",tL="copilot-project-youtube-urls",Xh="project.md",ff="unsupported"});var qUt,wr,br=b(()=>{qUt=Object.defineProperty,wr=(t,e)=>{let n={};for(var r in t)qUt(n,r,{get:t[r],enumerable:!0});return e||qUt(n,Symbol.toStringTag,{value:"Module"}),n}});function yd(t){if(typeof t!="object"||t===null)return!1;let e=t;if(!("_zod"in e))return!1;let n=e._zod;return typeof n=="object"&&n!==null&&"def"in n}function ev(t){if(typeof t!="object"||t===null)return!1;let e=t;if(!("_def"in e)||"_zod"in e)return!1;let n=e._def;return typeof n=="object"&&n!=null&&"typeName"in n}function ki(t){return!t||typeof t!="object"||Array.isArray(t)?!1:!!(yd(t)||ev(t))}async function oL(t,e){if(yd(t))try{return{success:!0,data:await $N(t,e)}}catch(n){return{success:!1,error:n}}if(ev(t))return await t.safeParseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function iL(t,e){if(yd(t))return await $N(t,e);if(ev(t))return await t.parseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Fk(t){if(yd(t))return Vs.get(t)?.description;if(ev(t)||"description"in t&&typeof t.description=="string")return t.description}function fY(t){return ki(t)?ev(t)?t._def.typeName==="ZodString":yd(t)?t._zod.def.type==="string":!1:!1}function KUt(t){return typeof t=="object"&&t!==null&&"_def"in t&&typeof t._def=="object"&&t._def!==null&&"typeName"in t._def&&t._def.typeName==="ZodObject"}function rL(t){return yd(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="object":!1}function oHe(t){return yd(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="array":!1}function GUt(t){return yd(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="optional":!1}function ZUt(t){return yd(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="nullable":!1}function dY(t,e=!1){if(KUt(t))return t.strict();if(rL(t)){let n=t._zod.def.shape;if(e)for(let[i,s]of Object.entries(t._zod.def.shape)){if(rL(s))n[i]=dY(s,e);else if(oHe(s)){let l=s._zod.def.element;rL(l)&&(l=dY(l,e)),n[i]=Va(s,{...s._zod.def,element:l})}else n[i]=s;let a=Vs.get(s);a&&Vs.add(n[i],a)}let r=Va(t,{...t._zod.def,shape:n,catchall:x8(p8)}),o=Vs.get(t);return o&&Vs.add(r,o),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Vtr(t){return ev(t)&&"typeName"in t._def&&t._def.typeName==="ZodEffects"}function qtr(t){return yd(t)&&t._zod.def.type==="pipe"}function nL(t,e,n){let r=n.get(t);if(r!==void 0)return r;if(ev(t))return Vtr(t)?nL(t._def.schema,e,n):t;if(yd(t)){let o=t;if(qtr(t)&&(o=nL(t._zod.def.in,e,n)),e){if(rL(o)){let s={};for(let[a,l]of Object.entries(o._zod.def.shape))s[a]=nL(l,e,n);o=Va(o,{...o._zod.def,shape:s})}else if(oHe(o)){let s=nL(o._zod.def.element,e,n);o=Va(o,{...o._zod.def,element:s})}else if(GUt(o)){let s=nL(o._zod.def.innerType,e,n);o=Va(o,{...o._zod.def,innerType:s})}else if(ZUt(o)){let s=nL(o._zod.def.innerType,e,n);o=Va(o,{...o._zod.def,innerType:s})}}let i=Vs.get(t);return i&&Vs.add(o,i),n.set(t,o),o}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function iHe(t,e=!1){return nL(t,e,new WeakMap)}function sHe(t){return t instanceof Error&&(t.constructor.name==="ZodError"||t.constructor.name==="$ZodError")}var Px=b(()=>{tf()});var tv=b(()=>{br();Px()});var lHe,aHe,cHe,wme=b(()=>{lHe=Symbol("Let zodToJsonSchema decide on which parser to use"),aHe={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},cHe=t=>typeof t=="string"?{...aHe,name:t}:{...aHe,...t}});var uHe,dHe=b(()=>{wme();uHe=t=>{let e=cHe(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}}});var pY,bme=b(()=>{pY=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")}});function ea(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?pY(e,t.currentPath):e.join("/")}}var nv=b(()=>{bme()});function _me(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function Ro(t,e,n,r,o){t[e]=n,_me(t,e,r,o)}var aA=b(()=>{});var To,fHe,Wt,Ax,mY=b(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,t.arrayToEnum=o=>{let i={};for(let s of o)i[s]=s;return i},t.getValidEnumValues=o=>{let i=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),s={};for(let a of i)s[a]=o[a];return t.objectValues(s)},t.objectValues=o=>t.objectKeys(o).map(function(i){return o[i]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},t.find=(o,i)=>{for(let s of o)if(i(s))return s},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(To||(To={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(fHe||(fHe={}));Wt=To.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ax=t=>{switch(typeof t){case"undefined":return Wt.undefined;case"string":return Wt.string;case"number":return Number.isNaN(t)?Wt.nan:Wt.number;case"boolean":return Wt.boolean;case"function":return Wt.function;case"bigint":return Wt.bigint;case"symbol":return Wt.symbol;case"object":return Array.isArray(t)?Wt.array:t===null?Wt.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Wt.promise:typeof Map<"u"&&t instanceof Map?Wt.map:typeof Set<"u"&&t instanceof Set?Wt.set:typeof Date<"u"&&t instanceof Date?Wt.date:Wt.object;default:return Wt.unknown}}});var rt,Ktr,Pm,xme=b(()=>{mY();rt=To.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Ktr=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Pm=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(i){return i.message},r={_errors:[]},o=i=>{for(let s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)r._errors.push(n(s));else{let a=r,l=0;for(;l<s.path.length;){let c=s.path[l];l===s.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(s))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return o(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,To.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n=Object.create(null),r=[];for(let o of this.issues)if(o.path.length>0){let i=o.path[0];n[i]=n[i]||[],n[i].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Pm.create=t=>new Pm(t)});var Gtr,Uk,pHe=b(()=>{xme();mY();Gtr=(t,e)=>{let n;switch(t.code){case rt.invalid_type:t.received===Wt.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case rt.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,To.jsonStringifyReplacer)}`;break;case rt.unrecognized_keys:n=`Unrecognized key(s) in object: ${To.joinValues(t.keys,", ")}`;break;case rt.invalid_union:n="Invalid input";break;case rt.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${To.joinValues(t.options)}`;break;case rt.invalid_enum_value:n=`Invalid enum value. Expected ${To.joinValues(t.options)}, received '${t.received}'`;break;case rt.invalid_arguments:n="Invalid function arguments";break;case rt.invalid_return_type:n="Invalid function return type";break;case rt.invalid_date:n="Invalid date";break;case rt.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:To.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case rt.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case rt.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case rt.custom:n="Invalid input";break;case rt.invalid_intersection_types:n="Intersection results could not be merged";break;case rt.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case rt.not_finite:n="Number must be finite";break;default:n=e.defaultError,To.assertNever(t)}return{message:n}},Uk=Gtr});function Ztr(t){YUt=t}function pz(){return YUt}var YUt,Sme=b(()=>{pHe();YUt=Uk});function Lt(t,e){let n=pz(),r=hY({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Uk?void 0:Uk].filter(o=>!!o)});t.common.issues.push(r)}var hY,Ytr,vd,Xn,sL,pf,Cme,kme,lA,mz,mHe=b(()=>{Sme();pHe();hY=t=>{let{data:e,path:n,errorMaps:r,issueData:o}=t,i=[...n,...o.path||[]],s={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let a="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(s,{data:e,defaultError:a}).message;return{...o,path:i,message:a}},Ytr=[];vd=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let o of n){if(o.status==="aborted")return Xn;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let o of n){let i=await o.key,s=await o.value;r.push({key:i,value:s})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let o of n){let{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Xn;i.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:e.value,value:r}}},Xn=Object.freeze({status:"aborted"}),sL=t=>({status:"dirty",value:t}),pf=t=>({status:"valid",value:t}),Cme=t=>t.status==="aborted",kme=t=>t.status==="dirty",lA=t=>t.status==="valid",mz=t=>typeof Promise<"u"&&t instanceof Promise});var JUt=b(()=>{});var bn,XUt=b(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(bn||(bn={}))});function Gr(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(s,a)=>{let{message:l}=t;return s.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:o}}function njt(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function pnr(t){return new RegExp(`^${njt(t)}$`)}function rjt(t){let e=`${tjt}T${njt(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function mnr(t,e){return!!((e==="v4"||!e)&&snr.test(t)||(e==="v6"||!e)&&lnr.test(t))}function hnr(t,e){if(!nnr.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function gnr(t,e){return!!((e==="v4"||!e)&&anr.test(t)||(e==="v6"||!e)&&cnr.test(t))}function ynr(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,i=Number.parseInt(t.toFixed(o).replace(".","")),s=Number.parseInt(e.toFixed(o).replace(".",""));return i%s/10**o}function hz(t){if(t instanceof Am){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=rv.create(hz(r))}return new Am({...t._def,shape:()=>e})}else return t instanceof zk?new zk({...t._def,type:hz(t.element)}):t instanceof rv?rv.create(hz(t.unwrap())):t instanceof Mx?Mx.create(hz(t.unwrap())):t instanceof Ex?Ex.create(t.items.map(e=>hz(e))):t}function gHe(t,e){let n=Ax(t),r=Ax(e);if(t===e)return{valid:!0,data:t};if(n===Wt.object&&r===Wt.object){let o=To.objectKeys(e),i=To.objectKeys(t).filter(a=>o.indexOf(a)!==-1),s={...t,...e};for(let a of i){let l=gHe(t[a],e[a]);if(!l.valid)return{valid:!1};s[a]=l.data}return{valid:!0,data:s}}else if(n===Wt.array&&r===Wt.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let i=0;i<t.length;i++){let s=t[i],a=e[i],l=gHe(s,a);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===Wt.date&&r===Wt.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function ojt(t,e){return new yL({values:t,typeName:Ie.ZodEnum,...Gr(e)})}function ejt(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function ijt(t,e={},n){return t?uA.create().superRefine((r,o)=>{let i=t(r);if(i instanceof Promise)return i.then(s=>{if(!s){let a=ejt(e,r),l=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:l})}});if(!i){let s=ejt(e,r),a=s.fatal??n??!0;o.addIssue({code:"custom",...s,fatal:a})}}):uA.create()}var ov,QUt,oo,Jtr,Xtr,Qtr,enr,tnr,nnr,rnr,onr,inr,hHe,snr,anr,lnr,cnr,unr,dnr,tjt,fnr,cA,aL,lL,cL,uL,gz,dL,fL,uA,Bk,pb,yz,zk,Am,pL,jk,Ime,mL,Ex,Tme,vz,wz,Pme,hL,gL,yL,vL,dA,iv,rv,Mx,wL,bL,bz,vnr,gY,yY,_L,wnr,Ie,bnr,sjt,ajt,_nr,xnr,ljt,Snr,Cnr,knr,Inr,Tnr,Pnr,Anr,Enr,Mnr,Onr,Nnr,Rnr,Lnr,$nr,Dnr,Fnr,Unr,jnr,Bnr,znr,Hnr,Wnr,Vnr,qnr,Knr,Gnr,Znr,Ynr,Jnr,Xnr,Qnr,err,trr,nrr,cjt=b(()=>{xme();Sme();XUt();mHe();mY();ov=class{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},QUt=(t,e)=>{if(lA(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Pm(t.common.issues);return this._error=n,this._error}}};oo=class{get description(){return this._def.description}_getType(e){return Ax(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Ax(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new vd,ctx:{common:e.parent.common,data:e.data,parsedType:Ax(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(mz(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ax(e)},o=this._parseSync({data:e,path:r.path,parent:r});return QUt(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ax(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return lA(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>lA(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ax(e)},o=this._parse({data:e,path:r.path,parent:r}),i=await(mz(o)?o:Promise.resolve(o));return QUt(r,i)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{let s=e(o),a=()=>i.addIssue({code:rt.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new iv({schema:this,typeName:Ie.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return rv.create(this,this._def)}nullable(){return Mx.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return zk.create(this)}promise(){return dA.create(this,this._def)}or(e){return pL.create([this,e],this._def)}and(e){return mL.create(this,e,this._def)}transform(e){return new iv({...Gr(this._def),schema:this,typeName:Ie.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new wL({...Gr(this._def),innerType:this,defaultValue:n,typeName:Ie.ZodDefault})}brand(){return new gY({typeName:Ie.ZodBranded,type:this,...Gr(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new bL({...Gr(this._def),innerType:this,catchValue:n,typeName:Ie.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return yY.create(this,e)}readonly(){return _L.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Jtr=/^c[^\s-]{8,}$/i,Xtr=/^[0-9a-z]+$/,Qtr=/^[0-9A-HJKMNP-TV-Z]{26}$/i,enr=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,tnr=/^[a-z0-9_-]{21}$/i,nnr=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,rnr=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,onr=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,inr="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",snr=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,anr=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,lnr=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,cnr=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,unr=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,dnr=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,tjt="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",fnr=new RegExp(`^${tjt}$`);cA=class t extends oo{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Wt.string){let i=this._getOrReturnCtx(e);return Lt(i,{code:rt.invalid_type,expected:Wt.string,received:i.parsedType}),Xn}let r=new vd,o;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(o=this._getOrReturnCtx(e,o),Lt(o,{code:rt.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(o=this._getOrReturnCtx(e,o),Lt(o,{code:rt.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let s=e.data.length>i.value,a=e.data.length<i.value;(s||a)&&(o=this._getOrReturnCtx(e,o),s?Lt(o,{code:rt.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&Lt(o,{code:rt.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")onr.test(e.data)||(o=this._getOrReturnCtx(e,o),Lt(o,{validation:"email",code:rt.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")hHe||(hHe=new RegExp(inr,"u")),hHe.test(e.data)||(o=this._getOrReturnCtx(e,o),Lt(o,{validation:"emoji",code:rt.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")enr.test(e.data)||(o=this._getOrReturnCtx(e,o),Lt(o,{validation:"uuid",code:rt.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")tnr.test(e.data)||(o=this._getOrReturnCtx(e,o),Lt(o,{validation:"nanoid",code:rt.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Jtr.test(e.data)||(o=this._getOrReturnCtx(e,o),Lt(o,{validation:"cuid",code:rt.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Xtr.test(e.data)||(o=this._getOrReturnCtx(e,o),Lt(o,{validation:"cuid2",code:rt.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Qtr.test(e.data)||(o=this._getOrReturnCtx(e,o),Lt(o,{validation:"ulid",code:rt.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),Lt(o,{validation:"url",code:rt.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),Lt(o,{validation:"regex",code:rt.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(e,o),Lt(o,{code:rt.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(o=this._getOrReturnCtx(e,o),Lt(o,{code:rt.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(o=this._getOrReturnCtx(e,o),Lt(o,{code:rt.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?rjt(i).test(e.data)||(o=this._getOrReturnCtx(e,o),Lt(o,{code:rt.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?fnr.test(e.data)||(o=this._getOrReturnCtx(e,o),Lt(o,{code:rt.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?pnr(i).test(e.data)||(o=this._getOrReturnCtx(e,o),Lt(o,{code:rt.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?rnr.test(e.data)||(o=this._getOrReturnCtx(e,o),Lt(o,{validation:"duration",code:rt.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?mnr(e.data,i.version)||(o=this._getOrReturnCtx(e,o),Lt(o,{validation:"ip",code:rt.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?hnr(e.data,i.alg)||(o=this._getOrReturnCtx(e,o),Lt(o,{validation:"jwt",code:rt.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?gnr(e.data,i.version)||(o=this._getOrReturnCtx(e,o),Lt(o,{validation:"cidr",code:rt.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?unr.test(e.data)||(o=this._getOrReturnCtx(e,o),Lt(o,{validation:"base64",code:rt.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?dnr.test(e.data)||(o=this._getOrReturnCtx(e,o),Lt(o,{validation:"base64url",code:rt.invalid_string,message:i.message}),r.dirty()):To.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:rt.invalid_string,...bn.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...bn.errToObj(e)})}url(e){return this._addCheck({kind:"url",...bn.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...bn.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...bn.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...bn.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...bn.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...bn.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...bn.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...bn.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...bn.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...bn.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...bn.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...bn.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...bn.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...bn.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...bn.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...bn.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...bn.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...bn.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...bn.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...bn.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...bn.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...bn.errToObj(n)})}nonempty(e){return this.min(1,bn.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};cA.create=t=>new cA({checks:[],typeName:Ie.ZodString,coerce:t?.coerce??!1,...Gr(t)});aL=class t extends oo{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Wt.number){let i=this._getOrReturnCtx(e);return Lt(i,{code:rt.invalid_type,expected:Wt.number,received:i.parsedType}),Xn}let r,o=new vd;for(let i of this._def.checks)i.kind==="int"?To.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),Lt(r,{code:rt.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),Lt(r,{code:rt.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),Lt(r,{code:rt.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?ynr(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),Lt(r,{code:rt.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),Lt(r,{code:rt.not_finite,message:i.message}),o.dirty()):To.assertNever(i);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,bn.toString(n))}gt(e,n){return this.setLimit("min",e,!1,bn.toString(n))}lte(e,n){return this.setLimit("max",e,!0,bn.toString(n))}lt(e,n){return this.setLimit("max",e,!1,bn.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:bn.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:bn.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:bn.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:bn.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:bn.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:bn.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:bn.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:bn.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:bn.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:bn.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&To.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};aL.create=t=>new aL({checks:[],typeName:Ie.ZodNumber,coerce:t?.coerce||!1,...Gr(t)});lL=class t extends oo{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==Wt.bigint)return this._getInvalidInput(e);let r,o=new vd;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),Lt(r,{code:rt.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),Lt(r,{code:rt.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),Lt(r,{code:rt.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):To.assertNever(i);return{status:o.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return Lt(n,{code:rt.invalid_type,expected:Wt.bigint,received:n.parsedType}),Xn}gte(e,n){return this.setLimit("min",e,!0,bn.toString(n))}gt(e,n){return this.setLimit("min",e,!1,bn.toString(n))}lte(e,n){return this.setLimit("max",e,!0,bn.toString(n))}lt(e,n){return this.setLimit("max",e,!1,bn.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:bn.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:bn.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:bn.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:bn.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:bn.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:bn.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};lL.create=t=>new lL({checks:[],typeName:Ie.ZodBigInt,coerce:t?.coerce??!1,...Gr(t)});cL=class extends oo{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Wt.boolean){let r=this._getOrReturnCtx(e);return Lt(r,{code:rt.invalid_type,expected:Wt.boolean,received:r.parsedType}),Xn}return pf(e.data)}};cL.create=t=>new cL({typeName:Ie.ZodBoolean,coerce:t?.coerce||!1,...Gr(t)});uL=class t extends oo{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Wt.date){let i=this._getOrReturnCtx(e);return Lt(i,{code:rt.invalid_type,expected:Wt.date,received:i.parsedType}),Xn}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return Lt(i,{code:rt.invalid_date}),Xn}let r=new vd,o;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(o=this._getOrReturnCtx(e,o),Lt(o,{code:rt.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(o=this._getOrReturnCtx(e,o),Lt(o,{code:rt.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):To.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:bn.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:bn.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};uL.create=t=>new uL({checks:[],coerce:t?.coerce||!1,typeName:Ie.ZodDate,...Gr(t)});gz=class extends oo{_parse(e){if(this._getType(e)!==Wt.symbol){let r=this._getOrReturnCtx(e);return Lt(r,{code:rt.invalid_type,expected:Wt.symbol,received:r.parsedType}),Xn}return pf(e.data)}};gz.create=t=>new gz({typeName:Ie.ZodSymbol,...Gr(t)});dL=class extends oo{_parse(e){if(this._getType(e)!==Wt.undefined){let r=this._getOrReturnCtx(e);return Lt(r,{code:rt.invalid_type,expected:Wt.undefined,received:r.parsedType}),Xn}return pf(e.data)}};dL.create=t=>new dL({typeName:Ie.ZodUndefined,...Gr(t)});fL=class extends oo{_parse(e){if(this._getType(e)!==Wt.null){let r=this._getOrReturnCtx(e);return Lt(r,{code:rt.invalid_type,expected:Wt.null,received:r.parsedType}),Xn}return pf(e.data)}};fL.create=t=>new fL({typeName:Ie.ZodNull,...Gr(t)});uA=class extends oo{constructor(){super(...arguments),this._any=!0}_parse(e){return pf(e.data)}};uA.create=t=>new uA({typeName:Ie.ZodAny,...Gr(t)});Bk=class extends oo{constructor(){super(...arguments),this._unknown=!0}_parse(e){return pf(e.data)}};Bk.create=t=>new Bk({typeName:Ie.ZodUnknown,...Gr(t)});pb=class extends oo{_parse(e){let n=this._getOrReturnCtx(e);return Lt(n,{code:rt.invalid_type,expected:Wt.never,received:n.parsedType}),Xn}};pb.create=t=>new pb({typeName:Ie.ZodNever,...Gr(t)});yz=class extends oo{_parse(e){if(this._getType(e)!==Wt.undefined){let r=this._getOrReturnCtx(e);return Lt(r,{code:rt.invalid_type,expected:Wt.void,received:r.parsedType}),Xn}return pf(e.data)}};yz.create=t=>new yz({typeName:Ie.ZodVoid,...Gr(t)});zk=class t extends oo{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==Wt.array)return Lt(n,{code:rt.invalid_type,expected:Wt.array,received:n.parsedType}),Xn;if(o.exactLength!==null){let s=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(s||a)&&(Lt(n,{code:s?rt.too_big:rt.too_small,minimum:a?o.exactLength.value:void 0,maximum:s?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(Lt(n,{code:rt.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(Lt(n,{code:rt.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,a)=>o.type._parseAsync(new ov(n,s,n.path,a)))).then(s=>vd.mergeArray(r,s));let i=[...n.data].map((s,a)=>o.type._parseSync(new ov(n,s,n.path,a)));return vd.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:bn.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:bn.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:bn.toString(n)}})}nonempty(e){return this.min(1,e)}};zk.create=(t,e)=>new zk({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Ie.ZodArray,...Gr(e)});Am=class t extends oo{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=To.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==Wt.object){let c=this._getOrReturnCtx(e);return Lt(c,{code:rt.invalid_type,expected:Wt.object,received:c.parsedType}),Xn}let{status:r,ctx:o}=this._processInputParams(e),{shape:i,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof pb&&this._def.unknownKeys==="strip"))for(let c in o.data)s.includes(c)||a.push(c);let l=[];for(let c of s){let u=i[c],d=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new ov(o,d,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof pb){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")a.length>0&&(Lt(o,{code:rt.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of a){let d=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new ov(o,d,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let d=await u.key,f=await u.value;c.push({key:d,value:f,alwaysSet:u.alwaysSet})}return c}).then(c=>vd.mergeObjectSync(r,c)):vd.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return bn.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:bn.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Ie.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of To.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of To.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return hz(this)}partial(e){let n={};for(let r of To.objectKeys(this.shape)){let o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of To.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof rv;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return ojt(To.objectKeys(this.shape))}};Am.create=(t,e)=>new Am({shape:()=>t,unknownKeys:"strip",catchall:pb.create(),typeName:Ie.ZodObject,...Gr(e)});Am.strictCreate=(t,e)=>new Am({shape:()=>t,unknownKeys:"strict",catchall:pb.create(),typeName:Ie.ZodObject,...Gr(e)});Am.lazycreate=(t,e)=>new Am({shape:t,unknownKeys:"strip",catchall:pb.create(),typeName:Ie.ZodObject,...Gr(e)});pL=class extends oo{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function o(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let s=i.map(a=>new Pm(a.ctx.common.issues));return Lt(n,{code:rt.invalid_union,unionErrors:s}),Xn}if(n.common.async)return Promise.all(r.map(async i=>{let s={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(o);{let i,s=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:c}),c.common.issues.length&&s.push(c.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map(l=>new Pm(l));return Lt(n,{code:rt.invalid_union,unionErrors:a}),Xn}}get options(){return this._def.options}};pL.create=(t,e)=>new pL({options:t,typeName:Ie.ZodUnion,...Gr(e)});jk=t=>t instanceof hL?jk(t.schema):t instanceof iv?jk(t.innerType()):t instanceof gL?[t.value]:t instanceof yL?t.options:t instanceof vL?To.objectValues(t.enum):t instanceof wL?jk(t._def.innerType):t instanceof dL?[void 0]:t instanceof fL?[null]:t instanceof rv?[void 0,...jk(t.unwrap())]:t instanceof Mx?[null,...jk(t.unwrap())]:t instanceof gY||t instanceof _L?jk(t.unwrap()):t instanceof bL?jk(t._def.innerType):[],Ime=class t extends oo{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==Wt.object)return Lt(n,{code:rt.invalid_type,expected:Wt.object,received:n.parsedType}),Xn;let r=this.discriminator,o=n.data[r],i=this.optionsMap.get(o);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(Lt(n,{code:rt.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Xn)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let o=new Map;for(let i of n){let s=jk(i.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,i)}}return new t({typeName:Ie.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...Gr(r)})}};mL=class extends oo{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(i,s)=>{if(Cme(i)||Cme(s))return Xn;let a=gHe(i.value,s.value);return a.valid?((kme(i)||kme(s))&&n.dirty(),{status:n.value,value:a.data}):(Lt(r,{code:rt.invalid_intersection_types}),Xn)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,s])=>o(i,s)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};mL.create=(t,e,n)=>new mL({left:t,right:e,typeName:Ie.ZodIntersection,...Gr(n)});Ex=class t extends oo{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Wt.array)return Lt(r,{code:rt.invalid_type,expected:Wt.array,received:r.parsedType}),Xn;if(r.data.length<this._def.items.length)return Lt(r,{code:rt.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Xn;!this._def.rest&&r.data.length>this._def.items.length&&(Lt(r,{code:rt.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((s,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new ov(r,s,r.path,a)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>vd.mergeArray(n,s)):vd.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Ex.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ex({items:t,typeName:Ie.ZodTuple,rest:null,...Gr(e)})};Tme=class t extends oo{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Wt.object)return Lt(r,{code:rt.invalid_type,expected:Wt.object,received:r.parsedType}),Xn;let o=[],i=this._def.keyType,s=this._def.valueType;for(let a in r.data)o.push({key:i._parse(new ov(r,a,r.path,a)),value:s._parse(new ov(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?vd.mergeObjectAsync(n,o):vd.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof oo?new t({keyType:e,valueType:n,typeName:Ie.ZodRecord,...Gr(r)}):new t({keyType:cA.create(),valueType:e,typeName:Ie.ZodRecord,...Gr(n)})}},vz=class extends oo{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Wt.map)return Lt(r,{code:rt.invalid_type,expected:Wt.map,received:r.parsedType}),Xn;let o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([a,l],c)=>({key:o._parse(new ov(r,a,r.path,[c,"key"])),value:i._parse(new ov(r,l,r.path,[c,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of s){let c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return Xn;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let l of s){let c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return Xn;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}}}};vz.create=(t,e,n)=>new vz({valueType:e,keyType:t,typeName:Ie.ZodMap,...Gr(n)});wz=class t extends oo{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Wt.set)return Lt(r,{code:rt.invalid_type,expected:Wt.set,received:r.parsedType}),Xn;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(Lt(r,{code:rt.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(Lt(r,{code:rt.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let i=this._def.valueType;function s(l){let c=new Set;for(let u of l){if(u.status==="aborted")return Xn;u.status==="dirty"&&n.dirty(),c.add(u.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>i._parse(new ov(r,l,r.path,c)));return r.common.async?Promise.all(a).then(l=>s(l)):s(a)}min(e,n){return new t({...this._def,minSize:{value:e,message:bn.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:bn.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};wz.create=(t,e)=>new wz({valueType:t,minSize:null,maxSize:null,typeName:Ie.ZodSet,...Gr(e)});Pme=class t extends oo{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==Wt.function)return Lt(n,{code:rt.invalid_type,expected:Wt.function,received:n.parsedType}),Xn;function r(a,l){return hY({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,pz(),Uk].filter(c=>!!c),issueData:{code:rt.invalid_arguments,argumentsError:l}})}function o(a,l){return hY({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,pz(),Uk].filter(c=>!!c),issueData:{code:rt.invalid_return_type,returnTypeError:l}})}let i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof dA){let a=this;return pf(async function(...l){let c=new Pm([]),u=await a._def.args.parseAsync(l,i).catch(p=>{throw c.addIssue(r(l,p)),c}),d=await Reflect.apply(s,this,u);return await a._def.returns._def.type.parseAsync(d,i).catch(p=>{throw c.addIssue(o(d,p)),c})})}else{let a=this;return pf(function(...l){let c=a._def.args.safeParse(l,i);if(!c.success)throw new Pm([r(l,c.error)]);let u=Reflect.apply(s,this,c.data),d=a._def.returns.safeParse(u,i);if(!d.success)throw new Pm([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Ex.create(e).rest(Bk.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||Ex.create([]).rest(Bk.create()),returns:n||Bk.create(),typeName:Ie.ZodFunction,...Gr(r)})}},hL=class extends oo{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};hL.create=(t,e)=>new hL({getter:t,typeName:Ie.ZodLazy,...Gr(e)});gL=class extends oo{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return Lt(n,{received:n.data,code:rt.invalid_literal,expected:this._def.value}),Xn}return{status:"valid",value:e.data}}get value(){return this._def.value}};gL.create=(t,e)=>new gL({value:t,typeName:Ie.ZodLiteral,...Gr(e)});yL=class t extends oo{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return Lt(n,{expected:To.joinValues(r),received:n.parsedType,code:rt.invalid_type}),Xn}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return Lt(n,{received:n.data,code:rt.invalid_enum_value,options:r}),Xn}return pf(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};yL.create=ojt;vL=class extends oo{_parse(e){let n=To.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==Wt.string&&r.parsedType!==Wt.number){let o=To.objectValues(n);return Lt(r,{expected:To.joinValues(o),received:r.parsedType,code:rt.invalid_type}),Xn}if(this._cache||(this._cache=new Set(To.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=To.objectValues(n);return Lt(r,{received:r.data,code:rt.invalid_enum_value,options:o}),Xn}return pf(e.data)}get enum(){return this._def.values}};vL.create=(t,e)=>new vL({values:t,typeName:Ie.ZodNativeEnum,...Gr(e)});dA=class extends oo{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==Wt.promise&&n.common.async===!1)return Lt(n,{code:rt.invalid_type,expected:Wt.promise,received:n.parsedType}),Xn;let r=n.parsedType===Wt.promise?n.data:Promise.resolve(n.data);return pf(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};dA.create=(t,e)=>new dA({type:t,typeName:Ie.ZodPromise,...Gr(e)});iv=class extends oo{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ie.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,i={addIssue:s=>{Lt(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){let s=o.transform(r.data,i);if(r.common.async)return Promise.resolve(s).then(async a=>{if(n.value==="aborted")return Xn;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?Xn:l.status==="dirty"?sL(l.value):n.value==="dirty"?sL(l.value):l});{if(n.value==="aborted")return Xn;let a=this._def.schema._parseSync({data:s,path:r.path,parent:r});return a.status==="aborted"?Xn:a.status==="dirty"?sL(a.value):n.value==="dirty"?sL(a.value):a}}if(o.type==="refinement"){let s=a=>{let l=o.refinement(a,i);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?Xn:(a.status==="dirty"&&n.dirty(),s(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?Xn:(a.status==="dirty"&&n.dirty(),s(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!lA(s))return Xn;let a=o.transform(s.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>lA(s)?Promise.resolve(o.transform(s.value,i)).then(a=>({status:n.value,value:a})):Xn);To.assertNever(o)}};iv.create=(t,e,n)=>new iv({schema:t,typeName:Ie.ZodEffects,effect:e,...Gr(n)});iv.createWithPreprocess=(t,e,n)=>new iv({schema:e,effect:{type:"preprocess",transform:t},typeName:Ie.ZodEffects,...Gr(n)});rv=class extends oo{_parse(e){return this._getType(e)===Wt.undefined?pf(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};rv.create=(t,e)=>new rv({innerType:t,typeName:Ie.ZodOptional,...Gr(e)});Mx=class extends oo{_parse(e){return this._getType(e)===Wt.null?pf(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Mx.create=(t,e)=>new Mx({innerType:t,typeName:Ie.ZodNullable,...Gr(e)});wL=class extends oo{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===Wt.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};wL.create=(t,e)=>new wL({innerType:t,typeName:Ie.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Gr(e)});bL=class extends oo{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return mz(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Pm(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Pm(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};bL.create=(t,e)=>new bL({innerType:t,typeName:Ie.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Gr(e)});bz=class extends oo{_parse(e){if(this._getType(e)!==Wt.nan){let r=this._getOrReturnCtx(e);return Lt(r,{code:rt.invalid_type,expected:Wt.nan,received:r.parsedType}),Xn}return{status:"valid",value:e.data}}};bz.create=t=>new bz({typeName:Ie.ZodNaN,...Gr(t)});vnr=Symbol("zod_brand"),gY=class extends oo{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},yY=class t extends oo{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Xn:i.status==="dirty"?(n.dirty(),sL(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Xn:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:Ie.ZodPipeline})}},_L=class extends oo{_parse(e){let n=this._def.innerType._parse(e),r=o=>(lA(o)&&(o.value=Object.freeze(o.value)),o);return mz(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};_L.create=(t,e)=>new _L({innerType:t,typeName:Ie.ZodReadonly,...Gr(e)});wnr={object:Am.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Ie||(Ie={}));bnr=(t,e={message:`Input not instance of ${t.name}`})=>ijt(n=>n instanceof t,e),sjt=cA.create,ajt=aL.create,_nr=bz.create,xnr=lL.create,ljt=cL.create,Snr=uL.create,Cnr=gz.create,knr=dL.create,Inr=fL.create,Tnr=uA.create,Pnr=Bk.create,Anr=pb.create,Enr=yz.create,Mnr=zk.create,Onr=Am.create,Nnr=Am.strictCreate,Rnr=pL.create,Lnr=Ime.create,$nr=mL.create,Dnr=Ex.create,Fnr=Tme.create,Unr=vz.create,jnr=wz.create,Bnr=Pme.create,znr=hL.create,Hnr=gL.create,Wnr=yL.create,Vnr=vL.create,qnr=dA.create,Knr=iv.create,Gnr=rv.create,Znr=Mx.create,Ynr=iv.createWithPreprocess,Jnr=yY.create,Xnr=()=>sjt().optional(),Qnr=()=>ajt().optional(),err=()=>ljt().optional(),trr={string:t=>cA.create({...t,coerce:!0}),number:t=>aL.create({...t,coerce:!0}),boolean:t=>cL.create({...t,coerce:!0}),bigint:t=>lL.create({...t,coerce:!0}),date:t=>uL.create({...t,coerce:!0})},nrr=Xn});var Qh={};sr(Qh,{BRAND:()=>vnr,DIRTY:()=>sL,EMPTY_PATH:()=>Ytr,INVALID:()=>Xn,NEVER:()=>nrr,OK:()=>pf,ParseStatus:()=>vd,Schema:()=>oo,ZodAny:()=>uA,ZodArray:()=>zk,ZodBigInt:()=>lL,ZodBoolean:()=>cL,ZodBranded:()=>gY,ZodCatch:()=>bL,ZodDate:()=>uL,ZodDefault:()=>wL,ZodDiscriminatedUnion:()=>Ime,ZodEffects:()=>iv,ZodEnum:()=>yL,ZodError:()=>Pm,ZodFirstPartyTypeKind:()=>Ie,ZodFunction:()=>Pme,ZodIntersection:()=>mL,ZodIssueCode:()=>rt,ZodLazy:()=>hL,ZodLiteral:()=>gL,ZodMap:()=>vz,ZodNaN:()=>bz,ZodNativeEnum:()=>vL,ZodNever:()=>pb,ZodNull:()=>fL,ZodNullable:()=>Mx,ZodNumber:()=>aL,ZodObject:()=>Am,ZodOptional:()=>rv,ZodParsedType:()=>Wt,ZodPipeline:()=>yY,ZodPromise:()=>dA,ZodReadonly:()=>_L,ZodRecord:()=>Tme,ZodSchema:()=>oo,ZodSet:()=>wz,ZodString:()=>cA,ZodSymbol:()=>gz,ZodTransformer:()=>iv,ZodTuple:()=>Ex,ZodType:()=>oo,ZodUndefined:()=>dL,ZodUnion:()=>pL,ZodUnknown:()=>Bk,ZodVoid:()=>yz,addIssueToContext:()=>Lt,any:()=>Tnr,array:()=>Mnr,bigint:()=>xnr,boolean:()=>ljt,coerce:()=>trr,custom:()=>ijt,date:()=>Snr,datetimeRegex:()=>rjt,defaultErrorMap:()=>Uk,discriminatedUnion:()=>Lnr,effect:()=>Knr,enum:()=>Wnr,function:()=>Bnr,getErrorMap:()=>pz,getParsedType:()=>Ax,instanceof:()=>bnr,intersection:()=>$nr,isAborted:()=>Cme,isAsync:()=>mz,isDirty:()=>kme,isValid:()=>lA,late:()=>wnr,lazy:()=>znr,literal:()=>Hnr,makeIssue:()=>hY,map:()=>Unr,nan:()=>_nr,nativeEnum:()=>Vnr,never:()=>Anr,null:()=>Inr,nullable:()=>Znr,number:()=>ajt,object:()=>Onr,objectUtil:()=>fHe,oboolean:()=>err,onumber:()=>Qnr,optional:()=>Gnr,ostring:()=>Xnr,pipeline:()=>Jnr,preprocess:()=>Ynr,promise:()=>qnr,quotelessJson:()=>Ktr,record:()=>Fnr,set:()=>jnr,setErrorMap:()=>Ztr,strictObject:()=>Nnr,string:()=>sjt,symbol:()=>Cnr,transformer:()=>Knr,tuple:()=>Dnr,undefined:()=>knr,union:()=>Rnr,unknown:()=>Pnr,util:()=>To,void:()=>Enr});var yHe=b(()=>{Sme();mHe();JUt();mY();cjt();xme()});var Ox=b(()=>{yHe();yHe()});function vHe(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==Ie.ZodAny&&(n.items=lr(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Ro(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Ro(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Ro(n,"minItems",t.exactLength.value,t.exactLength.message,e),Ro(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}var wHe=b(()=>{aA();Kl();Ox()});function bHe(t,e){let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?Ro(n,"minimum",r.value,r.message,e):Ro(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),Ro(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?Ro(n,"maximum",r.value,r.message,e):Ro(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),Ro(n,"maximum",r.value,r.message,e));break;case"multipleOf":Ro(n,"multipleOf",r.value,r.message,e);break}return n}var _He=b(()=>{aA()});function xHe(){return{type:"boolean"}}var SHe=b(()=>{});function vY(t,e){return lr(t.type._def,e)}var Ame=b(()=>{Kl()});var CHe,kHe=b(()=>{Kl();CHe=(t,e)=>lr(t.innerType._def,e)});function Eme(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(o=>Eme(t,e,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return rrr(t,e)}}var rrr,IHe=b(()=>{aA();rrr=(t,e)=>{let n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(let r of t.checks)switch(r.kind){case"min":Ro(n,"minimum",r.value,r.message,e);break;case"max":Ro(n,"maximum",r.value,r.message,e);break}return n}});function THe(t,e){return{...lr(t.innerType._def,e),default:t.defaultValue()}}var PHe=b(()=>{Kl()});function AHe(t,e){return e.effectStrategy==="input"?lr(t.schema._def,e):ea(e)}var EHe=b(()=>{nv();Kl()});function MHe(t){return{type:"string",enum:Array.from(t.values)}}var OHe=b(()=>{});function NHe(t,e){let n=[lr(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),lr(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return n.forEach(i=>{if(orr(i))o.push(...i.allOf),i.unevaluatedProperties===void 0&&(r=void 0);else{let s=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:a,...l}=i;s=l}else r=void 0;o.push(s)}}),o.length?{allOf:o,...r}:void 0}var orr,RHe=b(()=>{Kl();orr=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function LHe(t,e){let n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}var $He=b(()=>{});function wY(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":Ro(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":Ro(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":mb(n,"email",r.message,e);break;case"format:idn-email":mb(n,"idn-email",r.message,e);break;case"pattern:zod":Sp(n,sv.email,r.message,e);break}break;case"url":mb(n,"uri",r.message,e);break;case"uuid":mb(n,"uuid",r.message,e);break;case"regex":Sp(n,r.regex,r.message,e);break;case"cuid":Sp(n,sv.cuid,r.message,e);break;case"cuid2":Sp(n,sv.cuid2,r.message,e);break;case"startsWith":Sp(n,RegExp(`^${FHe(r.value,e)}`),r.message,e);break;case"endsWith":Sp(n,RegExp(`${FHe(r.value,e)}$`),r.message,e);break;case"datetime":mb(n,"date-time",r.message,e);break;case"date":mb(n,"date",r.message,e);break;case"time":mb(n,"time",r.message,e);break;case"duration":mb(n,"duration",r.message,e);break;case"length":Ro(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),Ro(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":Sp(n,RegExp(FHe(r.value,e)),r.message,e);break;case"ip":r.version!=="v6"&&mb(n,"ipv4",r.message,e),r.version!=="v4"&&mb(n,"ipv6",r.message,e);break;case"base64url":Sp(n,sv.base64url,r.message,e);break;case"jwt":Sp(n,sv.jwt,r.message,e);break;case"cidr":r.version!=="v6"&&Sp(n,sv.ipv4Cidr,r.message,e),r.version!=="v4"&&Sp(n,sv.ipv6Cidr,r.message,e);break;case"emoji":Sp(n,sv.emoji(),r.message,e);break;case"ulid":Sp(n,sv.ulid,r.message,e);break;case"base64":switch(e.base64Strategy){case"format:binary":mb(n,"binary",r.message,e);break;case"contentEncoding:base64":Ro(n,"contentEncoding","base64",r.message,e);break;case"pattern:zod":Sp(n,sv.base64,r.message,e);break}break;case"nanoid":Sp(n,sv.nanoid,r.message,e);break;case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function FHe(t,e){return e.patternStrategy==="escape"?srr(t):t}function srr(t){let e="";for(let n=0;n<t.length;n++)irr.has(t[n])||(e+="\\"),e+=t[n];return e}function mb(t,e,n,r){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&r.errorMessages&&{errorMessage:{format:n}}})):Ro(t,"format",e,n,r)}function Sp(t,e,n,r){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:ujt(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Ro(t,"pattern",ujt(e,r),n,r)}function ujt(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source,o="",i=!1,s=!1,a=!1;for(let l=0;l<r.length;l++){if(i){o+=r[l],i=!1;continue}if(n.i){if(s){if(r[l].match(/[a-z]/)){a?(o+=r[l],o+=`${r[l-2]}-${r[l]}`.toUpperCase(),a=!1):r[l+1]==="-"&&r[l+2]?.match(/[a-z]/)?(o+=r[l],a=!0):o+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){o+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(n.m){if(r[l]==="^"){o+=`(^|(?<=[\r
]))`;continue}else if(r[l]==="$"){o+=`($|(?=[\r
]))`;continue}}if(n.s&&r[l]==="."){o+=s?`${r[l]}\r
`:`[${r[l]}\r
]`;continue}o+=r[l],r[l]==="\\"?i=!0:s&&r[l]==="]"?s=!1:!s&&r[l]==="["&&(s=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var DHe,sv,irr,Mme=b(()=>{aA();sv={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(DHe===void 0&&(DHe=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),DHe),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};irr=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function bY(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===Ie.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,o)=>({...r,[o]:lr(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??ea(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:lr(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===Ie.ZodString&&t.keyType._def.checks?.length){let{type:r,...o}=wY(t.keyType._def,e);return{...n,propertyNames:o}}else{if(t.keyType?._def.typeName===Ie.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Ie.ZodBranded&&t.keyType._def.type._def.typeName===Ie.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...o}=vY(t.keyType._def,e);return{...n,propertyNames:o}}}return n}var Ome=b(()=>{nv();Ame();Mme();Kl();Ox()});function UHe(t,e){return e.mapStrategy==="record"?bY(t,e):{type:"array",maxItems:125,items:{type:"array",items:[lr(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ea(e),lr(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ea(e)],minItems:2,maxItems:2}}}var jHe=b(()=>{nv();Ome();Kl()});function BHe(t){let e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),r=Array.from(new Set(n.map(o=>typeof o)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:n}}var zHe=b(()=>{});function HHe(t){return t.target==="openAi"?void 0:{not:ea({...t,currentPath:[...t.currentPath,"not"]})}}var WHe=b(()=>{nv()});function VHe(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var qHe=b(()=>{});function KHe(t,e){if(e.target==="openApi3")return djt(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in _z&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((o,i)=>{let s=_z[i._def.typeName];return s&&!o.includes(s)?[...o,s]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.reduce((o,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];case"bigint":return[...o,"integer"];case"object":return i._def.value===null?[...o,"null"]:o;default:return o}},[]);if(r.length===n.length){let o=r.filter((i,s,a)=>a.indexOf(i)===s);return{type:o.length>1?o:o[0],enum:n.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(i=>!r.includes(i))],[])};return djt(t,e)}var _z,djt,Nme=b(()=>{Kl();_z={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};djt=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,o)=>lr(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0}});function GHe(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:_z[t.innerType._def.typeName],nullable:!0}:{type:[_z[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=lr(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=lr(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}var ZHe=b(()=>{Nme();Kl()});function YHe(t,e){let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",_me(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?Ro(n,"minimum",r.value,r.message,e):Ro(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),Ro(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?Ro(n,"maximum",r.value,r.message,e):Ro(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),Ro(n,"maximum",r.value,r.message,e));break;case"multipleOf":Ro(n,"multipleOf",r.value,r.message,e);break}return n}var JHe=b(()=>{aA()});function XHe(t,e){let n=e.target==="openAi",r={type:"object",properties:{}},o=[],i=t.shape();for(let a in i){let l=i[a];if(l===void 0||l._def===void 0)continue;let c=lrr(l);c&&n&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),c=!1);let u=lr(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});u!==void 0&&(r.properties[a]=u,c||o.push(a))}o.length&&(r.required=o);let s=arr(t,e);return s!==void 0&&(r.additionalProperties=s),r}function arr(t,e){if(t.catchall._def.typeName!=="ZodNever")return lr(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function lrr(t){try{return t.isOptional()}catch{return!0}}var QHe=b(()=>{Kl()});var eWe,tWe=b(()=>{nv();Kl();eWe=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return lr(t.innerType._def,e);let n=lr(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:ea(e)},n]}:ea(e)}});var nWe,rWe=b(()=>{Kl();nWe=(t,e)=>{if(e.pipeStrategy==="input")return lr(t.in._def,e);if(e.pipeStrategy==="output")return lr(t.out._def,e);let n=lr(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]});return{allOf:[n,lr(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]})].filter(r=>r!==void 0)}}});function oWe(t,e){return lr(t.type._def,e)}var iWe=b(()=>{Kl()});function sWe(t,e){let n={type:"array",uniqueItems:!0,items:lr(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&Ro(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&Ro(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var aWe=b(()=>{aA();Kl()});function lWe(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>lr(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:lr(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>lr(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}var cWe=b(()=>{Kl()});function uWe(t){return{not:ea(t)}}var dWe=b(()=>{nv()});function fWe(t){return ea(t)}var pWe=b(()=>{nv()});var mWe,hWe=b(()=>{Kl();mWe=(t,e)=>lr(t.innerType._def,e)});var gWe,yWe=b(()=>{nv();wHe();_He();SHe();Ame();kHe();IHe();PHe();EHe();OHe();RHe();$He();Mme();Ome();jHe();zHe();WHe();qHe();Nme();ZHe();JHe();QHe();tWe();rWe();iWe();aWe();cWe();dWe();pWe();hWe();Ox();gWe=(t,e,n)=>{switch(e){case Ie.ZodString:return wY(t,n);case Ie.ZodNumber:return YHe(t,n);case Ie.ZodObject:return XHe(t,n);case Ie.ZodBigInt:return bHe(t,n);case Ie.ZodBoolean:return xHe();case Ie.ZodDate:return Eme(t,n);case Ie.ZodUndefined:return uWe(n);case Ie.ZodNull:return VHe(n);case Ie.ZodArray:return vHe(t,n);case Ie.ZodUnion:case Ie.ZodDiscriminatedUnion:return KHe(t,n);case Ie.ZodIntersection:return NHe(t,n);case Ie.ZodTuple:return lWe(t,n);case Ie.ZodRecord:return bY(t,n);case Ie.ZodLiteral:return LHe(t,n);case Ie.ZodEnum:return MHe(t);case Ie.ZodNativeEnum:return BHe(t);case Ie.ZodNullable:return GHe(t,n);case Ie.ZodOptional:return eWe(t,n);case Ie.ZodMap:return UHe(t,n);case Ie.ZodSet:return sWe(t,n);case Ie.ZodLazy:return()=>t.getter()._def;case Ie.ZodPromise:return oWe(t,n);case Ie.ZodNaN:case Ie.ZodNever:return HHe(n);case Ie.ZodEffects:return AHe(t,n);case Ie.ZodAny:return ea(n);case Ie.ZodUnknown:return fWe(n);case Ie.ZodDefault:return THe(t,n);case Ie.ZodBranded:return vY(t,n);case Ie.ZodReadonly:return mWe(t,n);case Ie.ZodCatch:return CHe(t,n);case Ie.ZodPipeline:return nWe(t,n);case Ie.ZodFunction:case Ie.ZodVoid:case Ie.ZodSymbol:return;default:return(r=>{})(e)}}});function lr(t,e,n=!1){let r=e.seen.get(t);if(e.override){let a=e.override?.(t,e,r,n);if(a!==lHe)return a}if(r&&!n){let a=crr(r,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let i=gWe(t,t.typeName,e),s=typeof i=="function"?lr(i(),e):i;if(s&&urr(t,e,s),e.postProcess){let a=e.postProcess(s,t,e);return o.jsonSchema=s,a}return o.jsonSchema=s,s}var crr,urr,Kl=b(()=>{wme();bme();nv();yWe();crr=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:pY(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,r)=>e.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),ea(e)):e.$refStrategy==="seen"?ea(e):void 0}},urr=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n)});var vWe,wWe=b(()=>{dHe();nv();Kl();vWe=(t,e)=>{let n=uHe(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[c,u])=>({...l,[c]:lr(u._def,{...n,currentPath:[...n.basePath,n.definitionPath,c]},!0)??ea(n)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=lr(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1)??ea(n),s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(i.title=s),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let a=o===void 0?r?{...i,[n.definitionPath]:r}:i:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...r,[o]:i}};return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var fjt=b(()=>{wme();dHe();aA();bme();nv();wHe();_He();SHe();Ame();kHe();IHe();PHe();EHe();OHe();RHe();$He();Mme();Ome();jHe();zHe();WHe();qHe();Nme();ZHe();JHe();QHe();tWe();rWe();iWe();aWe();cWe();dWe();pWe();hWe();yWe();Kl();wWe()});function drr(t){return(typeof t=="object"||typeof t=="function")&&t!==null&&"~standard"in t&&typeof t["~standard"]=="object"&&t["~standard"]!==null&&"validate"in t["~standard"]}function bWe(t){return(typeof t=="object"||typeof t=="function")&&t!==null&&"~standard"in t&&typeof t["~standard"]=="object"&&t["~standard"]!==null&&"jsonSchema"in t["~standard"]}function Ya(t){return drr(t)&&bWe(t)}var Nx=b(()=>{br()});function Hk(t,e){let n=typeof t;if(n!==typeof e)return!1;if(Array.isArray(t)){if(!Array.isArray(e))return!1;let r=t.length;if(r!==e.length)return!1;for(let o=0;o<r;o++)if(!Hk(t[o],e[o]))return!1;return!0}if(n==="object"){if(!t||!e)return t===e;let r=Object.keys(t),o=Object.keys(e);if(r.length!==o.length)return!1;for(let s of r)if(!Hk(t[s],e[s]))return!1;return!0}return t===e}var _We=b(()=>{});function eg(t){return encodeURI(frr(t))}function frr(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var Rme=b(()=>{});function Wk(t,e=Object.create(null),n=grr,r=""){if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t.$id||t.id;if(i){let s=new URL(i,n.href);s.hash.length>1?e[s.href]=t:(s.hash="",r===""?n=s:Wk(t,e,n))}}else if(t!==!0&&t!==!1)return e;let o=n.href+(r?"#"+r:"");if(e[o]!==void 0)throw new Error(`Duplicate schema URI "${o}".`);if(e[o]=t,t===!0||t===!1)return e;if(t.__absolute_uri__===void 0&&Object.defineProperty(t,"__absolute_uri__",{enumerable:!1,value:o}),t.$ref&&t.__absolute_ref__===void 0){let i=new URL(t.$ref,n.href);i.hash=i.hash,Object.defineProperty(t,"__absolute_ref__",{enumerable:!1,value:i.href})}if(t.$recursiveRef&&t.__absolute_recursive_ref__===void 0){let i=new URL(t.$recursiveRef,n.href);i.hash=i.hash,Object.defineProperty(t,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(t.$anchor){let i=new URL("#"+t.$anchor,n.href);e[i.href]=t}for(let i in t){if(hrr[i])continue;let s=`${r}/${eg(i)}`,a=t[i];if(Array.isArray(a)){if(prr[i]){let l=a.length;for(let c=0;c<l;c++)Wk(a[c],e,n,`${s}/${c}`)}}else if(mrr[i])for(let l in a)Wk(a[l],e,n,`${s}/${eg(l)}`);else Wk(a,e,n,s)}return e}var prr,mrr,hrr,grr,Lme=b(()=>{Rme();prr={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},mrr={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},hrr={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},grr=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker")});function Rx(t){return t.test.bind(t)}function Orr(t){return t%4===0&&(t%100!==0||t%400===0)}function pjt(t){let e=t.match(yrr);if(!e)return!1;let n=+e[1],r=+e[2],o=+e[3];return r>=1&&r<=12&&o>=1&&o<=(r==2&&Orr(n)?29:vrr[r])}function mjt(t,e){let n=e.match(wrr);if(!n)return!1;let r=+n[1],o=+n[2],i=+n[3],s=!!n[5];return(r<=23&&o<=59&&i<=59||r==23&&o==59&&i==60)&&(!t||s)}function Rrr(t){let e=t.split(Nrr);return e.length==2&&pjt(e[0])&&mjt(!0,e[1])}function Drr(t){return Lrr.test(t)&&$rr.test(t)}function Urr(t){if(Frr.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}var yrr,vrr,wrr,brr,_rr,xrr,Srr,Crr,krr,Irr,Trr,Prr,Arr,Err,Mrr,xWe,Nrr,Lrr,$rr,Frr,SWe=b(()=>{yrr=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,vrr=[0,31,28,31,30,31,30,31,31,30,31,30,31],wrr=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,brr=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,_rr=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,xrr=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,Srr=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,Crr=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,krr=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Irr=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Trr=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Prr=t=>{if(t[0]==='"')return!1;let[e,n,...r]=t.split("@");return!e||!n||r.length!==0||e.length>64||n.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:n.split(".").every(o=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(o))},Arr=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Err=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,Mrr=t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t));xWe={date:pjt,time:mjt.bind(void 0,!1),"date-time":Rrr,duration:Mrr,uri:Drr,"uri-reference":Rx(_rr),"uri-template":Rx(xrr),url:Rx(Srr),email:Prr,hostname:Rx(brr),ipv4:Rx(Arr),ipv6:Rx(Err),regex:Urr,uuid:Rx(Crr),"json-pointer":Rx(krr),"json-pointer-uri-fragment":Rx(Irr),"relative-json-pointer":Rx(Trr)};Nrr=/t|\s/i;Lrr=/\/|:/,$rr=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;Frr=/[^\\]\\Z/});var hjt,gjt=b(()=>{(function(t){t[t.Flag=1]="Flag",t[t.Basic=2]="Basic",t[t.Detailed=4]="Detailed"})(hjt||(hjt={}))});function yjt(t){let e=0,n=t.length,r=0,o;for(;r<n;)e++,o=t.charCodeAt(r++),o>=55296&&o<=56319&&r<n&&(o=t.charCodeAt(r),(o&64512)==56320&&r++);return e}var CWe=b(()=>{});function ta(t,e,n="2019-09",r=Wk(e),o=!0,i=null,s="#",a="#",l=Object.create(null)){if(e===!0)return{valid:!0,errors:[]};if(e===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};let c=typeof t,u;switch(c){case"boolean":case"number":case"string":u=c;break;case"object":t===null?u="null":Array.isArray(t)?u="array":u="object";break;default:throw new Error(`Instances of "${c}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:v,not:y,anyOf:w,allOf:_,oneOf:S,if:I,then:C,else:k,format:T,properties:P,patternProperties:E,additionalProperties:O,unevaluatedProperties:$,minProperties:U,maxProperties:V,propertyNames:K,dependentRequired:se,dependentSchemas:le,dependencies:Q,prefixItems:ne,items:ee,additionalItems:ae,unevaluatedItems:q,contains:F,minContains:z,maxContains:N,minItems:R,maxItems:X,uniqueItems:D,minimum:G,maximum:ce,exclusiveMinimum:Z,exclusiveMaximum:te,multipleOf:fe,minLength:de,maxLength:ye,pattern:Te,__absolute_ref__:Be,__absolute_recursive_ref__:qe}=e,Ae=[];if(p===!0&&i===null&&(i=e),f==="#"){let Ve=i===null?r[qe]:i,Ee=`${a}/$recursiveRef`,st=ta(t,i===null?e:i,n,r,o,Ve,s,Ee,l);st.valid||Ae.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:Ee,error:"A subschema had errors."},...st.errors)}if(d!==void 0){let Ee=r[Be||d];if(Ee===void 0){let He=`Unresolved $ref "${d}".`;throw Be&&Be!==d&&(He+=` Absolute URI "${Be}".`),He+=`
Known schemas:
- ${Object.keys(r).join(`
- `)}`,new Error(He)}let st=`${a}/$ref`,Ne=ta(t,Ee,n,r,o,i,s,st,l);if(Ne.valid||Ae.push({instanceLocation:s,keyword:"$ref",keywordLocation:st,error:"A subschema had errors."},...Ne.errors),n==="4"||n==="7")return{valid:Ae.length===0,errors:Ae}}if(Array.isArray(m)){let Ve=m.length,Ee=!1;for(let st=0;st<Ve;st++)if(u===m[st]||m[st]==="integer"&&u==="number"&&t%1===0&&t===t){Ee=!0;break}Ee||Ae.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join('", "')}".`})}else m==="integer"?(u!=="number"||t%1||t!==t)&&Ae.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&Ae.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u==="object"||u==="array"?Hk(t,h)||Ae.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):t!==h&&Ae.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),g!==void 0&&(u==="object"||u==="array"?g.some(Ve=>Hk(t,Ve))||Ae.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(Ve=>t===Ve)||Ae.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),y!==void 0){let Ve=`${a}/not`;ta(t,y,n,r,o,i,s,Ve).valid&&Ae.push({instanceLocation:s,keyword:"not",keywordLocation:Ve,error:'Instance matched "not" schema.'})}let Xt=[];if(w!==void 0){let Ve=`${a}/anyOf`,Ee=Ae.length,st=!1;for(let Ne=0;Ne<w.length;Ne++){let He=w[Ne],et=Object.create(l),it=ta(t,He,n,r,o,p===!0?i:null,s,`${Ve}/${Ne}`,et);Ae.push(...it.errors),st=st||it.valid,it.valid&&Xt.push(et)}st?Ae.length=Ee:Ae.splice(Ee,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:Ve,error:"Instance does not match any subschemas."})}if(_!==void 0){let Ve=`${a}/allOf`,Ee=Ae.length,st=!0;for(let Ne=0;Ne<_.length;Ne++){let He=_[Ne],et=Object.create(l),it=ta(t,He,n,r,o,p===!0?i:null,s,`${Ve}/${Ne}`,et);Ae.push(...it.errors),st=st&&it.valid,it.valid&&Xt.push(et)}st?Ae.length=Ee:Ae.splice(Ee,0,{instanceLocation:s,keyword:"allOf",keywordLocation:Ve,error:"Instance does not match every subschema."})}if(S!==void 0){let Ve=`${a}/oneOf`,Ee=Ae.length,st=S.filter((Ne,He)=>{let et=Object.create(l),it=ta(t,Ne,n,r,o,p===!0?i:null,s,`${Ve}/${He}`,et);return Ae.push(...it.errors),it.valid&&Xt.push(et),it.valid}).length;st===1?Ae.length=Ee:Ae.splice(Ee,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:Ve,error:`Instance does not match exactly one subschema (${st} matches).`})}if((u==="object"||u==="array")&&Object.assign(l,...Xt),I!==void 0){let Ve=`${a}/if`;if(ta(t,I,n,r,o,i,s,Ve,l).valid){if(C!==void 0){let st=ta(t,C,n,r,o,i,s,`${a}/then`,l);st.valid||Ae.push({instanceLocation:s,keyword:"if",keywordLocation:Ve,error:'Instance does not match "then" schema.'},...st.errors)}}else if(k!==void 0){let st=ta(t,k,n,r,o,i,s,`${a}/else`,l);st.valid||Ae.push({instanceLocation:s,keyword:"if",keywordLocation:Ve,error:'Instance does not match "else" schema.'},...st.errors)}}if(u==="object"){if(v!==void 0)for(let Ne of v)Ne in t||Ae.push({instanceLocation:s,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${Ne}".`});let Ve=Object.keys(t);if(U!==void 0&&Ve.length<U&&Ae.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${U} properties.`}),V!==void 0&&Ve.length>V&&Ae.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${V} properties.`}),K!==void 0){let Ne=`${a}/propertyNames`;for(let He in t){let et=`${s}/${eg(He)}`,it=ta(He,K,n,r,o,i,et,Ne);it.valid||Ae.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:Ne,error:`Property name "${He}" does not match schema.`},...it.errors)}}if(se!==void 0){let Ne=`${a}/dependantRequired`;for(let He in se)if(He in t){let et=se[He];for(let it of et)it in t||Ae.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:Ne,error:`Instance has "${He}" but does not have "${it}".`})}}if(le!==void 0)for(let Ne in le){let He=`${a}/dependentSchemas`;if(Ne in t){let et=ta(t,le[Ne],n,r,o,i,s,`${He}/${eg(Ne)}`,l);et.valid||Ae.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:He,error:`Instance has "${Ne}" but does not match dependant schema.`},...et.errors)}}if(Q!==void 0){let Ne=`${a}/dependencies`;for(let He in Q)if(He in t){let et=Q[He];if(Array.isArray(et))for(let it of et)it in t||Ae.push({instanceLocation:s,keyword:"dependencies",keywordLocation:Ne,error:`Instance has "${He}" but does not have "${it}".`});else{let it=ta(t,et,n,r,o,i,s,`${Ne}/${eg(He)}`);it.valid||Ae.push({instanceLocation:s,keyword:"dependencies",keywordLocation:Ne,error:`Instance has "${He}" but does not match dependant schema.`},...it.errors)}}}let Ee=Object.create(null),st=!1;if(P!==void 0){let Ne=`${a}/properties`;for(let He in P){if(!(He in t))continue;let et=`${s}/${eg(He)}`,it=ta(t[He],P[He],n,r,o,i,et,`${Ne}/${eg(He)}`);if(it.valid)l[He]=Ee[He]=!0;else if(st=o,Ae.push({instanceLocation:s,keyword:"properties",keywordLocation:Ne,error:`Property "${He}" does not match schema.`},...it.errors),st)break}}if(!st&&E!==void 0){let Ne=`${a}/patternProperties`;for(let He in E){let et=new RegExp(He,"u"),it=E[He];for(let Br in t){if(!et.test(Br))continue;let Xr=`${s}/${eg(Br)}`,An=ta(t[Br],it,n,r,o,i,Xr,`${Ne}/${eg(He)}`);An.valid?l[Br]=Ee[Br]=!0:(st=o,Ae.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:Ne,error:`Property "${Br}" matches pattern "${He}" but does not match associated schema.`},...An.errors))}}}if(!st&&O!==void 0){let Ne=`${a}/additionalProperties`;for(let He in t){if(Ee[He])continue;let et=`${s}/${eg(He)}`,it=ta(t[He],O,n,r,o,i,et,Ne);it.valid?l[He]=!0:(st=o,Ae.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:Ne,error:`Property "${He}" does not match additional properties schema.`},...it.errors))}}else if(!st&&$!==void 0){let Ne=`${a}/unevaluatedProperties`;for(let He in t)if(!l[He]){let et=`${s}/${eg(He)}`,it=ta(t[He],$,n,r,o,i,et,Ne);it.valid?l[He]=!0:Ae.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:Ne,error:`Property "${He}" does not match unevaluated properties schema.`},...it.errors)}}}else if(u==="array"){X!==void 0&&t.length>X&&Ae.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${t.length} > ${X}).`}),R!==void 0&&t.length<R&&Ae.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${t.length} < ${R}).`});let Ve=t.length,Ee=0,st=!1;if(ne!==void 0){let Ne=`${a}/prefixItems`,He=Math.min(ne.length,Ve);for(;Ee<He;Ee++){let et=ta(t[Ee],ne[Ee],n,r,o,i,`${s}/${Ee}`,`${Ne}/${Ee}`);if(l[Ee]=!0,!et.valid&&(st=o,Ae.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:Ne,error:"Items did not match schema."},...et.errors),st))break}}if(ee!==void 0){let Ne=`${a}/items`;if(Array.isArray(ee)){let He=Math.min(ee.length,Ve);for(;Ee<He;Ee++){let et=ta(t[Ee],ee[Ee],n,r,o,i,`${s}/${Ee}`,`${Ne}/${Ee}`);if(l[Ee]=!0,!et.valid&&(st=o,Ae.push({instanceLocation:s,keyword:"items",keywordLocation:Ne,error:"Items did not match schema."},...et.errors),st))break}}else for(;Ee<Ve;Ee++){let He=ta(t[Ee],ee,n,r,o,i,`${s}/${Ee}`,Ne);if(l[Ee]=!0,!He.valid&&(st=o,Ae.push({instanceLocation:s,keyword:"items",keywordLocation:Ne,error:"Items did not match schema."},...He.errors),st))break}if(!st&&ae!==void 0){let He=`${a}/additionalItems`;for(;Ee<Ve;Ee++){let et=ta(t[Ee],ae,n,r,o,i,`${s}/${Ee}`,He);l[Ee]=!0,et.valid||(st=o,Ae.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:He,error:"Items did not match additional items schema."},...et.errors))}}}if(F!==void 0)if(Ve===0&&z===void 0)Ae.push({instanceLocation:s,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(z!==void 0&&Ve<z)Ae.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${Ve}) than minContains (${z}).`});else{let Ne=`${a}/contains`,He=Ae.length,et=0;for(let it=0;it<Ve;it++){let Br=ta(t[it],F,n,r,o,i,`${s}/${it}`,Ne);Br.valid?(l[it]=!0,et++):Ae.push(...Br.errors)}et>=(z||0)&&(Ae.length=He),z===void 0&&N===void 0&&et===0?Ae.splice(He,0,{instanceLocation:s,keyword:"contains",keywordLocation:Ne,error:"Array does not contain item matching schema."}):z!==void 0&&et<z?Ae.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${z} items matching schema. Only ${et} items were found.`}):N!==void 0&&et>N&&Ae.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${N} items matching schema. ${et} items were found.`})}if(!st&&q!==void 0){let Ne=`${a}/unevaluatedItems`;for(Ee;Ee<Ve;Ee++){if(l[Ee])continue;let He=ta(t[Ee],q,n,r,o,i,`${s}/${Ee}`,Ne);l[Ee]=!0,He.valid||Ae.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:Ne,error:"Items did not match unevaluated items schema."},...He.errors)}}if(D)for(let Ne=0;Ne<Ve;Ne++){let He=t[Ne],et=typeof He=="object"&&He!==null;for(let it=0;it<Ve;it++){if(Ne===it)continue;let Br=t[it];(He===Br||et&&(typeof Br=="object"&&Br!==null)&&Hk(He,Br))&&(Ae.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${Ne} and ${it}.`}),Ne=Number.MAX_SAFE_INTEGER,it=Number.MAX_SAFE_INTEGER)}}}else if(u==="number"){if(n==="4"?(G!==void 0&&(Z===!0&&t<=G||t<G)&&Ae.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${t} is less than ${Z?"or equal to ":""} ${G}.`}),ce!==void 0&&(te===!0&&t>=ce||t>ce)&&Ae.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${t} is greater than ${te?"or equal to ":""} ${ce}.`})):(G!==void 0&&t<G&&Ae.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${t} is less than ${G}.`}),ce!==void 0&&t>ce&&Ae.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${t} is greater than ${ce}.`}),Z!==void 0&&t<=Z&&Ae.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${t} is less than ${Z}.`}),te!==void 0&&t>=te&&Ae.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${t} is greater than or equal to ${te}.`})),fe!==void 0){let Ve=t%fe;Math.abs(0-Ve)>=11920929e-14&&Math.abs(fe-Ve)>=11920929e-14&&Ae.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${t} is not a multiple of ${fe}.`})}}else if(u==="string"){let Ve=de===void 0&&ye===void 0?0:yjt(t);de!==void 0&&Ve<de&&Ae.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${Ve} < ${de}).`}),ye!==void 0&&Ve>ye&&Ae.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${Ve} > ${ye}).`}),Te!==void 0&&!new RegExp(Te,"u").test(t)&&Ae.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."}),T!==void 0&&xWe[T]&&!xWe[T](t)&&Ae.push({instanceLocation:s,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${T}".`})}return{valid:Ae.length===0,errors:Ae}}var kWe=b(()=>{_We();Lme();SWe();Rme();CWe()});var vjt=b(()=>{Lme();kWe()});var $me=b(()=>{_We();Lme();SWe();Rme();gjt();CWe();kWe();vjt()});function Ki(t,e){let n=!e&&t!=null&&typeof t=="object";if(n){let o=wjt.get(t);if(o)return o}let r;if(bWe(t)&&!yd(t))r=t["~standard"].jsonSchema.input({target:"draft-07"});else if(yd(t)){let o=iHe(t,!0);rL(o)?r=lk(dY(o,!0),e):r=lk(t,e)}else ev(t)?r=vWe(t):r=t;return n&&r!=null&&typeof r=="object"&&wjt.set(t,r),r}function _Y(t){if(!t||typeof t!="object"||Object.keys(t).length===0||Array.isArray(t))return!1;if("type"in t)return typeof t.type=="string"?t.type==="string":Array.isArray(t.type)?t.type.every(e=>e==="string"):!1;if("enum"in t)return Array.isArray(t.enum)&&t.enum.length>0&&t.enum.every(e=>typeof e=="string");if("const"in t)return typeof t.const=="string";if("allOf"in t&&Array.isArray(t.allOf))return t.allOf.some(e=>_Y(e));if("anyOf"in t&&Array.isArray(t.anyOf)||"oneOf"in t&&Array.isArray(t.oneOf)){let e="anyOf"in t?t.anyOf:t.oneOf;return e.length>0&&e.every(n=>_Y(n))}if("not"in t)return!1;if("$ref"in t&&typeof t.$ref=="string"){let e=t.$ref,n=Wk(t);return n[e]?_Y(n[e]):!1}return!1}var wjt,tg=b(()=>{br();Px();wWe();fjt();Nx();tf();$me();wjt=new WeakMap});function Vk(t){if(typeof t=="object"&&t!==null){let e={...t};"additionalProperties"in e&&delete e.additionalProperties,"$schema"in e&&delete e.$schema,"strict"in e&&delete e.strict;for(let n in e)n in e&&(Array.isArray(e[n])?e[n]=e[n].map(Vk):typeof e[n]=="object"&&e[n]!==null&&(e[n]=Vk(e[n])));return e}return t}function xY(t){let{$schema:e,...n}=Vk(ki(t)||Ya(t)?Ki(t):t);return n}function bjt(t){let{$schema:e,...n}=Vk(t);return n}var Dme=b(()=>{tv();tg();Nx()});function xL(t,e,n=[]){if(t==null||typeof t!="object")return;let r=t;if(Array.isArray(r.enum)&&r.enum.some(o=>o==="")){let o=n.length?` at path "${n.join(".")}"`:"",i=e?` in tool "${e}"`:"";throw new Error(`Invalid enum: empty string not allowed${i}${o}. Gemini API rejects empty strings in enums.`)}if(r.type==="object"&&r.properties&&typeof r.properties=="object")for(let[o,i]of Object.entries(r.properties))xL(i,e,[...n,o]);r.items&&xL(r.items,e,[...n,"[]"]);for(let o of["anyOf","oneOf","allOf"]){let i=r[o];Array.isArray(i)&&i.forEach((s,a)=>xL(s,e,[...n,`${o}[${a}]`]))}r.additionalProperties&&typeof r.additionalProperties=="object"&&xL(r.additionalProperties,e,[...n,"additionalProperties"])}var _jt=b(()=>{});function mf(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}function SY(t){return mf(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}function CY(t){return mf(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}function IWe(t){return mf(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}function TWe(t){if(mf(t)){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url}};if(t.source_type==="base64"){if(!t.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${t.mime_type};base64,${t.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function Fme(t){let e=t.split(";")[0].split("/");if(e.length!==2)throw new Error(`Invalid mime type: "${t}" - does not match type/subtype format.`);let n=e[0].trim(),r=e[1].trim();if(n===""||r==="")throw new Error(`Invalid mime type: "${t}" - type or subtype is empty.`);let o={};for(let i of t.split(";").slice(1)){let s=i.split("=");if(s.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${t}".`);let a=s[0].trim(),l=s[1].trim();if(a==="")throw new Error(`Invalid parameter syntax in mime type: "${t}".`);o[a]=l}return{type:n,subtype:r,parameters:o}}function hf({dataUrl:t,asTypedArray:e=!1}){let n=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),r;if(n){r=n[1].toLowerCase();let o=e?Uint8Array.from(atob(n[2]),i=>i.charCodeAt(0)):n[2];return{mime_type:r,data:o}}}function qk(t,e){if(t.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(t)}if(t.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(t)}if(t.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(t)}if(t.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(t)}throw new Error(`Unable to convert content block type '${t.type}' to provider-specific format: not recognized.`)}var kY=b(()=>{});function PWe(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}var AWe=b(()=>{});function Hrr(t){return t.replace(jrr,"$1_$2").replace(Brr,"$1_$2").replace(zrr,"_").toLowerCase()}function xjt(t,e){return e?.[t]||Hrr(t)}function Sjt(t,e,n){let r={};for(let o in t)Object.hasOwn(t,o)&&(r[e(o,n)]=t[o]);return r}var jrr,Brr,zrr,Cjt=b(()=>{jrr=/([A-Z]+)([A-Z][a-z0-9]+)/g,Brr=/([a-z0-9])([A-Z])/g,zrr=/[-_\s]+/g});function Vrr(t){return"lc"in t||Object.keys(t).length===1&&"__lc_escaped__"in t}function qrr(t){return{[Wrr]:t}}function Krr(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}function Grr(t){let e;return t!==null&&typeof t=="object"?"lc_id"in t&&Array.isArray(t.lc_id)?e=t.lc_id:e=[t.constructor?.name??"Object"]:e=[typeof t],{lc:1,type:"not_implemented",id:e}}function Ume(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return Grr(t);if(Krr(t))return t;e.add(t);let n=t;if(Vrr(n))return e.delete(t),qrr(n);let r={};for(let[o,i]of Object.entries(n))r[o]=Ume(i,e);return e.delete(t),r}return Array.isArray(t)?t.map(n=>Ume(n,e)):t}var Wrr,kjt=b(()=>{Wrr="__lc_escaped__"});function Ijt(t){return Array.isArray(t)?[...t]:{...t}}function Zrr(t,e){let n=Ijt(t);for(let[r,o]of Object.entries(e)){let[i,...s]=r.split(".").reverse(),a=n;for(let l of s.reverse()){if(a[l]===void 0)break;a[l]=Ijt(a[l]),a=a[l]}a[i]!==void 0&&(a[i]={lc:1,type:"secret",id:[o]})}return n}function EWe(t){let e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}var av,SL=b(()=>{br();Cjt();kjt();av=class Tjt{constructor(e,...n){M(this,"lc_serializable",!1);M(this,"lc_kwargs");this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([r])=>this.lc_serializable_keys?.includes(r))):this.lc_kwargs=e??{}}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,EWe(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof Tjt||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let e={},n={},r=Object.keys(this.lc_kwargs).reduce((a,l)=>(a[l]=l in this?this[l]:this.lc_kwargs[l],a),{});for(let a=Object.getPrototypeOf(this);a;a=Object.getPrototypeOf(a))Object.assign(e,Reflect.get(a,"lc_aliases",this)),Object.assign(n,Reflect.get(a,"lc_secrets",this)),Object.assign(r,Reflect.get(a,"lc_attributes",this));Object.keys(n).forEach(a=>{let l=this,c=r,[u,...d]=a.split(".").reverse();for(let f of d.reverse()){if(!(f in l)||l[f]===void 0)return;(!(f in c)||c[f]===void 0)&&(typeof l[f]=="object"&&l[f]!=null?c[f]={}:Array.isArray(l[f])&&(c[f]=[])),l=l[f],c=c[f]}u in l&&l[u]!==void 0&&(c[u]=c[u]||l[u])});let o={},i=new WeakSet;i.add(this);for(let[a,l]of Object.entries(r))o[a]=Ume(l,i);let s=Sjt(Object.keys(n).length?Zrr(o,n):o,xjt,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:s}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}});function Ft(t,e){return hn(t)&&t.type===e}function hn(t){return typeof t=="object"&&t!==null}function zc(t){return Array.isArray(t)}function Fe(t){return typeof t=="string"}function ng(t){return typeof t=="number"}function jme(t){return t instanceof Uint8Array}function MWe(t){try{return JSON.parse(t)}catch{return}}var rg,og=b(()=>{rg=t=>t()});function Yrr(t){if(t.type==="char_location"&&Fe(t.document_title)&&ng(t.start_char_index)&&ng(t.end_char_index)&&Fe(t.cited_text)){let{document_title:e,start_char_index:n,end_char_index:r,cited_text:o,...i}=t;return{...i,type:"citation",source:"char",title:e??void 0,startIndex:n,endIndex:r,citedText:o}}if(t.type==="page_location"&&Fe(t.document_title)&&ng(t.start_page_number)&&ng(t.end_page_number)&&Fe(t.cited_text)){let{document_title:e,start_page_number:n,end_page_number:r,cited_text:o,...i}=t;return{...i,type:"citation",source:"page",title:e??void 0,startIndex:n,endIndex:r,citedText:o}}if(t.type==="content_block_location"&&Fe(t.document_title)&&ng(t.start_block_index)&&ng(t.end_block_index)&&Fe(t.cited_text)){let{document_title:e,start_block_index:n,end_block_index:r,cited_text:o,...i}=t;return{...i,type:"citation",source:"block",title:e??void 0,startIndex:n,endIndex:r,citedText:o}}if(t.type==="web_search_result_location"&&Fe(t.url)&&Fe(t.title)&&Fe(t.encrypted_index)&&Fe(t.cited_text)){let{url:e,title:n,encrypted_index:r,cited_text:o,...i}=t;return{...i,type:"citation",source:"url",url:e,title:n,startIndex:Number(r),endIndex:Number(r),citedText:o}}if(t.type==="search_result_location"&&Fe(t.source)&&Fe(t.title)&&ng(t.start_block_index)&&ng(t.end_block_index)&&Fe(t.cited_text)){let{source:e,title:n,start_block_index:r,end_block_index:o,cited_text:i,...s}=t;return{...s,type:"citation",source:"search",url:e,title:n??void 0,startIndex:r,endIndex:o,citedText:i}}}function Ajt(t){if(Ft(t,"document")&&hn(t.source)&&"type"in t.source){if(t.source.type==="base64"&&Fe(t.source.media_type)&&Fe(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&Fe(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&Fe(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&Fe(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(Ft(t,"image")&&hn(t.source)&&"type"in t.source){if(t.source.type==="base64"&&Fe(t.source.media_type)&&Fe(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&Fe(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&Fe(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}function Ejt(t){function*e(){for(let n of t){let r=Ajt(n);r?yield r:yield n}}return Array.from(e())}function Pjt(t){function*e(){let n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let r of n){if(Ft(r,"text")&&Fe(r.text)){let{text:o,citations:i,...s}=r;if(zc(i)&&i.length){let a=i.reduce((l,c)=>{let u=Yrr(c);return u?[...l,u]:l},[]);yield{...s,type:"text",text:o,annotations:a};continue}else{yield{...s,type:"text",text:o};continue}}else if(Ft(r,"thinking")&&Fe(r.thinking)){let{thinking:o,signature:i,...s}=r;yield{...s,type:"reasoning",reasoning:o,signature:i};continue}else if(Ft(r,"redacted_thinking")){yield{type:"non_standard",value:r};continue}else if(Ft(r,"tool_use")&&Fe(r.name)&&Fe(r.id)){yield{type:"tool_call",id:r.id,name:r.name,args:r.input};continue}else if(Ft(r,"input_json_delta")){if(Jrr(t)&&t.tool_call_chunks?.length){let o=t.tool_call_chunks[0];yield{type:"tool_call_chunk",id:o.id,name:o.name,args:o.args,index:o.index};continue}}else if(Ft(r,"server_tool_use")&&Fe(r.name)&&Fe(r.id)){let{name:o,id:i}=r;if(o==="web_search"){yield{id:i,type:"server_tool_call",name:"web_search",args:{query:rg(()=>{if(typeof r.input=="string")return r.input;if(hn(r.input)&&Fe(r.input.query))return r.input.query;if(Fe(r.partial_json)){let s=MWe(r.partial_json);if(s?.query)return s.query}return""})}};continue}else if(r.name==="code_execution"){yield{id:i,type:"server_tool_call",name:"code_execution",args:{code:rg(()=>{if(typeof r.input=="string")return r.input;if(hn(r.input)&&Fe(r.input.code))return r.input.code;if(Fe(r.partial_json)){let s=MWe(r.partial_json);if(s?.code)return s.code}return""})}};continue}}else if(Ft(r,"web_search_tool_result")&&Fe(r.tool_use_id)&&zc(r.content)){let{content:o,tool_use_id:i}=r;yield{type:"server_tool_call_result",name:"web_search",toolCallId:i,status:"success",output:{urls:o.reduce((s,a)=>Ft(a,"web_search_result")?[...s,a.url]:s,[])}};continue}else if(Ft(r,"code_execution_tool_result")&&Fe(r.tool_use_id)&&hn(r.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}else if(Ft(r,"mcp_tool_use")){yield{id:r.id,type:"server_tool_call",name:"mcp_tool_use",args:r.input};continue}else if(Ft(r,"mcp_tool_result")&&Fe(r.tool_use_id)&&hn(r.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}else if(Ft(r,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:r.input};continue}else if(Ft(r,"search_result")){yield{id:r.id,type:"non_standard",value:r};continue}else if(Ft(r,"tool_result")){yield{id:r.id,type:"non_standard",value:r};continue}else{let o=Ajt(r);if(o){yield o;continue}}yield{type:"non_standard",value:r}}}return Array.from(e())}function Jrr(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}var Mjt,OWe=b(()=>{og();Mjt={translateContent:Pjt,translateContentChunk:Pjt}});function Xrr(t){return SY(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:CY(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:IWe(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}function Ojt(t){return t.map(Xrr)}function Njt(t){return!!(Ft(t,"image_url")&&hn(t.image_url)||Ft(t,"input_audio")&&hn(t.input_audio)||Ft(t,"file")&&hn(t.file))}function Rjt(t){if(Ft(t,"image_url")&&hn(t.image_url)&&Fe(t.image_url.url)){let e=hf({dataUrl:t.image_url.url});return e?{type:"image",mimeType:e.mime_type,data:e.data}:{type:"image",url:t.image_url.url}}else{if(Ft(t,"input_audio")&&hn(t.input_audio)&&Fe(t.input_audio.data)&&Fe(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(Ft(t,"file")&&hn(t.file)&&Fe(t.file.data)){let e=hf({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(Fe(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}var NWe=b(()=>{kY();og()});function Qrr(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Bme(t.content));for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}function eor(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Bme(t.content));for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}function Bme(t){let e=[];for(let n of t)Njt(n)?e.push(Rjt(n)):e.push(n);return e}function tor(t){if(t.type==="url_citation"){let{url:e,title:n,start_index:r,end_index:o}=t;return{type:"citation",url:e,title:n,startIndex:r,endIndex:o}}if(t.type==="file_citation"){let{file_id:e,filename:n,index:r}=t;return{type:"citation",title:n,startIndex:r,endIndex:r,fileId:e}}return t}function Ljt(t){function*e(){hn(t.additional_kwargs?.reasoning)&&zc(t.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:t.additional_kwargs.reasoning.summary.reduce((r,o)=>hn(o)&&Fe(o.text)?`${r}${o.text}`:r,"")});let n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let r of n)if(Ft(r,"text")){let{text:o,annotations:i,phase:s,extras:a,...l}=r,c=hn(a)?{...a}:{};Fe(s)&&(c.phase=s);let u=Object.keys(c).length>0?{extras:c}:{};Array.isArray(i)?yield{...l,...u,type:"text",text:String(o),annotations:i.map(tor)}:yield{...l,...u,type:"text",text:String(o)}}for(let r of t.tool_calls??[])yield{type:"tool_call",id:r.id,name:r.name,args:r.args};if(hn(t.additional_kwargs)&&zc(t.additional_kwargs.tool_outputs))for(let r of t.additional_kwargs.tool_outputs){if(Ft(r,"web_search_call")){let o={};if(hn(r.action)&&Fe(r.action.query)&&(o.query=r.action.query),yield{id:r.id,type:"server_tool_call",name:"web_search",args:o},r.status==="completed"||r.status==="failed"){let i={};hn(r.action)&&(i.action=r.action),yield{type:"server_tool_call_result",toolCallId:Fe(r.id)?r.id:"",status:r.status==="completed"?"success":"error",output:i}}continue}else if(Ft(r,"file_search_call")){yield{id:r.id,type:"server_tool_call",name:"file_search",args:{queries:zc(r.queries)?r.queries:[]}},(r.status==="completed"||r.status==="failed")&&(yield{type:"server_tool_call_result",toolCallId:Fe(r.id)?r.id:"",status:r.status==="completed"?"success":"error",output:zc(r.results)?{results:r.results}:{}});continue}else if(Ft(r,"computer_call")){yield{type:"non_standard",value:r};continue}else if(Ft(r,"code_interpreter_call")){if(Fe(r.code)&&(yield{id:r.id,type:"server_tool_call",name:"code_interpreter",args:{code:r.code}}),zc(r.outputs)){let o=rg(()=>{if(r.status!=="in_progress"){if(r.status==="completed")return 0;if(r.status==="incomplete")return 127;if(r.status!=="interpreting"&&r.status==="failed")return 1}});for(let i of r.outputs)if(Ft(i,"logs")){yield{type:"server_tool_call_result",toolCallId:r.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:o??0,stderr:[0,void 0].includes(o)?void 0:String(i.logs),stdout:[0,void 0].includes(o)?String(i.logs):void 0}};continue}}continue}else if(Ft(r,"mcp_call")){yield{id:r.id,type:"server_tool_call",name:"mcp_call",args:r.input};continue}else if(Ft(r,"mcp_list_tools")){yield{id:r.id,type:"server_tool_call",name:"mcp_list_tools",args:r.input};continue}else if(Ft(r,"mcp_approval_request")){yield{type:"non_standard",value:r};continue}else if(Ft(r,"tool_search_call")){let o={};hn(r.arguments)&&Object.assign(o,r.arguments);let i={};Fe(r.execution)&&(i.execution=r.execution),Fe(r.status)&&(i.status=r.status),Fe(r.call_id)&&(i.call_id=r.call_id),yield{id:Fe(r.id)?r.id:"",type:"server_tool_call",name:"tool_search",args:o,...Object.keys(i).length>0?{extras:i}:{}};continue}else if(Ft(r,"tool_search_output")){let o={name:"tool_search"};Fe(r.execution)&&(o.execution=r.execution),yield{type:"server_tool_call_result",toolCallId:Fe(r.id)?r.id:"",status:r.status==="completed"?"success":r.status==="failed"?"error":"success",output:{tools:zc(r.tools)?r.tools:[]},extras:o};continue}else if(Ft(r,"image_generation_call")){Fe(r.result)&&(yield{type:"image",mimeType:"image/png",data:r.result,id:Fe(r.id)?r.id:void 0,metadata:{status:Fe(r.status)?r.status:void 0}}),yield{type:"non_standard",value:r};continue}hn(r)&&(yield{type:"non_standard",value:r})}}return Array.from(e())}function nor(t){function*e(){yield*Ljt(t);for(let n of t.tool_call_chunks??[])yield{type:"tool_call_chunk",id:n.id,name:n.name,args:n.args}}return Array.from(e())}var $jt,RWe=b(()=>{og();NWe();$jt={translateContent:t=>typeof t.content=="string"?Qrr(t):Ljt(t),translateContentChunk:t=>typeof t.content=="string"?eor(t):nor(t)}});function Djt(t,e="pretty"){return e==="pretty"?ror(t):JSON.stringify(t)}function ror(t){let e=[],n=` ${t.type.charAt(0).toUpperCase()+t.type.slice(1)} Message `,r=Math.floor((80-n.length)/2),o="=".repeat(r),i=n.length%2===0?o:`${o}=`;if(e.push(`${o}${n}${i}`),t.type==="ai"){let s=t;if(s.tool_calls&&s.tool_calls.length>0){e.push("Tool Calls:");for(let a of s.tool_calls){e.push(` ${a.name} (${a.id})`),e.push(` Call ID: ${a.id}`),e.push(" Args:");for(let[l,c]of Object.entries(a.args))e.push(` ${l}: ${typeof c=="object"?JSON.stringify(c):c}`)}}}if(t.type==="tool"){let s=t;s.name&&e.push(`Name: ${s.name}`)}return typeof t.content=="string"&&t.content.trim()&&(e.length>1&&e.push(""),e.push(t.content)),e.join(`
`)}var Fjt=b(()=>{});function Ujt(t){return Array.isArray(t)?t:typeof t=="string"?t===""?[]:[{type:"text",text:t}]:t==null?[]:[t]}function Cp(t,e){if(typeof t=="string")return t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.length===0?t:Array.isArray(e)&&e.some(n=>mf(n))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e];if(Array.isArray(e)){let n=Ujt(t);return CL(n,e)??[...n,...e]}else return e===""?t:Array.isArray(t)&&t.some(n=>mf(n))?[...t,{type:"file",source_type:"text",text:e}]:[...Ujt(t),{type:"text",text:e}]}function $We(t,e){return t==="error"||e==="error"?"error":"success"}function oor(t,e){function n(r,o){if(typeof r!="object"||r===null||r===void 0)return r;if(o>=e)return Array.isArray(r)?"[Array]":"[Object]";if(Array.isArray(r))return r.map(s=>n(s,o+1));let i={};for(let s of Object.keys(r))i[s]=n(r[s],o+1);return i}return JSON.stringify(n(t,0),null,2)}function Oa(t,e,n){let r=n?.ignoreKeys??Wjt;if(t==null&&e==null)return;if(t==null||e==null)return t??e;let o={...t};for(let[i,s]of Object.entries(e))if(o[i]==null)o[i]=s;else{if(s==null)continue;if(typeof o[i]!=typeof s||Array.isArray(o[i])!==Array.isArray(s))throw new Error(`field[${i}] already exists in the message chunk, but with a different type.`);if(typeof o[i]=="string"){if(i==="type")continue;if(["id","name","output_version","model_provider"].includes(i))s&&(o[i]=s);else{if(r.includes(i))continue;o[i]+=s}}else if(typeof o[i]=="number"){if(r.includes(i))continue;o[i]=o[i]+s}else if(typeof o[i]=="object"&&!Array.isArray(o[i]))o[i]=Oa(o[i],s,n);else if(Array.isArray(o[i]))o[i]=CL(o[i],s,n);else{if(o[i]===s)continue;console.warn(`field[${i}] already exists in this message chunk and value has unsupported type.`)}}return o}function ior(t){return typeof t=="number"||typeof t=="string"}function jjt(t){return typeof t!="object"||t===null||!("index"in t)?!1:ior(t.index)}function Bjt(t){if(typeof t!="object"||t===null||!("id"in t))return!1;let e=t.id;return e!=null&&e!==""}function zjt(t){return t.endsWith("_delta")?t.slice(0,-6):t}function sor(t,e){return typeof t!="object"||t===null||typeof e!="object"||e===null||!("type"in t)||!("type"in e)?!1:typeof t.type=="string"&&typeof e.type=="string"&&zjt(t.type)!==zjt(e.type)}function aor(t,e){let n=jjt(e),r=Bjt(e);return!n&&!r?-1:t.findIndex(o=>{let i=jjt(o),s=Bjt(o);return n&&i?o.index!==e.index||sor(o,e)?!1:s&&r?o.id===e.id:!0:!n&&!i&&r&&s?o.id===e.id:!1})}function CL(t,e,n){if(!(t==null&&e==null)){if(t==null||e==null)return t||e;{let r=[...t];for(let o of e){let i=aor(r,o);if(i!==-1)r[i]=Oa(r[i],o,n);else{if(typeof o=="object"&&o!==null&&"text"in o&&o.text==="")continue;r.push(o)}}return r}}}function DWe(t,e,n){if(!(t==null&&e==null)){if(t==null||e==null)return t??e;if(typeof t!=typeof e)throw new Error(`Cannot merge objects of different types.
Left ${typeof t}
Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return CL(t,e,n);if(typeof t=="object"&&typeof e=="object")return Oa(t,e,n);if(t===e)return t;throw new Error(`Can not merge objects of different types.
Left ${t}
Right ${e}`)}}function FWe(t){return typeof t.role=="string"}function lv(t){return typeof t?._getType=="function"}function zme(t){return Em.isInstance(t)}var LWe,Hjt,bl,Wjt,Em,gf=b(()=>{SL();kY();OWe();NWe();RWe();AWe();Fjt();LWe=Symbol.for("langchain.message");bl=class extends av{constructor(e){let n=typeof e=="string"||Array.isArray(e)?{content:e}:e;n.additional_kwargs||(n.additional_kwargs={}),n.response_metadata||(n.response_metadata={});super(n);M(this,"lc_namespace",["langchain_core","messages"]);M(this,"lc_serializable",!0);M(this,Hjt,!0);M(this,"id");M(this,"name");M(this,"content");M(this,"additional_kwargs");M(this,"response_metadata");this.name=n.name,n.content===void 0&&n.contentBlocks!==void 0?(this.content=n.contentBlocks,this.response_metadata={output_version:"v1",...n.response_metadata}):n.content!==void 0?(this.content=n.content??[],this.response_metadata=n.response_metadata):(this.content=[],this.response_metadata=n.response_metadata),this.additional_kwargs=n.additional_kwargs,this.id=n.id}get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}_getType(){return this.type}getType(){return this._getType()}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}get contentBlocks(){let e=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[Ojt,Bme,Ejt].reduce((n,r)=>r(n),e)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){return typeof e=="object"&&e!==null&&LWe in e&&e[LWe]===!0&&PWe(e)}static[(Hjt=LWe,Symbol.hasInstance)](e){return this.isInstance(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;let n=oor(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${n}`}toFormattedString(e="pretty"){return Djt(this,e)}},Wjt=["index","created","timestamp"];Em=class Vjt extends bl{static isInstance(e){if(!super.isInstance(e))return!1;let n=Object.getPrototypeOf(e);for(;n!==null;){if(n===Vjt.prototype)return!0;n=Object.getPrototypeOf(n)}return!1}static[Symbol.hasInstance](e){return this.isInstance(e)}}});function UWe(t,e){return Oa(t,e)??{}}function qjt(t,e){let n={};return(t?.audio!==void 0||e?.audio!==void 0)&&(n.audio=(t?.audio??0)+(e?.audio??0)),(t?.image!==void 0||e?.image!==void 0)&&(n.image=(t?.image??0)+(e?.image??0)),(t?.video!==void 0||e?.video!==void 0)&&(n.video=(t?.video??0)+(e?.video??0)),(t?.document!==void 0||e?.document!==void 0)&&(n.document=(t?.document??0)+(e?.document??0)),(t?.text!==void 0||e?.text!==void 0)&&(n.text=(t?.text??0)+(e?.text??0)),n}function lor(t,e){let n={...qjt(t,e)};return(t?.cache_read!==void 0||e?.cache_read!==void 0)&&(n.cache_read=(t?.cache_read??0)+(e?.cache_read??0)),(t?.cache_creation!==void 0||e?.cache_creation!==void 0)&&(n.cache_creation=(t?.cache_creation??0)+(e?.cache_creation??0)),n}function cor(t,e){let n={...qjt(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(n.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),n}function IY(t,e){return{input_tokens:(t?.input_tokens??0)+(e?.input_tokens??0),output_tokens:(t?.output_tokens??0)+(e?.output_tokens??0),total_tokens:(t?.total_tokens??0)+(e?.total_tokens??0),input_token_details:lor(t?.input_token_details,e?.input_token_details),output_token_details:cor(t?.output_token_details,e?.output_token_details)}}var Hme=b(()=>{gf()});function jWe(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}function BWe(t){let e=[],n=[];for(let r of t)if(r.function){let o=r.function.name;try{let i=JSON.parse(r.function.arguments);e.push({name:o||"",args:i||{},id:r.id})}catch{n.push({name:o,args:r.function.arguments,id:r.id,error:"Malformed args."})}}else continue;return[e,n]}function zWe(t){return typeof t=="object"&&t!==null&&"getType"in t&&typeof t.getType=="function"&&t.getType()==="tool"}var ig,xz,Sz=b(()=>{br();gf();ig=class extends bl{constructor(e,n,r){let o=typeof e=="string"||Array.isArray(e)?{content:e,name:r,tool_call_id:n}:e;super(o);M(this,"lc_direct_tool_output",!0);M(this,"type","tool");M(this,"status");M(this,"tool_call_id");M(this,"metadata");M(this,"artifact");this.tool_call_id=o.tool_call_id,this.artifact=o.artifact,this.status=o.status,this.metadata=o.metadata}static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}static isInstance(e){return super.isInstance(e)&&e.type==="tool"}static[Symbol.hasInstance](e){return this.isInstance(e)}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},xz=class extends Em{constructor(e){super(e);M(this,"type","tool");M(this,"tool_call_id");M(this,"status");M(this,"artifact");this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}concat(e){let n=this.constructor;return new n({content:Cp(this.content,e.content),additional_kwargs:Oa(this.additional_kwargs,e.additional_kwargs),response_metadata:Oa(this.response_metadata,e.response_metadata),artifact:DWe(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:$We(this.status,e.status)})}static isInstance(e){return super.isInstance(e)&&e.type==="tool"}static[Symbol.hasInstance](e){return this.isInstance(e)}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}});function HWe(t){switch(t){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}function uor(t){if(hn(t.document)&&hn(t.document.source)){let e=HWe(hn(t.document)&&Fe(t.document.format)?t.document.format:"");if(hn(t.document.source)){if(hn(t.document.source.s3Location)&&Fe(t.document.source.s3Location.uri))return{type:"file",mimeType:e,fileId:t.document.source.s3Location.uri};if(jme(t.document.source.bytes))return{type:"file",mimeType:e,data:t.document.source.bytes};if(Fe(t.document.source.text))return{type:"file",mimeType:e,data:Buffer.from(t.document.source.text).toString("base64")};if(zc(t.document.source.content))return{type:"file",mimeType:e,data:t.document.source.content.reduce((n,r)=>hn(r)&&Fe(r.text)?n+r.text:n,"")}}}return{type:"non_standard",value:t}}function dor(t){if(Ft(t,"image")&&hn(t.image)){let e=HWe(hn(t.image)&&Fe(t.image.format)?t.image.format:"");if(hn(t.image.source)){if(hn(t.image.source.s3Location)&&Fe(t.image.source.s3Location.uri))return{type:"image",mimeType:e,fileId:t.image.source.s3Location.uri};if(jme(t.image.source.bytes))return{type:"image",mimeType:e,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}function por(t){if(Ft(t,"video")&&hn(t.video)){let e=HWe(hn(t.video)&&Fe(t.video.format)?t.video.format:"");if(hn(t.video.source)){if(hn(t.video.source.s3Location)&&Fe(t.video.source.s3Location.uri))return{type:"video",mimeType:e,fileId:t.video.source.s3Location.uri};if(jme(t.video.source.bytes))return{type:"video",mimeType:e,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}function Kjt(t){function*e(){let n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let r of n){if(Ft(r,"reasoning")&&Fe(r.reasoning)){yield{...r,type:"reasoning",reasoning:r.reasoning};continue}else if(Ft(r,"cache_point")){yield{type:"non_standard",value:r};continue}else if(Ft(r,"citations_content")&&hn(r.citationsContent)){yield{type:"text",text:zc(r.citationsContent.content)?r.citationsContent.content.reduce((o,i)=>hn(i)&&Fe(i.text)?o+i.text:o,""):"",annotations:zc(r.citationsContent.citations)?r.citationsContent.citations.reduce((o,i)=>{if(hn(i)){let s=zc(i.sourceContent)?i.sourceContent.reduce((l,c)=>hn(c)&&Fe(c.text)?l+c.text:l,""):"",a=rg(()=>{if(hn(i.location)){let l=i.location.documentChar||i.location.documentPage||i.location.documentChunk;if(hn(l))return{source:ng(l.documentIndex)?l.documentIndex.toString():void 0,startIndex:ng(l.start)?l.start:void 0,endIndex:ng(l.end)?l.end:void 0}}return{}});o.push({type:"citation",citedText:s,...a})}return o},[]):[]};continue}else if(Ft(r,"document")&&hn(r.document)){yield uor(r);continue}else if(Ft(r,"guard_content")){yield{type:"non_standard",value:r};continue}else if(Ft(r,"image")&&hn(r.image)){yield dor(r);continue}else if(Ft(r,"reasoning_content")&&hn(r.reasoningText)&&Fe(r.reasoningText.text)){yield{type:"reasoning",reasoning:r.reasoningText.text,...Fe(r.reasoningText.signature)?{signature:r.reasoningText.signature}:{}};continue}else if(Ft(r,"reasoning_content")&&Fe(r.reasoningText)){yield{type:"reasoning",reasoning:r.reasoningText};continue}else if(Ft(r,"text")&&Fe(r.text)){yield{type:"text",text:r.text};continue}else if(Ft(r,"tool_result")){yield{type:"non_standard",value:r};continue}else{if(Ft(r,"tool_call"))continue;if(Ft(r,"video")&&hn(r.video)){yield por(r);continue}}yield{type:"non_standard",value:r}}}return Array.from(e())}var Gjt,Zjt=b(()=>{og();Gjt={translateContent:Kjt,translateContentChunk:Kjt}});function Yjt(t){let e=[],n=t.additional_kwargs?.reasoning_content;if(Fe(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let r of t.content)typeof r=="object"&&"type"in r&&r.type==="text"&&"text"in r&&Fe(r.text)&&e.push({type:"text",text:r.text});for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}var Jjt,Xjt=b(()=>{og();Jjt={translateContent:Yjt,translateContentChunk:Yjt}});function Qjt(t){function*e(){let n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let r of n){if(Ft(r,"text")&&Fe(r.text)){yield{type:"text",text:r.text};continue}else if(Ft(r,"thinking")&&Fe(r.thinking)){yield{type:"reasoning",reasoning:r.thinking,...r.signature?{signature:r.signature}:{}};continue}else if(Ft(r,"inlineData")&&hn(r.inlineData)&&Fe(r.inlineData.mimeType)&&Fe(r.inlineData.data)){yield{type:"file",mimeType:r.inlineData.mimeType,data:r.inlineData.data};continue}else if(Ft(r,"functionCall")&&hn(r.functionCall)&&Fe(r.functionCall.name)&&hn(r.functionCall.args)){yield{type:"tool_call",id:t.id,name:r.functionCall.name,args:r.functionCall.args};continue}else if(Ft(r,"functionResponse")){yield{type:"non_standard",value:r};continue}else if(Ft(r,"fileData")&&hn(r.fileData)&&Fe(r.fileData.mimeType)&&Fe(r.fileData.fileUri)){yield{type:"file",mimeType:r.fileData.mimeType,fileId:r.fileData.fileUri};continue}else if(Ft(r,"executableCode")){yield{type:"non_standard",value:r};continue}else if(Ft(r,"codeExecutionResult")){yield{type:"non_standard",value:r};continue}yield{type:"non_standard",value:r}}}return Array.from(e())}var eBt,tBt=b(()=>{og();eBt={translateContent:Qjt,translateContentChunk:Qjt}});function nBt(t){function*e(){let n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let r of n){if(Ft(r,"reasoning")&&Fe(r.reasoning)){let o=rg(()=>{let i=n.indexOf(r);if(zc(t.additional_kwargs?.signatures)&&i>=0)return t.additional_kwargs.signatures.at(i)});Fe(o)?yield{type:"reasoning",reasoning:r.reasoning,signature:o}:yield{type:"reasoning",reasoning:r.reasoning};continue}else if(Ft(r,"thinking")&&Fe(r.thinking)){yield{type:"reasoning",reasoning:r.thinking,...r.signature?{signature:r.signature}:{}};continue}else if(Ft(r,"text")&&Fe(r.text)){yield{type:"text",text:r.text};continue}else if(Ft(r,"image_url")){if(Fe(r.image_url))if(r.image_url.startsWith("data:")){let o=r.image_url.match(/^data:([^;]+);base64,(.+)$/);o?yield{type:"image",data:o[2],mimeType:o[1]}:yield{type:"image",url:r.image_url}}else yield{type:"image",url:r.image_url};continue}else if(Ft(r,"media")&&Fe(r.mimeType)&&Fe(r.data)){yield{type:"file",mimeType:r.mimeType,data:r.data};continue}yield{type:"non_standard",value:r}}}return Array.from(e())}var rBt,oBt=b(()=>{og();rBt={translateContent:nBt,translateContentChunk:nBt}});function iBt(t){let e=[],n=t.additional_kwargs?.reasoning;if(Fe(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string"){let r=t.content,o=r.match(/<think>([\s\S]*?)<\/think>/);if(o){let i=o[1].trim();i.length>0&&e.push({type:"reasoning",reasoning:i}),r=r.replace(/<think>[\s\S]*?<\/think>/,"").trim()}r.length>0&&e.push({type:"text",text:r})}else for(let r of t.content)if(typeof r=="object"&&"type"in r&&r.type==="text"&&"text"in r&&Fe(r.text)){let o=r.text,i=o.match(/<think>([\s\S]*?)<\/think>/);if(i){let s=i[1].trim();s.length>0&&e.push({type:"reasoning",reasoning:s}),o=o.replace(/<think>[\s\S]*?<\/think>/,"").trim()}o.length>0&&e.push({type:"text",text:o})}for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}var sBt,aBt=b(()=>{og();sBt={translateContent:iBt,translateContentChunk:iBt}});function lBt(t){let e=[],n=t.additional_kwargs?.reasoning_content;if(Fe(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let r of t.content)typeof r=="object"&&"type"in r&&r.type==="text"&&"text"in r&&Fe(r.text)&&e.push({type:"text",text:r.text});for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}var cBt,uBt=b(()=>{og();cBt={translateContent:lBt,translateContentChunk:lBt}});function dBt(t){let e=[],n=t.additional_kwargs?.reasoning_details,r=!1;if(Array.isArray(n)&&n.length>0)for(let o of n){if(o==null||typeof o!="object")continue;let i=o.type;if(i==="reasoning.summary"){let s=o.summary;Fe(s)&&s.length>0&&(e.push({type:"reasoning",reasoning:s}),r=!0)}else if(i==="reasoning.text"){let s=o.text;Fe(s)&&s.length>0&&(e.push({type:"reasoning",reasoning:s}),r=!0)}}if(!r){let o=t.additional_kwargs?.reasoning_content;Fe(o)&&o.length>0&&e.push({type:"reasoning",reasoning:o})}if(typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let o of t.content)typeof o=="object"&&"type"in o&&o.type==="text"&&"text"in o&&Fe(o.text)&&e.push({type:"text",text:o.text});for(let o of t.tool_calls??[])e.push({type:"tool_call",id:o.id,name:o.name,args:o.args});return e}var fBt,pBt=b(()=>{og();fBt={translateContent:dBt,translateContentChunk:dBt}});function mBt(t){let e=[];if(hn(t.additional_kwargs?.reasoning)){let r=t.additional_kwargs.reasoning;if(zc(r.summary)){let o=r.summary.reduce((i,s)=>hn(s)&&Fe(s.text)?`${i}${s.text}`:i,"");o.length>0&&e.push({type:"reasoning",reasoning:o})}}let n=t.additional_kwargs?.reasoning_content;if(Fe(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let r of t.content)typeof r=="object"&&"type"in r&&r.type==="text"&&"text"in r&&Fe(r.text)&&e.push({type:"text",text:r.text});for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}var hBt,gBt=b(()=>{og();hBt={translateContent:mBt,translateContentChunk:mBt}});function yBt(t){function*e(){let n=rg(()=>{if(typeof t.content=="string")return t.additional_kwargs.originalTextContentBlock?[{...t.additional_kwargs.originalTextContentBlock,type:"text"}]:[{type:"text",text:t.content}];{let r=t.additional_kwargs?.originalTextContentBlock;if(r?.thoughtSignature&&!t.content.some(o=>"thoughtSignature"in o)){let o=[...t.content];for(let i=o.length-1;i>=0;i--){let s=o[i];if(s.type==="text"&&!s.thought)return s.thoughtSignature=r.thoughtSignature,o}}return t.content}});for(let r of n){let o=rg(()=>Ft(r,"text")&&Fe(r.text)?{type:"text",text:r.text}:Ft(r,"inlineData")&&hn(r.inlineData)&&Fe(r.inlineData.mimeType)&&Fe(r.inlineData.data)?{type:"file",mimeType:r.inlineData.mimeType,data:r.inlineData.data}:Ft(r,"functionCall")&&hn(r.functionCall)&&Fe(r.functionCall.name)&&hn(r.functionCall.args)?{type:"tool_call",id:t.id,name:r.functionCall.name,args:r.functionCall.args}:Ft(r,"functionResponse")?{type:"non_standard",value:r}:Ft(r,"fileData")&&hn(r.fileData)&&Fe(r.fileData.mimeType)&&Fe(r.fileData.fileUri)?{type:"file",mimeType:r.fileData.mimeType,fileId:r.fileData.fileUri}:Ft(r,"executableCode")?{type:"non_standard",value:r}:Ft(r,"codeExecutionResult")?{type:"non_standard",value:r}:{type:"non_standard",value:r}),i=rg(()=>"thought"in r&&r.thought?{type:"reasoning",reasoning:o.type==="text"?o.text:"",reasoningContentBlock:o}:o),s={thought:r.thought,thoughtSignature:r.thoughtSignature,partMetadata:r.partMetadata,...i};for(let a in s)s[a]===void 0&&delete s[a];yield s}}return Array.from(e())}var vBt,wBt=b(()=>{og();vBt={translateContent:yBt,translateContentChunk:yBt}});function WWe(t){return globalThis.lc_block_translators_registry.get(t)}var bBt=b(()=>{OWe();RWe();Zjt();Xjt();tBt();oBt();aBt();uBt();pBt();gBt();wBt();globalThis.lc_block_translators_registry??(globalThis.lc_block_translators_registry=new Map([["anthropic",Mjt],["bedrock-converse",Gjt],["deepseek",Jjt],["google",vBt],["google-genai",eBt],["google-vertexai",rBt],["groq",sBt],["ollama",cBt],["openai",$jt],["openrouter",fBt],["xai",hBt]]))});function _Bt(t){let e=Symbol.for(t);return{brand(n,r){var s;let o=r?Symbol.for(`${t}.${r}`):e;class i extends n{constructor(...c){super(...c);M(this,s,!0)}static isInstance(c){return typeof c=="object"&&c!==null&&o in c&&c[o]===!0}static[(s=o,Symbol.hasInstance)](c){return this.isInstance(c)}}return Object.defineProperty(i,"name",{value:n.name}),i},sub(n){return _Bt(`${t}.${n}`)},isInstance(n){return typeof n=="object"&&n!==null&&e in n&&n[e]===!0}}}var xBt,SBt=b(()=>{xBt=_Bt("langchain")});function fA(t,e){return t.lc_error_code=e,t.message=`${t.message}
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
`,t}function Gl(t,e){if(typeof t!="object"||t===null)return t;try{Object.defineProperty(t,CBt,{value:e,configurable:!0})}catch{}return t}function kBt(t){if(!(typeof t!="object"||t===null))return Object.getOwnPropertyDescriptor(t,CBt)?.value}var VWe,CBt,IBt,qWe,Wme,Kk=b(()=>{br();SBt();VWe=xBt.sub("error"),CBt=Symbol.for("langchain.errors.retryable");IBt=class extends VWe.brand(Error){constructor(e){super(e);M(this,"name","LangChainError");Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},qWe=class extends VWe.brand(IBt,"model-abort"){constructor(e,n){super(e);M(this,"name","ModelAbortError");M(this,"partialOutput");this.partialOutput=n,Gl(this,!1)}},Wme=class TBt extends VWe.brand(IBt,"context-overflow"){constructor(n){super(n??"Input exceeded the model's context window.");M(this,"name","ContextOverflowError");M(this,"cause");Gl(this,!1)}static fromError(n){let r=new TBt(n.message);return r.cause=n,r}}});function pA(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function PBt(t){return!!(t&&typeof t=="object"&&"toolCall"in t&&t.toolCall!=null&&typeof t.toolCall=="object"&&"id"in t.toolCall&&typeof t.toolCall.id=="string")}var TY,Vme=b(()=>{TY=class extends Error{constructor(e,n){super(e);M(this,"output");this.output=n}}});function Cz(t,e=kL){t=t.trim();let n=t.indexOf("```");if(n===-1)return e(t);let r=t.substring(n+3);r.startsWith(`json
`)?r=r.substring(5):r.startsWith("json")?r=r.substring(4):r.startsWith(`
`)&&(r=r.substring(1));let o=r.indexOf("```"),i=r;return o!==-1&&(i=r.substring(0,o)),e(i.trim())}function mor(t){try{return JSON.parse(t)}catch{}let e=t.trim();if(e.length===0)throw new Error("Unexpected end of JSON input");let n=0;function r(){for(;n<e.length&&/\s/.test(e[n]);)n+=1}function o(){if(e[n]!=='"')throw new Error(`Expected '"' at position ${n}, got '${e[n]}'`);n+=1;let u="",d=!1;for(;n<e.length;){let f=e[n];if(d){if(f==="n")u+=`
`;else if(f==="t")u+=" ";else if(f==="r")u+="\r";else if(f==="\\")u+="\\";else if(f==='"')u+='"';else if(f==="b")u+="\b";else if(f==="f")u+="\f";else if(f==="/")u+="/";else if(f==="u"){let p=e.substring(n+1,n+5);if(/^[0-9A-Fa-f]{0,4}$/.test(p))p.length===4?u+=String.fromCharCode(Number.parseInt(p,16)):u+=`u${p}`,n+=p.length;else throw new Error(`Invalid unicode escape sequence '\\u${p}' at position ${n}`)}else throw new Error(`Invalid escape sequence '\\${f}' at position ${n}`);d=!1}else if(f==="\\")d=!0;else{if(f==='"')return n+=1,u;u+=f}n+=1}return d&&(u+="\\"),u}function i(){let u=n,d="";if(e[n]==="-"&&(d+="-",n+=1),n<e.length&&e[n]==="0"&&(d+="0",n+=1,e[n]>="0"&&e[n]<="9"))throw new Error(`Invalid number at position ${u}`);if(n<e.length&&e[n]>="1"&&e[n]<="9")for(;n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(n<e.length&&e[n]===".")for(d+=".",n+=1;n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(n<e.length&&(e[n]==="e"||e[n]==="E"))for(d+=e[n],n+=1,n<e.length&&(e[n]==="+"||e[n]==="-")&&(d+=e[n],n+=1);n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(d==="-")return-0;let f=Number.parseFloat(d);if(Number.isNaN(f))throw n=u,new Error(`Invalid number '${d}' at position ${u}`);return f}function s(){if(r(),n>=e.length)throw new Error(`Unexpected end of input at position ${n}`);let u=e[n];if(u==="{")return l();if(u==="[")return a();if(u==='"')return o();if("null".startsWith(e.substring(n,n+4)))return n+=Math.min(4,e.length-n),null;if("true".startsWith(e.substring(n,n+4)))return n+=Math.min(4,e.length-n),!0;if("false".startsWith(e.substring(n,n+5)))return n+=Math.min(5,e.length-n),!1;if(u==="-"||u>="0"&&u<="9")return i();throw new Error(`Unexpected character '${u}' at position ${n}`)}function a(){if(e[n]!=="[")throw new Error(`Expected '[' at position ${n}, got '${e[n]}'`);let u=[];if(n+=1,r(),n>=e.length)return u;if(e[n]==="]")return n+=1,u;for(;n<e.length;){if(r(),n>=e.length||(u.push(s()),r(),n>=e.length))return u;if(e[n]==="]")return n+=1,u;if(e[n]===","){n+=1;continue}throw new Error(`Expected ',' or ']' at position ${n}, got '${e[n]}'`)}return u}function l(){if(e[n]!=="{")throw new Error(`Expected '{' at position ${n}, got '${e[n]}'`);let u={};if(n+=1,r(),n>=e.length)return u;if(e[n]==="}")return n+=1,u;for(;n<e.length;){if(r(),n>=e.length)return u;let d=o();if(r(),n>=e.length)return u;if(e[n]!==":")throw new Error(`Expected ':' at position ${n}, got '${e[n]}'`);if(n+=1,r(),n>=e.length||(u[d]=s(),r(),n>=e.length))return u;if(e[n]==="}")return n+=1,u;if(e[n]===","){n+=1;continue}throw new Error(`Expected ',' or '}' at position ${n}, got '${e[n]}'`)}return u}let c=s();if(r(),n<e.length)throw new Error(`Unexpected character '${e[n]}' at position ${n}`);return c}function kL(t){try{return typeof t>"u"?null:mor(t)}catch{return null}}var kz=b(()=>{});var yf,mA,PY=b(()=>{gf();yf=class ABt extends bl{constructor(n,r){(typeof n=="string"||Array.isArray(n))&&(n={content:n,role:r});super(n);M(this,"type","generic");M(this,"role");this.role=n.role}static lc_name(){return"ChatMessage"}static _chatMessageClass(){return ABt}static isInstance(n){return super.isInstance(n)&&n.type==="generic"}static[Symbol.hasInstance](n){return this.isInstance(n)}get _printableFields(){return{...super._printableFields,role:this.role}}},mA=class extends Em{constructor(e,n){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:n});super(e);M(this,"type","generic");M(this,"role");this.role=e.role}static lc_name(){return"ChatMessageChunk"}concat(e){let n=this.constructor;return new n({content:Cp(this.content,e.content),additional_kwargs:Oa(this.additional_kwargs,e.additional_kwargs),response_metadata:Oa(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="generic"}static[Symbol.hasInstance](e){return this.isInstance(e)}get _printableFields(){return{...super._printableFields,role:this.role}}}});var hA,qme=b(()=>{gf();hA=class extends Em{constructor(){super(...arguments);M(this,"type","function")}static lc_name(){return"FunctionMessageChunk"}concat(e){let n=this.constructor;return new n({content:Cp(this.content,e.content),additional_kwargs:Oa(this.additional_kwargs,e.additional_kwargs),response_metadata:Oa(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="function"}static[Symbol.hasInstance](e){return this.isInstance(e)}}});var na,gA,yA=b(()=>{gf();na=class extends bl{constructor(e){super(e);M(this,"type","human")}static lc_name(){return"HumanMessage"}static isInstance(e){return super.isInstance(e)&&e.type==="human"}static[Symbol.hasInstance](e){return this.isInstance(e)}},gA=class extends Em{constructor(e){super(e);M(this,"type","human")}static lc_name(){return"HumanMessageChunk"}concat(e){let n=this.constructor;return new n({content:Cp(this.content,e.content),additional_kwargs:Oa(this.additional_kwargs,e.additional_kwargs),response_metadata:Oa(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="human"}static[Symbol.hasInstance](e){return this.isInstance(e)}}});var Kme,Gme=b(()=>{gf();Kme=class extends bl{constructor(e){super({...e,content:[]});M(this,"type","remove");M(this,"id");this.id=e.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(e){return super.isInstance(e)&&e.type==="remove"}static[Symbol.hasInstance](e){return this.isInstance(e)}}});var sg,Lx,AY=b(()=>{gf();sg=class Zme extends bl{constructor(n){super(n);M(this,"type","system")}static lc_name(){return"SystemMessage"}concat(n){if(typeof n=="string")return new Zme({content:Cp(this.content,n),additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata,id:this.id,name:this.name});if(Zme.isInstance(n))return new Zme({content:Cp(this.content,n.content),additional_kwargs:{...this.additional_kwargs,...n.additional_kwargs},response_metadata:{...this.response_metadata,...n.response_metadata},id:this.id??n.id,name:this.name??n.name});throw new Error("Unexpected chunk type for system message")}static isInstance(n){return super.isInstance(n)&&n.type==="system"}static[Symbol.hasInstance](n){return this.isInstance(n)}},Lx=class extends Em{constructor(e){super(e);M(this,"type","system")}static lc_name(){return"SystemMessageChunk"}concat(e){let n=this.constructor;return new n({content:Cp(this.content,e.content),additional_kwargs:Oa(this.additional_kwargs,e.additional_kwargs),response_metadata:Oa(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="system"}static[Symbol.hasInstance](e){return this.isInstance(e)}}});function hor(t){return t.isCustomTool===!0}function gor(t){return pA(t)?t:typeof t.id=="string"&&t.type==="function"&&typeof t.function=="object"&&t.function!==null&&"arguments"in t.function&&typeof t.function.arguments=="string"&&"name"in t.function&&typeof t.function.name=="string"?{id:t.id,args:JSON.parse(t.function.arguments),name:t.function.name,type:"tool_call"}:t}function yor(t){return typeof t=="object"&&t!=null&&t.lc===1&&Array.isArray(t.id)&&t.kwargs!=null&&typeof t.kwargs=="object"}function KWe(t){let e,n;if(yor(t)){let r=t.id.at(-1);r==="HumanMessage"||r==="HumanMessageChunk"?e="user":r==="AIMessage"||r==="AIMessageChunk"?e="assistant":r==="SystemMessage"||r==="SystemMessageChunk"?e="system":r==="FunctionMessage"||r==="FunctionMessageChunk"?e="function":r==="ToolMessage"||r==="ToolMessageChunk"?e="tool":e="unknown",n=t.kwargs}else{let{type:r,...o}=t;e=r,n=o}if(e==="human"||e==="user")return new na(n);if(e==="ai"||e==="assistant"){let{tool_calls:r,...o}=n;if(!Array.isArray(r))return new cr(n);let i=r.map(gor);return new cr({...o,tool_calls:i})}else{if(e==="system")return new sg(n);if(e==="developer")return new sg({...n,additional_kwargs:{...n.additional_kwargs,__openai_role__:"developer"}});if(e==="tool"&&"tool_call_id"in n)return new ig({...n,content:n.content,tool_call_id:n.tool_call_id,name:n.name});if(e==="remove"&&"id"in n&&typeof n.id=="string")return new Kme({...n,id:n.id});throw fA(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
Received: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function hb(t){if(typeof t=="string")return new na(t);if(lv(t))return t;if(Array.isArray(t)){let[e,n]=t;return KWe({type:e,content:n})}else if(FWe(t)){let{role:e,...n}=t;return KWe({...n,type:e})}else return KWe(t)}function vor(t){if(typeof t=="string")return t;switch(t.type){case"text":return t.text??"";case"text-plain":return t.text??"[text-plain file]";case"image":case"image_url":return"[image]";case"audio":case"input_audio":return"[audio]";case"video":return"[video]";case"file":return"[file]";case"reasoning":case"tool_call":case"tool_call_chunk":case"invalid_tool_call":case"server_tool_call":case"server_tool_call_chunk":case"server_tool_call_result":case"non_standard":return"";default:return t.type?`[${t.type}]`:""}}function Mm(t,e="Human",n="AI"){let r=[];for(let o of t){let i;if(o.type==="human")i=e;else if(o.type==="ai")i=n;else if(o.type==="system")i="System";else if(o.type==="tool")i="Tool";else if(o.type==="generic")i=o.role;else throw new Error(`Got unsupported message type: ${o.type}`);let s=o.name?`${o.name}, `:"",a=typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.map(vor).filter(Boolean).join(""):"",l=`${i}: ${s}${a}`;if(o.type==="ai"){let c=o;c.tool_calls&&c.tool_calls.length>0?l+=JSON.stringify(c.tool_calls):c.additional_kwargs&&"function_call"in c.additional_kwargs&&(l+=JSON.stringify(c.additional_kwargs.function_call))}r.push(l)}return r.join(`
`)}function Yme(t){let e=t._getType();if(e==="human")return new gA({...t});if(e==="ai"){let n={...t};return"tool_calls"in n&&(n={...n,tool_call_chunks:n.tool_calls?.map(r=>({...r,type:"tool_call_chunk",index:void 0,args:JSON.stringify(r.args)}))}),new On({...n})}else{if(e==="system")return new Lx({...t});if(e==="function")return new hA({...t});if(yf.isInstance(t))return new mA({...t});throw new Error("Unknown message type.")}}function ZWe(t){let e=t.reduce((o,i)=>{let s=o.findIndex(([a])=>"id"in i&&i.id&&"index"in i&&i.index!==void 0?i.id===a.id&&i.index===a.index:"id"in i&&i.id?i.id===a.id:"index"in i&&i.index!==void 0?i.index===a.index:!1);return s!==-1?o[s].push(i):o.push([i]),o},[]),n=[],r=[];for(let o of e){let i=null,s=o.some(hor),a=o[0]?.name??"",l=o.map(f=>f.args||"").join(""),c=s?l:l.trim(),u=c.length?c:"{}",d=o.find(f=>f.id)?.id??o[0]?.id;if(s&&d){n.push({name:a,args:{input:c},id:d,type:"tool_call"});continue}try{if(i=kL(u),!d||i===null||typeof i!="object"||Array.isArray(i))throw new Error("Malformed tool call chunk args.");n.push({name:a,args:i,id:d,type:"tool_call"})}catch{r.push({name:a,args:u,id:d,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:t,tool_calls:n,invalid_tool_calls:r}}var GWe,gb=b(()=>{Kk();Vme();kz();gf();Sz();Om();PY();qme();yA();Gme();AY();GWe=t=>t()});function MBt(t){return typeof t=="string"?t.length>0?[{type:"text",text:t}]:[]:Array.isArray(t)?t:t==null?[]:[t]}function cv(t){return t._getType()==="ai"}function Jme(t){return t._getType()==="ai"}var cr,On,Om=b(()=>{gf();bBt();Hme();Sz();gb();cr=class extends bl{constructor(e){let n;if(typeof e=="string"||Array.isArray(e))n={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{n=e;let r=n.additional_kwargs?.tool_calls,o=n.tool_calls;r!=null&&r.length>0&&(o===void 0||o.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(r!=null&&o===void 0){let[i,s]=BWe(r);n.tool_calls=i??[],n.invalid_tool_calls=s??[]}else n.tool_calls=n.tool_calls??[],n.invalid_tool_calls=n.invalid_tool_calls??[]}catch{n.tool_calls=[],n.invalid_tool_calls=[]}if(n.response_metadata!==void 0&&"output_version"in n.response_metadata&&n.response_metadata.output_version==="v1"&&n.content!==void 0&&(n.contentBlocks=MBt(n.content),n.content=void 0),n.contentBlocks!==void 0){if(Array.isArray(n.contentBlocks)||(n.contentBlocks=MBt(n.contentBlocks)),n.tool_calls){let s=n.tool_calls.filter(a=>!n.contentBlocks?.some(l=>l.type==="tool_call"&&l.id===a.id&&l.name===a.name));n.contentBlocks.push(...s.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args})))}let i=n.contentBlocks.filter(s=>s.type==="tool_call").filter(s=>!n.tool_calls?.some(a=>a.id===s.id&&a.name===s.name));i.length>0&&(n.tool_calls=[...n.tool_calls??[],...i.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args}))])}}super(n);M(this,"type","ai");M(this,"tool_calls",[]);M(this,"invalid_tool_calls",[]);M(this,"usage_metadata");typeof n!="string"&&(this.tool_calls=n.tool_calls??this.tool_calls,this.invalid_tool_calls=n.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=n.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let n=WWe(this.response_metadata.model_provider);if(n)return n.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls){let n=this.tool_calls.filter(r=>!e.some(o=>o.id===r.id&&o.name===r.name));e.push(...n.map(r=>({type:"tool_call",id:r.id,name:r.name,args:r.args})))}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}static[Symbol.hasInstance](e){return this.isInstance(e)}};On=class extends Em{constructor(e){let n;if(typeof e=="string"||Array.isArray(e))n={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0||e.tool_call_chunks.length===0)n={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{let r=ZWe(e.tool_call_chunks??[]);n={...e,tool_call_chunks:r.tool_call_chunks,tool_calls:r.tool_calls,invalid_tool_calls:r.invalid_tool_calls,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(n);M(this,"type","ai");M(this,"tool_calls",[]);M(this,"invalid_tool_calls",[]);M(this,"tool_call_chunks",[]);M(this,"usage_metadata");this.tool_call_chunks=n.tool_call_chunks??this.tool_call_chunks,this.tool_calls=n.tool_calls??this.tool_calls,this.invalid_tool_calls=n.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=n.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let n=WWe(this.response_metadata.model_provider);if(n)return n.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){let n=this.content.filter(r=>r.type==="tool_call").map(r=>r.id);for(let r of this.tool_calls)r.id&&!n.includes(r.id)&&e.push({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){let n={content:Cp(this.content,e.content),additional_kwargs:Oa(this.additional_kwargs,e.additional_kwargs),response_metadata:UWe(this.response_metadata,e.response_metadata),tool_call_chunks:[],tool_calls:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){let o=CL(this.tool_call_chunks,e.tool_call_chunks);o!==void 0&&o.length>0&&(n.tool_call_chunks=o)}if(this.tool_calls!==void 0||e.tool_calls!==void 0){let o=CL(this.tool_calls,e.tool_calls);o!==void 0&&o.length>0&&(n.tool_calls=o)}(this.usage_metadata!==void 0||e.usage_metadata!==void 0)&&(n.usage_metadata=IY(this.usage_metadata,e.usage_metadata));let r=this.constructor;return new r(n)}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}static[Symbol.hasInstance](e){return this.isInstance(e)}}});var OBt=b(()=>{});var NBt=b(()=>{});var RBt,LBt=b(()=>{RBt=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});function Iz(t){return typeof t=="string"&&RBt.test(t)}var EY=b(()=>{LBt()});function MY(t){if(!Iz(t))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(t.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(t.slice(9,13),16))>>>8,e&255,(e=parseInt(t.slice(14,18),16))>>>8,e&255,(e=parseInt(t.slice(19,23),16))>>>8,e&255,(e=parseInt(t.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}var Xme=b(()=>{EY()});function Gk(t,e=0){return(wd[t[e+0]]+wd[t[e+1]]+wd[t[e+2]]+wd[t[e+3]]+"-"+wd[t[e+4]]+wd[t[e+5]]+"-"+wd[t[e+6]]+wd[t[e+7]]+"-"+wd[t[e+8]]+wd[t[e+9]]+"-"+wd[t[e+10]]+wd[t[e+11]]+wd[t[e+12]]+wd[t[e+13]]+wd[t[e+14]]+wd[t[e+15]]).toLowerCase()}var wd,vA=b(()=>{EY();wd=[];for(let t=0;t<256;++t)wd.push((t+256).toString(16).slice(1))});function Tz(){return crypto.getRandomValues(wor)}var wor,Qme=b(()=>{wor=new Uint8Array(16)});var YWe=b(()=>{vA();Qme()});function $Bt(t,e,n){return!e&&!t&&crypto.randomUUID?crypto.randomUUID():bor(t,e,n)}function bor(t,e,n){t=t||{};let r=t.random??t.rng?.()??Tz();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return Gk(r)}var DBt=b(()=>{vA();Qme()});function _or(t,e,n,r){switch(t){case 0:return e&n^~e&r;case 1:return e^n^r;case 2:return e&n^e&r^n&r;case 3:return e^n^r}}function JWe(t,e){return t<<e|t>>>32-e}function FBt(t){let e=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520],r=new Uint8Array(t.length+1);r.set(t),r[t.length]=128,t=r;let o=t.length/4+2,i=Math.ceil(o/16),s=new Array(i);for(let a=0;a<i;++a){let l=new Uint32Array(16);for(let c=0;c<16;++c)l[c]=t[a*64+c*4]<<24|t[a*64+c*4+1]<<16|t[a*64+c*4+2]<<8|t[a*64+c*4+3];s[a]=l}s[i-1][14]=(t.length-1)*8/2**32,s[i-1][14]=Math.floor(s[i-1][14]),s[i-1][15]=(t.length-1)*8&4294967295;for(let a=0;a<i;++a){let l=new Uint32Array(80);for(let m=0;m<16;++m)l[m]=s[a][m];for(let m=16;m<80;++m)l[m]=JWe(l[m-3]^l[m-8]^l[m-14]^l[m-16],1);let c=n[0],u=n[1],d=n[2],f=n[3],p=n[4];for(let m=0;m<80;++m){let h=Math.floor(m/20),g=JWe(c,5)+_or(h,u,d,f)+p+e[h]+l[m]>>>0;p=f,f=d,d=JWe(u,30)>>>0,u=c,c=g}n[0]=n[0]+c>>>0,n[1]=n[1]+u>>>0,n[2]=n[2]+d>>>0,n[3]=n[3]+f>>>0,n[4]=n[4]+p>>>0}return Uint8Array.of(n[0]>>24,n[0]>>16,n[0]>>8,n[0],n[1]>>24,n[1]>>16,n[1]>>8,n[1],n[2]>>24,n[2]>>16,n[2]>>8,n[2],n[3]>>24,n[3]>>16,n[3]>>8,n[3],n[4]>>24,n[4]>>16,n[4]>>8,n[4])}var UBt=b(()=>{});function xor(t){t=unescape(encodeURIComponent(t));let e=new Uint8Array(t.length);for(let n=0;n<t.length;++n)e[n]=t.charCodeAt(n);return e}function zBt(t,e,n,r,o,i){let s=typeof n=="string"?xor(n):n,a=typeof r=="string"?MY(r):r;if(typeof r=="string"&&(r=MY(r)),r?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+s.length);if(l.set(a),l.set(s,a.length),l=e(l),l[6]=l[6]&15|t,l[8]=l[8]&63|128,o){if(i??(i=0),i<0||i+16>o.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);for(let c=0;c<16;++c)o[i+c]=l[c];return o}return Gk(l)}var jBt,BBt,HBt=b(()=>{Xme();vA();jBt="6ba7b810-9dad-11d1-80b4-00c04fd430c8",BBt="6ba7b811-9dad-11d1-80b4-00c04fd430c8"});function XWe(t,e,n,r){return zBt(80,FBt,t,e,n,r)}var WBt=b(()=>{UBt();HBt();XWe.DNS=jBt;XWe.URL=BBt});var VBt=b(()=>{Xme();vA()});var qBt=b(()=>{vA();YWe();VBt()});function GBt(t,e,n){let r;if(t)r=KBt(t.random??t.rng?.()??Tz(),t.msecs,t.seq,e,n);else{let o=Date.now(),i=Tz();Cor(QWe,o,i),r=KBt(i,QWe.msecs,QWe.seq,e,n)}return e??Gk(r)}function Cor(t,e,n){return t.msecs??(t.msecs=-1/0),t.seq??(t.seq=0),e>t.msecs?(t.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}function KBt(t,e,n,r,o=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!r)r=new Uint8Array(16),o=0;else if(o<0||o+16>r.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);return e??(e=Date.now()),n??(n=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9]),r[o++]=e/1099511627776&255,r[o++]=e/4294967296&255,r[o++]=e/16777216&255,r[o++]=e/65536&255,r[o++]=e/256&255,r[o++]=e&255,r[o++]=112|n>>>28&15,r[o++]=n>>>20&255,r[o++]=128|n>>>14&63,r[o++]=n>>>6&255,r[o++]=n<<2&255|t[10]&3,r[o++]=t[11],r[o++]=t[12],r[o++]=t[13],r[o++]=t[14],r[o++]=t[15],r}var QWe,ZBt=b(()=>{vA();Qme();QWe={}});var YBt=b(()=>{EY()});var IL,yb,OY,TL=b(()=>{br();OBt();NBt();EY();Xme();vA();YWe();DBt();WBt();qBt();ZBt();YBt();IL=$Bt,yb=GBt,OY=Iz});var JBt,PL,XBt,wA,NY=b(()=>{JBt=Symbol.for("ls:tracing_async_local_storage"),PL=Symbol.for("lc:context_variables"),XBt=t=>{globalThis[JBt]=t},wA=()=>globalThis[JBt]});function QBt(){return e6e===void 0&&(e6e={library:"langchain-js",runtime:n6e()}),e6e}function Nn(t){try{return typeof process<"u"?process.env?.[t]:t6e()?Deno?.env.get(t):void 0}catch{return}}var kor,Ior,Tor,t6e,Por,n6e,e6e,ys=b(()=>{br();kor=()=>typeof window<"u"&&typeof window.document<"u",Ior=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Tor=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),t6e=()=>typeof Deno<"u",Por=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!t6e(),n6e=()=>{let t;return kor()?t="browser":Por()?t="node":Ior()?t="webworker":Tor()?t="jsdom":t6e()?t="deno":t="other",t}});function r6e(t){return"lc_prefer_streaming"in t&&t.lc_prefer_streaming}function ezt(t){return"lc_prefer_chat_model_stream_events"in t&&t.lc_prefer_chat_model_stream_events}var Aor,Pz,tzt,RY=b(()=>{br();SL();TL();ys();Aor=class{};Pz=class extends Aor{constructor(e){super();M(this,"lc_serializable",!1);M(this,"lc_kwargs");M(this,"ignoreLLM",!1);M(this,"ignoreChain",!1);M(this,"ignoreAgent",!1);M(this,"ignoreRetriever",!1);M(this,"ignoreCustomEvent",!1);M(this,"raiseError",!1);M(this,"awaitHandlers",Nn("LANGCHAIN_CALLBACKS_BACKGROUND")==="false");this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,EWe(this.constructor)]}copy(){return new this.constructor(this)}toJSON(){return av.prototype.toJSON.call(this)}toJSONNotImplemented(){return av.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class n extends Pz{constructor(){super();M(this,"name",yb());Object.assign(this,e)}}return new n}},tzt=t=>{let e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"}});var nzt=b(()=>{});var rzt=b(()=>{});var ozt,izt=b(()=>{ozt=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});function Eor(t){return typeof t=="string"&&ozt.test(t)}var LY,$Y=b(()=>{izt();LY=Eor});function Mor(t){if(!LY(t))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(t.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(t.slice(9,13),16))>>>8,e&255,(e=parseInt(t.slice(14,18),16))>>>8,e&255,(e=parseInt(t.slice(19,23),16))>>>8,e&255,(e=parseInt(t.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}var ehe,o6e=b(()=>{$Y();ehe=Mor});function Az(t,e=0){return(bd[t[e+0]]+bd[t[e+1]]+bd[t[e+2]]+bd[t[e+3]]+"-"+bd[t[e+4]]+bd[t[e+5]]+"-"+bd[t[e+6]]+bd[t[e+7]]+"-"+bd[t[e+8]]+bd[t[e+9]]+"-"+bd[t[e+10]]+bd[t[e+11]]+bd[t[e+12]]+bd[t[e+13]]+bd[t[e+14]]+bd[t[e+15]]).toLowerCase()}var bd,DY=b(()=>{$Y();bd=[];for(let t=0;t<256;++t)bd.push((t+256).toString(16).slice(1))});function Ez(){return crypto.getRandomValues(Oor)}var Oor,i6e=b(()=>{Oor=new Uint8Array(16)});function Nor(t,e,n){return!e&&!t&&crypto.randomUUID?crypto.randomUUID():Ror(t,e,n)}function Ror(t,e,n){t=t||{};let r=t.random??t.rng?.()??Ez();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return Az(r)}var AL,szt=b(()=>{i6e();DY();AL=Nor});function Lor(t,e,n,r){switch(t){case 0:return e&n^~e&r;case 1:return e^n^r;case 2:return e&n^e&r^n&r;case 3:return e^n^r}}function s6e(t,e){return t<<e|t>>>32-e}function $or(t){let e=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520],r=new Uint8Array(t.length+1);r.set(t),r[t.length]=128,t=r;let o=t.length/4+2,i=Math.ceil(o/16),s=new Array(i);for(let a=0;a<i;++a){let l=new Uint32Array(16);for(let c=0;c<16;++c)l[c]=t[a*64+c*4]<<24|t[a*64+c*4+1]<<16|t[a*64+c*4+2]<<8|t[a*64+c*4+3];s[a]=l}s[i-1][14]=(t.length-1)*8/2**32,s[i-1][14]=Math.floor(s[i-1][14]),s[i-1][15]=(t.length-1)*8&4294967295;for(let a=0;a<i;++a){let l=new Uint32Array(80);for(let m=0;m<16;++m)l[m]=s[a][m];for(let m=16;m<80;++m)l[m]=s6e(l[m-3]^l[m-8]^l[m-14]^l[m-16],1);let c=n[0],u=n[1],d=n[2],f=n[3],p=n[4];for(let m=0;m<80;++m){let h=Math.floor(m/20),g=s6e(c,5)+Lor(h,u,d,f)+p+e[h]+l[m]>>>0;p=f,f=d,d=s6e(u,30)>>>0,u=c,c=g}n[0]=n[0]+c>>>0,n[1]=n[1]+u>>>0,n[2]=n[2]+d>>>0,n[3]=n[3]+f>>>0,n[4]=n[4]+p>>>0}return Uint8Array.of(n[0]>>24,n[0]>>16,n[0]>>8,n[0],n[1]>>24,n[1]>>16,n[1]>>8,n[1],n[2]>>24,n[2]>>16,n[2]>>8,n[2],n[3]>>24,n[3]>>16,n[3]>>8,n[3],n[4]>>24,n[4]>>16,n[4]>>8,n[4])}var azt,lzt=b(()=>{azt=$or});function Dor(t){t=unescape(encodeURIComponent(t));let e=new Uint8Array(t.length);for(let n=0;n<t.length;++n)e[n]=t.charCodeAt(n);return e}function c6e(t,e,n,r,o,i){let s=typeof n=="string"?Dor(n):n,a=typeof r=="string"?ehe(r):r;if(typeof r=="string"&&(r=ehe(r)),r?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+s.length);if(l.set(a),l.set(s,a.length),l=e(l),l[6]=l[6]&15|t,l[8]=l[8]&63|128,o){if(i??(i=0),i<0||i+16>o.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);for(let c=0;c<16;++c)o[i+c]=l[c];return o}return Az(l)}var a6e,l6e,u6e=b(()=>{o6e();DY();a6e="6ba7b810-9dad-11d1-80b4-00c04fd430c8",l6e="6ba7b811-9dad-11d1-80b4-00c04fd430c8"});function d6e(t,e,n,r){return c6e(80,azt,t,e,n,r)}var f6e,czt=b(()=>{lzt();u6e();u6e();d6e.DNS=a6e;d6e.URL=l6e;f6e=d6e});function For(t,e,n){let r;if(t)r=uzt(t.random??t.rng?.()??Ez(),t.msecs,t.seq,e,n);else{let o=Date.now(),i=Ez();Uor(p6e,o,i),r=uzt(i,p6e.msecs,p6e.seq,e,n)}return e??Az(r)}function Uor(t,e,n){return t.msecs??(t.msecs=-1/0),t.seq??(t.seq=0),e>t.msecs?(t.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}function uzt(t,e,n,r,o=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!r)r=new Uint8Array(16),o=0;else if(o<0||o+16>r.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);return e??(e=Date.now()),n??(n=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9]),r[o++]=e/1099511627776&255,r[o++]=e/4294967296&255,r[o++]=e/16777216&255,r[o++]=e/65536&255,r[o++]=e/256&255,r[o++]=e&255,r[o++]=112|n>>>28&15,r[o++]=n>>>20&255,r[o++]=128|n>>>14&63,r[o++]=n>>>6&255,r[o++]=n<<2&255|t[10]&3,r[o++]=t[11],r[o++]=t[12],r[o++]=t[13],r[o++]=t[14],r[o++]=t[15],r}var p6e,Mz,dzt=b(()=>{i6e();DY();p6e={};Mz=For});var fzt=b(()=>{$Y()});var FY=b(()=>{nzt();rzt();o6e();DY();szt();czt();dzt();$Y();fzt()});var pzt,mzt,m6e,hzt,h6e,g6e,y6e,gzt,yzt,vzt,wzt,bzt,_zt,xzt,Szt,Czt,kzt,Izt,Tzt,Pzt,Azt,Ezt,Mzt,Ozt,Nzt,Rzt,Lzt,$zt,Dzt,Fzt,v6e,Uzt,jzt,w6e,Bzt=b(()=>{pzt="gen_ai.operation.name",mzt="gen_ai.system",m6e="gen_ai.request.model",hzt="gen_ai.response.model",h6e="gen_ai.usage.input_tokens",g6e="gen_ai.usage.output_tokens",y6e="gen_ai.usage.total_tokens",gzt="gen_ai.request.max_tokens",yzt="gen_ai.request.temperature",vzt="gen_ai.request.top_p",wzt="gen_ai.request.frequency_penalty",bzt="gen_ai.request.presence_penalty",_zt="gen_ai.response.finish_reasons",xzt="gen_ai.prompt",Szt="gen_ai.completion",Czt="gen_ai.request.extra_query",kzt="gen_ai.request.extra_body",Izt="gen_ai.serialized.name",Tzt="gen_ai.serialized.signature",Pzt="gen_ai.serialized.doc",Azt="gen_ai.response.id",Ezt="gen_ai.response.service_tier",Mzt="gen_ai.response.system_fingerprint",Ozt="gen_ai.usage.input_token_details",Nzt="gen_ai.usage.output_token_details",Rzt="langsmith.trace.session_id",Lzt="langsmith.trace.session_name",$zt="langsmith.span.kind",Dzt="langsmith.trace.name",Fzt="langsmith.metadata",v6e="langsmith.span.tags",Uzt="langsmith.request.streaming",jzt="langsmith.request.headers",w6e="langsmith.usage_metadata"});var zor,Hor,zzt,Hzt,Wzt,b6e=b(()=>{$x();zor=(...t)=>fetch(...t),zzt=Symbol.for("ls:fetch_implementation"),Hzt=()=>globalThis[zzt]===void 0?!0:Hor??!1,Wzt=t=>async(...e)=>{if(t||Os("DEBUG")==="true"){let[r,o]=e;console.log(`\u2192 ${o?.method||"GET"} ${r}`)}let n=await(globalThis[zzt]??zor)(...e);return(t||Os("DEBUG")==="true")&&console.log(`\u2190 ${n.status} ${n.statusText} ${n.url}`),n}});var UY,_6e=b(()=>{$x();UY=()=>Os("PROJECT")??Ou("LANGCHAIN_SESSION")??"default"});function Nu(t,e){let n=e?.code??t;Vzt[n]||(Vzt[n]=!0,e?.type&&typeof process<"u"&&typeof process.emitWarning=="function"?process.emitWarning(t,{type:e.type,code:e.code}):e?.type&&e?.code?console.warn(`${e.type} [${e.code}]: ${t}`):console.warn(t))}var Vzt,the=b(()=>{Vzt={}});function Gor(t){let e=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)e[n/2]=parseInt(t.substring(n,n+2),16);return e}function Ns(t,e=0){return new Uint8Array(t.buffer,t.byteOffset+e,t.length-e)}function ra(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getBigUint64(0,!0)}function Oz(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getUint32(0,!0)}function x6e(t,e=0){return t[e]}function Qor(t,e){return(t<<e|t>>Ge(32)-e)&ihe}function Qzt(t,e,n){for(let r=0;r<Xzt;r++){let o=ra(e,r*8),i=o^ra(n,r*8);t[r^1]+=o,t[r]+=Xor(i,i>>Ge(32))}return t}function qzt(t,e,n,r){for(let o=0;o<r;o++)Qzt(t,Ns(e,o*Zk),Ns(n,o*8));return t}function eir(t,e){for(let n=0;n<Xzt;n++){let r=ra(e,n*8),o=t[n];o=S6e(o,Ge(47)),o^=r,o*=Zzt,t[n]=o&no}return t}function rhe(t,e){return e4t(t[0]^ra(e,0),t[1]^ra(e,Zor))}function Kzt(t,e,n){let r=n;return r+=rhe(t.slice(0),Ns(e,0*nhe)),r+=rhe(t.slice(2),Ns(e,4*nhe)),r+=rhe(t.slice(4),Ns(e,8*nhe)),r+=rhe(t.slice(6),Ns(e,12*nhe)),Fx(r&no)}function tir(t,e,n,r,o){let i=Math.floor((n.byteLength-Zk)/8),s=Zk*i,a=Math.floor((e.byteLength-1)/s);for(let l=0;l<a;l++)t=qzt(t,Ns(e,l*s),n,i),t=o(t,Ns(n,n.byteLength-Zk));{let l=Math.floor((e.byteLength-1-s*a)/Zk);t=qzt(t,Ns(e,a*s),n,l),t=r(t,Ns(e,e.byteLength-Zk),Ns(n,n.byteLength-Zk-7))}return t}function nir(t,e,n){let r=new BigUint64Array([Wor,bA,EL,Jzt,k6e,Yzt,Vor,Zzt]);Rz(t.length>128),r=tir(r,t,e,Qzt,eir),Rz(r.length*8==64);{let o=Kzt(r,Ns(e,11),Ge(t.byteLength)*bA&no);return Kzt(r,Ns(e,e.byteLength-Zk-11),~(Ge(t.byteLength)*EL)&no)<<Ge(64)|o}}function e4t(t,e){let n=t*e&Nz;return n&no^n>>Ge(64)}function Gzt(t,e,n){return e4t((ra(t,0)^ra(e,0)+n)&no,(ra(t,8)^ra(e,8)-n)&no)}function ohe(t,e,n,r,o){let i=t&no,s=t>>Ge(64)&no;return i+=Gzt(e,r,o),i^=ra(n,0)+ra(n,8),i&=no,s+=Gzt(n,Ns(r,16),o),s^=ra(e,0)+ra(e,8),s&=no,s<<Ge(64)|i}function Fx(t){return t^=t>>Ge(37),t*=qor,t&=no,t^=t>>Ge(32),t}function she(t){return t^=t>>Ge(33),t*=EL,t&=no,t^=t>>Ge(29),t*=Jzt,t&=no,t^=t>>Ge(32),t}function rir(t,e,n){let r=t.byteLength;Rz(r>0&&r<=3);let o=Ge(x6e(t,r-1))|Ge(r<<8)|Ge(x6e(t,0)<<16)|Ge(x6e(t,r>>1)<<24),i=(Ge(Oz(e,0))^Ge(Oz(e,4)))+n,s=(o^i)&no,a=(Ge(Oz(e,8))^Ge(Oz(e,12)))-n,l=(Qor(Jor(o),Ge(13))^a)&no;return(she(l)&no)<<Ge(64)|she(s)}function S6e(t,e){return t^t>>e}function oir(t,e,n){let r=t.byteLength;Rz(r>=4&&r<=8);{let o=Oz(t,0),i=Oz(t,r-4),s=Ge(o)|Ge(i)<<Ge(32),a=(ra(e,16)^ra(e,24))+n&no,c=(s^a)*(bA+(Ge(r)<<Ge(2)))&Nz;return c+=(c&no)<<Ge(65),c&=Nz,c^=c>>Ge(67),S6e(S6e(c&no,Ge(35))*Kor&no,Ge(28))|Fx(c>>Ge(64))<<Ge(64)}}function iir(t,e,n){let r=t.byteLength;Rz(r>=9&&r<=16);{let o=(ra(e,32)^ra(e,40))+n&no,i=(ra(e,48)^ra(e,56))-n&no,s=ra(t),a=ra(t,r-8),l=(s^a^o)*bA,c=(l&no)+(Ge(r-1)<<Ge(54));l=l&(Nz^no)|c,a^=i,l+=a+(a&ihe)*(Yzt-Ge(1))<<Ge(64),l&=Nz,l^=Yor(l>>Ge(64));let u=(l&no)*EL;return u+=(l>>Ge(64))*EL<<Ge(64),u&=Nz,Fx(u&no)|Fx(u>>Ge(64))<<Ge(64)}}function sir(t,e){let n=t.byteLength;return Rz(n<=16),n>8?iir(t,Dx,e):n>=4?oir(t,Dx,e):n>0?rir(t,Dx,e):she(e^ra(Dx,64)^ra(Dx,72))|she(e^ra(Dx,80)^ra(Dx,88))<<Ge(64)}function C6e(t){return~t+Ge(1)&no}function air(t,e,n){let r=Ge(t.byteLength)*bA&no,o=Ge(t.byteLength-1)/Ge(32);for(;o>=0;){let a=Number(o);r=ohe(r,Ns(t,16*a),Ns(t,t.byteLength-16*(a+1)),Ns(e,32*a),n),o--}let i=r+(r>>Ge(64))&no;i=Fx(i);let s=(r&no)*bA+(r>>Ge(64))*k6e+(Ge(t.byteLength)-n&no)*EL;return s&=no,s=C6e(Fx(s)),i|s<<Ge(64)}function lir(t,e,n){let r=Ge(t.byteLength)*bA&no;for(let s=32;s<160;s+=32)r=ohe(r,Ns(t,s-32),Ns(t,s-16),Ns(e,s-32),n);r=Fx(r&no)|Fx(r>>Ge(64))<<Ge(64);for(let s=160;s<=t.byteLength;s+=32)r=ohe(r,Ns(t,s-32),Ns(t,s-16),Ns(e,3+s-160),n);r=ohe(r,Ns(t,t.byteLength-16),Ns(t,t.byteLength-32),Ns(e,103),C6e(n));let o=r+(r>>Ge(64))&no;o=Fx(o);let i=(r&no)*bA+(r>>Ge(64))*k6e+(Ge(t.byteLength)-n&no)*EL;return i&=no,i=C6e(Fx(i)),o|i<<Ge(64)}function t4t(t,e=Ge(0)){let n=t.byteLength;return n<=16?sir(t,e):n<=128?air(t,Dx,e):n<=240?lir(t,Dx,e):nir(t,Dx,e)}function n4t(t){let e=new Uint8Array(16),n=new DataView(e.buffer),r=t&no,o=t>>Ge(64);return n.setBigUint64(0,o,!1),n.setBigUint64(8,r,!1),e}var Ge,Zzt,Yzt,Wor,bA,EL,Jzt,k6e,Vor,qor,Kor,Dx,Nz,no,ihe,Zk,Xzt,Zor,nhe,Yor,Jor,Xor,Rz,r4t=b(()=>{Ge=t=>BigInt(t),Zzt=Ge("0x9E3779B1"),Yzt=Ge("0x85EBCA77"),Wor=Ge("0xC2B2AE3D"),bA=Ge("0x9E3779B185EBCA87"),EL=Ge("0xC2B2AE3D27D4EB4F"),Jzt=Ge("0x165667B19E3779F9"),k6e=Ge("0x85EBCA77C2B2AE63"),Vor=Ge("0x27D4EB2F165667C5"),qor=Ge("0x165667919E3779F9"),Kor=Ge("0x9FB21C651E98DF25");Dx=Gor("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Nz=(Ge(1)<<Ge(128))-Ge(1),no=(Ge(1)<<Ge(64))-Ge(1),ihe=(Ge(1)<<Ge(32))-Ge(1),Zk=64,Xzt=Zk/8,Zor=8,nhe=4;Yor=t=>(t&Ge(255))<<Ge(56)|(t&Ge(65280))<<Ge(40)|(t&Ge(16711680))<<Ge(24)|(t&Ge(4278190080))<<Ge(8)|(t&Ge(0xff00000000))>>Ge(8)|(t&Ge(0xff0000000000))>>Ge(24)|(t&Ge(0xff000000000000))>>Ge(40)|(t&Ge(0xff00000000000000))>>Ge(56),Jor=t=>(t=(t&Ge(65535))<<Ge(16)|(t&Ge(4294901760))>>Ge(16),t=(t&Ge(16711935))<<Ge(8)|(t&Ge(4278255360))>>Ge(8),t),Xor=(t,e)=>(t&ihe)*(e&ihe)&no,Rz=t=>{if(!t)throw new Error("Assert failed")}});function _r(t,e){if(!o4t.test(t)){let n=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(n)}return t}function ahe(t){let e=typeof t=="string"?Date.parse(t):t;return Mz({msecs:e,seq:0})}function i4t(t){if(!o4t.test(t))return null;let e=t[14];return parseInt(e,16)}function cir(t){let e=t.replace(/-/g,""),n=new Uint8Array(16);for(let r=0;r<16;r++)n[r]=parseInt(e.slice(r*2,r*2+2),16);return n}function uir(t){let e=Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function fir(t){let e=dir.encode(t),n=t4t(e);return n4t(n)}function Lz(t,e){let n=`${t}:${e}`,r=fir(n),o=new Uint8Array(16);if(i4t(t)===7){let s=cir(t);o.set(s.slice(0,6),0)}else{let s=Date.now();o[0]=s/1099511627776&255,o[1]=s/4294967296&255,o[2]=s/16777216&255,o[3]=s/65536&255,o[4]=s/256&255,o[5]=s&255}return o[6]=112|r[0]&15,o[7]=r[1],o[8]=128|r[2]&63,o.set(r.slice(3,10),9),uir(o)}var o4t,dir,jY=b(()=>{FY();the();r4t();o4t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;dir=new TextEncoder});var s4t=b(()=>{FY();jY();jY()});var I6e,T6e=b(()=>{$x();I6e=t=>t!==void 0?t:!!["TRACING_V2","TRACING"].find(n=>Os(n)==="true")});function M6e(t=!1){let e=mir.getInstance().getStore();if(!t&&e===void 0)throw new Error(`Could not get the current run tree.
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function lhe(t){return typeof t=="function"&&"langsmith:traceable"in t}var A6e,P6e,pir,E6e,mir,vSo,O6e=b(()=>{A6e=class{getStore(){}run(e,n){return n()}},P6e=Symbol.for("ls:tracing_async_local_storage"),pir=new A6e,E6e=class{getInstance(){return globalThis[P6e]??pir}initializeGlobalInstance(e){globalThis[P6e]===void 0&&(globalThis[P6e]=e)}},mir=new E6e;vSo=Symbol.for("langsmith:traceable:root")});var a4t=b(()=>{T6e();O6e()});async function che(t){}async function $z(t,e){}async function l4t(t){return[]}async function c4t(t){return{size:0}}function Dz(t){return!1}function ML(t){return""}async function u4t(t){}async function uhe(t){}var vb,BY=b(()=>{vb={join:(...t)=>t.join("/"),dirname:t=>t.split("/").slice(0,-1).join("/")}});function hir(t,e){return e===null?!1:Date.now()-t.createdAt>e*1e3}var dhe,fhe,R6e=b(()=>{BY();dhe=class{constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_metrics",{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.configure(e)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){let e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e,n){if(this.maxSize===0)return;let r=this.cache.get(e);if(!r){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,{...r,refreshFunc:n}),this._metrics.hits+=1,r.value}set(e,n,r){if(this.maxSize===0)return;if(this.refreshTimer===void 0&&this.startRefreshLoop(),!this.cache.has(e)&&this.cache.size>=this.maxSize){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i)}let o={value:n,createdAt:Date.now(),refreshFunc:r};this.cache.delete(e),this.cache.set(e,o)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(e){let n={};for(let[i,s]of this.cache.entries())n[i]=s.value;let r=vb.dirname(e);Dz(r)||void 0;let o=`${e}.tmp`;try{JSON.stringify({entries:n},null,2)}catch(i){throw Dz(o)&&void 0,i}}load(e){if(!Dz(e))return 0;let n;try{let i=ML(e);n=JSON.parse(i).entries??null}catch{return 0}if(!n)return 0;let r=0,o=Date.now();for(let[i,s]of Object.entries(n)){if(this.cache.size>=this.maxSize)break;let a={value:s,createdAt:o};this.cache.set(i,a),r+=1}return r}startRefreshLoop(){this.stop(),this.ttlSeconds!==null&&(this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(e=>{console.warn("Unexpected error in cache refresh loop:",e)})},this.refreshIntervalSeconds*1e3),this.refreshTimer.unref&&this.refreshTimer.unref())}getStaleEntries(){let e=[];for(let[n,r]of this.cache.entries())hir(r,this.ttlSeconds)&&e.push([n,r]);return e}async refreshStaleEntries(){let e=this.getStaleEntries();if(e.length!==0){for(let[n,r]of e)if(r.refreshFunc!==void 0)try{let o=await r.refreshFunc();this.set(n,o,r.refreshFunc),this._metrics.refreshes+=1}catch(o){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${n}:`,o)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??5*60}},fhe=new dhe});function d4t(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var zY,L6e=b(()=>{zY=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)}});var Nm,_d,_A,Yk,OL,NL,RL,LL,$L,DL,FL,UL,jL,BL=b(()=>{L6e();Nm=class extends Error{},_d=class t extends Nm{constructor(e,n,r,o){super(`${t.makeMessage(e,n,r)}`),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.status=e,this.headers=o,this.error=n}static makeMessage(e,n,r){let o=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,n,r,o){if(!e||!o)return new Yk({message:r,cause:zY(n)});let i=n;return e===400?new NL(e,i,r,o):e===401?new RL(e,i,r,o):e===403?new LL(e,i,r,o):e===404?new $L(e,i,r,o):e===409?new DL(e,i,r,o):e===422?new FL(e,i,r,o):e===429?new UL(e,i,r,o):e>=500?new jL(e,i,r,o):new t(e,i,r,o)}},_A=class extends _d{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Yk=class extends _d{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}},OL=class extends Yk{constructor({message:e}={}){super({message:e??"Request timed out."})}},NL=class extends _d{},RL=class extends _d{},LL=class extends _d{},$L=class extends _d{},DL=class extends _d{},FL=class extends _d{},UL=class extends _d{},jL=class extends _d{}});var phe,mhe=b(()=>{$6e();D6e();b6e();_6e();s4t();a4t();R6e();BL();phe="0.8.11"});function hhe(){if(F6e===void 0){let t=HY(),e=xir();F6e={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:phe,...e}}return F6e}function j6e(){let t=_ir(),e={},n=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_CONFIG_FILE","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(let[r,o]of Object.entries(t))typeof o=="string"&&!n.includes(r)&&!r.toLowerCase().includes("key")&&!r.toLowerCase().includes("secret")&&!r.toLowerCase().includes("token")&&(r==="LANGCHAIN_REVISION_ID"?e.revision_id=o:e[r]=o);return e}function _ir(){let t={};try{if(typeof process<"u"&&process.env)for(let[e,n]of Object.entries(process.env))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&n!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof n=="string"?t[e]=n.slice(0,2)+"*".repeat(n.length-4)+n.slice(-2):t[e]=n)}catch{}return t}function Ou(t){try{return typeof process<"u"?process.env?.[t]:void 0}catch{return}}function Os(t){return Ou(`LANGSMITH_${t}`)||Ou(`LANGCHAIN_${t}`)}function xir(){if(U6e!==void 0)return U6e;let t=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(let n of t){let r=Ou(n);r!==void 0&&(e[n]=r)}return U6e=e,e}function f4t(){return Ou("OTEL_ENABLED")==="true"||Os("OTEL_ENABLED")==="true"}function ghe(t){if(t!==void 0)return t;let e=Os("TRACING_MODE");if(e!==void 0&&e!==""){let n=e.toLowerCase();if(!p4t.has(n))throw new Error(`Invalid LANGSMITH_TRACING_MODE=${JSON.stringify(e)}. Must be one of: ${[...p4t].sort().join(", ")}`);return f4t()&&console.warn("Both LANGSMITH_TRACING_MODE and the legacy OTEL_ENABLED / LANGSMITH_OTEL_ENABLED env vars are set. LANGSMITH_TRACING_MODE takes precedence."),n}return f4t()?"otel":"langsmith"}var Ux,yir,vir,wir,m4t,bir,HY,F6e,U6e,p4t,$x=b(()=>{mhe();yir=()=>typeof window<"u"&&typeof window.document<"u",vir=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",wir=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),m4t=()=>typeof globalThis.Deno<"u",bir=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!m4t(),HY=()=>Ux||(typeof Bun<"u"?Ux="bun":yir()?Ux="browser":bir()?Ux="node":vir()?Ux="webworker":wir()?Ux="jsdom":m4t()?Ux="deno":Ux="other",Ux);p4t=new Set(["langsmith","otel"])});function yhe(){return K6e.getTraceInstance()}function g4t(){return K6e.getContextInstance()}function y4t(){return K6e.getDefaultOTLPTracerComponents()}var H6e,W6e,V6e,B6e,z6e,h4t,Sir,Cir,q6e,K6e,G6e=b(()=>{$x();H6e=class{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...n){!this.hasWarned&&ghe()==="otel"&&(console.warn('OTel tracing mode is active (via LANGSMITH_TRACING_MODE, OTEL_ENABLED, or LANGSMITH_OTEL_ENABLED), but the required OTEL instances have not been initialized. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let r;if(n.length===1&&typeof n[0]=="function"?r=n[0]:n.length===2&&typeof n[1]=="function"?r=n[1]:n.length===3&&typeof n[2]=="function"&&(r=n[2]),typeof r=="function")return r()}},W6e=class{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new H6e})}getTracer(e,n){return this.mockTracer}getActiveSpan(){}setSpan(e,n){return e}getSpan(e){}setSpanContext(e,n){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},V6e=class{active(){return{}}with(e,n){return n()}},B6e=Symbol.for("ls:otel_trace"),z6e=Symbol.for("ls:otel_context"),h4t=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),Sir=new W6e,Cir=new V6e,q6e=class{getTraceInstance(){return globalThis[B6e]??Sir}getContextInstance(){return globalThis[z6e]??Cir}initializeGlobalInstances(e){globalThis[B6e]===void 0&&(globalThis[B6e]=e.trace),globalThis[z6e]===void 0&&(globalThis[z6e]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[h4t]=e}getDefaultOTLPTracerComponents(){return globalThis[h4t]??void 0}},K6e=new q6e});function Iir(t){return kir[t]||t}function Tir(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}var kir,vhe,v4t=b(()=>{Bzt();G6e();kir={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};vhe=class{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,n){for(let r of e)try{if(!r.run)continue;if(r.operation==="post"){let o=this.createSpanForRun(r,r.run,n.get(r.id));o&&!r.run.end_time&&this.spans.set(r.id,o)}else this.updateSpanForRun(r,r.run)}catch(o){console.error(`Error processing operation ${r.id}:`,o)}}createSpanForRun(e,n,r){let o=r&&yhe().getSpan(r);if(o)try{return this.finishSpanSetup(o,n,e)}catch(i){console.error(`Failed to create span for run ${e.id}:`,i);return}}finishSpanSetup(e,n,r){return this.setSpanAttributes(e,n,r),n.error?(e.setStatus({code:2}),e.recordException(new Error(n.error))):e.setStatus({code:1}),n.end_time&&e.end(new Date(n.end_time)),e}updateSpanForRun(e,n){try{let r=this.spans.get(e.id);if(!r){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(r,n,e),n.error?(r.setStatus({code:2}),r.recordException(new Error(n.error))):r.setStatus({code:1});let o=n.end_time;o&&(r.end(new Date(o)),this.spans.delete(e.id))}catch(r){console.error(`Failed to update span for run ${e.id}:`,r)}}extractModelName(e){if(e.extra?.metadata){let n=e.extra.metadata;if(n.ls_model_name)return n.ls_model_name;if(n.invocation_params){let r=n.invocation_params;if(r.model)return r.model;if(r.model_name)return r.model_name}}}setSpanAttributes(e,n,r){if("run_type"in n&&n.run_type){e.setAttribute($zt,n.run_type);let a=Iir(n.run_type||"chain");e.setAttribute(pzt,a)}"name"in n&&n.name&&e.setAttribute(Dzt,n.name),"session_id"in n&&n.session_id&&e.setAttribute(Rzt,n.session_id),"session_name"in n&&n.session_name&&e.setAttribute(Lzt,n.session_name),this.setGenAiSystem(e,n);let o=this.extractModelName(n);o&&e.setAttribute(m6e,o),n.extra?.metadata?.usage_metadata&&typeof n.extra.metadata.usage_metadata=="object"&&e.setAttribute(w6e,JSON.stringify(n.extra.metadata.usage_metadata)),"prompt_tokens"in n&&typeof n.prompt_tokens=="number"&&e.setAttribute(h6e,n.prompt_tokens),"completion_tokens"in n&&typeof n.completion_tokens=="number"&&e.setAttribute(g6e,n.completion_tokens),"total_tokens"in n&&typeof n.total_tokens=="number"&&e.setAttribute(y6e,n.total_tokens),this.setInvocationParameters(e,n);let i=n.extra?.metadata||{};for(let[a,l]of Object.entries(i))l!=null&&e.setAttribute(`${Fzt}.${a}`,Tir(l)?String(l):JSON.stringify(l));let s=n.tags;if(s&&Array.isArray(s)?e.setAttribute(v6e,s.join(", ")):s&&e.setAttribute(v6e,String(s)),"serialized"in n&&typeof n.serialized=="object"){let a=n.serialized;a.name&&e.setAttribute(Izt,String(a.name)),a.signature&&e.setAttribute(Tzt,String(a.signature)),a.doc&&e.setAttribute(Pzt,String(a.doc))}this.setIOAttributes(e,r)}setGenAiSystem(e,n){let r="langchain",o=this.extractModelName(n);if(o){let i=o.toLowerCase();i.includes("anthropic")||i.startsWith("claude")?r="anthropic":i.includes("bedrock")?r="aws.bedrock":i.includes("azure")&&i.includes("openai")?r="az.ai.openai":i.includes("azure")&&i.includes("inference")?r="az.ai.inference":i.includes("cohere")?r="cohere":i.includes("deepseek")?r="deepseek":i.includes("gemini")?r="gemini":i.includes("groq")?r="groq":i.includes("watson")||i.includes("ibm")?r="ibm.watsonx.ai":i.includes("mistral")?r="mistral_ai":i.includes("gpt")||i.includes("openai")?r="openai":i.includes("perplexity")||i.includes("sonar")?r="perplexity":i.includes("vertex")?r="vertex_ai":(i.includes("xai")||i.includes("grok"))&&(r="xai")}e.setAttribute(mzt,r)}setInvocationParameters(e,n){if(!n.extra?.metadata?.invocation_params)return;let r=n.extra.metadata.invocation_params;r.max_tokens!==void 0&&e.setAttribute(gzt,r.max_tokens),r.temperature!==void 0&&e.setAttribute(yzt,r.temperature),r.top_p!==void 0&&e.setAttribute(vzt,r.top_p),r.frequency_penalty!==void 0&&e.setAttribute(wzt,r.frequency_penalty),r.presence_penalty!==void 0&&e.setAttribute(bzt,r.presence_penalty)}setIOAttributes(e,n){if(n.run.inputs)try{let r=n.run.inputs;typeof r=="object"&&r!==null&&(r.model&&Array.isArray(r.messages)&&e.setAttribute(m6e,r.model),r.stream!==void 0&&e.setAttribute(Uzt,r.stream),r.extra_headers&&e.setAttribute(jzt,JSON.stringify(r.extra_headers)),r.extra_query&&e.setAttribute(Czt,JSON.stringify(r.extra_query)),r.extra_body&&e.setAttribute(kzt,JSON.stringify(r.extra_body))),e.setAttribute(xzt,JSON.stringify(r))}catch(r){console.debug(`Failed to process inputs for run ${n.id}`,r)}if(n.run.outputs)try{let r=n.run.outputs,o=this.getUnifiedRunTokens(r);if(o&&(e.setAttribute(h6e,o[0]),e.setAttribute(g6e,o[1]),e.setAttribute(y6e,o[0]+o[1])),r&&typeof r=="object"){if(r.model&&e.setAttribute(hzt,String(r.model)),r.id&&e.setAttribute(Azt,r.id),r.choices&&Array.isArray(r.choices)){let i=r.choices.map(s=>s.finish_reason).filter(s=>s).map(String);i.length>0&&e.setAttribute(_zt,i.join(", "))}if(r.service_tier&&e.setAttribute(Ezt,r.service_tier),r.system_fingerprint&&e.setAttribute(Mzt,r.system_fingerprint),r.usage_metadata&&typeof r.usage_metadata=="object"){let i=r.usage_metadata;e.setAttribute(w6e,JSON.stringify(i)),i.input_token_details&&e.setAttribute(Ozt,JSON.stringify(i.input_token_details)),i.output_token_details&&e.setAttribute(Nzt,JSON.stringify(i.output_token_details))}}e.setAttribute(Szt,JSON.stringify(r))}catch(r){console.debug(`Failed to process outputs for run ${n.id}`,r)}}getUnifiedRunTokens(e){if(!e)return null;let n=this.extractUnifiedRunTokens(e.usage_metadata);if(n)return n;let r=Object.keys(e);for(let s of r){let a=e[s];if(!(!a||typeof a!="object")&&(n=this.extractUnifiedRunTokens(a.usage_metadata),n||a.lc===1&&a.kwargs&&typeof a.kwargs=="object"&&(n=this.extractUnifiedRunTokens(a.kwargs.usage_metadata),n)))return n}let o=e.generations||[];if(!Array.isArray(o))return null;let i=Array.isArray(o[0])?o.flat():o;for(let s of i)if(typeof s=="object"&&s.message&&typeof s.message=="object"&&s.message.kwargs&&typeof s.message.kwargs=="object"&&(n=this.extractUnifiedRunTokens(s.message.kwargs.usage_metadata),n))return n;return null}extractUnifiedRunTokens(e){return!e||typeof e!="object"||typeof e.input_tokens!="number"||typeof e.output_tokens!="number"?null:[e.input_tokens,e.output_tokens]}}});function Z6e(t){if(!(t&&Air(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;let{message:n,stack:r}=t;return n==="Load failed"?r===void 0||"__sentry_captured__"in t:n.startsWith("error sending request for url")?!0:Eir.has(n)}var Pir,Air,Eir,w4t=b(()=>{Pir=Object.prototype.toString,Air=t=>Pir.call(t)==="[object Error]",Eir=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"])});function Mir(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function whe(t,e,{min:n=0,allowInfinity:r=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${t}\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(e))throw new TypeError(`Expected \`${t}\` to be a finite number.`);if(e<n)throw new TypeError(`Expected \`${t}\` to be \u2265 ${n}.`)}}function Oir(t,e){let n=Math.max(1,t+1),r=e.randomize?Math.random()+1:1,o=Math.round(r*e.minTimeout*e.factor**(n-1));return o=Math.min(o,e.maxTimeout),o}function b4t(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}async function Nir({error:t,attemptNumber:e,retriesConsumed:n,startTime:r,options:o}){let i=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(i instanceof Y6e)throw i.originalError;let s=Number.isFinite(o.retries)?Math.max(0,o.retries-n):o.retries,a=o.maxRetryTime??Number.POSITIVE_INFINITY,l=Object.freeze({error:i,attemptNumber:e,retriesLeft:s,retriesConsumed:n});if(await o.onFailedAttempt(l),b4t(r,a)<=0)throw i;let c=await o.shouldConsumeRetry(l),u=b4t(r,a);if(u<=0||s<=0)throw i;if(i instanceof TypeError&&!Z6e(i)){if(c)throw i;return o.signal?.throwIfAborted(),!1}if(!await o.shouldRetry(l))throw i;if(!c)return o.signal?.throwIfAborted(),!1;let d=Oir(n,o),f=Math.min(d,u);return f>0&&await new Promise((p,m)=>{let h=()=>{clearTimeout(g),o.signal?.removeEventListener("abort",h),m(o.signal.reason)},g=setTimeout(()=>{o.signal?.removeEventListener("abort",h),p()},f);o.unref&&g.unref?.(),o.signal?.addEventListener("abort",h,{once:!0})}),o.signal?.throwIfAborted(),!0}async function J6e(t,e={}){if(e={...e},Mir(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??(e.retries=10),e.factor??(e.factor=2),e.minTimeout??(e.minTimeout=1e3),e.maxTimeout??(e.maxTimeout=Number.POSITIVE_INFINITY),e.maxRetryTime??(e.maxRetryTime=Number.POSITIVE_INFINITY),e.randomize??(e.randomize=!1),e.onFailedAttempt??(e.onFailedAttempt=()=>{}),e.shouldRetry??(e.shouldRetry=()=>!0),e.shouldConsumeRetry??(e.shouldConsumeRetry=()=>!0),whe("factor",e.factor,{min:0,allowInfinity:!1}),whe("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),whe("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),whe("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let n=0,r=0,o=performance.now();for(;!Number.isFinite(e.retries)||r<=e.retries;){n++;try{e.signal?.throwIfAborted();let i=await t(n);return e.signal?.throwIfAborted(),i}catch(i){await Nir({error:i,attemptNumber:n,retriesConsumed:r,startTime:o,options:e})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Y6e,_4t=b(()=>{w4t();Y6e=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}});var Q6e=wi((tCo,X6e)=>{"use strict";var Rir=Object.prototype.hasOwnProperty,kp="~";function WY(){}Object.create&&(WY.prototype=Object.create(null),new WY().__proto__||(kp=!1));function Lir(t,e,n){this.fn=t,this.context=e,this.once=n||!1}function x4t(t,e,n,r,o){if(typeof n!="function")throw new TypeError("The listener must be a function");var i=new Lir(n,r||t,o),s=kp?kp+e:e;return t._events[s]?t._events[s].fn?t._events[s]=[t._events[s],i]:t._events[s].push(i):(t._events[s]=i,t._eventsCount++),t}function bhe(t,e){--t._eventsCount===0?t._events=new WY:delete t._events[e]}function vf(){this._events=new WY,this._eventsCount=0}vf.prototype.eventNames=function(){var e=[],n,r;if(this._eventsCount===0)return e;for(r in n=this._events)Rir.call(n,r)&&e.push(kp?r.slice(1):r);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(n)):e};vf.prototype.listeners=function(e){var n=kp?kp+e:e,r=this._events[n];if(!r)return[];if(r.fn)return[r.fn];for(var o=0,i=r.length,s=new Array(i);o<i;o++)s[o]=r[o].fn;return s};vf.prototype.listenerCount=function(e){var n=kp?kp+e:e,r=this._events[n];return r?r.fn?1:r.length:0};vf.prototype.emit=function(e,n,r,o,i,s){var a=kp?kp+e:e;if(!this._events[a])return!1;var l=this._events[a],c=arguments.length,u,d;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),c){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,n),!0;case 3:return l.fn.call(l.context,n,r),!0;case 4:return l.fn.call(l.context,n,r,o),!0;case 5:return l.fn.call(l.context,n,r,o,i),!0;case 6:return l.fn.call(l.context,n,r,o,i,s),!0}for(d=1,u=new Array(c-1);d<c;d++)u[d-1]=arguments[d];l.fn.apply(l.context,u)}else{var f=l.length,p;for(d=0;d<f;d++)switch(l[d].once&&this.removeListener(e,l[d].fn,void 0,!0),c){case 1:l[d].fn.call(l[d].context);break;case 2:l[d].fn.call(l[d].context,n);break;case 3:l[d].fn.call(l[d].context,n,r);break;case 4:l[d].fn.call(l[d].context,n,r,o);break;default:if(!u)for(p=1,u=new Array(c-1);p<c;p++)u[p-1]=arguments[p];l[d].fn.apply(l[d].context,u)}}return!0};vf.prototype.on=function(e,n,r){return x4t(this,e,n,r,!1)};vf.prototype.once=function(e,n,r){return x4t(this,e,n,r,!0)};vf.prototype.removeListener=function(e,n,r,o){var i=kp?kp+e:e;if(!this._events[i])return this;if(!n)return bhe(this,i),this;var s=this._events[i];if(s.fn)s.fn===n&&(!o||s.once)&&(!r||s.context===r)&&bhe(this,i);else{for(var a=0,l=[],c=s.length;a<c;a++)(s[a].fn!==n||o&&!s[a].once||r&&s[a].context!==r)&&l.push(s[a]);l.length?this._events[i]=l.length===1?l[0]:l:bhe(this,i)}return this};vf.prototype.removeAllListeners=function(e){var n;return e?(n=kp?kp+e:e,this._events[n]&&bhe(this,n)):(this._events=new WY,this._eventsCount=0),this};vf.prototype.off=vf.prototype.removeListener;vf.prototype.addListener=vf.prototype.on;vf.prefixed=kp;vf.EventEmitter=vf;typeof X6e<"u"&&(X6e.exports=vf)});var eVe=wi((nCo,S4t)=>{"use strict";S4t.exports=(t,e)=>(e=e||(()=>{}),t.then(n=>new Promise(r=>{r(e())}).then(()=>n),n=>new Promise(r=>{r(e())}).then(()=>{throw n})))});var k4t=wi((rCo,xhe)=>{"use strict";var $ir=eVe(),_he=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},C4t=(t,e,n)=>new Promise((r,o)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){r(t);return}let i=setTimeout(()=>{if(typeof n=="function"){try{r(n())}catch(l){o(l)}return}let s=typeof n=="string"?n:`Promise timed out after ${e} milliseconds`,a=n instanceof Error?n:new _he(s);typeof t.cancel=="function"&&t.cancel(),o(a)},e);$ir(t.then(r,o),()=>{clearTimeout(i)})});xhe.exports=C4t;xhe.exports.default=C4t;xhe.exports.TimeoutError=_he});var I4t=wi(tVe=>{"use strict";Object.defineProperty(tVe,"__esModule",{value:!0});function Dir(t,e,n){let r=0,o=t.length;for(;o>0;){let i=o/2|0,s=r+i;n(t[s],e)<=0?(r=++s,o-=i+1):o=i}return r}tVe.default=Dir});var T4t=wi(rVe=>{"use strict";Object.defineProperty(rVe,"__esModule",{value:!0});var Fir=I4t(),nVe=class{constructor(){this._queue=[]}enqueue(e,n){n=Object.assign({priority:0},n);let r={priority:n.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=n.priority){this._queue.push(r);return}let o=Fir.default(this._queue,r,(i,s)=>s.priority-i.priority);this._queue.splice(o,0,r)}dequeue(){let e=this._queue.shift();return e?.run}filter(e){return this._queue.filter(n=>n.priority===e.priority).map(n=>n.run)}get size(){return this._queue.length}};rVe.default=nVe});var A4t=wi(iVe=>{"use strict";Object.defineProperty(iVe,"__esModule",{value:!0});var Uir=Q6e(),P4t=k4t(),jir=T4t(),She=()=>{},Bir=new P4t.TimeoutError,oVe=class extends Uir{constructor(e){var n,r,o,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=She,this._resolveIdle=She,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:jir.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(r=(n=e.intervalCap)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(i=(o=e.interval)===null||o===void 0?void 0:o.toString())!==null&&i!==void 0?i:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=She,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=She,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let n=this._intervalEnd-e;if(n<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},n)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let n=this._queue.dequeue();return n?(this.emit("active"),n(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,n={}){return new Promise((r,o)=>{let i=async()=>{this._pendingCount++,this._intervalCount++;try{let s=this._timeout===void 0&&n.timeout===void 0?e():P4t.default(Promise.resolve(e()),n.timeout===void 0?this._timeout:n.timeout,()=>{(n.throwOnTimeout===void 0?this._throwOnTimeout:n.throwOnTimeout)&&o(Bir)});r(await s)}catch(s){o(s)}this._next()};this._queue.enqueue(i,n),this._tryToStartAnother(),this.emit("add")})}async addAll(e,n){return Promise.all(e.map(async r=>this.add(r,n)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{let n=this._resolveEmpty;this._resolveEmpty=()=>{n(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let n=this._resolveIdle;this._resolveIdle=()=>{n(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};iVe.default=oVe});var Che,E4t,M4t=b(()=>{Che=L(A4t(),1),E4t="default"in Che.default?Che.default.default:Che.default});var zir,VY,O4t=b(()=>{_4t();M4t();zir=[408,425,429,500,502,503,504],VY=class{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxQueueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.maxQueueSizeBytes=e.maxQueueSizeBytes,this.queue=new E4t({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...n){return this.callWithOptions({},e,...n)}callWithOptions(e,n,...r){let o=e.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&o>0&&this.queueSizeBytes+o>this.maxQueueSizeBytes)return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${o} bytes.`));o>0&&(this.queueSizeBytes+=o);let i=this.onFailedResponseHook,s=this.queue.add(()=>J6e(()=>n(...r).catch(a=>{throw a instanceof Error?a:new Error(a)}),{async onFailedAttempt({error:a}){if(typeof a!="object"||a==null)throw a;let l="message"in a&&typeof a.message=="string"?a.message:void 0;if(l?.startsWith("Cancel")||l?.startsWith("TimeoutError")||l?.startsWith("AbortError")||"name"in a&&a.name==="TimeoutError"||"code"in a&&a.code==="ECONNABORTED")throw a;let c="response"in a?a.response:void 0;if(i&&await i(c))return;let u=c?.status??("status"in a?a.status:void 0);if(u!=null&&(typeof u=="number"||typeof u=="string")&&!zir.includes(+u))throw a},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return o>0&&(s=s.finally(()=>{this.queueSizeBytes-=o})),e.signal?Promise.race([s,new Promise((a,l)=>{e.signal?.addEventListener("abort",()=>{l(new Error("AbortError"))})})]):s}}});function sVe(t){return typeof t?._getType=="function"}function aVe(t){let e={type:t._getType(),data:{content:t.content}};return t?.additional_kwargs&&Object.keys(t.additional_kwargs).length>0&&(e.data.additional_kwargs={...t.additional_kwargs}),e}var N4t=b(()=>{});var lVe,R4t=b(()=>{lVe=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return lVe=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))}});function Fz(t){return typeof t!="object"?{}:t??{}}function uVe(t){if(!t)return!0;for(let e in t)return!1;return!0}function $4t(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var Hir,L4t,wf,cVe,D4t,F4t,SA=b(()=>{BL();Hir=/^[a-z][a-z0-9+.-]*:/i,L4t=t=>Hir.test(t),wf=t=>(wf=Array.isArray,wf(t)),cVe=wf;D4t=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Nm(`${t} must be an integer`);if(e<0)throw new Nm(`${t} must be a positive integer`);return e},F4t=t=>{try{return JSON.parse(t)}catch{return}}});var U4t,j4t=b(()=>{U4t=t=>new Promise(e=>setTimeout(e,t))});var CA,dVe=b(()=>{CA="0.0.1"});function Wir(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function qir(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:n}of t){let r=n.exec(navigator.userAgent);if(r){let o=r[1]||0,i=r[2]||0,s=r[3]||0;return{browser:e,version:`${o}.${i}.${s}`}}}return null}var Vir,B4t,z4t,Kir,H4t,W4t=b(()=>{dVe();Vir=()=>{let t=Wir();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":CA,"X-Stainless-OS":z4t(Deno.build.os),"X-Stainless-Arch":B4t(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":CA,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":CA,"X-Stainless-OS":z4t(globalThis.process.platform??"unknown"),"X-Stainless-Arch":B4t(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=qir();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":CA,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":CA,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};B4t=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",z4t=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),H4t=()=>Kir??(Kir=Vir())});function V4t(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Langsmith({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Gir(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function fVe(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Gir({start(){},async pull(n){let{done:r,value:o}=await e.next();r?n.close():n.enqueue(o)},async cancel(){await e.return?.()}})}async function q4t(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),n=e.cancel();e.releaseLock(),await n}var pVe=b(()=>{});var K4t,G4t=b(()=>{K4t=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)})});var mVe,hVe,gVe,Z4t,yVe=b(()=>{mVe="RFC3986",hVe=t=>String(t),gVe={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:hVe},Z4t="RFC1738"});function J4t(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function wVe(t,e){if(wf(t)){let n=[];for(let r=0;r<t.length;r+=1)n.push(e(t[r]));return n}return e(t)}var khe,jx,vVe,Y4t,X4t=b(()=>{yVe();SA();khe=(t,e)=>(khe=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),khe(t,e)),jx=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})(),vVe=1024,Y4t=(t,e,n,r,o)=>{if(t.length===0)return t;let i=t;if(typeof t=="symbol"?i=Symbol.prototype.toString.call(t):typeof t!="string"&&(i=String(t)),n==="iso-8859-1")return escape(i).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let s="";for(let a=0;a<i.length;a+=vVe){let l=i.length>=vVe?i.slice(a,a+vVe):i,c=[];for(let u=0;u<l.length;++u){let d=l.charCodeAt(u);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||o===Z4t&&(d===40||d===41)){c[c.length]=l.charAt(u);continue}if(d<128){c[c.length]=jx[d];continue}if(d<2048){c[c.length]=jx[192|d>>6]+jx[128|d&63];continue}if(d<55296||d>=57344){c[c.length]=jx[224|d>>12]+jx[128|d>>6&63]+jx[128|d&63];continue}u+=1,d=65536+((d&1023)<<10|l.charCodeAt(u)&1023),c[c.length]=jx[240|d>>18]+jx[128|d>>12&63]+jx[128|d>>6&63]+jx[128|d&63]}s+=c.join("")}return s}});function Xir(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}function tHt(t,e,n,r,o,i,s,a,l,c,u,d,f,p,m,h,g,v){let y=t,w=v,_=0,S=!1;for(;(w=w.get(bVe))!==void 0&&!S;){let P=w.get(t);if(_+=1,typeof P<"u"){if(P===_)throw new RangeError("Cyclic object value");S=!0}typeof w.get(bVe)>"u"&&(_=0)}if(typeof c=="function"?y=c(e,y):y instanceof Date?y=f?.(y):n==="comma"&&wf(y)&&(y=wVe(y,function(P){return P instanceof Date?f?.(P):P})),y===null){if(i)return l&&!h?l(e,Hc.encoder,g,"key",p):e;y=""}if(Xir(y)||J4t(y)){if(l){let P=h?e:l(e,Hc.encoder,g,"key",p);return[m?.(P)+"="+m?.(l(y,Hc.encoder,g,"value",p))]}return[m?.(e)+"="+m?.(String(y))]}let I=[];if(typeof y>"u")return I;let C;if(n==="comma"&&wf(y))h&&l&&(y=wVe(y,l)),C=[{value:y.length>0?y.join(",")||null:void 0}];else if(wf(c))C=c;else{let P=Object.keys(y);C=u?P.sort(u):P}let k=a?String(e).replace(/\./g,"%2E"):String(e),T=r&&wf(y)&&y.length===1?k+"[]":k;if(o&&wf(y)&&y.length===0)return T+"[]";for(let P=0;P<C.length;++P){let E=C[P],O=typeof E=="object"&&typeof E.value<"u"?E.value:y[E];if(s&&O===null)continue;let $=d&&a?E.replace(/\./g,"%2E"):E,U=wf(y)?typeof n=="function"?n(T,$):T:T+(d?"."+$:"["+$+"]");v.set(t,_);let V=new WeakMap;V.set(bVe,v),eHt(I,tHt(O,U,n,r,o,i,s,a,n==="comma"&&h&&wf(y)?null:l,c,u,d,f,p,m,h,g,V))}return I}function Qir(t=Hc){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||Hc.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=mVe;if(typeof t.format<"u"){if(!khe(gVe,t.format))throw new TypeError("Unknown format option provided.");n=t.format}let r=gVe[n],o=Hc.filter;(typeof t.filter=="function"||wf(t.filter))&&(o=t.filter);let i;if(t.arrayFormat&&t.arrayFormat in Q4t?i=t.arrayFormat:"indices"in t?i=t.indices?"indices":"repeat":i=Hc.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let s=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:Hc.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:Hc.addQueryPrefix,allowDots:s,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:Hc.allowEmptyArrays,arrayFormat:i,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:Hc.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?Hc.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:Hc.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:Hc.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:Hc.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:Hc.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:Hc.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:Hc.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:Hc.strictNullHandling}}function nHt(t,e={}){let n=t,r=Qir(e),o,i;typeof r.filter=="function"?(i=r.filter,n=i("",n)):wf(r.filter)&&(i=r.filter,o=i);let s=[];if(typeof n!="object"||n===null)return"";let a=Q4t[r.arrayFormat],l=a==="comma"&&r.commaRoundTrip;o||(o=Object.keys(n)),r.sort&&o.sort(r.sort);let c=new WeakMap;for(let f=0;f<o.length;++f){let p=o[f];r.skipNulls&&n[p]===null||eHt(s,tHt(n[p],p,a,l,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,c))}let u=s.join(r.delimiter),d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}var Q4t,eHt,Jir,Hc,bVe,rHt=b(()=>{X4t();yVe();SA();Q4t={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},eHt=function(t,e){Array.prototype.push.apply(t,wf(e)?e:[e])},Hc={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Y4t,encodeValuesOnly:!1,format:mVe,formatter:hVe,indices:!1,serializeDate(t){return(Jir??(Jir=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};bVe={}});function oHt(t){return nHt(t,{arrayFormat:"repeat"})}var iHt=b(()=>{rHt()});function qY(){}function Ihe(t,e,n){return!e||The[t]>The[n]?qY:e[t].bind(e)}function Ip(t){let e=t.logger,n=t.logLevel??"off";if(!e)return tsr;let r=sHt.get(e);if(r&&r[0]===n)return r[1];let o={error:Ihe("error",e,n),warn:Ihe("warn",e,n),info:Ihe("info",e,n),debug:Ihe("debug",e,n)};return sHt.set(e,[n,o]),o}var The,_Ve,tsr,sHt,Jk,xVe=b(()=>{SA();The={off:0,error:200,warn:300,info:400,debug:500},_Ve=(t,e,n)=>{if(t){if($4t(The,t))return t;Ip(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(The))}`)}};tsr={error:qY,warn:qY,info:qY,debug:qY},sHt=new WeakMap;Jk=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"||e.toLowerCase()==="x-tenant-id"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t)});async function Phe(t,e){let{response:n,requestLogID:r,retryOfRequestLogID:o,startTime:i}=e,s=await(async()=>{if(n.status===204)return null;if(e.options.__binaryResponse)return n;let l=n.headers.get("content-type")?.split(";")[0]?.trim();return l?.includes("application/json")||l?.endsWith("+json")?n.headers.get("content-length")==="0"?void 0:await n.json():await n.text()})();return Ip(t).debug(`[${r}] response parsed`,Jk({retryOfRequestLogID:o,url:n.url,status:n.status,body:s,durationMs:Date.now()-i})),s}var SVe=b(()=>{xVe()});var nsr,aHt,KY,zL,Ahe=b(()=>{SVe();nsr=function(t,e,n,r,o){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(t,n):o?o.value=n:e.set(t,n),n},aHt=function(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)},zL=class t extends Promise{constructor(e,n,r=Phe){super(o=>{o(null)}),Object.defineProperty(this,"responsePromise",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"parseResponse",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"parsedPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),KY.set(this,void 0),nsr(this,KY,e,"f")}_thenUnwrap(e){return new t(aHt(this,KY,"f"),this.responsePromise,async(n,r)=>e(await this.parseResponse(n,r),r))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(aHt(this,KY,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};KY=new WeakMap});var rsr,osr,Ehe,HL,GY,Mhe,Ohe,Nhe,Bx,Uz,bb=b(()=>{BL();SVe();Ahe();SA();rsr=function(t,e,n,r,o){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(t,n):o?o.value=n:e.set(t,n),n},osr=function(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)},HL=class{constructor(e,n,r,o){Ehe.set(this,void 0),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),rsr(this,Ehe,e,"f"),this.options=o,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new Nm("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await osr(this,Ehe,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ehe=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let n of e.getPaginatedItems())yield n}},GY=class extends zL{constructor(e,n,r){super(e,n,async(o,i)=>new r(o,i.response,await Phe(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let n of e)yield n}},Mhe=class extends HL{constructor(e,n,r,o){super(e,n,r,o),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.items=r||[]}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.options.query.offset??0,n=this.getPaginatedItems().length,r=e+n;return{...this.options,query:{...Fz(this.options.query),offset:r}}}},Ohe=class extends HL{constructor(e,n,r,o){super(e,n,r,o),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.items=r||[]}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.options.query.offset??0,n=this.getPaginatedItems().length,r=e+n;return{...this.options,query:{...Fz(this.options.query),offset:r}}}},Nhe=class extends HL{constructor(e,n,r,o){super(e,n,r,o),Object.defineProperty(this,"evaluators",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"total",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.evaluators=r.evaluators||[],this.total=r.total||0}getPaginatedItems(){return this.evaluators??[]}nextPageRequestOptions(){let e=this.options.query.offset??0,n=this.getPaginatedItems().length,r=e+n;return{...this.options,query:{...Fz(this.options.query),offset:r}}}},Bx=class extends HL{constructor(e,n,r,o){super(e,n,r,o),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"next_cursor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.items=r.items||[],this.next_cursor=r.next_cursor||""}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.next_cursor;return e?{...this.options,body:{...Fz(this.options.body),cursor:e}}:null}},Uz=class extends HL{constructor(e,n,r,o){super(e,n,r,o),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"next_cursor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.items=r.items||[],this.next_cursor=r.next_cursor||""}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.next_cursor;return e?{...this.options,query:{...Fz(this.options.query),cursor:e}}:null}}});function Rhe(t,e,n){return CVe(),new File(t,e??"unknown_file",n)}function lHt(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}var CVe,cHt,kVe=b(()=>{pVe();CVe=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};cHt=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"});async function Lhe(t,e,n){if(CVe(),t=await t,ssr(t))return t instanceof File?t:Rhe([await t.arrayBuffer()],t.name);if(asr(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Rhe(await IVe(o),e,n)}let r=await IVe(t);if(e||(e=lHt(t)),!n?.type){let o=r.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof o=="string"&&(n={...n,type:o})}return Rhe(r,e,n)}async function IVe(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(uHt(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(cHt(t))for await(let n of t)e.push(...await IVe(n));else{let n=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${n?`; constructor: ${n}`:""}${lsr(t)}`)}return e}function lsr(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}var uHt,ssr,asr,dHt=b(()=>{kVe();kVe();uHt=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",ssr=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&uHt(t),asr=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function"});var TVe=b(()=>{dHt()});var vo,Wc=b(()=>{vo=class{constructor(e){Object.defineProperty(this,"_client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._client=e}}});function pHt(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var fHt,usr,ln,Tp=b(()=>{BL();fHt=Object.freeze(Object.create(null)),usr=(t=pHt)=>function(n,...r){if(n.length===1)return n[0];let o=!1,i=[],s=n.reduce((u,d,f)=>{/[?#]/.test(d)&&(o=!0);let p=r[f],m=(o?encodeURIComponent:t)(""+p);return f!==r.length&&(p==null||typeof p=="object"&&p.toString===Object.getPrototypeOf(Object.getPrototypeOf(p.hasOwnProperty??fHt)??fHt)?.toString)&&(m=p+"",i.push({start:u.length+d.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(p).slice(8,-1)} is not a valid path parameter`})),u+d+(f===r.length?"":m)},""),a=s.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=l.exec(a))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(i.sort((u,d)=>u.start-d.start),i.length>0){let u=0,d=i.reduce((f,p)=>{let m=" ".repeat(p.start-u),h="^".repeat(p.length);return u=p.start+p.length,f+m+h},"");throw new Nm(`Path parameters result in path with invalid segments:
${i.map(f=>f.error).join(`
`)}
${s}
${d}`)}return s},ln=usr(pHt)});var jz,PVe=b(()=>{Wc();bb();Tp();jz=class extends vo{create(e,n,r){let{extend_trace_retention:o,...i}=n;return this._client.post(ln`/api/v1/platform/annotation-queues/${e}/items`,{query:{extend_trace_retention:o},body:i,...r})}update(e,n,r){let{queue_id:o,...i}=n;return this._client.patch(ln`/api/v1/platform/annotation-queues/${o}/items/${e}`,{body:i,...r})}list(e,n,r){return this._client.getAPIList(ln`/api/v1/platform/annotation-queues/${e}/items`,Uz,{query:n,...r})}createStatus(e,n,r){return this._client.post(ln`/api/v1/platform/annotation-queues/items/${e}/status`,{body:n,...r})}deleteAll(e,n,r){return this._client.post(ln`/api/v1/platform/annotation-queues/${e}/items/delete`,{body:n,...r})}retrieveCount(e,n,r){return this._client.get(ln`/api/v1/platform/annotation-queues/${e}/items/count`,{query:n,...r})}retrievePlacement(e,n,r){let{queue_id:o}=n;return this._client.get(ln`/api/v1/platform/annotation-queues/${o}/items/${e}/placement`,r)}}});var Bz,AVe=b(()=>{Wc();Tp();Bz=class extends vo{create(e,n,r){let{body:o,extend_trace_retention:i}=n;return this._client.post(ln`/api/v1/annotation-queues/${e}/runs`,{query:{extend_trace_retention:i},body:o,...r})}update(e,n,r){let{queue_id:o,...i}=n;return this._client.patch(ln`/api/v1/annotation-queues/${o}/runs/${e}`,{body:i,...r})}list(e,n={},r){return this._client.get(ln`/api/v1/annotation-queues/${e}/runs`,{query:n,...r})}createByKey(e,n,r){let{body:o,extend_trace_retention:i}=n;return this._client.post(ln`/api/v1/annotation-queues/${e}/runs/by-key`,{query:{extend_trace_retention:i},body:o,...r})}deleteAll(e,n,r){return this._client.post(ln`/api/v1/annotation-queues/${e}/runs/delete`,{body:n,...r})}deleteQueue(e,n,r){let{queue_id:o}=n;return this._client.delete(ln`/api/v1/annotation-queues/${o}/runs/${e}`,r)}}});var Xk,EVe=b(()=>{Wc();PVe();PVe();AVe();AVe();bb();Tp();Xk=class extends vo{constructor(){super(...arguments),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:new Bz(this._client)}),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:new jz(this._client)})}retrieve(e,n){return this._client.get(ln`/api/v1/annotation-queues/${e}`,n)}update(e,n,r){return this._client.patch(ln`/api/v1/annotation-queues/${e}`,{body:n,...r})}delete(e,n){return this._client.delete(ln`/api/v1/annotation-queues/${e}`,n)}annotationQueues(e,n){return this._client.post("/api/v1/annotation-queues",{body:e,...n})}createRunStatus(e,n,r){return this._client.post(ln`/api/v1/annotation-queues/status/${e}`,{body:n,...r})}export(e,n,r){return this._client.post(ln`/api/v1/annotation-queues/${e}/export`,{body:n,...r})}populate(e,n){return this._client.post("/api/v1/annotation-queues/populate",{body:e,...n})}retrieveAnnotationQueues(e={},n){return this._client.getAPIList("/api/v1/annotation-queues",Mhe,{query:e,...n})}retrieveQueues(e,n){return this._client.get(ln`/api/v1/annotation-queues/${e}/queues`,n)}retrieveRun(e,n,r){let{queue_id:o,...i}=n;return this._client.get(ln`/api/v1/annotation-queues/${o}/run/${e}`,{query:i,...r})}retrieveSize(e,n={},r){return this._client.get(ln`/api/v1/annotation-queues/${e}/size`,{query:n,...r})}retrieveTotalArchived(e,n={},r){return this._client.get(ln`/api/v1/annotation-queues/${e}/total_archived`,{query:n,...r})}retrieveTotalSize(e,n){return this._client.get(ln`/api/v1/annotation-queues/${e}/total_size`,n)}};Xk.Runs=Bz;Xk.Items=jz});var zz,MVe=b(()=>{Wc();bb();Tp();zz=class extends vo{query(e,n,r){return this._client.getAPIList(ln`/api/v2/datasets/${e}/experiment-runs`,Bx,{body:n,method:"post",...r})}}});var kA,OVe=b(()=>{Wc();MVe();MVe();kA=class extends vo{constructor(){super(...arguments),Object.defineProperty(this,"experimentRuns",{enumerable:!0,configurable:!0,writable:!0,value:new zz(this._client)})}};kA.ExperimentRuns=zz});var WL,NVe=b(()=>{Wc();WL=class extends vo{list(e){return this._client.get("/api/v1/info",e)}}});var VL,RVe=b(()=>{Wc();bb();Tp();VL=class extends vo{retrieve(e,n){return this._client.get(ln`/api/v1/platform/issues/${e}`,n)}list(e={},n){return this._client.getAPIList("/api/v1/platform/issues",Ohe,{query:e,...n})}}});function*msr(t){if(!t)return;if(mHt in t){let{values:r,nulls:o}=t;yield*r.entries();for(let i of o)yield[i,null];return}let e=!1,n;t instanceof Headers?n=t.entries():cVe(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let r of n){let o=r[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let i=cVe(r[1])?r[1]:[r[1]],s=!1;for(let a of i)a!==void 0&&(e&&!s&&(s=!0,yield[o,null]),yield[o,a])}}var mHt,oa,zx=b(()=>{SA();mHt=Symbol("brand.privateNullableHeaders");oa=t=>{let e=new Headers,n=new Set;for(let r of t){let o=new Set;for(let[i,s]of msr(r)){let a=i.toLowerCase();o.has(a)||(e.delete(i),o.add(a)),s===null?(e.delete(i),n.add(a)):(e.append(i,s),n.delete(a))}}return{[mHt]:!0,values:e,nulls:n}}});var qL,LVe=b(()=>{Wc();bb();zx();Tp();qL=class extends vo{create(e,n){return this._client.post("/api/v1/platform/evaluators",{body:e,...n})}retrieve(e,n){return this._client.get(ln`/api/v1/platform/evaluators/${e}`,n)}update(e,n,r){return this._client.patch(ln`/api/v1/platform/evaluators/${e}`,{body:n,...r})}list(e={},n){return this._client.getAPIList("/api/v1/platform/evaluators",Nhe,{query:e,...n})}delete(e,n={},r){let{delete_run_rules:o}=n??{};return this._client.delete(ln`/api/v1/platform/evaluators/${e}`,{query:{delete_run_rules:o},...r,headers:oa([{Accept:"*/*"},r?.headers])})}bulkDelete(e,n){let{evaluator_ids:r,delete_run_rules:o}=e;return this._client.delete("/api/v1/platform/evaluators",{query:{evaluator_ids:r,delete_run_rules:o},...n})}spend(e,n){return this._client.get("/api/v1/platform/evaluators/spend",{query:e,...n})}}});var Hz,$Ve=b(()=>{Wc();zx();Tp();Hz=class extends vo{retrieve(e,n,r){let{share_token:o,Accept:i,...s}=n;return this._client.get(ln`/api/v2/public/${o}/run/${e}`,{query:s,...r,headers:oa([{...i!=null?{Accept:i}:void 0},r?.headers])})}query(e,n,r){let{Accept:o,...i}=n;return this._client.post(ln`/api/v2/public/${e}/runs/query`,{body:i,...r,headers:oa([{...o!=null?{Accept:o}:void 0},r?.headers])})}}});var IA,DVe=b(()=>{Wc();$Ve();$Ve();IA=class extends vo{constructor(){super(...arguments),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:new Hz(this._client)})}};IA.Runs=Hz});var Wz,FVe=b(()=>{Wc();zx();Tp();Wz=class extends vo{create(e,n,r){return this._client.post(ln`/api/v2/runs/${e}/share`,{body:n,...r})}delete(e,n,r){return this._client.delete(ln`/api/v2/runs/${e}/share`,{body:n,...r,headers:oa([{Accept:"*/*"},r?.headers])})}}});var TA,UVe=b(()=>{Wc();FVe();FVe();bb();zx();Tp();TA=class extends vo{constructor(){super(...arguments),Object.defineProperty(this,"share",{enumerable:!0,configurable:!0,writable:!0,value:new Wz(this._client)}),Object.defineProperty(this,"retrieve",{enumerable:!0,configurable:!0,writable:!0,value:this.retrieveV2}),Object.defineProperty(this,"query",{enumerable:!0,configurable:!0,writable:!0,value:this.queryV2})}getURL(e,n,r){return this._client.get(ln`/api/v2/runs/${e}/url`,{query:n,...r})}queryV2(e,n){let{Accept:r,...o}=e;return this._client.getAPIList("/api/v2/runs/query",Bx,{body:o,method:"post",...n,headers:oa([{...r!=null?{Accept:r}:void 0},n?.headers])})}retrieveV2(e,n,r){let{Accept:o,...i}=n;return this._client.get(ln`/api/v2/runs/${e}`,{query:i,...r,headers:oa([{...o!=null?{Accept:o}:void 0},r?.headers])})}};TA.Share=Wz});var Vz,jVe=b(()=>{Wc();zx();Tp();Vz=class extends vo{create(e,n){return this._client.post("/api/v2/sandboxes/boxes",{body:e,...n})}retrieve(e,n){return this._client.get(ln`/api/v2/sandboxes/boxes/${e}`,n)}update(e,n,r){return this._client.patch(ln`/api/v2/sandboxes/boxes/${e}`,{body:n,...r})}list(e={},n){return this._client.get("/api/v2/sandboxes/boxes",{query:e,...n})}delete(e,n){return this._client.delete(ln`/api/v2/sandboxes/boxes/${e}`,{...n,headers:oa([{Accept:"*/*"},n?.headers])})}createSnapshot(e,n,r){return this._client.post(ln`/api/v2/sandboxes/boxes/${e}/snapshot`,{body:n,...r})}generateServiceURL(e,n,r){return this._client.post(ln`/api/v2/sandboxes/boxes/${e}/service-url`,{body:n,...r})}getStatus(e,n){return this._client.get(ln`/api/v2/sandboxes/boxes/${e}/status`,n)}start(e,n){return this._client.post(ln`/api/v2/sandboxes/boxes/${e}/start`,n)}stop(e,n){return this._client.post(ln`/api/v2/sandboxes/boxes/${e}/stop`,{...n,headers:oa([{Accept:"*/*"},n?.headers])})}}});var qz,BVe=b(()=>{Wc();zx();Tp();qz=class extends vo{create(e,n){return this._client.post("/api/v2/sandboxes/registries",{body:e,...n})}retrieve(e,n){return this._client.get(ln`/api/v2/sandboxes/registries/${e}`,n)}update(e,n,r){return this._client.patch(ln`/api/v2/sandboxes/registries/${e}`,{body:n,...r})}list(e={},n){return this._client.get("/api/v2/sandboxes/registries",{query:e,...n})}delete(e,n){return this._client.delete(ln`/api/v2/sandboxes/registries/${e}`,{...n,headers:oa([{Accept:"*/*"},n?.headers])})}}});var Kz,zVe=b(()=>{Wc();zx();Tp();Kz=class extends vo{create(e,n){return this._client.post("/api/v2/sandboxes/snapshots",{body:e,...n})}retrieve(e,n){return this._client.get(ln`/api/v2/sandboxes/snapshots/${e}`,n)}list(e={},n){return this._client.get("/api/v2/sandboxes/snapshots",{query:e,...n})}delete(e,n){return this._client.delete(ln`/api/v2/sandboxes/snapshots/${e}`,{...n,headers:oa([{Accept:"*/*"},n?.headers])})}}});var Hx,HVe=b(()=>{Wc();jVe();jVe();BVe();BVe();zVe();zVe();Hx=class extends vo{constructor(){super(...arguments),Object.defineProperty(this,"boxes",{enumerable:!0,configurable:!0,writable:!0,value:new Vz(this._client)}),Object.defineProperty(this,"registries",{enumerable:!0,configurable:!0,writable:!0,value:new qz(this._client)}),Object.defineProperty(this,"snapshots",{enumerable:!0,configurable:!0,writable:!0,value:new Kz(this._client)})}};Hx.Boxes=Vz;Hx.Registries=qz;Hx.Snapshots=Kz});var KL,WVe=b(()=>{Wc();bb();Tp();KL=class extends vo{listTraces(e,n,r){return this._client.getAPIList(ln`/api/v2/threads/${e}/traces`,Uz,{query:n,...r})}query(e,n){return this._client.getAPIList("/api/v2/threads/query",Bx,{body:e,method:"post",...n})}stats(e,n,r){return this._client.get(ln`/api/v2/threads/${e}/stats`,{query:n,...r})}}});var GL,VVe=b(()=>{Wc();bb();zx();Tp();GL=class extends vo{listRuns(e,n,r){let{Accept:o,...i}=n;return this._client.get(ln`/api/v2/traces/${e}/runs`,{query:i,...r,headers:oa([{...o!=null?{Accept:o}:void 0},r?.headers])})}query(e,n){return this._client.getAPIList("/api/v2/traces/query",Bx,{body:e,method:"post",...n})}}});var hHt=b(()=>{EVe();OVe();NVe();RVe();LVe();DVe();UVe();HVe();WVe();VVe()});var Gz,gHt=b(()=>{Gz=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0}});var _sr,yHt,qVe,KVe,$he,vHt,ri,GVe=b(()=>{R4t();SA();j4t();L6e();W4t();pVe();G4t();iHt();dVe();BL();bb();TVe();hHt();Ahe();NVe();RVe();LVe();WVe();VVe();EVe();OVe();DVe();UVe();HVe();zx();gHt();xVe();SA();_sr=function(t,e,n,r,o){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(t,n):o?o.value=n:e.set(t,n),n},yHt=function(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)},ri=class{constructor({baseURL:e=Gz("LANGCHAIN_BASE_URL"),apiKey:n=Gz("LANGSMITH_API_KEY")??null,tenantID:r=Gz("LANGSMITH_TENANT_ID")??null,...o}={}){qVe.add(this),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tenantID",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"baseURL",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logLevel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetch",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),$he.set(this,void 0),Object.defineProperty(this,"idempotencyHeader",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"datasets",{enumerable:!0,configurable:!0,writable:!0,value:new kA(this)}),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:new TA(this)}),Object.defineProperty(this,"threads",{enumerable:!0,configurable:!0,writable:!0,value:new KL(this)}),Object.defineProperty(this,"traces",{enumerable:!0,configurable:!0,writable:!0,value:new GL(this)}),Object.defineProperty(this,"onlineEvaluators",{enumerable:!0,configurable:!0,writable:!0,value:new qL(this)}),Object.defineProperty(this,"public",{enumerable:!0,configurable:!0,writable:!0,value:new IA(this)}),Object.defineProperty(this,"annotationQueues",{enumerable:!0,configurable:!0,writable:!0,value:new Xk(this)}),Object.defineProperty(this,"info",{enumerable:!0,configurable:!0,writable:!0,value:new WL(this)}),Object.defineProperty(this,"issues",{enumerable:!0,configurable:!0,writable:!0,value:new VL(this)}),Object.defineProperty(this,"sandboxes",{enumerable:!0,configurable:!0,writable:!0,value:new Hx(this)});let i={apiKey:n,tenantID:r,...o,baseURL:e||"https://api.smith.langchain.com/"};this.baseURL=i.baseURL,this.timeout=i.timeout??KVe.DEFAULT_TIMEOUT,this.logger=i.logger??console;let s="warn";this.logLevel=s,this.logLevel=_Ve(i.logLevel,"ClientOptions.logLevel",this)??_Ve(Gz("LANGCHAIN_LOG"),"process.env['LANGCHAIN_LOG']",this)??s,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??V4t(),_sr(this,$he,K4t,"f");let a=Gz("LANGCHAIN_CUSTOM_HEADERS");if(a){let l={};for(let c of a.split(`
`)){let u=c.indexOf(":");u>=0&&(l[c.substring(0,u).trim()]=c.substring(u+1).trim())}i.defaultHeaders={...l,...i.defaultHeaders}}this._options=i,this.apiKey=n,this.tenantID=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,tenantID:this.tenantID,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(!(this.apiKey&&e.get("x-api-key"))&&!n.has("x-api-key")&&!(this.tenantID&&e.get("x-tenant-id"))&&!n.has("x-tenant-id"))throw new Error('Could not resolve authentication method. Expected either apiKey or tenantID to be set. Or for one of the "X-API-Key" or "X-Tenant-Id" headers to be explicitly omitted')}async authHeaders(e){return oa([await this.apiKeyAuth(e),await this.tenantIDAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return oa([{"X-API-Key":this.apiKey}])}async tenantIDAuth(e){if(this.tenantID!=null)return oa([{"X-Tenant-Id":this.tenantID}])}stringifyQuery(e){return oHt(e)}getUserAgent(){return`${this.constructor.name}/JS ${CA}`}defaultIdempotencyKey(){return`stainless-node-retry-${lVe()}`}makeStatusError(e,n,r,o){return _d.generate(e,n,r,o)}buildURL(e,n,r){let o=!yHt(this,qVe,"m",vHt).call(this)&&r||this.baseURL,i=L4t(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery(),a=Object.fromEntries(i.searchParams);return(!uVe(s)||!uVe(a))&&(n={...a,...s,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(i.search=this.stringifyQuery(n)),i.toString()}async prepareOptions(e){}async prepareRequest(e,{url:n,options:r}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(o=>({method:e,path:n,...o})))}request(e,n=null){return new zL(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){let o=await e,i=o.maxRetries??this.maxRetries;n==null&&(n=i),await this.prepareOptions(o);let{req:s,url:a,timeout:l}=await this.buildRequest(o,{retryCount:i-n});await this.prepareRequest(s,{url:a,options:o});let c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(Ip(this).debug(`[${c}] sending request`,Jk({retryOfRequestLogID:r,method:o.method,url:a,options:o,headers:s.headers})),o.signal?.aborted)throw new _A;let f=new AbortController,p=await this.fetchWithTimeout(a,s,l,f).catch(zY),m=Date.now();if(p instanceof globalThis.Error){let g=`retrying, ${n} attempts remaining`;if(o.signal?.aborted)throw new _A;let v=d4t(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(n)return Ip(this).info(`[${c}] connection ${v?"timed out":"failed"} - ${g}`),Ip(this).debug(`[${c}] connection ${v?"timed out":"failed"} (${g})`,Jk({retryOfRequestLogID:r,url:a,durationMs:m-d,message:p.message})),this.retryRequest(o,n,r??c);throw Ip(this).info(`[${c}] connection ${v?"timed out":"failed"} - error; no more retries left`),Ip(this).debug(`[${c}] connection ${v?"timed out":"failed"} (error; no more retries left)`,Jk({retryOfRequestLogID:r,url:a,durationMs:m-d,message:p.message})),v?new OL:new Yk({cause:p})}let h=`[${c}${u}] ${s.method} ${a} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${m-d}ms`;if(!p.ok){let g=await this.shouldRetry(p);if(n&&g){let I=`retrying, ${n} attempts remaining`;return await q4t(p.body),Ip(this).info(`${h} - ${I}`),Ip(this).debug(`[${c}] response error (${I})`,Jk({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,durationMs:m-d})),this.retryRequest(o,n,r??c,p.headers)}let v=g?"error; no more retries left":"error; not retryable";Ip(this).info(`${h} - ${v}`);let y=await p.text().catch(I=>zY(I).message),w=F4t(y),_=w?void 0:y;throw Ip(this).debug(`[${c}] response error (${v})`,Jk({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,message:_,durationMs:Date.now()-d})),this.makeStatusError(p.status,w,_,p.headers)}return Ip(this).info(h),Ip(this).debug(`[${c}] response start`,Jk({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,durationMs:m-d})),{response:p,options:o,controller:f,requestLogID:c,retryOfRequestLogID:r,startTime:d}}getAPIList(e,n,r){return this.requestAPIList(n,r&&"then"in r?r.then(o=>({method:"get",path:e,...o})):{method:"get",path:e,...r})}requestAPIList(e,n){let r=this.makeRequest(n,null,void 0);return new GY(this,r,e)}async fetchWithTimeout(e,n,r,o){let{signal:i,method:s,...a}=n||{},l=this._makeAbort(o);i&&i.addEventListener("abort",l,{once:!0});let c=setTimeout(l,r),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:o.signal,...u?{duplex:"half"}:{},method:"GET",...a};s&&(d.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(c)}}async shouldRetry(e){let n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,r,o){let i,s=o?.get("retry-after-ms");if(s){let l=parseFloat(s);Number.isNaN(l)||(i=l)}let a=o?.get("retry-after");if(a&&!i){let l=parseFloat(a);Number.isNaN(l)?i=Date.parse(a)-Date.now():i=l*1e3}if(i===void 0){let l=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(n,l)}return await U4t(i),this.makeRequest(e,n-1,r)}calculateDefaultRetryTimeoutMillis(e,n){let i=n-e,s=Math.min(.5*Math.pow(2,i),16),a=1-Math.random()*.25;return s*a*1e3}async buildRequest(e,{retryCount:n=0}={}){let r={...e},{method:o,path:i,query:s,defaultBaseURL:a}=r,l=this.buildURL(i,s,a);"timeout"in r&&D4t("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:c,body:u}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:o,bodyHeaders:c,retryCount:n});return{req:{method:o,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...r.fetchOptions??{}},url:l,timeout:r.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:r,retryCount:o}){let i={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);let s=oa([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...H4t()},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(s),s.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=oa([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:fVe(e)}:typeof e=="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:yHt(this,$he,"f").call(this,{body:e,headers:r})}};KVe=ri,$he=new WeakMap,qVe=new WeakSet,vHt=function(){return this.baseURL!=="https://api.smith.langchain.com/"};Object.defineProperty(ri,"Langsmith",{enumerable:!0,configurable:!0,writable:!0,value:KVe});Object.defineProperty(ri,"DEFAULT_TIMEOUT",{enumerable:!0,configurable:!0,writable:!0,value:9e4});Object.defineProperty(ri,"LangsmithError",{enumerable:!0,configurable:!0,writable:!0,value:Nm});Object.defineProperty(ri,"APIError",{enumerable:!0,configurable:!0,writable:!0,value:_d});Object.defineProperty(ri,"APIConnectionError",{enumerable:!0,configurable:!0,writable:!0,value:Yk});Object.defineProperty(ri,"APIConnectionTimeoutError",{enumerable:!0,configurable:!0,writable:!0,value:OL});Object.defineProperty(ri,"APIUserAbortError",{enumerable:!0,configurable:!0,writable:!0,value:_A});Object.defineProperty(ri,"NotFoundError",{enumerable:!0,configurable:!0,writable:!0,value:$L});Object.defineProperty(ri,"ConflictError",{enumerable:!0,configurable:!0,writable:!0,value:DL});Object.defineProperty(ri,"RateLimitError",{enumerable:!0,configurable:!0,writable:!0,value:UL});Object.defineProperty(ri,"BadRequestError",{enumerable:!0,configurable:!0,writable:!0,value:NL});Object.defineProperty(ri,"AuthenticationError",{enumerable:!0,configurable:!0,writable:!0,value:RL});Object.defineProperty(ri,"InternalServerError",{enumerable:!0,configurable:!0,writable:!0,value:jL});Object.defineProperty(ri,"PermissionDeniedError",{enumerable:!0,configurable:!0,writable:!0,value:LL});Object.defineProperty(ri,"UnprocessableEntityError",{enumerable:!0,configurable:!0,writable:!0,value:FL});Object.defineProperty(ri,"toFile",{enumerable:!0,configurable:!0,writable:!0,value:Lhe});ri.Datasets=kA;ri.Runs=TA;ri.Threads=KL;ri.Traces=GL;ri.OnlineEvaluators=qL;ri.Public=IA;ri.AnnotationQueues=Xk;ri.Info=WL;ri.Issues=VL;ri.Sandboxes=Hx});var wHt=b(()=>{GVe();TVe();Ahe();GVe();bb();BL()});function bHt(t){let e=t??{},n=!!(e.ch_query_enabled??!0),r=!!(e.sdb_query_enabled??!1);return!n&&r?ZY.SMITHDB_ONLY:n&&r?ZY.DUAL:ZY.CLICKHOUSE_ONLY}var ZY,_Ht=b(()=>{ZY={CLICKHOUSE_ONLY:"clickhouse_only",SMITHDB_ONLY:"smithdb_only",DUAL:"dual"}});function Fhe(t){return`Invalid prompt identifier format: "${t}". Expected one of:
- "prompt-name" (for private prompts)
- "owner/prompt-name" (for prompts with explicit owner)
- "prompt-name:commit-hash" (with commit reference)
- "owner/prompt-name:commit-hash" (with owner and commit)`}function Uhe(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithNotFoundError"}function xHt(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithConflictError"}async function Yt(t,e,n){let r;if(t.ok){n&&(r=await t.text());return}if(t.status===403)try{(await t.json())?.error==="org_scoped_key_requires_workspace"&&(r="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{let a=new Error(`${t.status} ${t.statusText}`);throw a.status=t?.status,a}if(r===void 0)try{r=await t.text()}catch{r=""}let o=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Message: ${r}`;if(t.status===404)throw new YVe(o);if(t.status===409)throw new ZVe(o);let i=new Error(o);throw i.status=t.status,i}function CHt(t){return typeof t=="object"&&t!==null&&t.code===SHt}var ZVe,YVe,SHt,Dhe,jhe=b(()=>{ZVe=class extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}},YVe=class extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}};SHt="ERR_CONFLICTING_ENDPOINTS",Dhe=class extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:SHt}),this.name="ConflictingEndpointsError"}}});function bf(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(Fhe(t));let[e,n]=t.split(":"),r=n||"latest";if(e.includes("/")){let[o,i]=e.split("/",2);if(!o||!i)throw new Error(Fhe(t));return[o,i,r]}else{if(!e)throw new Error(Fhe(t));return["-",e,r]}}var kHt=b(()=>{jhe()});function Csr(t){return new Promise(e=>setTimeout(e,t))}function ksr(t){return typeof t=="object"&&t!==null&&t.code==="EEXIST"}function THt(t){try{return ML(vb.join(t,IHt)).split(`
`)}catch{return}}function Isr(t){let e=THt(t);if(e&&e[0]&&e[0].trim()){let n=Date.parse(e[0].trim());if(!Number.isNaN(n))return n}return void 0}function Tsr(t){let e=THt(t);if(e&&e.length>=2&&e[1].trim())return e[1].trim()}async function Psr(t){let e=Isr(t);return e===void 0||Date.now()-e<=Ssr?!1:(await uhe(t),!0)}async function PHt(t,e){let n=`${t}.oauth.lock.lock`,r=vb.dirname(n);r&&await che(r);let o=globalThis.crypto.randomUUID();for(;;){try{await u4t(n)}catch(i){if(!ksr(i))throw i;if(!await Psr(n)){if(Date.now()>=e)throw new Error("timed out acquiring OAuth refresh lock");await Csr(Math.min(xsr,Math.max(0,e-Date.now())))}continue}try{await $z(vb.join(n,IHt),`${new Date().toISOString()}
${o}
`)}catch(i){throw await uhe(n),i}break}return{async release(){Tsr(n)===o&&await uhe(n)}}}var xsr,Ssr,IHt,AHt=b(()=>{BY();xsr=10,Ssr=1e4,IHt="created_at"});function Nsr(){let t=HY();return t==="browser"||t==="webworker"}function Rsr(){let t=Ou("LANGSMITH_CONFIG_FILE");if(t)return t;let e=Ou("HOME")??Ou("USERPROFILE");if(e)return vb.join(e,".langsmith","config.json")}function Lsr(t){let e=Ou("LANGSMITH_PROFILE");if(e)return e;if(t.current_profile)return t.current_profile;if(t.profiles?.default)return"default"}function $sr(){if(Nsr())return;let t=Rsr();if(!(!t||!Dz(t)))try{let e=JSON.parse(ML(t)),n=Lsr(e),r=n?e.profiles?.[n]:void 0;return!n||!r?void 0:{configPath:t,config:e,profileName:n,profile:r}}catch{return}}function uv(t){return t!=null&&t.trim()!==""}function PA(t){return t?.trim().replace(/^["']|["']$/g,"")}function MHt(t){let e=t.oauth;if(!e?.refresh_token)return!1;if(!e.access_token)return!0;if(!e.expires_at)return!1;let n=Date.parse(e.expires_at);return Number.isNaN(n)?!1:n<=Date.now()+Esr}function NHt(t){let e=t;for(;e.endsWith("/");)e=e.slice(0,-1);let n="/api/v1";return e.endsWith(n)?e.slice(0,-n.length):e}function Dsr(t){let e=NHt(t),n=e.endsWith("/api")?e.slice(0,-4):e,r=[];for(let o of[e,`${n}/api`,n])o&&o!=="/api"&&!r.includes(o)&&r.push(o);return r}function Fsr(t,e){let{issuer:n}=t;if(typeof n!="string"||n.replace(/\/+$/,"")!==e.replace(/\/+$/,""))return!1;let r;try{r=new URL(n)}catch{return!1}for(let o of[t.device_authorization_endpoint,t.token_endpoint]){if(typeof o!="string"||!o)return!1;try{let i=new URL(o);if(i.protocol!==r.protocol||i.host!==r.host)return!1}catch{return!1}}return!0}function Usr(t){let e=`${t}${EHt}`,n;try{let r=new URL(t);n=`${r.origin}${EHt}${r.pathname==="/"?"":r.pathname}`}catch{return[e]}return n===e?[n]:[n,e]}async function jsr(t,e,n){let r;try{r=await n(t,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(Osr)})}catch{return}if(!r.ok)return;let o;try{o=await r.json()}catch{return}if(!(!o||typeof o!="object"||!Fsr(o,e)))return o}async function Bsr(t,e){for(let n of Dsr(t))for(let r of Usr(n)){let o=await jsr(r,n,e);if(o)return o.token_endpoint}return`${NHt(t)}/oauth/token`}function zsr(t,e){t.oauth??(t.oauth={}),e.access_token&&(t.oauth.access_token=e.access_token),e.refresh_token&&(t.oauth.refresh_token=e.refresh_token),typeof e.expires_in=="number"&&e.expires_in>0&&(t.oauth.expires_at=new Date(Date.now()+e.expires_in*1e3).toISOString())}function OHt(t){return t.reason??new Error("The operation was aborted.")}async function Hsr(t,e){if(!e)return t;if(e.aborted)throw OHt(e);let n,r=new Promise((o,i)=>{let s=()=>{i(OHt(e))};e.addEventListener("abort",s,{once:!0}),n=()=>{e.removeEventListener("abort",s)}});try{return await Promise.race([t,r])}finally{n?.()}}function RHt(){let t=$sr(),e=t?.profile;if(!t||!e)return{};let n=PA(e.api_key),r=PA(e.oauth?.access_token),o=PA(e.oauth?.refresh_token);return{apiUrl:e.api_url,apiKey:n,workspaceId:e.workspace_id,oauthAccessToken:r,oauthRefreshToken:o,profileAuth:n||r||o?new JVe(t):void 0}}function Wsr(t){let e=PA(t.oauth?.access_token);if(e)return{name:"Authorization",value:`Bearer ${e}`};if(!PA(t.oauth?.refresh_token))return LHt(t)}function LHt(t){let e=PA(t.oauth?.access_token);if(e)return{name:"Authorization",value:`Bearer ${e}`};let n=PA(t.api_key);if(n)return{name:"x-api-key",value:n}}var Bhe,Asr,Esr,Msr,Osr,EHt,JVe,$Ht=b(()=>{$x();BY();AHt();Bhe="https://api.smith.langchain.com",Asr="langsmith-cli",Esr=6e4,Msr=1e4,Osr=5e3,EHt="/.well-known/oauth-authorization-server";JVe=class{constructor(e){Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"refreshPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"managedAuthorizationValue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.rememberProfileAuthHeader(this.currentAuthHeader())}currentAuthHeader(){let e=Wsr(this.state.profile);return this.rememberProfileAuthHeader(e),e}async getAuthHeader(e,n){MHt(this.state.profile)&&(this.refreshPromise||(this.refreshPromise=this.refreshOAuthToken(e).finally(()=>{this.refreshPromise=void 0})),await Hsr(this.refreshPromise,n));let r=LHt(this.state.profile);return this.rememberProfileAuthHeader(r),r}isProfileAuthorizationHeader(e){return e===this.managedAuthorizationValue}reloadProfile(){try{let e=JSON.parse(ML(this.state.configPath)),n=e.profiles?.[this.state.profileName];return n?(this.state.config=e,this.state.profile=n,n):void 0}catch{return}}async refreshOAuthToken(e){var s;let n=this.state.profile.oauth?.refresh_token;if(!n)return;let r=PA(this.state.profile.api_url)??Bhe,o=Date.now()+Msr,i;try{if(i=await PHt(this.state.configPath,o),this.reloadProfile()&&!MHt(this.state.profile))return;let l=new URLSearchParams({grant_type:"refresh_token",client_id:Asr,refresh_token:this.state.profile.oauth?.refresh_token??n}),c=await Bsr(r,e),u=await e(c,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l.toString(),signal:AbortSignal.timeout(Math.max(0,o-Date.now()))});if(!u.ok)return;let d=await u.json();if(!d.access_token)return;zsr(this.state.profile,d),(s=this.state.config).profiles??(s.profiles={}),this.state.config.profiles[this.state.profileName]=this.state.profile,await $z(this.state.configPath,`${JSON.stringify(this.state.config,null,2)}
`)}catch{return}finally{await i?.release()}}rememberProfileAuthHeader(e){this.managedAuthorizationValue=e?.name==="Authorization"?e.value:void 0}}});function Ksr(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function zhe(t){return qsr.encode(t)}function FHt(t){if(t&&typeof t=="object"&&t!==null){if(t instanceof Map)return Object.fromEntries(t);if(t instanceof Set)return Array.from(t);if(t instanceof Date)return t.toISOString();if(t instanceof RegExp)return t.toString();if(t instanceof Error)return{name:t.name,message:t.message}}else if(typeof t=="bigint")return t.toString();return t}function Gsr(t){return function(e,n){if(t){let r=t.call(this,e,n);if(r!==void 0)return r}return FHt(n)}}function UHt(t){try{let o=function(u){let d=r(u);return d>n&&(n=d),d+2},i=function(u){return u===0?2:2+u*4},s=function(u){return u===void 0||typeof u=="function"||typeof u=="symbol"},a=function(u){return u===void 0||typeof u=="function"||typeof u=="symbol"?4:l(u)},l=function(u){if(u===null)return 4;if(u===void 0)return 0;let d=typeof u;if(d==="boolean")return 5;if(d==="number")return Number.isFinite(u)?u.toString().length:4;if(d==="bigint")return u.toString().length+2;if(d==="string")return o(u);if(d==="function"||d==="symbol")return 0;let f=u;if(f instanceof Date)return 26;if(f instanceof RegExp)return r(f.toString())+2;if(f instanceof Error){let m=f.name??"",h=f.message??"";return 22+r(m)+r(h)}if(typeof Buffer<"u"&&f instanceof Buffer)return 28+i(f.byteLength);if(ArrayBuffer.isView(f)){if(f instanceof DataView)return 2;let m=f.length??0,g=f instanceof Float32Array||f instanceof Float64Array?30:12;return 2+m*g}if(f instanceof ArrayBuffer)return 2;if(e.has(f))return 24;if(typeof f.toJSON=="function"){let m;try{m=f.toJSON("")}catch{return 16}e.add(f);let h=l(m);return e.delete(f),h}e.add(f);let p;if(Array.isArray(f)){p=2;let m=f.length;for(let h=0;h<m;h++)p+=a(f[h]),h<m-1&&(p+=1)}else if(f instanceof Map){p=2;let m=0;for(let[h,g]of f){if(s(g))continue;m>0&&(p+=1);let v=typeof h=="string"?h:String(h);p+=r(v)+3,p+=l(g),m++}}else if(f instanceof Set){p=2;let m=0;for(let h of f)m>0&&(p+=1),p+=a(h),m++}else{p=2;let m=0,h=Object.keys(f);for(let g=0;g<h.length;g++){let v=h[g],y=f[v];s(y)||(m>0&&(p+=1),p+=r(v)+3,p+=l(y),m++)}}return e.delete(f),p},e=new Set,n=0,r=typeof Buffer<"u"&&typeof Buffer.byteLength=="function"?u=>Buffer.byteLength(u,"utf8"):u=>u.length;return{size:l(t),maxStringLen:n}}catch{return{size:_f(t).length,maxStringLen:0}}}function _f(t,e,n,r,o){try{let i=JSON.stringify(t,Gsr(n),r);return zhe(i)}catch(i){if(!i.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
Context: ${e}`:""}`),zhe("[Unserializable]");Os("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
Context: ${e}`:""}`),typeof o>"u"&&(o=Ksr()),QVe(t,"",0,[],void 0,0,o);let s;try{Zz.length===0?s=JSON.stringify(t,n,r):s=JSON.stringify(t,Zsr(n),r)}catch{return zhe("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Hhe.length!==0;){let a=Hhe.pop();a.length===4?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return zhe(s)}}function XVe(t,e,n,r){var o=Object.getOwnPropertyDescriptor(r,n);o.get!==void 0?o.configurable?(Object.defineProperty(r,n,{value:t}),Hhe.push([r,n,e,o])):Zz.push([e,n,t]):(r[n]=t,Hhe.push([r,n,e]))}function QVe(t,e,n,r,o,i,s){i+=1;var a;if(typeof t=="object"&&t!==null){for(a=0;a<r.length;a++)if(r[a]===t){XVe(Vsr,t,e,o);return}if(typeof s.depthLimit<"u"&&i>s.depthLimit){XVe(DHt,t,e,o);return}if(typeof s.edgesLimit<"u"&&n+1>s.edgesLimit){XVe(DHt,t,e,o);return}if(r.push(t),Array.isArray(t))for(a=0;a<t.length;a++)QVe(t[a],a,a,r,t,i,s);else{t=FHt(t);var l=Object.keys(t);for(a=0;a<l.length;a++){var c=l[a];QVe(t[c],c,a,r,t,i,s)}}r.pop()}}function Zsr(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(Zz.length>0)for(var r=0;r<Zz.length;r++){var o=Zz[r];if(o[1]===e&&o[0]===n){n=o[2],Zz.splice(r,1);break}}return t.call(this,e,n)}}var DHt,Vsr,Hhe,Zz,qsr,jHt=b(()=>{$x();DHt="[...]",Vsr={result:"[Circular]"},Hhe=[],Zz=[],qsr=new TextEncoder});var BHt=b(()=>{});function HHt(){return e3e===null&&(e3e=new t3e),e3e}function WHt(t,e=Xsr,n=Qsr){if(t===null||typeof t!="object")return typeof t=="string"&&t.length>=e;let r=[t],o=new Set,i=0;for(;r.length>0;){if(i++>=n)return!1;let s=r.pop();if(s==null)continue;let a=typeof s;if(a==="string"){if(s.length>=e)return!0;continue}if(a!=="object")continue;let l=s;if(o.has(l)||(o.add(l),l instanceof Date||l instanceof RegExp||l instanceof Error||l instanceof ArrayBuffer||ArrayBuffer.isView(l)))continue;if(Array.isArray(l)){for(let u=l.length-1;u>=0;u--)r.push(l[u]);continue}if(l instanceof Map){for(let[,u]of l)r.push(u);continue}if(l instanceof Set){for(let u of l)r.push(u);continue}let c=Object.keys(l);for(let u=c.length-1;u>=0;u--)r.push(l[c[u]])}return!1}var Jsr,t3e,e3e,Xsr,Qsr,VHt=b(()=>{BHt();Jsr=`
const { parentPort } = require("worker_threads");
const CIRCULAR_REPLACE_NODE = { result: "[Circular]" };
function serializeWellKnownTypes(val) {
if (val && typeof val === "object") {
if (val instanceof Map) return Object.fromEntries(val);
if (val instanceof Set) return Array.from(val);
if (val instanceof Date) return val.toISOString();
if (val instanceof RegExp) return val.toString();
if (val instanceof Error) return { name: val.name, message: val.message };
} else if (typeof val === "bigint") {
return val.toString();
}
return val;
}
function defaultReplacer(_key, val) {
return serializeWellKnownTypes(val);
}
// Decirculate in-place: replace circular refs with { result: "[Circular]" }
// then restore after stringify. Mirrors fast-safe-stringify's decirc().
const restoreStack = [];
function decirc(val, k, stack, parent) {
if (typeof val === "object" && val !== null) {
for (let i = 0; i < stack.length; i++) {
if (stack[i] === val) {
const orig = parent[k];
parent[k] = CIRCULAR_REPLACE_NODE;
restoreStack.push([parent, k, orig]);
return;
}
}
stack.push(val);
if (Array.isArray(val)) {
for (let i = 0; i < val.length; i++) decirc(val[i], i, stack, val);
} else {
const normalized = serializeWellKnownTypes(val);
// Only recurse into normalized if it's still an object (arrays/objects),
// else it was replaced with a primitive (e.g. Date -> string).
if (normalized === val) {
const keys = Object.keys(val);
for (let i = 0; i < keys.length; i++) decirc(val[keys[i]], keys[i], stack, val);
}
}
stack.pop();
}
}
function serialize(obj) {
try {
return JSON.stringify(obj, defaultReplacer);
} catch (e) {
if (!String(e && e.message).includes("Converting circular structure to JSON")) {
return "[Unserializable]";
}
decirc(obj, "", [], { "": obj });
try {
return JSON.stringify(obj, defaultReplacer);
} catch (_) {
return "[unable to serialize, circular reference is too complex to analyze]";
} finally {
while (restoreStack.length) {
const [p, k, v] = restoreStack.pop();
p[k] = v;
}
}
}
}
parentPort.on("message", (msg) => {
const { id, op, payload } = msg;
try {
if (op === "serialize") {
const str = serialize(payload);
const buf = Buffer.from(str, "utf8");
// Slice into its own ArrayBuffer so we can transfer without dragging
// unrelated bytes from any shared pool buffer.
const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
parentPort.postMessage({ id, bytes: ab, length: buf.byteLength }, [ab]);
} else if (op === "ping") {
parentPort.postMessage({ id });
} else {
parentPort.postMessage({ id, error: "unknown op: " + op });
}
} catch (e) {
parentPort.postMessage({ id, error: String((e && e.message) || e) });
}
});
`,t3e=class{constructor(){Object.defineProperty(this,"worker",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"nextId",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"pending",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"disabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"startPromise",{enumerable:!0,configurable:!0,writable:!0,value:null})}async ensureStarted(){if(this.disabled)return!1;if(this.worker!==null)return!0;if(this.startPromise!==null)return this.startPromise;this.startPromise=this._start();try{return await this.startPromise}finally{this.startPromise=null}}async _start(){if(!!1||null===null)return this.disabled=!0,!1;try{let e=new null(Jsr,{eval:!0});return e.on("message",n=>{let r=this.pending.get(n.id);r&&(this.pending.delete(n.id),n.error?r.reject(new Error(n.error)):n.bytes&&typeof n.length=="number"?r.resolve(new Uint8Array(n.bytes,0,n.length)):r.reject(new Error("worker returned malformed message")))}),e.on("error",n=>{for(let[,r]of this.pending)r.reject(n);this.pending.clear(),this.disabled=!0,this.worker=null}),e.on("exit",n=>{for(let[,r]of this.pending)r.reject(new Error(`worker exited with code ${n}`));this.pending.clear(),this.worker=null}),e.unref(),this.worker=e,!0}catch{return this.disabled=!0,!1}}async serialize(e){if(!await this.ensureStarted())return null;let r=this.nextId++;return new Promise((o,i)=>{this.pending.set(r,{resolve:o,reject:i});try{this.worker.postMessage({id:r,op:"serialize",payload:e})}catch(s){this.pending.delete(r),i(s)}})}async terminate(){this.worker&&(await this.worker.terminate(),this.worker=null);for(let[,e]of this.pending)e.reject(new Error("worker terminated"));this.pending.clear()}},e3e=null;Xsr=64*1024,Qsr=2048});function ear(t,e){let[n]=bf(t);if(n!=="-"&&!e)throw new Error("Pulling a public prompt by owner/name is disabled by default because prompts may contain untrusted serialized LangChain objects. If you trust this prompt, set `dangerouslyPullPublicPrompt: true` to acknowledge the risk.")}function qHt(t){return typeof t=="string"&&t.length>0&&!t.includes("Z")&&!t.includes("+")&&!t.includes("-",10)?t+"Z":t}function Yz(t){return{...t,start_time:qHt(t.start_time),end_time:qHt(t.end_time)}}function KHt(t,e,n){if(n)return t;let r=hhe(),o=e??j6e(),i=t.extra??{},s=i.metadata;return t.extra={...i,runtime:{...r,...i?.runtime},metadata:{...o,...o.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??o.revision_id}:{},...s}},t}async function rar(t){let e=[];for await(let n of t)e.push(n);return e}function Whe(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}function GHt(t){return typeof t=="number"?Number(t.toFixed(4)):t}function iar(t,e){if(!t)return;let n=c=>c.split(".").map(u=>parseInt(u,10)),[r,o,i]=n(t),[s,a,l]=n(e);if(isNaN(r)||isNaN(o)||isNaN(i)||isNaN(s)||isNaN(a)||isNaN(l)){console.warn(`[LANGSMITH]: Could not parse backend version ${JSON.stringify(t)} for compatibility check.`);return}(r<s||r===s&&o<a||r===s&&o===a&&i<l)&&console.warn(`[LANGSMITH]: Backend version ${JSON.stringify(t)} is older than the minimum version required by this SDK (${JSON.stringify(e)}). Some features may not work as expected. See https://docs.langchain.com/langsmith/smithdb-sdk-migration`)}function QHt(t,e){new Headers({[t]:e})}function ZHt(t){for(let[e,n]of Object.entries(t??{}))QHt(e,n)}function YHt(t){if(!t)return{};let e=t instanceof Headers?[...t.entries()]:Array.isArray(t)?t.map(([o,i])=>[o,i]):Object.entries(t),n={},r=new Map;for(let[o,i]of e){QHt(o,i);let s=o.toLowerCase(),a=r.get(s);a===void 0?(r.set(s,o),n[o]=i):n[a]=i}return n}function car(t,e,n){let r={...t},o=new Map(Object.keys(r).map(i=>[i.toLowerCase(),i]));for(let[i,s]of Object.entries(e)){let a=i.toLowerCase();r[o.get(a)??i]=s}for(let i of Object.keys(r))n.has(i.toLowerCase())&&delete r[i];return r}function JHt(t){return"dataset_id"in t||"dataset_name"in t}var tar,nar,oar,sar,XHt,aar,lar,n3e,xA,$6e=b(()=>{FY();v4t();G6e();O4t();N4t();$x();mhe();wHt();jY();the();_Ht();kHt();jhe();R6e();BY();b6e();$Ht();jHt();VHt();tar=t=>{let e=t?.toString()??Os("TRACING_SAMPLING_RATE");if(e===void 0)return;let n=parseFloat(e);if(n<0||n>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${n}`);return n},nar=t=>{let n=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return n==="localhost"||n==="127.0.0.1"||n==="::1"};oar=async t=>{if(t?.status===429){let e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(n=>setTimeout(n,e)),!0}return!1};sar=24*1024*1024,XHt=1024*1024*1024,aar=1e4,lar=100;n3e=class{constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??XHt}peek(){return this.items[0]}push(e){let n,r=new Promise(i=>{n=i}),o=UHt(e.item).size;return this.sizeBytes+o>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${o} bytes.`),n(),r):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,workspaceId:e.workspaceId,itemPromiseResolve:n,itemPromise:r,size:o}),this.sizeBytes+=o,r)}pop({upToSizeBytes:e,upToSize:n}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");let r=[],o=0;for(;o+(this.peek()?.size??0)<e&&this.items.length>0&&r.length<n;){let i=this.items.shift();i&&(r.push(i),o+=i.size,this.sizeBytes-=i.size)}if(r.length===0&&this.items.length>0){let i=this.items.shift();r.push(i),o+=i.size,this.sizeBytes-=i.size}return[r.map(i=>({action:i.action,item:i.payload,otelContext:i.otelContext,apiKey:i.apiKey,apiUrl:i.apiUrl,workspaceId:i.workspaceId,size:i.size})),()=>r.forEach(i=>i.itemPromiseResolve())]}},xA=class t{get tracingMode(){return this._tracingMode}get _fetch(){let e=this.fetchImplementation||Wzt(this.debug);return async(n,r)=>{let o,i=this.getProfileManagedAuthorizationHeader(r);return this.apiKey!==void 0?o={name:"x-api-key",value:`${this.apiKey}`}:this.hasExplicitAuthHeader(r,i)||(o=await this.profileAuth?.getAuthHeader(e,r?.signal)),e(n,this.applyCurrentAuthHeaders(r,o,i))}}getProfileManagedAuthorizationHeader(e){if(!e?.headers||!this.profileAuth)return;let n=new Headers(e.headers).get("Authorization");if(uv(n))return this.profileAuth.isProfileAuthorizationHeader(n??"")?n??void 0:void 0}isProfileManagedAuthorizationHeader(e,n){return e===n||this.profileAuth?.isProfileAuthorizationHeader(e)===!0}hasExplicitAuthHeader(e,n){if(!e?.headers)return!1;let r=new Headers(e.headers);if(uv(r.get("x-api-key")))return!0;let o=r.get("Authorization");return uv(o)?!this.isProfileManagedAuthorizationHeader(o??"",n):!1}applyCurrentAuthHeaders(e,n,r){if(!n)return e;let o=d=>{if(this.apiKey!==void 0&&n.name==="x-api-key")return d.delete("Authorization"),d.has("x-api-key")||d.set("x-api-key",n.value),d;if(n.name==="Authorization"){if(uv(d.get("x-api-key")))return d;let p=d.get("Authorization");return uv(p)&&!this.isProfileManagedAuthorizationHeader(p??"",r)||d.set("Authorization",n.value),d}let f=d.get("Authorization");return uv(f)&&!this.isProfileManagedAuthorizationHeader(f??"",r)||(uv(f)&&d.delete("Authorization"),d.has("x-api-key")||d.set("x-api-key",n.value)),d};if(!e)return{headers:{[n.name]:n.value}};if(e.headers instanceof Headers)return{...e,headers:o(new Headers(e.headers))};if(Array.isArray(e.headers))return{...e,headers:o(new Headers(e.headers))};let i={...e.headers??{}},s=d=>Object.keys(i).find(f=>f.toLowerCase()===d),a=d=>{let f=s(d);return f?i[f]:void 0},l=uv(a("x-api-key")),c=a("authorization"),u=uv(c)&&!this.isProfileManagedAuthorizationHeader(c??"",r);if(this.apiKey!==void 0&&n.name==="x-api-key"){let d=s("authorization");return d&&delete i[d],l||(i["x-api-key"]=n.value),{...e,headers:i}}if(n.name==="Authorization"){if(!l&&!u){let d=s("authorization");d&&d!=="Authorization"&&delete i[d],i.Authorization=n.value}return{...e,headers:i}}if(!u){let d=s("authorization");d&&delete i[d],l||(i["x-api-key"]=n.value)}return{...e,headers:i}}_trackDrain(e){this._pendingDrains.add(e),e.finally(()=>{this._pendingDrains.delete(e)})}async _serializeBody(e,n){if(this.manualFlushMode)return _f(e,n);if(!WHt(e))return _f(e,n);if(this._serializeWorker===void 0&&(this._serializeWorker=HHt()),this._serializeWorker===null)return _f(e,n);try{let r=await this._serializeWorker.serialize(e);return r===null?(this._serializeWorker=null,_f(e,n)):r}catch{return _f(e,n)}}constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"anonymizer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitTracedRuntimeInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_fetchOptionsHeaders",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_openAPIClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_openAPIClientSignature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:Ou("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_stainlessVersionsChecked",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_serializeWorker",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pendingDrains",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tracingMode",{enumerable:!0,configurable:!0,writable:!0,value:"langsmith"}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_promptCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"profileAuth",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:Os("DISABLE_MULTIPART_STREAMING")==="true"}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:Os("DISABLE_RUN_COMPRESSION")==="true"}),Object.defineProperty(this,"failedTracesDir",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"failedTracesMaxBytes",{enumerable:!0,configurable:!0,writable:!0,value:100*1024*1024}),Object.defineProperty(this,"_customHeaders",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:Ou("LANGSMITH_DEBUG")==="true"});let n=t.getDefaultClientConfig();this.tracingSampleRate=tar(e.tracingSamplingRate),this.apiUrl=Whe(e.apiUrl??n.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1));let r=Whe(e.apiKey??n.apiKey);if(this.apiKey=uv(r)?r:void 0,this.profileAuth=this.apiKey!==void 0?void 0:n.profileAuth,this.webUrl=Whe(e.webUrl??n.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=Whe(e.workspaceId??n.workspaceId),this.timeout_ms=e.timeout_ms??9e4,this.caller=new VY({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.failedTracesDir=Os("FAILED_TRACES_DIR")||void 0;let o=Os("FAILED_TRACES_MAX_MB");if(o){let l=parseInt(o,10);Number.isFinite(l)&&l>0&&(this.failedTracesMaxBytes=l*1024*1024)}let i=e.maxIngestMemoryBytes??XHt;this.batchIngestCaller=new VY({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:i,...e.callerOptions??{},onFailedResponseHook:oar,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??n.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??n.hideOutputs,this.hideMetadata=e.hideMetadata??e.anonymizer??n.hideMetadata,this.anonymizer=e.anonymizer,this.omitTracedRuntimeInfo=e.omitTracedRuntimeInfo??!1,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new n3e(i),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit;let{headers:s,...a}=e.fetchOptions||{};this.fetchOptions=a,this._fetchOptionsHeaders=YHt(s),ZHt(e.headers),this._customHeaders=e.headers??{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,this._tracingMode=ghe(e.tracingMode),this._tracingMode==="otel"&&(this.langSmithToOTELTranslator=new vhe),this.cachedLSEnvVarsForMetadata=j6e(),e.cache!==void 0&&e.disablePromptCache&&Nu("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value."),e.cache!==void 0?(Nu("The 'cache' parameter is deprecated and will be removed in a future version. Use 'configureGlobalPromptCache()' to configure the global cache, or 'disablePromptCache: true' to disable caching for this client."),e.cache===!1?this._promptCache=void 0:e.cache===!0?this._promptCache=fhe:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=fhe)}static getDefaultClientConfig(){let e=RHt(),n=Os("API_KEY"),r=Os("ENDPOINT"),o=Os("WORKSPACE_ID"),i=uv(n),s=r??e.apiUrl??Bhe,a=o??e.workspaceId,l=Os("HIDE_INPUTS")==="true",c=Os("HIDE_OUTPUTS")==="true",u=Os("HIDE_METADATA")==="true";return{apiUrl:s,apiKey:n,webUrl:void 0,hideInputs:l,hideOutputs:c,hideMetadata:u,workspaceId:a,oauthAccessToken:i?void 0:e.oauthAccessToken,oauthRefreshToken:i?void 0:e.oauthRefreshToken,profileAuth:i?void 0:e.profileAuth}}getHostUrl(){return this.webUrl?this.webUrl:nar(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("aws")?(this.webUrl="https://aws.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("apac")?(this.webUrl="https://apac.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get _sdkControlledHeaders(){let e=new Set;if(this.apiKey!==void 0)e.add("x-api-key");else{let n=this.profileAuth?.currentAuthHeader();n&&e.add(n.name.toLowerCase())}return this.workspaceId&&e.add("x-tenant-id"),e}get _callerHeaders(){return car(YHt(this._customHeaders),this._fetchOptionsHeaders,this._sdkControlledHeaders)}get _mergedHeaders(){let e={"User-Agent":`langsmith-js/${phe}`,...this._callerHeaders};if(this.apiKey!==void 0)e["x-api-key"]=`${this.apiKey}`;else{let n=this.profileAuth?.currentAuthHeader();n&&(e[n.name]=n.value)}return this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}get _openAPIAuth(){let e={...this._callerHeaders},n=Object.keys(e).find(o=>o.toLowerCase()==="x-api-key"),r=this.apiKey;return r===void 0&&n!==void 0&&(r=e[n]??void 0,delete e[n]),r===void 0&&this.workspaceId===void 0&&(e["X-API-Key"]=null),{apiKey:r,defaultHeaders:Object.keys(e).length>0?e:void 0}}get headers(){return this._customHeaders}set headers(e){ZHt(e),this._customHeaders=e??{}}_getOpenAPIBaseUrl(){let e=this.apiUrl.replace(/\/$/,"");for(let n of["/api/v1","/api"])if(e.endsWith(n))return e.slice(0,-n.length);return e}get openAPIClient(){let e=this._openAPIAuth,n=JSON.stringify([e.apiKey,e.defaultHeaders]);return(this._openAPIClient===void 0||this._openAPIClientSignature!==n)&&(this._openAPIClientSignature=n,this._openAPIClient=this._newOpenAPIClient(e)),this._openAPIClient}_newOpenAPIClient(e=this._openAPIAuth){let{method:n,body:r,signal:o,...i}=this.fetchOptions;return new ri({apiKey:e.apiKey,tenantID:this.workspaceId,baseURL:this._getOpenAPIBaseUrl(),timeout:this.timeout_ms,fetch:this._fetch,fetchOptions:i,defaultHeaders:e.defaultHeaders})}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}get evaluators(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.onlineEvaluators}get runs(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.runs}get sandboxes(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.sandboxes}get datasets(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.datasets}get annotationQueues(){return this._checkStainlessVersion("0.16.14"),this.openAPIClient.annotationQueues}get threads(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.threads}get traces(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.traces}get public(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.public}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async processMetadata(e){return this.hideMetadata===!1?e:this.hideMetadata===!0?{}:typeof this.hideMetadata=="function"?this.hideMetadata(e):e}async processError(e){if(this.anonymizer==null)return e;let n=await this.anonymizer({error:e});return typeof n?.error=="string"?n.error:e}_filterNewTokenEvents(e){return!e||e.length===0?e:e.map(n=>{if(n.name==="new_token"){let{kwargs:r,...o}=n;return o}return n})}async prepareRunCreateOrUpdateInputs(e){let n={...e};return n.inputs!==void 0&&(n.inputs=await this.processInputs(n.inputs)),n.outputs!==void 0&&(n.outputs=await this.processOutputs(n.outputs)),n.error!==void 0&&(n.error=await this.processError(n.error)),n.extra!=null&&"metadata"in n.extra&&(n.extra={...n.extra,metadata:await this.processMetadata(n.extra.metadata)}),n.events!==void 0&&(n.events=this._filterNewTokenEvents(n.events)),n}async _getResponse(e,n){let r=n?.toString()??"",o=`${this.apiUrl}${e}?${r}`;return await this.caller.call(async()=>{let s=await this._fetch(o,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(s,`fetch ${e}`),s})}async _get(e,n){return(await this._getResponse(e,n)).json()}async*_getPaginated(e,n=new URLSearchParams,r){let o=Number(n.get("offset"))||0,i=Number(n.get("limit"))||100;for(;;){n.set("offset",String(o)),n.set("limit",String(i));let s=`${this.apiUrl}${e}?${n}`,a=await this.caller.call(async()=>{let c=await this._fetch(s,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(c,`fetch ${e}`),c}),l=r?r(await a.json()):await a.json();if(l.length===0||(yield l,l.length<i))break;o+=l.length}}async*_getCursorPaginatedList(e,n=null,r="POST",o="runs"){let i=n?{...n}:{};for(;;){let s=JSON.stringify(i),l=await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}${e}`,{method:r,headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await Yt(u,`fetch ${e}`),u})).json();if(!l||!l[o])break;yield l[o];let c=l.cursors;if(!c||!c.next)break;i.cursor=c.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,n=!1){if(this.tracingSampleRate===void 0)return e;if(n){let r=[];for(let o of e)this.filteredPostUuids.has(o.trace_id)?o.id===o.trace_id&&this.filteredPostUuids.delete(o.trace_id):r.push(o);return r}else{let r=[];for(let o of e){let i=o.trace_id??o.id;this.filteredPostUuids.has(i)||(o.id===i?this._shouldSample()?r.push(o):this.filteredPostUuids.add(i):r.push(o))}return r}}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e?.batch_ingest_config?.size_limit_bytes??sar}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??lar}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:n}){let r=[];for(;this.autoBatchQueue.items.length>0;){let[o,i]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:n});if(!o.length){i();break}let s=o.reduce((c,u)=>{let d=u.apiUrl??this.apiUrl,f=u.apiKey??this.apiKey,p=u.workspaceId??this.workspaceId,h=u.apiKey===this.apiKey&&u.apiUrl===this.apiUrl&&u.workspaceId===this.workspaceId?"default":`${d}|${f}|${p??""}`;return c[h]||(c[h]=[]),c[h].push(u),c},{}),a=[];for(let[c,u]of Object.entries(s)){let d=c==="default",f=d?[]:c.split("|"),p=f[2],m=this._processBatch(u,{apiUrl:d?void 0:f[0],apiKey:d?void 0:f[1],workspaceId:d||!p?void 0:p});a.push(m)}let l=Promise.all(a).finally(i);r.push(l)}return Promise.all(r)}static async _writeTraceToFallbackDir(e,n,r,o,i){try{let s=typeof n=="string"?Buffer.from(n,"utf8"):Buffer.from(n),a=JSON.stringify({version:1,endpoint:o,headers:r,body_base64:s.toString("base64")}),l=`trace_${Date.now()}_${AL().slice(0,8)}.json`,c=vb.join(e,l);if(t._fallbackDirsCreated.has(e)||(await che(e),t._fallbackDirsCreated.add(e)),i!==void 0&&i>0)try{let d=(await l4t(e)).filter(p=>p.startsWith("trace_")&&p.endsWith(".json")),f=0;for(let p of d){let{size:m}=await c4t(vb.join(e,p));f+=m}if(f>=i){console.warn(`Could not write trace to fallback dir ${e} as it's already over size limit (${f} bytes >= ${i} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`);return}}catch{}await $z(c,a),console.warn(`LangSmith trace upload failed; data saved to ${c} for later replay.`)}catch(s){console.error(`LangSmith tracing error: could not write trace to fallback dir ${e}:`,s)}}async _processBatch(e,n){if(!e.length)return;let r=e.reduce((o,i)=>o+(i.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0){for(let o of e)o.item=await this._maskRunMetadata(o.item);this._sendBatchToOTELTranslator(e)}else{let o={runCreates:e.filter(a=>a.action==="create").map(a=>a.item),runUpdates:e.filter(a=>a.action==="update").map(a=>a.item)},i=await this._ensureServerInfo();if(!this._multipartDisabled&&(i?.batch_ingest_config?.use_multipart_endpoint??!0)){let a=!this._runCompressionDisabled&&i?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(o,{...n,useGzip:a,sizeBytes:r})}catch(l){if(Uhe(l))this._multipartDisabled=!0,await this.batchIngestRuns(o,{...n,sizeBytes:r});else throw l}}else await this.batchIngestRuns(o,{...n,sizeBytes:r})}}catch(o){console.error("Error exporting batch:",o)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){let n=new Map,r=[];for(let o of e)o.item.id&&o.otelContext&&(n.set(o.item.id,o.otelContext),o.action==="create"?r.push({operation:"post",id:o.item.id,trace_id:o.item.trace_id??o.item.id,run:o.item}):r.push({operation:"patch",id:o.item.id,trace_id:o.item.trace_id??o.item.id,run:o.item}));this.langSmithToOTELTranslator.exportBatch(r,n)}}async _maskRunMetadata(e){return e.extra?.metadata==null?e:{...e,extra:{...e.extra,metadata:await this.processMetadata(e.extra.metadata)}}}async _mergeRuntimeEnvAndMaskMetadata(e){let n=KHt(e,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);return this.omitTracedRuntimeInfo?n:this._maskRunMetadata(n)}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=KHt(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let n=this.autoBatchQueue.push(e);if(this.manualFlushMode)return n;let r=await this._getBatchSizeLimitBytes(),o=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>r||this.autoBatchQueue.items.length>o)&&this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:o})),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:o}))},this.autoBatchAggregationDelayMs)),n}async _getServerInfo(){let n=await(await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(aar),...this.fetchOptions});return await Yt(r,"get server info"),r})).json();return this.debug&&console.log(`
=== LangSmith Server Configuration ===
`+JSON.stringify(n,null,2)+`
`),n}_checkStainlessVersion(e){this._stainlessVersionsChecked.has(e)||(this._stainlessVersionsChecked.add(e),this._ensureServerInfo().then(n=>{iar(n?.version,e)}).catch(()=>{}))}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _supportsSDBQuery(){return(await this._ensureServerInfo()).instance_flags?.sdb_query_enabled===!0}async _checkFeedbackSessionId(){let e="https://docs.langchain.com/langsmith/smithdb-sdk-migration#feedback-create",n=await this._ensureServerInfo();if(bHt(n.instance_flags)===ZY.SMITHDB_ONLY)throw new Error(`sessionId must be provided when creating feedback for a run: this deployment cannot locate the run without it. See ${e}`);Nu(`Creating feedback for a run without sessionId is deprecated and will stop working in a future release. See ${e}`)}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes(),n=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:n})}_cloneCurrentOTELContext(){let e=yhe(),n=g4t();if(this.langSmithToOTELTranslator!==void 0){let r=e.getActiveSpan();if(r)return e.setSpan(n.active(),r)}}async createRun(e,n){if(!this._filterForSampling([e]).length)return;let r={...this._mergedHeaders,"Content-Type":"application/json"},o=e.project_name;delete e.project_name;let i=await this.prepareRunCreateOrUpdateInputs({session_name:o,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let l=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:i,otelContext:l,apiKey:n?.apiKey,apiUrl:n?.apiUrl,workspaceId:n?.workspaceId}).catch(console.error);return}let s=await this._mergeRuntimeEnvAndMaskMetadata(i);n?.apiKey!==void 0&&(r["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(r["x-tenant-id"]=n.workspaceId);let a=_f(s,`Creating run with id: ${s.id}`);await this.caller.call(async()=>{let l=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await Yt(l,"create run",!0),l})}async batchIngestRuns({runCreates:e,runUpdates:n},r){if(e===void 0&&n===void 0)return;let o=await Promise.all(e?.map(l=>this.prepareRunCreateOrUpdateInputs(l))??[]),i=await Promise.all(n?.map(l=>this.prepareRunCreateOrUpdateInputs(l))??[]);if(o.length>0&&i.length>0){let l=o.reduce((u,d)=>(d.id&&(u[d.id]=d),u),{}),c=[];for(let u of i)u.id!==void 0&&l[u.id]?l[u.id]={...l[u.id],...u}:c.push(u);o=Object.values(l),i=c}let s={post:o,patch:i};if(!s.post.length&&!s.patch.length)return;let a={post:[],patch:[]};for(let l of["post","patch"]){let c=l,u=s[c].reverse(),d=u.pop();for(;d!==void 0;)a[c].push(d),d=u.pop()}if(a.post.length>0||a.patch.length>0){let l=a.post.map(c=>c.id).concat(a.patch.map(c=>c.id)).join(",");await this._postBatchIngestRuns(await this._serializeBody(a,`Ingesting runs with ids: ${l}`),r)}}async _postBatchIngestRuns(e,n){let r={...this._mergedHeaders,"Content-Type":"application/json",Accept:"application/json"};n?.apiKey!==void 0&&(r["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(r["x-tenant-id"]=n.workspaceId),await this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{let o=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await Yt(o,"batch create run",!0),o})}async multipartIngestRuns({runCreates:e,runUpdates:n},r){if(e===void 0&&n===void 0)return;let o={},i=[];for(let d of e??[]){let f=await this.prepareRunCreateOrUpdateInputs(d);f.id!==void 0&&f.attachments!==void 0&&(o[f.id]=f.attachments),delete f.attachments,i.push(f)}let s=[];for(let d of n??[])s.push(await this.prepareRunCreateOrUpdateInputs(d));if(i.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(s.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(i.length>0&&s.length>0){let d=i.reduce((p,m)=>(m.id&&(p[m.id]=m),p),{}),f=[];for(let p of s)p.id!==void 0&&d[p.id]?d[p.id]={...d[p.id],...p}:f.push(p);i=Object.values(d),s=f}if(i.length===0&&s.length===0)return;let c=[],u=[];for(let[d,f]of[["post",i],["patch",s]])for(let p of f){let{inputs:m,outputs:h,events:g,extra:v,error:y,serialized:w,attachments:_,...S}=p,I={inputs:m,outputs:h,events:g,extra:v,error:y,serialized:w},C=await this._serializeBody(S,`Serializing for multipart ingestion of run with id: ${S.id}`);u.push({name:`${d}.${S.id}`,payload:new Blob([C],{type:`application/json; length=${C.length}`})});for(let[k,T]of Object.entries(I)){if(T===void 0)continue;let P=await this._serializeBody(T,`Serializing ${k} for multipart ingestion of run with id: ${S.id}`);u.push({name:`${d}.${S.id}.${k}`,payload:new Blob([P],{type:`application/json; length=${P.length}`})})}if(S.id!==void 0){let k=o[S.id];if(k){delete o[S.id];for(let[T,P]of Object.entries(k)){let E,O;if(Array.isArray(P)?[E,O]=P:(E=P.mimeType,O=P.data),T.includes(".")){console.warn(`Skipping attachment '${T}' for run ${S.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}u.push({name:`attachment.${S.id}.${T}`,payload:new Blob([O],{type:`${E}; length=${O.byteLength}`})})}}}c.push(`trace=${S.trace_id},id=${S.id}`)}await this._sendMultipartRequest(u,c.join("; "),r)}async _createNodeFetchBody(e,n){let r=[];for(let s of e)r.push(new Blob([`--${n}\r
`])),r.push(new Blob([`Content-Disposition: form-data; name="${s.name}"\r
`,`Content-Type: ${s.payload.type}\r
\r
`])),r.push(s.payload),r.push(new Blob([`\r
`]));return r.push(new Blob([`--${n}--\r
`])),await new Blob(r).arrayBuffer()}async _createMultipartStream(e,n){let r=new TextEncoder;return new ReadableStream({async start(i){let s=async a=>{typeof a=="string"?i.enqueue(r.encode(a)):i.enqueue(a)};for(let a of e){await s(`--${n}\r
`),await s(`Content-Disposition: form-data; name="${a.name}"\r
`),await s(`Content-Type: ${a.payload.type}\r
\r
`);let c=a.payload.stream().getReader();try{let u;for(;!(u=await c.read()).done;)i.enqueue(u.value)}finally{c.releaseLock()}await s(`\r
`)}await s(`--${n}--\r
`),i.close()}})}async _sendMultipartRequest(e,n,r){let o="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),i=()=>this._createNodeFetchBody(e,o),s=()=>this._createMultipartStream(e,o),a=async l=>this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let c=await l(),u={...this._mergedHeaders,"Content-Type":`multipart/form-data; boundary=${o}`};r?.apiKey!==void 0&&(u["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(u["x-tenant-id"]=r.workspaceId);let d=c;r?.useGzip&&typeof c=="object"&&"pipeThrough"in c&&(d=c.pipeThrough(new CompressionStream("gzip")),u["Content-Encoding"]="gzip");let f=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:u,body:d,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(f,"Failed to send multipart request",!0),f});try{let l,c=!1;Hzt()&&!this.multipartStreamingDisabled&&HY()!=="bun"?(c=!0,l=await a(s)):l=await a(i),(!this.multipartStreamingDisabled||c)&&l.status===422&&(r?.apiUrl??this.apiUrl)!==Bhe&&(console.warn(`Streaming multipart upload to ${r?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${n}".`),this.multipartStreamingDisabled=!0,l=await a(i))}catch(l){if(Uhe(l))throw l;if(console.warn(`${l.message.trim()}
Context: ${n}`),this.failedTracesDir){let c=await this._createNodeFetchBody(e,o).catch(()=>null);c&&await t._writeTraceToFallbackDir(this.failedTracesDir,c,{"Content-Type":`multipart/form-data; boundary=${o}`},"runs/multipart",this.failedTracesMaxBytes)}}}async updateRun(e,n,r){_r(e),n.inputs&&(n.inputs=await this.processInputs(n.inputs)),n.outputs&&(n.outputs=await this.processOutputs(n.outputs)),n.error&&(n.error=await this.processError(n.error)),n.extra!=null&&"metadata"in n.extra&&(n.extra={...n.extra,metadata:await this.processMetadata(n.extra.metadata)}),n.events&&(n.events=this._filterNewTokenEvents(n.events));let o={...n,id:e};if(!this._filterForSampling([o],!0).length)return;if(this.autoBatchTracing&&o.trace_id!==void 0&&o.dotted_order!==void 0){let a=this._cloneCurrentOTELContext();if(n.end_time!==void 0&&o.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:o,otelContext:a,apiKey:r?.apiKey,apiUrl:r?.apiUrl,workspaceId:r?.workspaceId}).catch(console.error);return}else this.processRunOperation({action:"update",item:o,otelContext:a,apiKey:r?.apiKey,apiUrl:r?.apiUrl,workspaceId:r?.workspaceId}).catch(console.error);return}let i={...this._mergedHeaders,"Content-Type":"application/json"};r?.apiKey!==void 0&&(i["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(i["x-tenant-id"]=r.workspaceId);let s=_f(n,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let a=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await Yt(a,"update run",!0),a})}async readRun(e,{loadChildRuns:n}={loadChildRuns:!1}){return Nu("readRun() is deprecated and will be removed after Jan 31, 2027. Use client.runs.retrieve() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#runs-retrieve for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_READ_RUN"}),this._readRun(e,{loadChildRuns:n})}async _readRun(e,{loadChildRuns:n}={loadChildRuns:!1}){_r(e);let r=Yz(await this._get(`/runs/${e}`));return n&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:n,projectOpts:r}){if(Nu("getRunUrl() is deprecated and will be removed after Jan 31, 2027. Use client.runs.getURL() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#runs-get-url for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_GET_RUN_URL"}),n!==void 0){let o;n.session_id?o=n.session_id:r?.projectName?o=(await this.readProject({projectName:r?.projectName})).id:r?.projectId?o=r?.projectId:o=(await this.readProject({projectName:Os("PROJECT")||"default"})).id;let i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${o}/r/${n.id}?poll=true`}else if(e!==void 0){let o=await this._readRun(e);if(!o.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${o.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){let n=await rar(this._listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),r={},o={};n.sort((i,s)=>(i?.dotted_order??"").localeCompare(s?.dotted_order??""));for(let i of n){if(i.parent_run_id===null||i.parent_run_id===void 0)throw new Error(`Child run ${i.id} has no parent`);i.dotted_order?.startsWith(e.dotted_order??"")&&i.id!==e.id&&(i.parent_run_id in r||(r[i.parent_run_id]=[]),r[i.parent_run_id].push(i),o[i.id]=i)}e.child_runs=r[e.id]||[];for(let i in r)i!==e.id&&(o[i].child_runs=r[i]);return e}async*listRuns(e){Nu("listRuns() is deprecated and will be removed after Jan 31, 2027. Use client.runs.query() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#runs-query for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_LIST_RUNS"}),yield*this._listRuns(e)}async*_listRuns(e){let{projectId:n,projectName:r,parentRunId:o,traceId:i,referenceExampleId:s,startTime:a,executionOrder:l,isRoot:c,runType:u,error:d,id:f,query:p,filter:m,traceFilter:h,treeFilter:g,limit:v,select:y,order:w}=e,_=[];if(n&&(_=Array.isArray(n)?n:[n]),r){let k=Array.isArray(r)?r:[r],T=await Promise.all(k.map(P=>this.readProject({projectName:P}).then(E=>E.id)));_.push(...T)}let S=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],I={session:_.length?_:null,run_type:u,reference_example:s,query:p,filter:m,trace_filter:h,tree_filter:g,execution_order:l,parent_run:o,start_time:a?a.toISOString():null,error:d,id:f,limit:v,trace:i,select:y||S,is_root:c,order:w};I.select.includes("child_run_ids")&&Nu("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let C=0;for await(let k of this._getCursorPaginatedList("/runs/query",I)){let T=k.map(Yz);if(v){if(C>=v)break;if(T.length+C>v){yield*T.slice(0,v-C);break}C+=T.length,yield*T}else yield*T}}async*listGroupRuns(e){let{projectId:n,projectName:r,groupBy:o,filter:i,startTime:s,endTime:a,limit:l,offset:c}=e,d={session_id:n||(await this.readProject({projectName:r})).id,group_by:o,filter:i,start_time:s?s.toISOString():null,end_time:a?a.toISOString():null,limit:Number(l)||100},f=Number(c)||0,p="/runs/group",m=`${this.apiUrl}${p}`;for(;;){let h={...d,offset:f},g=Object.fromEntries(Object.entries(h).filter(([I,C])=>C!==void 0)),v=JSON.stringify(g),w=await(await this.caller.call(async()=>{let I=await this._fetch(m,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:v});return await Yt(I,`Failed to fetch ${p}`),I})).json(),{groups:_,total:S}=w;if(_.length===0)break;for(let I of _)yield I;if(f+=_.length,f>=S)break}}async*readThread(e){Nu("readThread() is deprecated and will be removed after Jan 31, 2027. Use client.threads.listTraces() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#threads-list-traces for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_READ_THREAD"});let{threadId:n,projectId:r,projectName:o,isRoot:i=!0,limit:s,filter:a,order:l="asc"}=e;if(!r&&!o)throw new Error("threadId requires projectId or projectName");let c=`eq(thread_id, ${JSON.stringify(n)})`,u=a?`and(${c}, ${a})`:c;yield*this._listRuns({projectId:r??void 0,projectName:o??void 0,isRoot:i,limit:s,filter:u,order:l})}async listThreads(e){Nu("listThreads() is deprecated and will be removed after Jan 31, 2027. Use client.threads.query() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#threads-query for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_LIST_THREADS"});let{projectId:n,projectName:r,limit:o,offset:i=0,filter:s,startTime:a,isRoot:l=!0}=e;if(!n&&!r)throw new Error("Either projectId or projectName must be provided");if(n&&r)throw new Error("Provide exactly one of projectId or projectName");let c=n??(await this.readProject({projectName:r})).id,u=a??new Date(Date.now()-1*24*60*60*1e3),f={session:[c],is_root:l,limit:100,order:"desc",select:["id","name","status","start_time","end_time","thread_id","trace_id","run_type","error","tags","session_id","parent_run_id","total_tokens","total_cost","dotted_order","reference_example_id","feedback_stats","app_path","completion_cost","completion_tokens","prompt_cost","prompt_tokens","first_token_time"],start_time:u.toISOString()};s!=null&&(f.filter=s);let p=new Map;for await(let v of this._getCursorPaginatedList("/runs/query",f))for(let y of v){let w=Yz(y),_=w.thread_id;if(_){let S=p.get(_)??[];S.push(w),p.set(_,S)}}let m=[];for(let[v,y]of p.entries()){y.sort((C,k)=>{let T=C,P=k,E=T.start_time??"",O=P.start_time??"";if(E!==O)return E.localeCompare(O);let $=T.dotted_order??"",U=P.dotted_order??"";return $.localeCompare(U)});let _=[...y.map(C=>C.start_time).filter(Boolean)].sort(),S=_.length?_[0]:"",I=_.length?_[_.length-1]:"";m.push({thread_id:v,runs:y,count:y.length,filter:"",total_tokens:0,total_cost:null,min_start_time:S,max_start_time:I,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:"",last_outputs:"",last_error:null})}m.sort((v,y)=>{let w=v.max_start_time??"";return(y.max_start_time??"").localeCompare(w)});let h=i>0?m.slice(i):m;return o!==void 0?h.slice(0,o):h}async getRunStats({id:e,trace:n,parentRun:r,runType:o,projectNames:i,projectIds:s,referenceExampleIds:a,startTime:l,endTime:c,error:u,query:d,filter:f,traceFilter:p,treeFilter:m,isRoot:h,dataSourceType:g}){let v=s||[];if(i&&(v=[...s||[],...await Promise.all(i.map(C=>this.readProject({projectName:C}).then(k=>k.id)))]),v.length===0)throw new Error("At least one of projectNames or projectIds must be provided.");let w=Object.fromEntries(Object.entries({id:e,trace:n,parent_run:r,run_type:o,session:v,reference_example:a,start_time:l,end_time:c,error:u,query:d,filter:f,trace_filter:p,tree_filter:m,is_root:h,data_source_type:g}).filter(([C,k])=>k!==void 0)),_=JSON.stringify(w);return await(await this.caller.call(async()=>{let C=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:_});return await Yt(C,"get run stats"),C})).json()}async shareRun(e,{shareId:n}={}){Nu("shareRun() is deprecated and will be removed after Jan 31, 2027. Use client.runs.share.create() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#share-and-read-public-runs for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_SHARE_RUN"});let r={run_id:e,share_token:n||AL()};_r(e);let o=JSON.stringify(r),s=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await Yt(a,"share run"),a})).json();if(s===null||!("share_token"in s))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${s.share_token}/r`}async unshareRun(e){Nu("unshareRun() is deprecated and will be removed after Jan 31, 2027. Use client.runs.share.delete() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#share-and-read-public-runs for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_UNSHARE_RUN"}),_r(e),await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(n,"unshare run",!0),n})}async readRunSharedLink(e){Nu('readRunSharedLink() is deprecated and will be removed after Jan 31, 2027. Use client.runs.retrieve({ selects: ["SHARE_URL"] }) instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#share-and-read-public-runs for the migration guide.',{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_READ_RUN_SHARED_LINK"}),_r(e);let r=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(o,"read run shared link"),o})).json();if(!(r===null||!("share_token"in r)))return`${this.getHostUrl()}/public/${r.share_token}/r`}async listSharedRuns(e,{runIds:n}={}){Nu("listSharedRuns() is deprecated and will be removed after Jan 31, 2027. Use client.public.runs.query() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#share-and-read-public-runs for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_LIST_SHARED_RUNS"});let r=new URLSearchParams({share_token:e});if(n!==void 0)for(let s of n)r.append("id",s);return _r(e),(await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/public/${e}/runs${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(s,"list shared runs"),s})).json()).map(Yz)}async readDatasetSharedSchema(e,n){if(!e&&!n)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:n})).id),_r(e);let o=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(i,"read dataset shared schema"),i})).json();return o.url=`${this.getHostUrl()}/public/${o.share_token}/d`,o}async shareDataset(e,n){if(!e&&!n)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:n})).id);let r={dataset_id:e};_r(e);let o=JSON.stringify(r),s=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await Yt(a,"share dataset"),a})).json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async unshareDataset(e){_r(e),await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(n,"unshare dataset",!0),n})}async readSharedDataset(e){return _r(e),await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(o,"read shared dataset"),o})).json()}async listSharedExamples(e,n){let r={};n?.exampleIds&&(r.id=n.exampleIds);let o=new URLSearchParams;Object.entries(r).forEach(([a,l])=>{Array.isArray(l)?l.forEach(c=>o.append(a,c)):o.append(a,l)});let i=await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/public/${e}/examples?${o.toString()}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(a,"list shared examples"),a}),s=await i.json();if(!i.ok)throw"detail"in s?new Error(`Failed to list shared examples.
Status: ${i.status}
Message: ${Array.isArray(s.detail)?s.detail.join(`
`):"Unspecified error"}`):new Error(`Failed to list shared examples: ${i.status} ${i.statusText}`);return s.map(a=>({...a,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:n=null,metadata:r=null,upsert:o=!1,projectExtra:i=null,referenceDatasetId:s=null,numExamples:a=null,numRepetitions:l=null,evaluatorKeys:c=null,tagValueIds:u=null}){let d=o?"?upsert=true":"",f=`${this.apiUrl}/sessions${d}`,p=i||{};r&&(p.metadata=r);let m={name:e,extra:p,description:n};s!==null&&(m.reference_dataset_id=s),a!=null&&(m.num_examples=a),l!=null&&(m.num_repetitions=l),c!=null&&c.length>0&&(m.evaluator_keys=c),u!==null&&(m.tag_value_ids=u);let h=JSON.stringify(m);return await(await this.caller.call(async()=>{let y=await this._fetch(f,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:h});return await Yt(y,"create project"),y})).json()}async updateProject(e,{name:n=null,description:r=null,metadata:o=null,projectExtra:i=null,endTime:s=null}){let a=`${this.apiUrl}/sessions/${e}`,l=i;o&&(l={...l||{},metadata:o});let c=JSON.stringify({name:n,extra:l,description:r,end_time:s?new Date(s).toISOString():null});return await(await this.caller.call(async()=>{let f=await this._fetch(a,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await Yt(f,"update project"),f})).json()}async hasProject({projectId:e,projectName:n}){let r="/sessions",o=new URLSearchParams;if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)_r(e),r+=`/${e}`;else if(n!==void 0)o.append("name",n);else throw new Error("Must provide projectName or projectId");let i=await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${r}?${o}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(s,"has project"),s});try{let s=await i.json();return i.ok?Array.isArray(s)?s.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:n,includeStats:r}){let o="/sessions",i=new URLSearchParams;if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)_r(e),o+=`/${e}`;else if(n!==void 0)i.append("name",n);else throw new Error("Must provide projectName or projectId");r!==void 0&&i.append("include_stats",r.toString());let s=await this._get(o,i),a;if(Array.isArray(s)){if(s.length===0)throw new Error(`Project[id=${e}, name=${n}] not found`);a=s[0]}else a=s;return a}async getProjectUrl({projectId:e,projectName:n}){if(e===void 0&&n===void 0)throw new Error("Must provide either projectName or projectId");let r=await this.readProject({projectId:e,projectName:n}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:n}){if(e===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");let r=await this.readDataset({datasetId:e,datasetName:n}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/datasets/${r.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let n of this._getPaginated("/sessions",e))return this._tenantId=n[0].tenant_id,n[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:n,nameContains:r,referenceDatasetId:o,referenceDatasetName:i,includeStats:s,datasetVersion:a,referenceFree:l,metadata:c}={}){let u=new URLSearchParams;if(e!==void 0)for(let d of e)u.append("id",d);if(n!==void 0&&u.append("name",n),r!==void 0&&u.append("name_contains",r),o!==void 0)u.append("reference_dataset",o);else if(i!==void 0){let d=await this.readDataset({datasetName:i});u.append("reference_dataset",d.id)}s!==void 0&&u.append("include_stats",s.toString()),a!==void 0&&u.append("dataset_version",a),l!==void 0&&u.append("reference_free",l.toString()),c!==void 0&&u.append("metadata",JSON.stringify(c));for await(let d of this._getPaginated("/sessions",u))yield*d}async deleteProject({projectId:e,projectName:n}){let r;if(e===void 0&&n===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?r=(await this.readProject({projectName:n})).id:r=e,_r(r),await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(o,`delete session ${r} (${n})`,!0),o})}async uploadCsv({csvFile:e,fileName:n,inputKeys:r,outputKeys:o,description:i,dataType:s,name:a}){let l=`${this.apiUrl}/datasets/upload`,c=new FormData,u=new Blob([e],{type:"text/csv"});return c.append("file",u,n),r.forEach(p=>{c.append("input_keys",p)}),o.forEach(p=>{c.append("output_keys",p)}),i&&c.append("description",i),s&&c.append("data_type",s),a&&c.append("name",a),await(await this.caller.call(async()=>{let p=await this._fetch(l,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await Yt(p,"upload CSV"),p})).json()}async createDataset(e,{description:n,dataType:r,inputsSchema:o,outputsSchema:i,metadata:s,tagValueIds:a}={}){let l={name:e,description:n,extra:{source:"sdk",...s?{metadata:s}:{}}};r&&(l.data_type=r),o&&(l.inputs_schema_definition=o),i&&(l.outputs_schema_definition=i),a!==void 0&&(l.tag_value_ids=a);let c=JSON.stringify(l);return await(await this.caller.call(async()=>{let f=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await Yt(f,"create dataset"),f})).json()}async readDataset({datasetId:e,datasetName:n}){let r="/datasets",o=new URLSearchParams({limit:"1"});if(e&&n)throw new Error("Must provide either datasetName or datasetId, not both");if(e)_r(e),r+=`/${e}`;else if(n)o.append("name",n);else throw new Error("Must provide datasetName or datasetId");let i=await this._get(r,o),s;if(Array.isArray(i)){if(i.length===0)throw new Error(`Dataset[id=${e}, name=${n}] not found`);s=i[0]}else s=i;return s}async hasDataset({datasetId:e,datasetName:n}){try{return await this.readDataset({datasetId:e,datasetName:n}),!0}catch(r){if(r instanceof Error&&r.message.toLocaleLowerCase().includes("not found"))return!1;throw r}}async diffDatasetVersions({datasetId:e,datasetName:n,fromVersion:r,toVersion:o}){let i=e;if(i===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");if(i!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");i===void 0&&(i=(await this.readDataset({datasetName:n})).id);let s=new URLSearchParams({from_version:typeof r=="string"?r:r.toISOString(),to_version:typeof o=="string"?o:o.toISOString()});return await this._get(`/datasets/${i}/versions/diff`,s)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:n}){let r="/datasets";if(e===void 0)if(n!==void 0)e=(await this.readDataset({datasetName:n})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${r}/${e}/openai_ft`)).text()).trim().split(`
`).map(a=>JSON.parse(a))}async*listDatasets({limit:e=100,offset:n=0,datasetIds:r,datasetName:o,datasetNameContains:i,metadata:s}={}){let a="/datasets",l=new URLSearchParams({limit:e.toString(),offset:n.toString()});if(r!==void 0)for(let c of r)l.append("id",c);o!==void 0&&l.append("name",o),i!==void 0&&l.append("name_contains",i),s!==void 0&&l.append("metadata",JSON.stringify(s));for await(let c of this._getPaginated(a,l))yield*c}async updateDataset(e){let{datasetId:n,datasetName:r,...o}=e;if(!n&&!r)throw new Error("Must provide either datasetName or datasetId");let i=n??(await this.readDataset({datasetName:r})).id;_r(i);let s=JSON.stringify(o);return await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await Yt(l,"update dataset"),l})).json()}async updateDatasetTag(e){let{datasetId:n,datasetName:r,asOf:o,tag:i}=e;if(!n&&!r)throw new Error("Must provide either datasetName or datasetId");let s=n??(await this.readDataset({datasetName:r})).id;_r(s);let a=JSON.stringify({as_of:typeof o=="string"?o:o.toISOString(),tag:i});await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${s}/tags`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await Yt(l,"update dataset tags",!0),l})}async deleteDataset({datasetId:e,datasetName:n}){let r="/datasets",o=e;if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(n!==void 0&&(o=(await this.readDataset({datasetName:n})).id),o!==void 0)_r(o),r+=`/${o}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let i=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(i,`delete ${r}`,!0),i})}async createExample(e,n,r){if(JHt(e)&&(n!==void 0||r!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let o=n?r?.datasetId:e.dataset_id,i=n?r?.datasetName:e.dataset_name;if(o===void 0&&i===void 0)throw new Error("Must provide either datasetName or datasetId");if(o!==void 0&&i!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");o===void 0&&(o=(await this.readDataset({datasetName:i})).id);let s=(n?r?.createdAt:e.created_at)||new Date,a;JHt(e)?a=e:a={inputs:e,outputs:n,created_at:s?.toISOString(),id:r?.exampleId,metadata:r?.metadata,split:r?.split,source_run_id:r?.sourceRunId,use_source_run_io:r?.useSourceRunIO,use_source_run_attachments:r?.useSourceRunAttachments,attachments:r?.attachments};let l=await this._uploadExamplesMultipart(o,[a]);return await this.readExample(l.example_ids?.[0]??AL())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let y=e,w=y[0].dataset_id,_=y[0].dataset_name;if(w===void 0&&_===void 0)throw new Error("Must provide either datasetName or datasetId");if(w!==void 0&&_!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");w===void 0&&(w=(await this.readDataset({datasetName:_})).id);let S=await this._uploadExamplesMultipart(w,y);return await Promise.all(S.example_ids.map(C=>this.readExample(C)))}let{inputs:n,outputs:r,metadata:o,splits:i,sourceRunIds:s,useSourceRunIOs:a,useSourceRunAttachments:l,attachments:c,exampleIds:u,datasetId:d,datasetName:f}=e;if(n===void 0)throw new Error("Must provide inputs when using legacy parameters");let p=d,m=f;if(p===void 0&&m===void 0)throw new Error("Must provide either datasetName or datasetId");if(p!==void 0&&m!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");p===void 0&&(p=(await this.readDataset({datasetName:m})).id);let h=n.map((y,w)=>({dataset_id:p,inputs:y,outputs:r?.[w],metadata:o?.[w],split:i?.[w],id:u?.[w],attachments:c?.[w],source_run_id:s?.[w],use_source_run_io:a?.[w],use_source_run_attachments:l?.[w]})),g=await this._uploadExamplesMultipart(p,h);return await Promise.all(g.example_ids.map(y=>this.readExample(y)))}async createLLMExample(e,n,r){return this.createExample({input:e},{output:n},r)}async createChatExample(e,n,r){let o=e.map(s=>sVe(s)?aVe(s):s),i=sVe(n)?aVe(n):n;return this.createExample({input:o},{output:i},r)}async readExample(e){_r(e);let n=`/examples/${e}`,r=await this._get(n),{attachment_urls:o,...i}=r,s=i;return o&&(s.attachments=Object.entries(o).reduce((a,[l,c])=>(a[l.slice(11)]={presigned_url:c.presigned_url,mime_type:c.mime_type},a),{})),s}async*listExamples({datasetId:e,datasetName:n,exampleIds:r,asOf:o,splits:i,inlineS3Urls:s,metadata:a,limit:l,offset:c,filter:u,includeAttachments:d}={}){let f;if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)f=e;else if(n!==void 0)f=(await this.readDataset({datasetName:n})).id;else throw new Error("Must provide a datasetName or datasetId");let p=new URLSearchParams({dataset:f}),m=o?typeof o=="string"?o:o?.toISOString():void 0;m&&p.append("as_of",m);let h=s??!0;if(p.append("inline_s3_urls",h.toString()),r!==void 0)for(let v of r)p.append("id",v);if(i!==void 0)for(let v of i)p.append("splits",v);if(a!==void 0){let v=JSON.stringify(a);p.append("metadata",v)}l!==void 0&&p.append("limit",l.toString()),c!==void 0&&p.append("offset",c.toString()),u!==void 0&&p.append("filter",u),d===!0&&["attachment_urls","outputs","metadata"].forEach(v=>p.append("select",v));let g=0;for await(let v of this._getPaginated("/examples",p)){for(let y of v){let{attachment_urls:w,..._}=y,S=_;w&&(S.attachments=Object.entries(w).reduce((I,[C,k])=>(I[C.slice(11)]={presigned_url:k.presigned_url,mime_type:k.mime_type||void 0},I),{})),yield S,g++}if(l!==void 0&&g>=l)break}}async deleteExample(e){_r(e);let n=`/examples/${e}`;await this.caller.call(async()=>{let r=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(r,`delete ${n}`,!0),r})}async deleteExamples(e,n){if(e.forEach(r=>_r(r)),n?.hardDelete){let r=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}${r}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},body:JSON.stringify({example_ids:e,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(o,"hard delete examples",!0),o})}else{let r=new URLSearchParams;e.forEach(o=>r.append("example_ids",o)),await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/examples?${r.toString()}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(o,"delete examples",!0),o})}}async updateExample(e,n){let r;n?r=e:r=e.id,_r(r);let o;n?o={id:r,...n}:o=e;let i;return o.dataset_id!==void 0?i=o.dataset_id:i=(await this.readExample(r)).dataset_id,this._updateExamplesMultipart(i,[o])}async updateExamples(e){let n;return e[0].dataset_id===void 0?n=(await this.readExample(e[0].id)).dataset_id:n=e[0].dataset_id,this._updateExamplesMultipart(n,e)}async readDatasetVersion({datasetId:e,datasetName:n,asOf:r,tag:o}){let i;if(e?i=e:i=(await this.readDataset({datasetName:n})).id,_r(i),r&&o||!r&&!o)throw new Error("Exactly one of asOf and tag must be specified.");let s=new URLSearchParams;return r!==void 0&&s.append("as_of",typeof r=="string"?r:r.toISOString()),o!==void 0&&s.append("tag",o),await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${i}/version?${s.toString()}`,{method:"GET",headers:{...this._mergedHeaders},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(l,"read dataset version"),l})).json()}async listDatasetSplits({datasetId:e,datasetName:n,asOf:r}){let o;if(e===void 0&&n===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?o=(await this.readDataset({datasetName:n})).id:o=e,_r(o);let i=new URLSearchParams,s=r?typeof r=="string"?r:r?.toISOString():void 0;return s&&i.append("as_of",s),await this._get(`/datasets/${o}/splits`,i)}async updateDatasetSplits({datasetId:e,datasetName:n,splitName:r,exampleIds:o,remove:i=!1}){let s;if(e===void 0&&n===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?s=(await this.readDataset({datasetName:n})).id:s=e,_r(s);let a={split_name:r,examples:o.map(c=>(_r(c),c)),remove:i},l=JSON.stringify(a);await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${s}/splits`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await Yt(c,"update dataset splits",!0),c})}async createFeedback(e,n,r){let{runId:o=null,key:i,score:s,value:a,correction:l,comment:c,sourceInfo:u,feedbackSourceType:d="api",sourceRunId:f,feedbackId:p,feedbackConfig:m,projectId:h,comparativeExperimentId:g,sessionId:v,startTime:y,extendTraceRetention:w}=typeof e=="object"&&e!==null?e:{runId:e,key:n,...r};if(!o&&!h)throw new Error("One of runId or projectId must be provided");if(o&&h)throw new Error("Only one of runId or projectId can be provided");o&&v===void 0&&await this._checkFeedbackSessionId();let _={type:d??"api",metadata:u??{}};f!==void 0&&_?.metadata!==void 0&&!_.metadata.__run&&(_.metadata.__run={run_id:f}),_?.metadata!==void 0&&_.metadata.__run?.run_id!==void 0&&_r(_.metadata.__run.run_id);let S={id:p??Mz(),run_id:o,key:i,score:GHt(s),value:a,correction:l,comment:c,feedback_source:_,comparative_experiment_id:g,feedbackConfig:m,session_id:v??h,start_time:y,extend_trace_retention:w},I=JSON.stringify(S),C=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let k=await this._fetch(C,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:I});return await Yt(k,"create feedback",!0),k}),S}async updateFeedback(e,{score:n,value:r,correction:o,comment:i}){let s={};n!=null&&(s.score=GHt(n)),r!=null&&(s.value=r),o!=null&&(s.correction=o),i!=null&&(s.comment=i),_r(e);let a=JSON.stringify(s);await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await Yt(l,"update feedback",!0),l})}async readFeedback(e){_r(e);let n=`/feedback/${e}`;return await this._get(n)}async deleteFeedback(e){_r(e);let n=`/feedback/${e}`;await this.caller.call(async()=>{let r=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(r,`delete ${n}`,!0),r})}async*listFeedback({runIds:e,feedbackKeys:n,feedbackSourceTypes:r}={}){let o=new URLSearchParams;if(e)for(let i of e)_r(i),o.append("run",i);if(n)for(let i of n)o.append("key",i);if(r)for(let i of r)o.append("source",i);for await(let i of this._getPaginated("/feedback",o))yield*i}async createPresignedFeedbackToken(e,n,{expiration:r,feedbackConfig:o}={}){let i={run_id:e,feedback_key:n,feedback_config:o};r?typeof r=="string"?i.expires_at=r:(r?.hours||r?.minutes||r?.days)&&(i.expires_in=r):i.expires_in={hours:3};let s=JSON.stringify(i);return await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await Yt(l,"create presigned feedback token"),l})).json()}async createComparativeExperiment({name:e,experimentIds:n,referenceDatasetId:r,createdAt:o,description:i,metadata:s,id:a}){if(n.length===0)throw new Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:n[0]})).reference_dataset_id),!r==null)throw new Error("A reference dataset is required");let l={id:a,name:e,experiment_ids:n,reference_dataset_id:r,description:i,created_at:(o??new Date)?.toISOString(),extra:{}};s&&(l.extra.metadata=s);let c=JSON.stringify(l);return(await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await Yt(d,"create comparative experiment"),d})).json()}async*listPresignedFeedbackTokens(e){_r(e);let n=new URLSearchParams({run_id:e});for await(let r of this._getPaginated("/feedback/tokens",n))yield*r}_selectEvalResults(e){let n;return"results"in e?n=e.results:Array.isArray(e)?n=e:n=[e],n}async _logEvaluationFeedback(e,n,r,o){let i=this._selectEvalResults(e),s=[];for(let a of i){let l=r||{};a.evaluatorInfo&&(l={...a.evaluatorInfo,...l});let c=null;a.targetRunId?c=a.targetRunId:n&&(c=n.id),s.push(await this.createFeedback(c,a.key,{score:a.score,value:a.value,comment:a.comment,correction:a.correction,sourceInfo:l,sourceRunId:a.sourceRunId,feedbackConfig:a.feedbackConfig,feedbackSourceType:"model",sessionId:n?.session_id??o,startTime:n?.start_time}))}return[i,s]}async logEvaluationFeedback(e,n,r,o){if(e!=null&&typeof e=="object"&&"evaluatorResponse"in e){let[s]=await this._logEvaluationFeedback(e.evaluatorResponse,e.run,e.sourceInfo,e.projectId);return s}let[i]=await this._logEvaluationFeedback(e,n,r,o);return i}async createFeedbackConfig(e){let{feedbackKey:n,feedbackConfig:r,isLowerScoreBetter:o=!1}=e,i={feedback_key:n,feedback_config:r,is_lower_score_better:o};return(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await Yt(a,"create feedback config"),a})).json()}async*listFeedbackConfigs(e={}){let{feedbackKeys:n,nameContains:r,limit:o}=e,i=new URLSearchParams;n&&n.forEach(a=>{i.append("key",a)}),r&&i.append("name_contains",r),i.append("limit",(o!==void 0?Math.min(o,100):100).toString());let s=0;for await(let a of this._getPaginated("/feedback-configs",i))if(yield*a,s+=a.length,o!==void 0&&s>=o)break}async updateFeedbackConfig(e,n={}){let{feedbackConfig:r,isLowerScoreBetter:o}=n,i={feedback_key:e};return r!==void 0&&(i.feedback_config=r),o!==void 0&&(i.is_lower_score_better=o),(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await Yt(a,"update feedback config"),a})).json()}async deleteFeedbackConfig(e){let n=new URLSearchParams({feedback_key:e});await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/feedback-configs?${n}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(r,"delete feedback config",!0),r})}async*listAnnotationQueues(e={}){let{queueIds:n,name:r,nameContains:o,limit:i}=e,s=new URLSearchParams;n&&n.forEach((l,c)=>{_r(l,`queueIds[${c}]`),s.append("ids",l)}),r&&s.append("name",r),o&&s.append("name_contains",o),s.append("limit",(i!==void 0?Math.min(i,100):100).toString());let a=0;for await(let l of this._getPaginated("/annotation-queues",s))if(yield*l,a++,i!==void 0&&a>=i)break}async createAnnotationQueue(e){let{name:n,description:r,queueId:o,rubricInstructions:i,rubricItems:s}=e,a={name:n,description:r,id:o||AL(),rubric_instructions:i,rubric_items:s},l=JSON.stringify(Object.fromEntries(Object.entries(a).filter(([u,d])=>d!==void 0)));return(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await Yt(u,"create annotation queue"),u})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/annotation-queues/${_r(e,"queueId")}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(r,"read annotation queue"),r})).json()}async updateAnnotationQueue(e,n){let{name:r,description:o,rubricInstructions:i,rubricItems:s}=n,a={};r!==void 0&&(a.name=r),o!==void 0&&(a.description=o),i!==void 0&&(a.rubric_instructions=i),s!==void 0&&(a.rubric_items=s);let l=JSON.stringify(a);await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/annotation-queues/${_r(e,"queueId")}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await Yt(c,"update annotation queue",!0),c})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${_r(e,"queueId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(n,"delete annotation queue",!0),n})}async addRunsToAnnotationQueue(e,n){let r=`${this.apiUrl}/annotation-queues/${_r(e,"queueId")}/runs`,o=n.every(a=>typeof a=="string"),i,s;o?(Nu("Passing run IDs as strings to addRunsToAnnotationQueue() is deprecated and will be removed after Jan 31, 2027. Use RunKey[] instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#annotation-queues-add-runs for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_ADD_RUNS_STRING_IDS"}),i=r,s=JSON.stringify(n.map((a,l)=>_r(a,`runs[${l}]`).toString()))):(i=`${r}/by-key`,s=JSON.stringify(n.map((a,l)=>{let c={run_id:_r(a.runId,`runs[${l}].runId`).toString(),session_id:_r(a.sessionId,`runs[${l}].sessionId`).toString(),start_time:typeof a.startTime=="string"?a.startTime:new Date(a.startTime).toISOString()};return a.sourceProposedExampleId!=null&&(c.source_proposed_example_id=_r(a.sourceProposedExampleId,`runs[${l}].sourceProposedExampleId`).toString()),c}))),await this.caller.call(async()=>{let a=await this._fetch(i,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await Yt(a,"add runs to annotation queue",!0),a})}async getRunFromAnnotationQueue(e,n){let r=`/annotation-queues/${_r(e,"queueId")}/run`,i=await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${r}/${n}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(s,"get run from annotation queue"),s})).json();return Yz(i)}async*listRunsFromAnnotationQueue(e,n={}){let{status:r,limit:o}=n,i=new URLSearchParams,s=o!==void 0&&Number.isFinite(o)?Math.min(o,100):100;r&&i.append("status",r),i.append("limit",s.toString());let a=0,l=`/annotation-queues/${_r(e,"queueId")}/runs`;for await(let c of this._getPaginated(l,i))for(let u of c)if(yield Yz(u),a++,a>=s)return}async deleteRunFromAnnotationQueue(e,n){await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/annotation-queues/${_r(e,"queueId")}/runs/${_r(n,"queueRunId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(r,"delete run from annotation queue",!0),r})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/annotation-queues/${_r(e,"queueId")}/size`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(r,"get size from annotation queue"),r})).json()}async _currentTenantIsOwner(e){let n=await this._getSettings();return e=="-"||n.tenant_handle===e}async _ownerConflictError(e,n){let r=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
Current tenant: ${r.tenant_handle}
Requested tenant: ${n}`)}async _getLatestCommitHash(e){let r=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(o,"get latest commit hash"),o})).json();if(r.commits.length!==0)return r.commits[0].commit_hash}async _createCommitTags(e,n,r){let o=typeof r=="string"?[r]:r;await Promise.all(o.map(async i=>this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/repos/${e}/tags`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify({tag_name:i,commit_id:n})});return await Yt(s,"create commit tag"),s})))}async _likeOrUnlikePrompt(e,n){let[r,o,i]=bf(e),s=JSON.stringify({like:n});return(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/likes/${r}/${o}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await Yt(l,`${n?"like":"unlike"} prompt`),l})).json()}async _getPromptUrl(e){let[n,r,o]=bf(e);if(await this._currentTenantIsOwner(n)){let i=await this._getSettings();return o!=="latest"?`${this.getHostUrl()}/prompts/${r}/${o.substring(0,8)}?organizationId=${i.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${i.id}`}else return o!=="latest"?`${this.getHostUrl()}/hub/${n}/${r}/${o.substring(0,8)}`:`${this.getHostUrl()}/hub/${n}/${r}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){let[n,r,o]=bf(e);for await(let i of this._getPaginated(`/commits/${n}/${r}/`,new URLSearchParams,s=>s.commits))yield*i}async*listPrompts(e){let n=new URLSearchParams;n.append("sort_field",e?.sortField??"updated_at"),n.append("sort_direction","desc"),n.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&n.append("is_public",e.isPublic.toString()),e?.query&&n.append("query",e.query);for await(let r of this._getPaginated("/repos",n,o=>o.repos))yield*r}async getPrompt(e){let[n,r,o]=bf(e),s=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/repos/${n}/${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return a?.status===404?null:(await Yt(a,"get prompt"),a)}))?.json();return s?.repo?s.repo:null}async createPrompt(e,n){let r=await this._getSettings();if(n?.isPublic&&!r.tenant_handle)throw new Error(`Cannot create a public prompt without first
creating a LangChain Hub handle.
You can add a handle by creating a public prompt at:
https://smith.langchain.com/prompts`);let[o,i,s]=bf(e);if(!await this._currentTenantIsOwner(o))throw await this._ownerConflictError("create a prompt",o);let a={repo_handle:i,...n?.description&&{description:n.description},...n?.readme&&{readme:n.readme},...n?.tags&&{tags:n.tags},is_public:!!n?.isPublic},l=JSON.stringify(a),c=await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await Yt(d,"create prompt"),d}),{repo:u}=await c.json();return u}async createCommit(e,n,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[o,i,s]=bf(e),a=r?.parentCommitHash==="latest"||!r?.parentCommitHash?await this._getLatestCommitHash(`${o}/${i}`):r?.parentCommitHash,l={manifest:JSON.parse(JSON.stringify(n)),parent_commit:a,...r?.description!==void 0&&{description:r.description}},c=JSON.stringify(l),d=await(await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}/commits/${o}/${i}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await Yt(p,"create commit"),p})).json(),f=d.commit??d;return r?.tags&&await this._createCommitTags(`${o}/${i}`,f.id,r.tags),this._getPromptUrl(`${o}/${i}${f.commit_hash?`:${f.commit_hash}`:""}`)}async updateExamplesMultipart(e,n=[]){return this._updateExamplesMultipart(e,n)}async _updateExamplesMultipart(e,n=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let r=new FormData;for(let s of n){let a=s.id,l={...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split}},c=_f(l,`Serializing body for example with id: ${a}`),u=new Blob([c],{type:"application/json"});if(r.append(a,u),s.inputs){let d=_f(s.inputs,`Serializing inputs for example with id: ${a}`),f=new Blob([d],{type:"application/json"});r.append(`${a}.inputs`,f)}if(s.outputs){let d=_f(s.outputs,`Serializing outputs whle updating example with id: ${a}`),f=new Blob([d],{type:"application/json"});r.append(`${a}.outputs`,f)}if(s.attachments)for(let[d,f]of Object.entries(s.attachments)){let p,m;Array.isArray(f)?[p,m]=f:(p=f.mimeType,m=f.data);let h=new Blob([m],{type:`${p}; length=${m.byteLength}`});r.append(`${a}.attachment.${d}`,h)}if(s.attachments_operations){let d=_f(s.attachments_operations,`Serializing attachments while updating example with id: ${a}`),f=new Blob([d],{type:"application/json"});r.append(`${a}.attachments_operations`,f)}}let o=e??n[0]?.dataset_id;return(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${o}/examples`)}`,{method:"PATCH",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await Yt(s,"update examples"),s})).json()}async uploadExamplesMultipart(e,n=[]){return this._uploadExamplesMultipart(e,n)}async _uploadExamplesMultipart(e,n=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let r=new FormData;for(let i of n){let s=(i.id??AL()).toString(),a={created_at:i.created_at,...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split},...i.source_run_id&&{source_run_id:i.source_run_id},...i.use_source_run_io&&{use_source_run_io:i.use_source_run_io},...i.use_source_run_attachments&&{use_source_run_attachments:i.use_source_run_attachments}},l=_f(a,`Serializing body for uploaded example with id: ${s}`),c=new Blob([l],{type:"application/json"});if(r.append(s,c),i.inputs){let u=_f(i.inputs,`Serializing inputs for uploaded example with id: ${s}`),d=new Blob([u],{type:"application/json"});r.append(`${s}.inputs`,d)}if(i.outputs){let u=_f(i.outputs,`Serializing outputs for uploaded example with id: ${s}`),d=new Blob([u],{type:"application/json"});r.append(`${s}.outputs`,d)}if(i.attachments)for(let[u,d]of Object.entries(i.attachments)){let f,p;Array.isArray(d)?[f,p]=d:(f=d.mimeType,p=d.data);let m=new Blob([p],{type:`${f}; length=${p.byteLength}`});r.append(`${s}.attachment.${u}`,m)}}return(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await Yt(i,"upload examples"),i})).json()}async updatePrompt(e,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[r,o]=bf(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);let i={};if(n?.description!==void 0&&(i.description=n.description),n?.readme!==void 0&&(i.readme=n.readme),n?.tags!==void 0&&(i.tags=n.tags),n?.isPublic!==void 0&&(i.is_public=n.isPublic),n?.isArchived!==void 0&&(i.is_archived=n.isArchived),Object.keys(i).length===0)throw new Error("No valid update options provided");let s=JSON.stringify(i);return(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/repos/${r}/${o}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await Yt(l,"update prompt"),l})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[n,r,o]=bf(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("delete a prompt",n);return(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/repos/${n}/${r}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(s,"delete prompt"),s})).json()}_getPromptCacheKey(e,n){return`${e}${n?":with_model":""}`}async _fetchPromptFromApi(e,n){let[r,o,i]=bf(e),a=await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/commits/${r}/${o}/${i}${n?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(l,"pull prompt commit"),l})).json();return{owner:r,repo:o,commit_hash:a.commit_hash,manifest:a.manifest,examples:a.examples,hub_model_config:a.model_config,hub_model_provider:a.model_provider}}async pullPromptCommit(e,n){ear(e,n?.dangerouslyPullPublicPrompt);let r=this._fetchPromptFromApi.bind(this,e,n);if(!n?.skipCache&&this._promptCache){let o=this._getPromptCacheKey(e,n?.includeModel),i=this._promptCache.get(o,r);if(i)return i;let s=await r();return this._promptCache.set(o,s,r),s}return this._fetchPromptFromApi(e,n)}async _pullPrompt(e,n){let r=await this.pullPromptCommit(e,{includeModel:n?.includeModel,skipCache:n?.skipCache,dangerouslyPullPublicPrompt:n?.dangerouslyPullPublicPrompt});return JSON.stringify(r.manifest)}async pushPrompt(e,n){return await this.promptExists(e)?n&&["description","readme","tags","isPublic"].some(o=>n[o]!==void 0)&&await this.updatePrompt(e,{description:n?.description,readme:n?.readme,tags:n?.tags,isPublic:n?.isPublic}):await this.createPrompt(e,{description:n?.description,readme:n?.readme,tags:n?.tags,isPublic:n?.isPublic}),n?.object?await this.createCommit(e,n?.object,{parentCommitHash:n?.parentCommitHash,tags:n?.commitTags,description:n?.commitDescription}):await this._getPromptUrl(e)}async agentExists(e){let[n,r]=bf(e);return this._repoExists(n,r)}async skillExists(e){let[n,r]=bf(e);return this._repoExists(n,r)}async pullAgent(e,n){return await this._pullDirectory(e,"agent",n?.version)}async pullSkill(e,n){return await this._pullDirectory(e,"skill",n?.version)}async pushAgent(e,n){return this._pushDirectory(e,"agent",n)}async pushSkill(e,n){return this._pushDirectory(e,"skill",n)}async deleteAgent(e){return this._deleteDirectory(e)}async deleteSkill(e){return this._deleteDirectory(e)}async*listAgents(e){yield*this._listReposByType("agent",e)}async*listSkills(e){yield*this._listReposByType("skill",e)}async*_listReposByType(e,n){let r=new URLSearchParams;r.append("repo_type",e),r.append("is_archived",(!!n?.isArchived).toString()),n?.isPublic!==void 0&&r.append("is_public",n.isPublic.toString()),n?.query&&r.append("query",n.query);for await(let o of this._getPaginated("/repos",r,i=>i.repos))yield*o}async _pullDirectory(e,n,r){let[o,i,s]=bf(e),a=r??(s!=="latest"?s:void 0),l=new URL(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${o}/${i}/directories`)}`);return l.searchParams.set("repo_type",n),a&&l.searchParams.set("commit",a),await(await this.caller.call(async()=>{let u=await this._fetch(l.toString(),{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(u,"pull directory"),u})).json()}async _pushDirectory(e,n,r){if(r.parentCommit!==void 0&&(r.parentCommit.length<8||r.parentCommit.length>64))throw new Error("parent_commit must be 8-64 characters");let[o,i]=bf(e);if(!await this._currentTenantIsOwner(o))throw await this._ownerConflictError(`push ${n}`,o);if(await this._repoExists(o,i))(r.description!==void 0||r.readme!==void 0||r.tags!==void 0||r.isPublic!==void 0)&&await this._updateRepoMetadata(o,i,r);else{let f=/^[a-z][a-z0-9-_]*$/;if(!f.test(i))throw new Error(`Invalid repo_handle ${JSON.stringify(i)}: must match ${f}`);await this._createRepo(i,n,r)}let s={files:r.files};r.parentCommit&&(s.parent_commit=r.parentCommit);let c=(await(await this.caller.call(async()=>{let f=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${o}/${i}/directories/commits`)}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(s)});return await Yt(f,`push ${n}`),f})).json()).commit.commit_hash,u=await this._getSettings(),d=new URLSearchParams({organizationId:u.id});return`${this.getHostUrl()}/context/${i}/${c.slice(0,8)}?${d.toString()}`}async _deleteDirectory(e){let[n,r]=bf(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("delete",n);await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${n}/${r}/directories`)}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(o,"delete directory"),o})}async _repoExists(e,n){try{return await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/repos/${e}/${n}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Yt(r,"check repo exists"),r}),!0}catch(r){if(Uhe(r))return!1;throw r}}async _createRepo(e,n,r){let o={repo_handle:e,repo_type:n,is_public:!!r.isPublic};r.description!==void 0&&(o.description=r.description),r.readme!==void 0&&(o.readme=r.readme),r.tags!==void 0&&(o.tags=r.tags);try{await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(o)});return await Yt(i,`create ${n}`),i})}catch(i){if(xHt(i))return;throw i}}async _updateRepoMetadata(e,n,r){let o={};r.description!==void 0&&(o.description=r.description),r.readme!==void 0&&(o.readme=r.readme),r.tags!==void 0&&(o.tags=r.tags),r.isPublic!==void 0&&(o.is_public=r.isPublic),Object.keys(o).length!==0&&await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/repos/${e}/${n}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(o)});return await Yt(i,"update repo metadata"),i})}async clonePublicDataset(e,n={}){let{sourceApiUrl:r=this.apiUrl,datasetName:o}=n,[i,s]=this.parseTokenOrUrl(e,r),a=new t({apiUrl:i,apiKey:"placeholder"}),l=await a.readSharedDataset(s),c=o||l.name;try{if(await this.hasDataset({datasetId:c})){console.log(`Dataset ${c} already exists in your tenant. Skipping.`);return}}catch{}let u=await a.listSharedExamples(s),d=await this.createDataset(c,{description:l.description,dataType:l.data_type||"kv",inputsSchema:l.inputs_schema_definition??void 0,outputsSchema:l.outputs_schema_definition??void 0});try{await this.createExamples({inputs:u.map(f=>f.inputs),outputs:u.flatMap(f=>f.outputs?[f.outputs]:[]),datasetId:d.id})}catch(f){throw console.error(`An error occurred while creating dataset ${c}. You should delete it manually.`),f}}parseTokenOrUrl(e,n,r=2,o="dataset"){try{return _r(e),[n,e]}catch{}try{let s=new URL(e).pathname.split("/").filter(a=>a!=="");if(s.length>=r){let a=s[s.length-r];return[n,a]}else throw new Error(`Invalid public ${o} URL: ${e}`)}catch{throw new Error(`Invalid public ${o} URL or token: ${e}`)}}cleanup(){this._promptCache&&this._promptCache.stop()}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();for(await new Promise(e=>setTimeout(e,1));this._pendingDrains.size>0;)await Promise.all([...this._pendingDrains]);await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await y4t()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}toString(){let e=[`apiUrl=${JSON.stringify(this.apiUrl)}`];return this.webUrl!==void 0&&e.push(`webUrl=${JSON.stringify(this.webUrl)}`),this.workspaceId!==void 0&&e.push(`workspaceId=${JSON.stringify(this.workspaceId)}`),`[LangSmithClient ${e.join(" ")}]`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}};Object.defineProperty(xA,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set})});var Wx,k0o,Vhe,r3e=b(()=>{Wx=Symbol.for("lc:context_variables"),k0o=Symbol.for("lc:child_run_end_promises"),Vhe=Symbol.for("langsmith:replica_trace_roots")});function o3e(t,e){if(Wx in t)return t[Wx][e]}function eWt(t,e,n){let r=Wx in t?t[Wx]:{};r[e]=n,t[Wx]=r}var tWt=b(()=>{r3e()});function nWt(t){let n=Object.keys(t).sort().map(r=>`${r}:${t[r]??""}`).join("|");return f6e(n,uar)}function dar(t){return t.replace(/[-:.]/g,"")}function oWt(t,e=1){let n=e.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(t).toISOString().slice(0,-1)}${n}Z`}function i3e(t,e,n=1){let r=oWt(t,n);return{dottedOrder:dar(r)+e,microsecondPrecisionDatestring:r}}function par(t){let e={};for(let n of Object.keys(t))n==="primary"&&typeof t[n]!="boolean"||far.has(n)&&(e[n]=t[n]);return e}function iWt(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}function sWt(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}function rWt(t){return Array.isArray(t)&&t.some(e=>sWt(e))}function mar(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}function har(t){let e=t?.callbacks;return t!=null&&typeof e=="object"&&(rWt(e?.handlers)||rWt(e))}function gar(){let t=Ou("LANGSMITH_RUNS_ENDPOINTS");if(!t)return[];try{let e=JSON.parse(t);if(Array.isArray(e)){let n=[];for(let r of e){if(typeof r!="object"||r===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof r}`);continue}if(typeof r.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_url}`);continue}if(typeof r.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_key}`);continue}if(r.project_name!==void 0&&r.project_name!==null&&typeof r.project_name!="string"){console.warn(`Invalid project_name type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.project_name}`);continue}if(r.primary!==void 0&&typeof r.primary!="boolean"){console.warn(`Invalid primary type in LANGSMITH_RUNS_ENDPOINTS: expected boolean, got ${typeof r.primary}`);continue}n.push({apiUrl:r.api_url.replace(/\/$/,""),apiKey:r.api_key,projectName:r.project_name??void 0,primary:r.primary??void 0})}return n}else if(typeof e=="object"&&e!==null){war(e);let n=[];for(let[r,o]of Object.entries(e)){let i=r.replace(/\/$/,"");if(typeof o=="string")n.push({apiUrl:i,apiKey:o});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${r}: expected string, got ${typeof o}`);continue}}return n}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof e}`),[]}catch(e){if(CHt(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function yar(t){let e=t?t.map(n=>Array.isArray(n)?{projectName:n[0],updates:n[1]}:n):gar();if(e.filter(n=>n.primary===!0).length>1)throw new Error("Only one replica can be marked as primary.");return e}function war(t){if(Object.keys(t).length>0&&Os("ENDPOINT"))throw new Dhe}var YY,uar,far,qhe,wb,D6e=b(()=>{$6e();T6e();jhe();r3e();tWt();$x();_6e();$x();the();jY();FY();YY=36,uar="6ba7b810-9dad-11d1-80b4-00c04fd430c8";far=new Set(["projectName","primary","updates","reroot"]);qhe=class t{constructor(e,n,r,o){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=n,this.project_name=r,this.replicas=o}static fromHeader(e){let n=e.split(","),r={},o=[],i,s;for(let a of n){let[l,c]=a.split("="),u=decodeURIComponent(c);l==="langsmith-metadata"?r=JSON.parse(u):l==="langsmith-tags"?o=u.split(","):l==="langsmith-project"?i=u:l==="langsmith-replicas"&&(s=JSON.parse(u).map(f=>Array.isArray(f)?f:par(f)))}return new t(r,o,i,s)}toHeader(){let e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}},wb=class t{constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),iWt(e)){Object.assign(this,{...e});return}let n=t.getDefaultConfig(),{metadata:r,...o}=e,i=o.client??t.getSharedClient(),s={...r,...o?.extra?.metadata};if(o.extra={...o.extra,metadata:s},"id"in o&&o.id==null&&delete o.id,Object.assign(this,{...n,...o,client:i}),this.execution_order??(this.execution_order=1),this.child_execution_order??(this.child_execution_order=1),this.dotted_order||(this._serialized_start_time=oWt(this.start_time,this.execution_order)),this.id||(this.id=ahe(this._serialized_start_time??this.start_time)),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=yar(this.replicas),!this.dotted_order){let{dottedOrder:a}=i3e(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+a:this.dotted_order=a}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){let e=Date.now();return{run_type:"chain",project_name:UY(),child_runs:[],api_url:Ou("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Ou("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return t.sharedClient||(t.sharedClient=new xA),t.sharedClient}createChild(e){let n=this.child_execution_order+1,r=this.replicas?.map(f=>{let{reroot:p,...m}=f;return m}),o=e.replicas??r,i=new t({...e,parent_run:this,project_name:this.project_name,replicas:o,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:n,child_execution_order:n}),s=this.extra?.metadata??{},a=i.extra?.metadata??{};Object.keys(s).length>0&&(i.extra={...i.extra,metadata:{...s,...a}}),Wx in this&&(i[Wx]=this[Wx]);let l=Symbol.for("lc:child_config"),c=e.extra?.[l]??this.extra[l];if(har(c)){let f={...c},p=mar(f.callbacks)?f.callbacks.copy?.():void 0;p&&(Object.assign(p,{_parentRunId:i.id}),p.handlers?.find(sWt)?.updateFromRunTree?.(i),f.callbacks=p),i.extra[l]=f}let u=new Set,d=this;for(;d!=null&&!u.has(d.id);)u.add(d.id),d.child_execution_order=Math.max(d.child_execution_order,n),d=d.parent_run;return this.child_runs.push(i),i}async end(e,n,r=Date.now(),o){this.outputs=this.outputs??e,this.error=this.error??n,this.end_time=this.end_time??r,o&&Object.keys(o).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...o}}:{metadata:o})}_convertToCreate(e,n,r=!0){let o=e.extra??{};if(o?.runtime?.library===void 0&&(o.runtime||(o.runtime={}),n))for(let[a,l]of Object.entries(n))o.runtime[a]||(o.runtime[a]=l);let i=e.parent_run?.id??e.parent_run_id,s;return r?s=[]:s=e.child_runs.map(a=>this._convertToCreate(a,n,r)),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:o,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:s,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_sliceParentId(e,n){if(n.dotted_order){let r=n.dotted_order.split("."),o=null;for(let i=0;i<r.length;i++)if(r[i].slice(-YY)===e){o=i;break}if(o!==null){let i=r.slice(o+1);n.dotted_order=i.join("."),i.length>0?n.trace_id=i[0].slice(-YY):n.trace_id=n.id}}n.parent_run_id===e&&(n.parent_run_id=void 0)}_setReplicaTraceRoot(e,n){let r=o3e(this,Vhe)??{};r[e]=n,eWt(this,Vhe,r);for(let o of this.child_runs)o._setReplicaTraceRoot(e,n)}_remapForProject(e){let{projectName:n,primary:r,runtimeEnv:o,excludeChildRuns:i=!0,reroot:s=!1,distributedParentId:a,apiUrl:l,apiKey:c,workspaceId:u}=e,d=this._convertToCreate(this,o,i);if(r===void 0&&n===this.project_name)return{...d,session_name:n};if(s){if(a)this._sliceParentId(a,d);else if(d.parent_run_id=void 0,d.dotted_order){let w=d.dotted_order.split(".");w.length>0&&(d.dotted_order=w[w.length-1],d.trace_id=d.id)}let y=nWt({projectName:n,apiUrl:l,apiKey:c,workspaceId:u});this._setReplicaTraceRoot(y,d.id)}let f;if(!s){let y=o3e(this,Vhe)??{},w=nWt({projectName:n,apiUrl:l,apiKey:c,workspaceId:u});if(f=y[w],f&&(d.trace_id=f,d.dotted_order)){let _=d.dotted_order.split("."),S=null;for(let I=0;I<_.length;I++)if(_[I].slice(-YY)===f){S=I;break}if(S!==null){let I=_.slice(S);d.dotted_order=I.join(".")}}}if(r)return{...d,session_name:n};let p=d.id,m=Lz(p,n),h;d.trace_id?h=Lz(d.trace_id,n):h=m;let g;d.parent_run_id&&(g=Lz(d.parent_run_id,n));let v;return d.dotted_order&&(v=d.dotted_order.split(".").map(_=>{let S=_.slice(-YY),I=Lz(S,n);return _.slice(0,-YY)+I}).join(".")),{...d,id:m,trace_id:h,parent_run_id:g,dotted_order:v,session_name:n}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let n=hhe();if(this.replicas&&this.replicas.length>0)for(let{projectName:r,primary:o,apiKey:i,apiUrl:s,workspaceId:a,reroot:l,client:c}of this.replicas){let u=this._remapForProject({projectName:r??this.project_name,primary:o,runtimeEnv:n,excludeChildRuns:!0,reroot:l,distributedParentId:this.distributedParentId,apiUrl:s,apiKey:i,workspaceId:a});await(c??this.client).createRun(u,{apiKey:i,apiUrl:s,workspaceId:a})}else{let r=this._convertToCreate(this,n,e);await this.client.createRun(r)}if(!e){Nu("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(let r of this.child_runs)await r.postRun(!1)}this.child_runs=[]}catch(n){console.error(`Error in postRun for run ${this.id}:`,n)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(let{projectName:n,primary:r,apiKey:o,apiUrl:i,workspaceId:s,updates:a,reroot:l,client:c}of this.replicas){let u=this._remapForProject({projectName:n??this.project_name,primary:r,runtimeEnv:void 0,excludeChildRuns:!0,reroot:l,distributedParentId:this.distributedParentId,apiUrl:i,apiKey:o,workspaceId:s}),d={id:u.id,name:u.name,run_type:u.run_type,start_time:u.start_time,outputs:u.outputs,error:u.error,parent_run_id:u.parent_run_id,session_name:u.session_name,reference_example_id:u.reference_example_id,end_time:u.end_time,dotted_order:u.dotted_order,trace_id:u.trace_id,events:u.events,tags:u.tags,extra:u.extra,attachments:this.attachments,...a};e?.excludeInputs||(d.inputs=u.inputs),await(c??this.client).updateRun(u.id,d,{apiKey:o,apiUrl:i,workspaceId:s})}else try{let n={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e?.excludeInputs||(n.inputs=this.inputs),await this.client.updateRun(this.id,n)}catch(n){console.error(`Error in patchRun for run ${this.id}`,n)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,n){let r=e?.callbacks,o,i,s,a=I6e();if(r){let c=r?.getParentRunId?.()??"",u=r?.handlers?.find(d=>d?.name=="langchain_tracer");o=u?.getRun?.(c),i=u?.projectName,s=u?.client,a=a||!!u}return o?new t({name:o.name,id:o.id,trace_id:o.trace_id,dotted_order:o.dotted_order,client:s,tracingEnabled:a,project_name:i,tags:[...new Set((o?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...o?.extra?.metadata,...e?.metadata}}}).createChild(n):new t({...n,client:s,tracingEnabled:a,project_name:i})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,n){let r="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,o=r["langsmith-trace"];if(!o||typeof o!="string")return;let i=o.trim(),s=i.split(".").map(u=>{let[d,f]=u.split("Z");return{strTime:d,time:Date.parse(d+"Z"),uuid:f}}),a=s[0].uuid,l={...n,name:n?.name??"parent",run_type:n?.run_type??"chain",start_time:n?.start_time??Date.now(),id:s.at(-1)?.uuid,trace_id:a,dotted_order:i};if(r.baggage&&typeof r.baggage=="string"){let u=qhe.fromHeader(r.baggage);l.metadata=u.metadata,l.tags=u.tags,l.project_name=u.project_name,l.replicas=u.replicas}let c=new t(l);return c.distributedParentId=c.id,c}toHeaders(e){let n={"langsmith-trace":this.dotted_order,baggage:new qhe(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(let[r,o]of Object.entries(n))e.set(r,o);return n}};Object.defineProperty(wb,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null})});var Khe=b(()=>{D6e()});function a3e(t,e){if(t)return new wb({...t,start_time:t._serialized_start_time??t.start_time,parent_run:a3e(e),child_runs:t.child_runs.map(n=>a3e(n)).filter(n=>n!==void 0),extra:{...t.extra,runtime:QBt()},tracingEnabled:!1})}function s3e(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}function Jz(t){return typeof t._addRunToRunMap=="function"}var bar,Vx,ZL=b(()=>{br();ys();RY();Khe();bar=t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t};Vx=class extends Pz{constructor(e){super(...arguments);M(this,"runMap",new Map);M(this,"runTreeMap",new Map);M(this,"usesRunTreeMap",!1)}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?bar(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`
${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,n){e.child_runs.push(n)}_addRunToRunMap(e){let{dottedOrder:n,microsecondPrecisionDatestring:r}=i3e(new Date(e.start_time).getTime(),e.id,e.execution_order),o={...e},i=this.getRunById(o.parent_run_id);if(o.parent_run_id!==void 0?i?(this._addChildRun(i,o),i.child_execution_order=Math.max(i.child_execution_order,o.child_execution_order),o.trace_id=i.trace_id,i.dotted_order!==void 0&&(o.dotted_order=[i.dotted_order,n].join("."),o._serialized_start_time=r)):o.parent_run_id=void 0:(o.trace_id=o.id,o.dotted_order=n,o._serialized_start_time=r),this.usesRunTreeMap){let s=a3e(o,i);s!==void 0&&this.runTreeMap.set(o.id,s)}else this.runMap.set(o.id,o);return o}async _endTrace(e){let n=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);n?n.child_execution_order=Math.max(n.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){let n=e!==void 0&&this.getRunById(e);return n?n.child_execution_order+1:1}_createRunForLLMStart(e,n,r,o,i,s,a,l){let c=this._getExecutionOrder(o),u=Date.now(),d=a?{...i,metadata:a}:i,f={id:r,name:l??e.id[e.id.length-1],parent_run_id:o,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:n},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:s||[]};return this._addRunToRunMap(f)}async handleLLMStart(e,n,r,o,i,s,a,l){let c=this.getRunById(r)??this._createRunForLLMStart(e,n,r,o,i,s,a,l);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,n,r,o,i,s,a,l){let c=this._getExecutionOrder(o),u=Date.now(),d=a?{...i,metadata:a}:i,f={id:r,name:l??e.id[e.id.length-1],parent_run_id:o,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:n},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:s||[]};return this._addRunToRunMap(f)}async handleChatModelStart(e,n,r,o,i,s,a,l){let c=this.getRunById(r)??this._createRunForChatModelStart(e,n,r,o,i,s,a,l);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,n,r,o,i){let s=this.getRunById(n);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.outputs=e,s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...i},await this.onLLMEnd?.(s),await this._endTrace(s),s}async handleLLMError(e,n,r,o,i){let s=this.getRunById(n);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(e),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...i},await this.onLLMError?.(s),await this._endTrace(s),s}_createRunForChainStart(e,n,r,o,i,s,a,l,c){let u=this._getExecutionOrder(o),d=Date.now(),f={id:r,name:l??e.id[e.id.length-1],parent_run_id:o,start_time:d,serialized:e,events:[{name:"start",time:new Date(d).toISOString()}],inputs:n,execution_order:u,child_execution_order:u,run_type:a??"chain",child_runs:[],extra:s?{...c,metadata:s}:{...c},tags:i||[]};return this._addRunToRunMap(f)}async handleChainStart(e,n,r,o,i,s,a,l){let c=this.getRunById(r)??this._createRunForChainStart(e,n,r,o,i,s,a,l);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,n,r,o,i){let s=this.getRunById(n);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.outputs=s3e(e,"output"),s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=s3e(i.inputs,"input")),await this.onChainEnd?.(s),await this._endTrace(s),s}async handleChainError(e,n,r,o,i){let s=this.getRunById(n);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(e),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=s3e(i.inputs,"input")),await this.onChainError?.(s),await this._endTrace(s),s}_createRunForToolStart(e,n,r,o,i,s,a){let l=this._getExecutionOrder(o),c=Date.now(),u={id:r,name:a??e.id[e.id.length-1],parent_run_id:o,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:n},execution_order:l,child_execution_order:l,run_type:"tool",child_runs:[],extra:s?{metadata:s}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleToolStart(e,n,r,o,i,s,a){let l=this.getRunById(r)??this._createRunForToolStart(e,n,r,o,i,s,a);return await this.onRunCreate?.(l),await this.onToolStart?.(l),l}async handleToolEnd(e,n){let r=this.getRunById(n);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(e,n){let r=this.getRunById(n);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(e,n){let r=this.getRunById(n);if(!r||r?.run_type!=="chain")return;let o=r;o.actions=o.actions||[],o.actions.push(e),o.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(r)}async handleAgentEnd(e,n){let r=this.getRunById(n);!r||r?.run_type!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(e,n,r,o,i,s,a){let l=this._getExecutionOrder(o),c=Date.now(),u={id:r,name:a??e.id[e.id.length-1],parent_run_id:o,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:n},execution_order:l,child_execution_order:l,run_type:"retriever",child_runs:[],extra:s?{metadata:s}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(e,n,r,o,i,s,a){let l=this.getRunById(r)??this._createRunForRetrieverStart(e,n,r,o,i,s,a);return await this.onRunCreate?.(l),await this.onRetrieverStart?.(l),l}async handleRetrieverEnd(e,n){let r=this.getRunById(n);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(e,n){let r=this.getRunById(n);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(e,n){let r=this.getRunById(n);!r||r?.run_type!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(r))}async handleLLMNewToken(e,n,r,o,i,s){let a=this.getRunById(r);if(!a||a?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return a.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:n,chunk:s?.chunk}}),await this.onLLMNewToken?.(a,e,{chunk:s?.chunk}),a}}});function Pp(t,e){return`${t.open}${e}${t.close}`}function dv(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}function aWt(t){return typeof t=="string"?t.trim():t==null?t:dv(t,t.toString())}function AA(t){if(!t.end_time)return"";let e=t.end_time-t.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}var lWt,Rm,l3e,cWt=b(()=>{br();ZL();lWt={bold:{open:"\x1B[1m",close:"\x1B[22m"},color:{grey:{open:"\x1B[90m",close:"\x1B[39m"},green:{open:"\x1B[32m",close:"\x1B[39m"},cyan:{open:"\x1B[36m",close:"\x1B[39m"},red:{open:"\x1B[31m",close:"\x1B[39m"},blue:{open:"\x1B[34m",close:"\x1B[39m"}}};({color:Rm}=lWt),l3e=class extends Vx{constructor(){super(...arguments);M(this,"name","console_callback_handler")}persistRun(e){return Promise.resolve()}getParents(e){let n=[],r=e;for(;r.parent_run_id;){let o=this.runMap.get(r.parent_run_id);if(o)n.push(o),r=o;else break}return n}getBreadcrumbs(e){let n=[...this.getParents(e).reverse(),e].map((r,o,i)=>{let s=`${r.execution_order}:${r.run_type}:${r.name}`;return o===i.length-1?Pp(lWt.bold,s):s}).join(" > ");return Pp(Rm.grey,n)}onChainStart(e){let n=this.getBreadcrumbs(e);console.log(`${Pp(Rm.green,"[chain/start]")} [${n}] Entering Chain run with input: ${dv(e.inputs,"[inputs]")}`)}onChainEnd(e){let n=this.getBreadcrumbs(e);console.log(`${Pp(Rm.cyan,"[chain/end]")} [${n}] [${AA(e)}] Exiting Chain run with output: ${dv(e.outputs,"[outputs]")}`)}onChainError(e){let n=this.getBreadcrumbs(e);console.log(`${Pp(Rm.red,"[chain/error]")} [${n}] [${AA(e)}] Chain run errored with error: ${dv(e.error,"[error]")}`)}onLLMStart(e){let n=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(o=>o.trim())}:e.inputs;console.log(`${Pp(Rm.green,"[llm/start]")} [${n}] Entering LLM run with input: ${dv(r,"[inputs]")}`)}onLLMEnd(e){let n=this.getBreadcrumbs(e);console.log(`${Pp(Rm.cyan,"[llm/end]")} [${n}] [${AA(e)}] Exiting LLM run with output: ${dv(e.outputs,"[response]")}`)}onLLMError(e){let n=this.getBreadcrumbs(e);console.log(`${Pp(Rm.red,"[llm/error]")} [${n}] [${AA(e)}] LLM run errored with error: ${dv(e.error,"[error]")}`)}onToolStart(e){let n=this.getBreadcrumbs(e);console.log(`${Pp(Rm.green,"[tool/start]")} [${n}] Entering Tool run with input: "${aWt(e.inputs.input)}"`)}onToolEnd(e){let n=this.getBreadcrumbs(e);console.log(`${Pp(Rm.cyan,"[tool/end]")} [${n}] [${AA(e)}] Exiting Tool run with output: "${aWt(e.outputs?.output)}"`)}onToolError(e){let n=this.getBreadcrumbs(e);console.log(`${Pp(Rm.red,"[tool/error]")} [${n}] [${AA(e)}] Tool run errored with error: ${dv(e.error,"[error]")}`)}onRetrieverStart(e){let n=this.getBreadcrumbs(e);console.log(`${Pp(Rm.green,"[retriever/start]")} [${n}] Entering Retriever run with input: ${dv(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){let n=this.getBreadcrumbs(e);console.log(`${Pp(Rm.cyan,"[retriever/end]")} [${n}] [${AA(e)}] Exiting Retriever run with output: ${dv(e.outputs,"[outputs]")}`)}onRetrieverError(e){let n=this.getBreadcrumbs(e);console.log(`${Pp(Rm.red,"[retriever/error]")} [${n}] [${AA(e)}] Retriever run errored with error: ${dv(e.error,"[error]")}`)}onAgentAction(e){let n=e,r=this.getBreadcrumbs(e);console.log(`${Pp(Rm.blue,"[agent/action]")} [${r}] Agent selected action: ${dv(n.actions[n.actions.length-1],"[action]")}`)}}});var Ghe=b(()=>{mhe()});var c3e,u3e,d3e=b(()=>{ys();Ghe();u3e=()=>(c3e===void 0&&(c3e=new xA(Nn("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{})),c3e)});var f3e=b(()=>{O6e()});function _ar(t){let e;for(let n of t)for(let r of n)cr.isInstance(r.message)&&r.message.usage_metadata!==void 0&&(e=IY(e,r.message.usage_metadata));return e}function uWt(t,e){if(t.tracingMetadata){e.extra??(e.extra={});let n=e.extra.metadata??{},r=!1;for(let[o,i]of Object.entries(t.tracingMetadata))(!Object.prototype.hasOwnProperty.call(n,o)||dWt.has(o))&&n[o]!==i&&(n[o]=i,r=!0);r&&(e.extra.metadata=n)}t.tracingTags.length>0&&(e.tags=Array.from(new Set([...e.tags??[],...t.tracingTags])))}var dWt,YL,fWt=b(()=>{br();Hme();Om();ZL();d3e();Khe();Ghe();f3e();dWt=new Set(["ls_agent_type"]);YL=class p3e extends Vx{constructor(n={}){super(n);M(this,"fields");M(this,"name","langchain_tracer");M(this,"projectName");M(this,"exampleId");M(this,"client");M(this,"replicas");M(this,"usesRunTreeMap",!0);M(this,"tracingMetadata");M(this,"tracingTags",[]);this.fields=n;let{exampleId:r,projectName:o,client:i,replicas:s,metadata:a,tags:l}=n;this.projectName=o??UY(),this.replicas=s,this.exampleId=r,this.client=i??u3e(),this.tracingMetadata=a?{...a}:void 0,this.tracingTags=l??[];let c=p3e.getTraceableRunTree();c&&this.updateFromRunTree(c)}async persistRun(n){}async onRunCreate(n){uWt(this,n),n.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(n.id)?.postRun()}async onRunUpdate(n){uWt(this,n);let r=this.getRunTreeWithTracingConfig(n.id);n.extra?.lc_defers_inputs?await r?.postRun():await r?.patchRun()}onLLMEnd(n){let r=n.outputs;if(r?.generations){let o=_ar(r.generations);if(o!==void 0){n.extra=n.extra??{};let i=n.extra.metadata??{};i.usage_metadata=o,n.extra.metadata=i}}}copyWithTracingConfig({metadata:n,tags:r}){let o;if(n===void 0)o=this.tracingMetadata?{...this.tracingMetadata}:void 0;else if(this.tracingMetadata===void 0)o={...n};else{o={...this.tracingMetadata};for(let[a,l]of Object.entries(n))(!Object.prototype.hasOwnProperty.call(o,a)||dWt.has(a))&&(o[a]=l)}let i=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],s=new p3e({...this.fields,metadata:o,tags:i});return s.runMap=this.runMap,s.runTreeMap=this.runTreeMap,s}_getRunStoreKey(){return this.runTreeMap}getRun(n){return this.runTreeMap.get(n)}updateFromRunTree(n){this.runTreeMap.set(n.id,n);let r=n,o=new Set;for(;r.parent_run&&!(o.has(r.id)||(o.add(r.id),!r.parent_run));)r=r.parent_run;o.clear();let i=[r];for(;i.length>0;){let s=i.shift();!s||o.has(s.id)||(o.add(s.id),this.runTreeMap.set(s.id,s),s.child_runs&&i.push(...s.child_runs))}this.client=n.client??this.client,this.replicas=n.replicas??this.replicas,this.projectName=n.project_name??this.projectName,this.exampleId=n.reference_example_id??this.exampleId,this.fields={...this.fields,client:this.client,replicas:this.replicas,projectName:this.projectName,exampleId:this.exampleId}}getRunTreeWithTracingConfig(n){let r=this.runTreeMap.get(n);if(r)return new wb({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return M6e(!0)}catch{return}}static[Symbol.hasInstance](n){if(typeof n!="object"||n===null)return!1;let r=n;return"name"in r&&r.name==="langchain_tracer"&&"copyWithTracingConfig"in r&&typeof r.copyWithTracingConfig=="function"&&"getRunTreeWithTracingConfig"in r&&typeof r.getRunTreeWithTracingConfig=="function"}}});var mWt=wi((vTo,Yhe)=>{"use strict";var xar=eVe(),Zhe=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},pWt=(t,e,n)=>new Promise((r,o)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){r(t);return}let i=setTimeout(()=>{if(typeof n=="function"){try{r(n())}catch(l){o(l)}return}let s=typeof n=="string"?n:`Promise timed out after ${e} milliseconds`,a=n instanceof Error?n:new Zhe(s);typeof t.cancel=="function"&&t.cancel(),o(a)},e);xar(t.then(r,o),()=>{clearTimeout(i)})});Yhe.exports=pWt;Yhe.exports.default=pWt;Yhe.exports.TimeoutError=Zhe});var hWt=wi(m3e=>{"use strict";Object.defineProperty(m3e,"__esModule",{value:!0});function Sar(t,e,n){let r=0,o=t.length;for(;o>0;){let i=o/2|0,s=r+i;n(t[s],e)<=0?(r=++s,o-=i+1):o=i}return r}m3e.default=Sar});var gWt=wi(g3e=>{"use strict";Object.defineProperty(g3e,"__esModule",{value:!0});var Car=hWt(),h3e=class{constructor(){this._queue=[]}enqueue(e,n){n=Object.assign({priority:0},n);let r={priority:n.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=n.priority){this._queue.push(r);return}let o=Car.default(this._queue,r,(i,s)=>s.priority-i.priority);this._queue.splice(o,0,r)}dequeue(){let e=this._queue.shift();return e?.run}filter(e){return this._queue.filter(n=>n.priority===e.priority).map(n=>n.run)}get size(){return this._queue.length}};g3e.default=h3e});var w3e=wi(v3e=>{"use strict";Object.defineProperty(v3e,"__esModule",{value:!0});var kar=Q6e(),yWt=mWt(),Iar=gWt(),Jhe=()=>{},Tar=new yWt.TimeoutError,y3e=class extends kar{constructor(e){var n,r,o,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=Jhe,this._resolveIdle=Jhe,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:Iar.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(r=(n=e.intervalCap)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(i=(o=e.interval)===null||o===void 0?void 0:o.toString())!==null&&i!==void 0?i:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=Jhe,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=Jhe,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let n=this._intervalEnd-e;if(n<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},n)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let n=this._queue.dequeue();return n?(this.emit("active"),n(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,n={}){return new Promise((r,o)=>{let i=async()=>{this._pendingCount++,this._intervalCount++;try{let s=this._timeout===void 0&&n.timeout===void 0?e():yWt.default(Promise.resolve(e()),n.timeout===void 0?this._timeout:n.timeout,()=>{(n.throwOnTimeout===void 0?this._throwOnTimeout:n.throwOnTimeout)&&o(Tar)});r(await s)}catch(s){o(s)}this._next()};this._queue.enqueue(i,n),this._tryToStartAnother(),this.emit("add")})}async addAll(e,n){return Promise.all(e.map(async r=>this.add(r,n)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{let n=this._resolveEmpty;this._resolveEmpty=()=>{n(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let n=this._resolveIdle;this._resolveIdle=()=>{n(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};v3e.default=y3e});function Par(){return new("default"in Xhe.default?Xhe.default.default:Xhe.default)({autoStart:!0,concurrency:1})}function Aar(){return typeof JY>"u"&&(JY=Par()),JY}async function Na(t,e){if(e===!0){let n=wA();n!==void 0?await n.run(void 0,async()=>t()):await t()}else JY=Aar(),JY.add(async()=>{let n=wA();n!==void 0?await n.run(void 0,async()=>t()):await t()})}var Xhe,JY,b3e=b(()=>{d3e();NY();Xhe=L(w3e(),1)});var vWt=b(()=>{br();b3e()});var wWt,bWt=b(()=>{ys();wWt=t=>t!==void 0?t:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>Nn(e)==="true")});function _3e(t){let e=wA();if(e!==void 0)return e.getStore()?.[PL]?.[t]}var Ear,_Wt,xWt=b(()=>{NY();Khe();Ear=Symbol("lc:configure_hooks"),_Wt=()=>_3e(Ear)||[]});function x3e(t){return t._getRunStoreKey?.()??t}function Mar(t,e){return t===e?t:t.copyWithTracingConfig({metadata:e.tracingMetadata,tags:e.tracingTags})}function Oar(t,e){let n=new Set(e),r=new Map,o=[],i=a=>{let l=x3e(a),c=n.has(a),u=r.get(l);if(u===void 0){r.set(l,{index:o.length,tracer:a,hasInheritable:c}),o.push(a);return}c&&!u.hasInheritable?(u.tracer=a,u.hasInheritable=!0):(c||!u.hasInheritable)&&(u.tracer=Mar(u.tracer,a)),o[u.index]=u.tracer};for(let a of t)a instanceof YL?i(a):o.push(a);for(let a of e)a instanceof YL&&!r.has(x3e(a))&&i(a);let s=new Set;return{handlers:o,inheritableHandlers:e.flatMap(a=>{if(!(a instanceof YL))return[a];let l=x3e(a);return s.has(l)?[]:(s.add(l),[r.get(l)?.tracer??a])})}}function JL(t){return t?Array.isArray(t)||"name"in t?{callbacks:t}:t:{}}function QY(t){return"name"in t?t:Pz.fromMethods(t)}var Nar,Qhe,Rar,SWt,Lar,$ar,Ru,EA=b(()=>{br();gb();TL();ys();RY();ZL();cWt();fWt();b3e();vWt();bWt();xWt();Nar=class{setHandler(t){return this.setHandlers([t])}},Qhe=class{constructor(t,e,n,r,o,i,s,a){M(this,"runId");M(this,"handlers");M(this,"inheritableHandlers");M(this,"tags");M(this,"inheritableTags");M(this,"metadata");M(this,"inheritableMetadata");M(this,"_parentRunId");this.runId=t,this.handlers=e,this.inheritableHandlers=n,this.tags=r,this.inheritableTags=o,this.metadata=i,this.inheritableMetadata=s,this._parentRunId=a}get parentRunId(){return this._parentRunId}async handleText(t){await Promise.all(this.handlers.map(e=>Na(async()=>{try{await e.handleText?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleText: ${n}`),e.raiseError)throw n}},e.awaitHandlers)))}async handleCustomEvent(t,e,n,r,o){await Promise.all(this.handlers.map(i=>Na(async()=>{try{await i.handleCustomEvent?.(t,e,this.runId,this.tags,this.metadata)}catch(s){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${s}`),i.raiseError)throw s}},i.awaitHandlers)))}},Rar=class extends Qhe{getChild(t){let e=new Ru(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleRetrieverEnd(t){await Promise.all(this.handlers.map(e=>Na(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetriever`),e.raiseError)throw n}},e.awaitHandlers)))}async handleRetrieverError(t){await Promise.all(this.handlers.map(e=>Na(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverError?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetrieverError: ${n}`),e.raiseError)throw t}},e.awaitHandlers)))}},SWt=class extends Qhe{async handleLLMNewToken(t,e,n,r,o,i){await Promise.all(this.handlers.map(s=>Na(async()=>{if(!s.ignoreLLM)try{await s.handleLLMNewToken?.(t,e??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,i)}catch(a){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMNewToken: ${a}`),s.raiseError)throw a}},s.awaitHandlers)))}async handleChatModelStreamEvent(t){await Promise.all(this.handlers.map(e=>Na(async()=>{if(!e.ignoreLLM)try{await e.handleChatModelStreamEvent?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleChatModelStreamEvent: ${n}`),e.raiseError)throw n}},e.awaitHandlers)))}async handleLLMError(t,e,n,r,o){await Promise.all(this.handlers.map(i=>Na(async()=>{if(!i.ignoreLLM)try{await i.handleLLMError?.(t,this.runId,this._parentRunId,this.tags,o)}catch(s){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMError: ${s}`),i.raiseError)throw s}},i.awaitHandlers)))}async handleLLMEnd(t,e,n,r,o){await Promise.all(this.handlers.map(i=>Na(async()=>{if(!i.ignoreLLM)try{await i.handleLLMEnd?.(t,this.runId,this._parentRunId,this.tags,o)}catch(s){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMEnd: ${s}`),i.raiseError)throw s}},i.awaitHandlers)))}},Lar=class extends Qhe{getChild(t){let e=new Ru(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleChainError(t,e,n,r,o){await Promise.all(this.handlers.map(i=>Na(async()=>{if(!i.ignoreChain)try{await i.handleChainError?.(t,this.runId,this._parentRunId,this.tags,o)}catch(s){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainError: ${s}`),i.raiseError)throw s}},i.awaitHandlers)))}async handleChainEnd(t,e,n,r,o){await Promise.all(this.handlers.map(i=>Na(async()=>{if(!i.ignoreChain)try{await i.handleChainEnd?.(t,this.runId,this._parentRunId,this.tags,o)}catch(s){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainEnd: ${s}`),i.raiseError)throw s}},i.awaitHandlers)))}async handleAgentAction(t){await Promise.all(this.handlers.map(e=>Na(async()=>{if(!e.ignoreAgent)try{await e.handleAgentAction?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentAction: ${n}`),e.raiseError)throw n}},e.awaitHandlers)))}async handleAgentEnd(t){await Promise.all(this.handlers.map(e=>Na(async()=>{if(!e.ignoreAgent)try{await e.handleAgentEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentEnd: ${n}`),e.raiseError)throw n}},e.awaitHandlers)))}},$ar=class extends Qhe{getChild(t){let e=new Ru(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleToolError(t){await Promise.all(this.handlers.map(e=>Na(async()=>{if(!e.ignoreAgent)try{await e.handleToolError?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolError: ${n}`),e.raiseError)throw n}},e.awaitHandlers)))}async handleToolEvent(t){await Promise.all(this.handlers.map(e=>Na(async()=>{if(!e.ignoreAgent)try{await e.handleToolEvent?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if(e.raiseError)throw n}},e.awaitHandlers)))}async handleToolEnd(t){await Promise.all(this.handlers.map(e=>Na(async()=>{if(!e.ignoreAgent)try{await e.handleToolEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolEnd: ${n}`),e.raiseError)throw n}},e.awaitHandlers)))}},Ru=class XY extends Nar{constructor(n,r){super();M(this,"handlers",[]);M(this,"inheritableHandlers",[]);M(this,"tags",[]);M(this,"inheritableTags",[]);M(this,"metadata",{});M(this,"inheritableMetadata",{});M(this,"name","callback_manager");M(this,"_parentRunId");this.handlers=r?.handlers??this.handlers,this.inheritableHandlers=r?.inheritableHandlers??this.inheritableHandlers,this.tags=r?.tags??this.tags,this.inheritableTags=r?.inheritableTags??this.inheritableTags,this.metadata=r?.metadata??this.metadata,this.inheritableMetadata=r?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=n}getParentRunId(){return this._parentRunId}async handleLLMStart(n,r,o=void 0,i=void 0,s=void 0,a=void 0,l=void 0,c=void 0){return Promise.all(r.map(async(u,d)=>{let f=d===0&&o?o:yb();return await Promise.all(this.handlers.map(p=>{if(!p.ignoreLLM)return Jz(p)&&p._createRunForLLMStart(n,[u],f,this._parentRunId,s,this.tags,this.metadata,c),Na(async()=>{try{await p.handleLLMStart?.(n,[u],f,this._parentRunId,s,this.tags,this.metadata,c)}catch(m){if((p.raiseError?console.error:console.warn)(`Error in handler ${p.constructor.name}, handleLLMStart: ${m}`),p.raiseError)throw m}},p.awaitHandlers)})),new SWt(f,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(n,r,o=void 0,i=void 0,s=void 0,a=void 0,l=void 0,c=void 0){return Promise.all(r.map(async(u,d)=>{let f=d===0&&o?o:yb();return await Promise.all(this.handlers.map(p=>{if(!p.ignoreLLM)return Jz(p)&&p._createRunForChatModelStart(n,[u],f,this._parentRunId,s,this.tags,this.metadata,c),Na(async()=>{try{if(p.handleChatModelStart)await p.handleChatModelStart?.(n,[u],f,this._parentRunId,s,this.tags,this.metadata,c);else if(p.handleLLMStart){let m=Mm(u);await p.handleLLMStart?.(n,[m],f,this._parentRunId,s,this.tags,this.metadata,c)}}catch(m){if((p.raiseError?console.error:console.warn)(`Error in handler ${p.constructor.name}, handleLLMStart: ${m}`),p.raiseError)throw m}},p.awaitHandlers)})),new SWt(f,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(n,r,o=yb(),i=void 0,s=void 0,a=void 0,l=void 0,c=void 0,u=void 0){return await Promise.all(this.handlers.map(d=>{if(!d.ignoreChain)return Jz(d)&&d._createRunForChainStart(n,r,o,this._parentRunId,this.tags,this.metadata,i,l,u),Na(async()=>{try{await d.handleChainStart?.(n,r,o,this._parentRunId,this.tags,this.metadata,i,l,u)}catch(f){if((d.raiseError?console.error:console.warn)(`Error in handler ${d.constructor.name}, handleChainStart: ${f}`),d.raiseError)throw f}},d.awaitHandlers)})),new Lar(o,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(n,r,o=yb(),i=void 0,s=void 0,a=void 0,l=void 0,c=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreAgent)return Jz(u)&&u._createRunForToolStart(n,r,o,this._parentRunId,this.tags,this.metadata,l),Na(async()=>{try{await u.handleToolStart?.(n,r,o,this._parentRunId,this.tags,this.metadata,l,c)}catch(d){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleToolStart: ${d}`),u.raiseError)throw d}},u.awaitHandlers)})),new $ar(o,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(n,r,o=yb(),i=void 0,s=void 0,a=void 0,l=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return Jz(c)&&c._createRunForRetrieverStart(n,r,o,this._parentRunId,this.tags,this.metadata,l),Na(async()=>{try{await c.handleRetrieverStart?.(n,r,o,this._parentRunId,this.tags,this.metadata,l)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleRetrieverStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new Rar(o,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(n,r,o,i,s){await Promise.all(this.handlers.map(a=>Na(async()=>{if(!a.ignoreCustomEvent)try{await a.handleCustomEvent?.(n,r,o,this.tags,this.metadata)}catch(l){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${l}`),a.raiseError)throw l}},a.awaitHandlers)))}addHandler(n,r=!0){this.handlers.push(n),r&&this.inheritableHandlers.push(n)}removeHandler(n){this.handlers=this.handlers.filter(r=>r!==n),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==n)}setHandlers(n,r=!0){this.handlers=[],this.inheritableHandlers=[];for(let o of n)this.addHandler(o,r)}addTags(n,r=!0){this.removeTags(n),this.tags.push(...n),r&&this.inheritableTags.push(...n)}removeTags(n){this.tags=this.tags.filter(r=>!n.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!n.includes(r))}addMetadata(n,r=!0){this.metadata={...this.metadata,...n},r&&(this.inheritableMetadata={...this.inheritableMetadata,...n})}removeMetadata(n){for(let r of Object.keys(n))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(n=[],r=!0){let o=new XY(this._parentRunId);for(let i of this.handlers){let s=this.inheritableHandlers.includes(i);o.addHandler(i,s)}for(let i of this.tags){let s=this.inheritableTags.includes(i);o.addTags([i],s)}for(let i of Object.keys(this.metadata)){let s=Object.keys(this.inheritableMetadata).includes(i);o.addMetadata({[i]:this.metadata[i]},s)}for(let i of n)o.handlers.filter(s=>s.name==="console_callback_handler").some(s=>s.name===i.name)||o.addHandler(i,r);return o}static fromHandlers(n){class r extends Pz{constructor(){super();M(this,"name",yb());Object.assign(this,n)}}let o=new this;return o.addHandler(new r),o}static configure(n,r,o,i,s,a,l){return this._configureSync(n,r,o,i,s,a,l)}static _configureSync(n,r,o,i,s,a,l){let c;(n||r)&&(Array.isArray(n)||!n?(c=new XY,c.setHandlers(n?.map(QY)??[],!0)):c=n,c=c.copy(Array.isArray(r)?r.map(QY):r?.handlers,!1));let u=Nn("LANGCHAIN_VERBOSE")==="true"||l?.verbose,d=YL.getTraceableRunTree(),f=d?.tracingEnabled??wWt();if(d?.tracingEnabled===!1&&c){let g=c.handlers.filter(v=>v.name==="langchain_tracer");for(let v of g)c.removeHandler(v)}let p=f||(Nn("LANGCHAIN_TRACING")??!1);if(u||p){if(c||(c=new XY),u&&!c.handlers.some(g=>g.name===l3e.prototype.name)){let g=new l3e;c.addHandler(g,!0)}if(p&&!c.handlers.some(g=>g.name==="langchain_tracer")&&f){let g=new YL;c.addHandler(g,!0)}f&&d&&c._parentRunId===void 0&&(c._parentRunId=d.id,c.handlers.find(g=>g.name==="langchain_tracer")?.updateFromRunTree(d))}for(let{contextVar:g,inheritable:v=!0,handlerClass:y,envVar:w}of _Wt()){let _=w&&Nn(w)==="true"&&y,S,I=g!==void 0?_3e(g):void 0;I&&tzt(I)?S=I:_&&(S=new y({})),S!==void 0&&(c||(c=new XY),c.handlers.some(C=>C.name===S.name)||c.addHandler(S,v))}(o||i)&&c&&(c.addTags(o??[]),c.addTags(i??[],!1)),(s||a)&&c&&(c.addMetadata(s??{}),c.addMetadata(a??{},!1));let m=l?.tracerInheritableMetadata,h=l?.tracerInheritableTags;if(c&&(m||h)){let g=new Map,v=y=>{if(!(y instanceof YL))return y;let w=g.get(y);if(w!==void 0)return w;let _=y.copyWithTracingConfig({metadata:m,tags:h});return g.set(y,_),_};c.handlers=c.handlers.map(v),c.inheritableHandlers=c.inheritableHandlers.map(v)}if(c){let g=Oar(c.handlers,c.inheritableHandlers);c.handlers=g.handlers,c.inheritableHandlers=g.inheritableHandlers}return c}}});var kWt,Dar,CWt,Far,xd,XL=b(()=>{NY();EA();Ghe();kWt=class{getStore(){}run(t,e){return e()}enterWith(t){}},Dar=new kWt,CWt=Symbol.for("lc:child_config"),Far=class{getInstance(){return wA()??Dar}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[CWt]}runWithConfig(t,e,n){let r=Ru._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata),o=this.getInstance(),i=o.getStore(),s=r?.getParentRunId(),a=r?.handlers?.find(c=>c?.name==="langchain_tracer"),l;return a&&s?l=a.getRunTreeWithTracingConfig(s):n||(l=new wb({name:"<runnable_lambda>",tracingEnabled:!1})),l&&(l.extra={...l.extra,[CWt]:t}),i!==void 0&&i[PL]!==void 0&&(l===void 0&&(l={}),l[PL]=i[PL]),o.run(l,e)}initializeGlobalInstance(t){wA()===void 0&&XBt(t)}},xd=new Far});var QL=b(()=>{br();NY();XL()});function Bar(t){let e=t.configurable??{},n=t.metadata??{},r={};for(let[o,i]of Object.entries(e))!o.startsWith("__")&&!Object.prototype.hasOwnProperty.call(n,o)&&!Uar.has(o)&&jar.has(typeof i)&&(r[o]=i);return Object.keys(r).length>0?r:void 0}async function Lm(t){return Ru._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata,void 0,{tracerInheritableMetadata:t?Bar(t):void 0})}function Xz(...t){let e={};for(let n of t.filter(r=>!!r))for(let r of Object.keys(n))if(r==="metadata")e[r]={...e[r],...n[r]};else if(r==="tags"){let o=e[r]??[];e[r]=[...new Set(o.concat(n[r]??[]))]}else if(r==="configurable")e[r]={...e[r],...n[r]};else if(r==="timeout")e.timeout===void 0?e.timeout=n.timeout:n.timeout!==void 0&&(e.timeout=Math.min(e.timeout,n.timeout));else if(r==="signal")e.signal===void 0?e.signal=n.signal:n.signal!==void 0&&("any"in AbortSignal?e.signal=AbortSignal.any([e.signal,n.signal]):e.signal=n.signal);else if(r==="callbacks"){let o=e.callbacks,i=n.callbacks;if(Array.isArray(i))if(!o)e.callbacks=i;else if(Array.isArray(o))e.callbacks=o.concat(i);else{let s=o.copy();for(let a of i)s.addHandler(QY(a),!0);e.callbacks=s}else if(i)if(!o)e.callbacks=i;else if(Array.isArray(o)){let s=i.copy();for(let a of o)s.addHandler(QY(a),!0);e.callbacks=s}else e.callbacks=new Ru(i._parentRunId,{handlers:o.handlers.concat(i.handlers),inheritableHandlers:o.inheritableHandlers.concat(i.inheritableHandlers),tags:Array.from(new Set(o.tags.concat(i.tags))),inheritableTags:Array.from(new Set(o.inheritableTags.concat(i.inheritableTags))),metadata:{...o.metadata,...i.metadata}})}else{let o=r;e[o]=n[o]??e[o]}return e}function wo(t){let e=xd.getRunnableConfig(),n={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(e){let{runId:r,runName:o,...i}=e;n=Object.entries(i).reduce((s,[a,l])=>(l!==void 0&&(s[a]=l),s),n)}if(t&&(n=Object.entries(t).reduce((r,[o,i])=>(i!==void 0&&(r[o]=i),r),n)),n?.configurable&&typeof n.configurable.model=="string"&&n.metadata?.model===void 0&&(n.metadata||(n.metadata={}),n.metadata.model=n.configurable.model),n.timeout!==void 0){if(n.timeout<=0)throw new Error("Timeout must be a positive number");let r=n.timeout,o=AbortSignal.timeout(r);n.metadata||(n.metadata={}),n.metadata.timeoutMs===void 0&&(n.metadata.timeoutMs=r),n.signal!==void 0?"any"in AbortSignal&&(n.signal=AbortSignal.any([n.signal,o])):n.signal=o,delete n.timeout}return n}function Ja(t={},{callbacks:e,maxConcurrency:n,recursionLimit:r,runName:o,configurable:i,runId:s}={}){let a=wo(t);return e!==void 0&&(delete a.runName,a.callbacks=e),r!==void 0&&(a.recursionLimit=r),n!==void 0&&(a.maxConcurrency=n),o!==void 0&&(a.runName=o),i!==void 0&&(a.configurable={...a.configurable,...i}),s!==void 0&&delete a.runId,a}function $m(t){if(t)return{configurable:t.configurable,recursionLimit:t.recursionLimit,callbacks:t.callbacks,tags:t.tags,metadata:t.metadata,maxConcurrency:t.maxConcurrency,timeout:t.timeout,signal:t.signal,store:t.store}}var Uar,jar,qx=b(()=>{EA();XL();QL();Uar=new Set(["api_key"]),jar=new Set(["string","number","boolean"])});async function fv(t,e){if(e===void 0)return t;let n;return Promise.race([t.catch(r=>{if(!e?.aborted)throw r}),new Promise((r,o)=>{n=()=>{o(MA(e))},e.addEventListener("abort",n,{once:!0}),e.aborted&&o(MA(e))})]).finally(()=>e.removeEventListener("abort",n))}function MA(t){return t?.reason instanceof Error?t.reason:typeof t?.reason=="string"?new Error(t.reason):new Error("Aborted")}var Qz=b(()=>{});function C3e(t,e=2){let n=Array.from({length:e},()=>[]);return n.map(async function*(o){for(;;)if(o.length===0){let i=await t.next();for(let s of n)s.push(i)}else{if(o[0].done)return;yield o.shift().value}})}function _b(t,e){if(Array.isArray(t)&&Array.isArray(e))return t.concat(e);if(typeof t=="string"&&typeof e=="string")return t+e;if(typeof t=="number"&&typeof e=="number")return t+e;if("concat"in t&&typeof t.concat=="function")return t.concat(e);if(typeof t=="object"&&typeof e=="object"){let n={...t};for(let[r,o]of Object.entries(e))r in n&&!Array.isArray(n[r])?n[r]=_b(n[r],o):n[r]=o;return n}else throw new Error(`Cannot concat ${typeof t} and ${typeof e}`)}async function IWt(t,e,n,r,...o){let i=new e1({generator:e,startSetup:n,signal:r}),s=await i.setup;return{output:t(i,s,...o),setup:s}}var Dm,e1,Kx=b(()=>{br();XL();QL();qx();Qz();Dm=class S3e extends ReadableStream{constructor(){super(...arguments);M(this,"reader")}ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{let n=await this.reader.read();return n.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:n.value}}catch(n){throw this.reader.releaseLock(),n}}async return(){if(this.ensureReader(),this.locked){let n=this.reader.cancel();this.reader.releaseLock(),await n}return{done:!0,value:void 0}}async throw(n){if(this.ensureReader(),this.locked){let r=this.reader.cancel();this.reader.releaseLock(),await r}throw n}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(n){let r=n.getReader();return new S3e({start(o){return i();function i(){return r.read().then(({done:s,value:a})=>{if(s){o.close();return}return o.enqueue(a),i()})}},cancel(){r.releaseLock()}})}static fromAsyncGenerator(n){return new S3e({async pull(r){let{value:o,done:i}=await n.next();i&&r.close(),r.enqueue(o)},async cancel(r){await n.return(r)}})}};e1=class{constructor(t){M(this,"generator");M(this,"setup");M(this,"config");M(this,"signal");M(this,"firstResult");M(this,"firstResultUsed",!1);this.generator=t.generator,this.config=t.config,this.signal=t.signal??this.config?.signal,this.setup=new Promise((e,n)=>{xd.runWithConfig($m(t.config),async()=>{this.firstResult=this.signal?fv(t.generator.next(),this.signal):t.generator.next(),t.startSetup?this.firstResult.then(t.startSetup).then(e,n):this.firstResult.then(r=>e(void 0),n)},!0)})}async next(...t){return this.signal?.throwIfAborted(),this.firstResultUsed?xd.runWithConfig($m(this.config),this.signal?async()=>fv(this.generator.next(...t),this.signal):async()=>this.generator.next(...t),!0):(this.firstResultUsed=!0,this.firstResult)}async return(t){return this.generator.return(t)}async throw(t){return this.generator.throw(t)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}}});function tge(t,e){return zar.call(t,e)}function nge(t){if(Array.isArray(t)){let n=new Array(t.length);for(let r=0;r<n.length;r++)n[r]=""+r;return n}if(Object.keys)return Object.keys(t);let e=[];for(let n in t)tge(t,n)&&e.push(n);return e}function ag(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function rge(t){let e=0,n=t.length,r;for(;e<n;){if(r=t.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}function t1(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function PWt(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function ege(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let n=0,r=t.length;n<r;n++)if(ege(t[n]))return!0}else if(typeof t=="object"){let n=nge(t),r=n.length;for(var e=0;e<r;e++)if(ege(t[n[e]]))return!0}}return!1}function TWt(t,e){let n=[t];for(let r in e){let o=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof o<"u"&&n.push(`${r}: ${o}`)}return n.join(`
`)}var zar,AWt,oge=b(()=>{zar=Object.prototype.hasOwnProperty;AWt=class extends Error{constructor(e,n,r,o,i){super(TWt(e,{name:n,index:r,operation:o,tree:i}));M(this,"name");M(this,"index");M(this,"operation");M(this,"tree");this.name=n,this.index=r,this.operation=o,this.tree=i,Object.setPrototypeOf(this,new.target.prototype),this.message=TWt(e,{name:n,index:r,operation:o,tree:i})}}});function eJ(t,e){if(e=="")return t;var n={op:"_get",path:e};return OA(t,n),n.value}function OA(t,e,n=!1,r=!0,o=!0,i=0){if(n&&(typeof n=="function"?n(e,0,t,e.path):tJ(e,0)),e.path===""){let s={newDocument:t};if(e.op==="add")return s.newDocument=e.value,s;if(e.op==="replace")return s.newDocument=e.value,s.removed=t,s;if(e.op==="move"||e.op==="copy")return s.newDocument=eJ(t,e.from),e.op==="move"&&(s.removed=t),s;if(e.op==="test"){if(s.test=t4(t,e.value),s.test===!1)throw new Xa("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return s.newDocument=t,s}else{if(e.op==="remove")return s.removed=t,s.newDocument=null,s;if(e.op==="_get")return e.value=t,s;if(n)throw new Xa("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return s}}else{r||(t=ag(t));let s=(e.path||"").split("/"),a=t,l=1,c=s.length,u,d,f;for(typeof n=="function"?f=n:f=tJ;;){if(d=s[l],d&&d.indexOf("~")!=-1&&(d=PWt(d)),o&&(d=="__proto__"||d=="prototype"&&l>0&&s[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&u===void 0&&(a[d]===void 0?u=s.slice(0,l).join("/"):l==c-1&&(u=e.path),u!==void 0&&f(e,0,t,u)),l++,Array.isArray(a)){if(d==="-")d=a.length;else{if(n&&!rge(d))throw new Xa("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);rge(d)&&(d=~~d)}if(l>=c){if(n&&e.op==="add"&&d>a.length)throw new Xa("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);let p=War[e.op].call(e,a,d,t);if(p.test===!1)throw new Xa("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return p}}else if(l>=c){let p=e4[e.op].call(e,a,d,t);if(p.test===!1)throw new Xa("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return p}if(a=a[d],n&&l<c&&(!a||typeof a!="object"))throw new Xa("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function NA(t,e,n,r=!0,o=!0){if(n&&!Array.isArray(e))throw new Xa("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(t=ag(t));let i=new Array(e.length);for(let s=0,a=e.length;s<a;s++)i[s]=OA(t,e[s],n,!0,o,s),t=i[s].newDocument;return i.newDocument=t,i}function MWt(t,e,n){let r=OA(t,e);if(r.test===!1)throw new Xa("Test operation failed","TEST_OPERATION_FAILED",n,e,t);return r.newDocument}function tJ(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t))throw new Xa("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,n);if(e4[t.op]){if(typeof t.path!="string")throw new Xa("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,n);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new Xa('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,n);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new Xa("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new Xa("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&ege(t.value))throw new Xa("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,n);if(n){if(t.op=="add"){var o=t.path.split("/").length,i=r.split("/").length;if(o!==i+1&&o!==i)throw new Xa("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,n)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==r)throw new Xa("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,n)}else if(t.op==="move"||t.op==="copy"){var s=k3e([{op:"_get",path:t.from,value:void 0}],n);if(s&&s.name==="OPERATION_PATH_UNRESOLVABLE")throw new Xa("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,n)}}}else throw new Xa("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,n)}function k3e(t,e,n){try{if(!Array.isArray(t))throw new Xa("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)NA(ag(e),ag(t),n||!0);else{n=n||tJ;for(var r=0;r<t.length;r++)n(t[r],r,e,void 0)}}catch(o){if(o instanceof Xa)return o;throw o}}function t4(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var n=Array.isArray(t),r=Array.isArray(e),o,i,s;if(n&&r){if(i=t.length,i!=e.length)return!1;for(o=i;o--!==0;)if(!t4(t[o],e[o]))return!1;return!0}if(n!=r)return!1;var a=Object.keys(t);if(i=a.length,i!==Object.keys(e).length)return!1;for(o=i;o--!==0;)if(!e.hasOwnProperty(a[o]))return!1;for(o=i;o--!==0;)if(s=a[o],!t4(t[s],e[s]))return!1;return!0}return t!==t&&e!==e}var EWt,Xa,Har,e4,War,nJ=b(()=>{br();oge();EWt=wr({JsonPatchError:()=>Xa,_areEquals:()=>t4,applyOperation:()=>OA,applyPatch:()=>NA,applyReducer:()=>MWt,deepClone:()=>Har,getValueByPointer:()=>eJ,validate:()=>k3e,validator:()=>tJ});Xa=AWt,Har=ag,e4={add:function(t,e,n){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return t[e]=this.value,{newDocument:n}},remove:function(t,e,n){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=t[e];return delete t[e],{newDocument:n,removed:r}},replace:function(t,e,n){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:function(t,e,n){let r=eJ(n,this.path);r&&(r=ag(r));let o=OA(n,{op:"remove",path:this.from}).removed;return OA(n,{op:"add",path:this.path,value:o}),{newDocument:n,removed:r}},copy:function(t,e,n){let r=eJ(n,this.from);return OA(n,{op:"add",path:this.path,value:ag(r)}),{newDocument:n}},test:function(t,e,n){return{newDocument:n,test:t4(t[e],this.value)}},_get:function(t,e,n){return this.value=t[e],{newDocument:n}}},War={add:function(t,e,n){return rge(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:n,index:e}},remove:function(t,e,n){return{newDocument:n,removed:t.splice(e,1)[0]}},replace:function(t,e,n){var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:e4.move,copy:e4.copy,test:e4.test,_get:e4._get}});function OWt(t,e,n,r,o){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var i=nge(e),s=nge(t),a=!1,l=s.length-1;l>=0;l--){var c=s[l],u=t[c];if(tge(e,c)&&!(e[c]===void 0&&u!==void 0&&Array.isArray(e)===!1)){var d=e[c];typeof u=="object"&&u!=null&&typeof d=="object"&&d!=null&&Array.isArray(u)===Array.isArray(d)?OWt(u,d,n,r+"/"+t1(c),o):u!==d&&(o&&n.push({op:"test",path:r+"/"+t1(c),value:ag(u)}),n.push({op:"replace",path:r+"/"+t1(c),value:ag(d)}))}else Array.isArray(t)===Array.isArray(e)?(o&&n.push({op:"test",path:r+"/"+t1(c),value:ag(u)}),n.push({op:"remove",path:r+"/"+t1(c)}),a=!0):(o&&n.push({op:"test",path:r,value:t}),n.push({op:"replace",path:r,value:e}))}if(!(!a&&i.length==s.length))for(var l=0;l<i.length;l++){var c=i[l];!tge(t,c)&&e[c]!==void 0&&n.push({op:"add",path:r+"/"+t1(c),value:ag(e[c])})}}}function rJ(t,e,n=!1){var r=[];return OWt(t,e,r,"",n),r}var oJ=b(()=>{oge();nJ();});var I3e=b(()=>{oge();nJ();oJ();({...EWt})});async function NWt(t,e){if(e==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");let{inputs:n}=t;if(["retriever","llm","prompt"].includes(t.run_type))return n;if(!(Object.keys(n).length===1&&n?.input===""))return n.input}async function RWt(t,e){let{outputs:n}=t;return e==="original"||["retriever","llm","prompt"].includes(t.run_type)?n:n!==void 0&&Object.keys(n).length===1&&n?.output!==void 0?n.output:n}function Var(t){return t!==void 0&&t.message!==void 0}var Qk,P3e,LWt,A3e,$Wt=b(()=>{br();Om();ZL();nJ();I3e();Kx();Qk=class{constructor(t){M(this,"ops");this.ops=t.ops??[]}concat(t){let e=this.ops.concat(t.ops),n=NA({},e);return new P3e({ops:e,state:n[n.length-1].newDocument})}},P3e=class T3e extends Qk{constructor(n){super(n);M(this,"state");this.state=n.state}concat(n){let r=this.ops.concat(n.ops),o=NA(this.state,n.ops);return new T3e({ops:r,state:o[o.length-1].newDocument})}static fromRunLogPatch(n){let r=NA({},n.ops);return new T3e({ops:n.ops,state:r[r.length-1].newDocument})}},LWt=t=>t.name==="log_stream_tracer";A3e=class extends Vx{constructor(e){super({_awaitHandler:!0,...e});M(this,"autoClose",!0);M(this,"includeNames");M(this,"includeTypes");M(this,"includeTags");M(this,"excludeNames");M(this,"excludeTypes");M(this,"excludeTags");M(this,"_schemaFormat","original");M(this,"rootId");M(this,"keyMapByRunId",{});M(this,"counterMapByRunName",{});M(this,"transformStream");M(this,"writer");M(this,"receiveStream");M(this,"name","log_stream_tracer");M(this,"lc_prefer_streaming",!0);this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Dm.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;let n=e.tags??[],r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(r=r||n.find(o=>this.includeTags?.includes(o))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(r=r&&n.every(o=>!this.excludeTags?.includes(o))),r}async*tapOutputIterable(e,n){for await(let r of n){if(e!==this.rootId){let o=this.keyMapByRunId[e];o&&await this.writer.write(new Qk({ops:[{op:"add",path:`/logs/${o}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new Qk({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;let n=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=n===1?e.name:`${e.name}:${n}`;let r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(r.inputs=await NWt(e,this._schemaFormat)),await this.writer.write(new Qk({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{let n=this.keyMapByRunId[e.id];if(n===void 0)return;let r=[];this._schemaFormat==="streaming_events"&&r.push({op:"replace",path:`/logs/${n}/inputs`,value:await NWt(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${n}/final_output`,value:await RWt(e,this._schemaFormat)}),e.end_time!==void 0&&r.push({op:"add",path:`/logs/${n}/end_time`,value:new Date(e.end_time).toISOString()});let o=new Qk({ops:r});await this.writer.write(o)}finally{if(e.id===this.rootId){let n=new Qk({ops:[{op:"replace",path:"/final_output",value:await RWt(e,this._schemaFormat)}]});await this.writer.write(n),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,n,r){let o=this.keyMapByRunId[e.id];if(o===void 0)return;let i=e.inputs.messages!==void 0,s;i?Var(r?.chunk)?s=r?.chunk:s=new On({id:`run-${e.id}`,content:n}):s=n;let a=new Qk({ops:[{op:"add",path:`/logs/${o}/streamed_output_str/-`,value:n},{op:"add",path:`/logs/${o}/streamed_output/-`,value:s}]});await this.writer.write(a)}}});var iJ,eI,di,Sd=b(()=>{br();iJ="__run",eI=class DWt{constructor(e){M(this,"text");M(this,"generationInfo");this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new DWt({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}},di=class FWt extends eI{constructor(n){super(n);M(this,"message");this.message=n.message}concat(n){return new FWt({text:this.text+n.text,generationInfo:{...this.generationInfo,...n.generationInfo},message:this.message.concat(n.message)})}}});function ige({name:t,serialized:e}){return t!==void 0?t:e?.name!==void 0?e.name:e?.id!==void 0&&Array.isArray(e?.id)?e.id[e.id.length-1]:"Unnamed"}var UWt,jWt,BWt=b(()=>{Om();ZL();Kx();Sd();UWt=t=>t.name==="event_stream_tracer",jWt=class extends Vx{constructor(e){super({_awaitHandler:!0,...e});M(this,"autoClose",!0);M(this,"includeNames");M(this,"includeTypes");M(this,"includeTags");M(this,"excludeNames");M(this,"excludeTypes");M(this,"excludeTags");M(this,"runInfoMap",new Map);M(this,"tappedPromises",new Map);M(this,"transformStream");M(this,"writer");M(this,"receiveStream");M(this,"readableStreamClosed",!1);M(this,"name","event_stream_tracer");M(this,"lc_prefer_streaming",!0);this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Dm.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){let n=e.tags??[],r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(r=r||n.find(o=>this.includeTags?.includes(o))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(r=r&&n.every(o=>!this.excludeTags?.includes(o))),r}async*tapOutputIterable(e,n){let r=await n.next();if(r.done)return;let o=this.runInfoMap.get(e);if(o===void 0){yield r.value;return}function i(a,l){return a==="llm"&&typeof l=="string"?new eI({text:l}):l}let s=this.tappedPromises.get(e);if(s===void 0){let a;s=new Promise(l=>{a=l}),this.tappedPromises.set(e,s);try{let l={event:`on_${o.runType}_stream`,run_id:e,name:o.name,tags:o.tags,metadata:o.metadata,data:{}};await this.send({...l,data:{chunk:i(o.runType,r.value)}},o),yield r.value;for await(let c of n)o.runType!=="tool"&&o.runType!=="retriever"&&await this.send({...l,data:{chunk:i(o.runType,c)}},o),yield c}finally{a?.()}}else{yield r.value;for await(let a of n)yield a}}async send(e,n){this.readableStreamClosed||this._includeRun(n)&&await this.writer.write(e)}async sendEndEvent(e,n){let r=this.tappedPromises.get(e.run_id);r!==void 0?r.then(()=>{this.send(e,n)}):await this.send(e,n)}async onLLMStart(e){let n=ige(e),r=e.inputs.messages!==void 0?"chat_model":"llm",o={tags:e.tags??[],metadata:e.extra?.metadata??{},name:n,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,o);let i=`on_${r}_start`;await this.send({event:i,data:{input:e.inputs},name:n,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},o)}async onLLMNewToken(e,n,r){let o=this.runInfoMap.get(e.id),i,s;if(o===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(o.runType==="chat_model")s="on_chat_model_stream",r?.chunk===void 0?i=new On({content:n,id:`run-${e.id}`}):i=r.chunk.message;else if(o.runType==="llm")s="on_llm_stream",r?.chunk===void 0?i=new eI({text:n}):i=r.chunk;else throw new Error(`Unexpected run type ${o.runType}`);await this.send({event:s,data:{chunk:i},run_id:e.id,name:o.name,tags:o.tags,metadata:o.metadata},o)}}async onLLMEnd(e){let n=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let r;if(n===void 0)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);let o=e.outputs?.generations,i;if(n.runType==="chat_model"){for(let s of o??[]){if(i!==void 0)break;i=s[0]?.message}r="on_chat_model_end"}else if(n.runType==="llm")i={generations:o?.map(s=>s.map(a=>({text:a.text,generationInfo:a.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},r="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${n.runType}`);await this.sendEndEvent({event:r,data:{output:i,input:n.inputs},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async onChainStart(e){let n=ige(e),r=e.run_type??"chain",o={tags:e.tags??[],metadata:e.extra?.metadata??{},name:n,runType:e.run_type},i={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(i={},o.inputs={}):e.inputs.input!==void 0?(i.input=e.inputs.input,o.inputs=e.inputs.input):(i.input=e.inputs,o.inputs=e.inputs),this.runInfoMap.set(e.id,o),await this.send({event:`on_${r}_start`,data:i,name:n,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},o)}async onChainEnd(e){let n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),n===void 0)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);let r=`on_${e.run_type}_end`,o=e.inputs??n.inputs??{},i={output:e.outputs?.output??e.outputs,input:o};o.input&&Object.keys(o).length===1&&(i.input=o.input,n.inputs=o.input),await this.sendEndEvent({event:r,data:i,run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata??{}},n)}async onToolStart(e){let n=ige(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:n,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:n,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},r)}async onToolEnd(e){let n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),n===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(n.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);let r=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:n.inputs},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async onToolError(e){let n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),n===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(n.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);await this.sendEndEvent({event:"on_tool_error",data:{input:n.inputs,error:e.error},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async onRetrieverStart(e){let n=ige(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:n,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,r),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:n,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onRetrieverEnd(e){let n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),n===void 0)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:n.inputs},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async handleCustomEvent(e,n,r){let o=this.runInfoMap.get(r);if(o===void 0)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:o.tags,metadata:o.metadata,data:n},o)}async finish(){let e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}}});function zWt(t){if(!(t&&Kar(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;let{message:e,stack:n}=t;return e==="Load failed"?n===void 0||"__sentry_captured__"in t:e.startsWith("error sending request for url")?!0:Gar.has(e)}var qar,Kar,Gar,HWt=b(()=>{qar=Object.prototype.toString,Kar=t=>qar.call(t)==="[object Error]",Gar=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"])});function Zar(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function sge(t,e,{min:n=0,allowInfinity:r=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${t}\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(e))throw new TypeError(`Expected \`${t}\` to be a finite number.`);if(e<n)throw new TypeError(`Expected \`${t}\` to be \u2265 ${n}.`)}}function Jar(t,e){let n=Math.max(1,t+1),r=e.randomize?Math.random()+1:1,o=Math.round(r*e.minTimeout*e.factor**(n-1));return o=Math.min(o,e.maxTimeout),o}function WWt(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}async function Xar({error:t,attemptNumber:e,retriesConsumed:n,startTime:r,options:o}){let i=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(i instanceof Yar)throw i.originalError;let s=Number.isFinite(o.retries)?Math.max(0,o.retries-n):o.retries,a=o.maxRetryTime??Number.POSITIVE_INFINITY,l=Object.freeze({error:i,attemptNumber:e,retriesLeft:s,retriesConsumed:n});if(await o.onFailedAttempt(l),WWt(r,a)<=0)throw i;let c=await o.shouldConsumeRetry(l),u=WWt(r,a);if(u<=0||s<=0)throw i;if(i instanceof TypeError&&!zWt(i)){if(c)throw i;return o.signal?.throwIfAborted(),!1}if(!await o.shouldRetry(l))throw i;if(!c)return o.signal?.throwIfAborted(),!1;let d=Jar(n,o),f=typeof i.retryAfterMs=="number"&&i.retryAfterMs>=0?i.retryAfterMs:void 0;f!==void 0&&(d=Math.max(d,f));let p=Math.min(d,u);return p>0&&await new Promise((m,h)=>{let g=()=>{clearTimeout(v),o.signal?.removeEventListener("abort",g),h(o.signal.reason)},v=setTimeout(()=>{o.signal?.removeEventListener("abort",g),m()},p);o.unref&&v.unref?.(),o.signal?.addEventListener("abort",g,{once:!0})}),o.signal?.throwIfAborted(),!0}async function sJ(t,e={}){if(e={...e},Zar(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??(e.retries=10),e.factor??(e.factor=2),e.minTimeout??(e.minTimeout=1e3),e.maxTimeout??(e.maxTimeout=Number.POSITIVE_INFINITY),e.maxRetryTime??(e.maxRetryTime=Number.POSITIVE_INFINITY),e.randomize??(e.randomize=!1),e.onFailedAttempt??(e.onFailedAttempt=()=>{}),e.shouldRetry??(e.shouldRetry=()=>!0),e.shouldConsumeRetry??(e.shouldConsumeRetry=()=>!0),sge("factor",e.factor,{min:0,allowInfinity:!1}),sge("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),sge("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),sge("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let n=0,r=0,o=performance.now();for(;!Number.isFinite(e.retries)||r<=e.retries;){n++;try{e.signal?.throwIfAborted();let i=await t(n);return e.signal?.throwIfAborted(),i}catch(i){await Xar({error:i,attemptNumber:n,retriesConsumed:r,startTime:o,options:e})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Yar,E3e=b(()=>{HWt();Yar=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}}});function qWt(t){return typeof t=="object"&&t!==null&&"response"in t&&typeof t.response=="object"&&t.response!==null&&"status"in t.response&&typeof t.response.status=="number"?t.response.status:void 0}function KWt(t){if(!(typeof t!="object"||t===null)){if("status"in t&&typeof t.status=="number")return t.status;if("statusCode"in t&&typeof t.statusCode=="number")return t.statusCode}}function O3e(t){return typeof t=="object"&&t!==null&&"message"in t&&typeof t.message=="string"?t.message:void 0}function GWt(t){if(!(typeof t!="object"||t===null))return"code"in t&&typeof t.code=="string"?t.code:"error"in t&&typeof t.error=="object"&&t.error!==null&&"code"in t.error&&typeof t.error.code=="string"?t.error.code:void 0}function rlr(t){if(t?.headers)return typeof t.headers.get=="function"?t.headers.get("retry-after"):t.headers["retry-after"]??t.headers["Retry-After"];if(t?.response?.headers)return typeof t.response.headers.get=="function"?t.response.headers.get("retry-after"):t.response.headers["retry-after"]??t.response.headers["Retry-After"]}function olr(t){if(t==null)return;let e=nlr.exec(t);if(!e)return;let n=Number(e[1]),r=e[2]?.toLowerCase();if(!(Number.isNaN(n)||!r))return r==="ms"||r.startsWith("millisecond")?n:r==="m"||r.startsWith("min")?n*6e4:r==="h"||r.startsWith("hr")||r.startsWith("hour")?n*36e5:n*1e3}function VWt(t,e){if(t instanceof Error)return t;let n=new Error(e);return typeof t=="object"&&t!==null&&Object.assign(n,t),n}function M3e(t,e){if(typeof t!="object"||t===null)return;let n=t;n.rateLimitType=e.action,n.rateLimitReason=e.reason,e.retryAfterMs!==void 0&&(n.retryAfterMs=e.retryAfterMs)}function ilr(t){if(t==null)return;let e=t.trim();if(!e)return;let n=Number(e);if(!Number.isNaN(n)&&n>=0)return n*1e3;let r=Date.parse(e);if(!Number.isNaN(r)){let o=r-Date.now();return o>0?o:0}}function slr(t){if((qWt(t)??KWt(t))!==429)return;if(GWt(t)==="insufficient_quota")return{action:"stop",reason:"insufficient_quota"};let e=O3e(t);if(e&&tlr.some(r=>r.test(e)))return{action:"stop",reason:"quota_message"};let n=ilr(rlr(t))??olr(e);return n!==void 0?n<=elr?{action:"wait",retryAfterMs:n,reason:"retry_after_hint"}:{action:"capacity",retryAfterMs:n,reason:"retry_after_too_large"}:{action:"capacity",reason:"headerless_429"}}var age,Qar,elr,tlr,nlr,alr,RA,aJ=b(()=>{br();Kk();Qz();E3e();age=L(w3e(),1),Qar=[400,401,402,403,404,405,406,407,409,413],elr=6e4,tlr=[/insufficient[_ -]?quota/i,/exceeded (?:your|the current|the available).+quota/i,/usage quota/i,/quota (?:has been )?exhausted/i,/billing/i,/credit balance/i,/out of credits/i,/will reset at/i],nlr=/(?:try again in|retry after)\s+(\d+(?:\.\d+)?)\s*(milliseconds?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h)\b/i;alr=t=>{if(typeof t!="object"||t===null)return;if(kBt(t)===!1)throw t;if("message"in t&&typeof t.message=="string"&&(t.message.startsWith("Cancel")||t.message.startsWith("AbortError"))||"name"in t&&typeof t.name=="string"&&t.name==="AbortError")throw Gl(t,!1);if("code"in t&&typeof t.code=="string"&&t.code==="ECONNABORTED")throw t;let e=qWt(t)??KWt(t);if(e&&Qar.includes(+e))throw Gl(t,!1);if(GWt(t)==="insufficient_quota"){let r=VWt(t,O3e(t)??"Insufficient quota");throw r.name="InsufficientQuotaError",M3e(r,{action:"stop",reason:"insufficient_quota"}),Gl(r,!1)}let n=slr(t);if(n){if(n.action==="wait"){M3e(t,n),Gl(t,!0);return}let r=VWt(t,O3e(t)??"Rate limit exceeded");throw r.name==="Error"&&(r.name=n.action==="stop"?"RateLimitQuotaExhaustedError":"RateLimitCapacityError"),M3e(r,n),Gl(r,n.action!=="stop")}},RA=class{constructor(t){M(this,"maxConcurrency");M(this,"maxRetries");M(this,"onFailedAttempt");M(this,"queue");this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,this.onFailedAttempt=t.onFailedAttempt??alr;let e="default"in age.default?age.default.default:age.default;this.queue=new e({concurrency:this.maxConcurrency})}async call(t,...e){return this.callWithRetries(this.maxRetries,t,e)}callWithRetries(t,e,n){return this.queue.add(()=>sJ(()=>e(...n).catch(r=>{throw r instanceof Error?r:new Error(r)}),{onFailedAttempt:({error:r})=>this.onFailedAttempt?.(r),retries:t,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(t,e,...n){let r=t.maxRetries??this.maxRetries;if(t.signal){let o;return Promise.race([this.callWithRetries(r,e,n),new Promise((i,s)=>{o=()=>{s(MA(t.signal))},t.signal?.addEventListener("abort",o,{once:!0})})]).finally(()=>{t.signal&&o&&t.signal.removeEventListener("abort",o)})}return this.callWithRetries(r,e,n)}fetch(...t){return this.call(()=>fetch(...t).then(e=>e.ok?e:Promise.reject(e)))}}});var N3e,ZWt=b(()=>{ZL();N3e=class extends Vx{constructor({config:e,onStart:n,onEnd:r,onError:o}){super({_awaitHandler:!0});M(this,"name","RootListenersTracer");M(this,"rootId");M(this,"config");M(this,"argOnStart");M(this,"argOnEnd");M(this,"argOnError");this.config=e,this.argOnStart=n,this.argOnEnd=r,this.argOnError=o}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}}});function lJ(t){return t?t.lc_runnable:!1}var YWt,JWt,lge=b(()=>{YWt=class{constructor(t){M(this,"includeNames");M(this,"includeTypes");M(this,"includeTags");M(this,"excludeNames");M(this,"excludeTypes");M(this,"excludeTags");this.includeNames=t.includeNames,this.includeTypes=t.includeTypes,this.includeTags=t.includeTags,this.excludeNames=t.excludeNames,this.excludeTypes=t.excludeTypes,this.excludeTags=t.excludeTags}includeEvent(t,e){let n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,r=t.tags??[];return this.includeNames!==void 0&&(n=n||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(e)),this.includeTags!==void 0&&(n=n||r.some(o=>this.includeTags?.includes(o))),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(e)),this.excludeTags!==void 0&&(n=n&&r.every(o=>!this.excludeTags?.includes(o))),n}},JWt=t=>btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")});function R3e(t){return t.replace(/[^a-zA-Z-_0-9]/g,"_")}function clr(t){let e="";for(let[n,r]of Object.entries(t))e+=` classDef ${n} ${r};
`;return e}function XWt(t,e,n){let{firstNode:r,lastNode:o,nodeColors:i,withStyles:s=!0,curveStyle:a="linear",wrapLabelNWords:l=9}=n??{},c=s?`%%{init: {'flowchart': {'curve': '${a}'}}}%%
graph TD;
`:`graph TD;
`;if(s){let m="default",h={[m]:"{0}({1})"};r!==void 0&&(h[r]="{0}([{1}]):::first"),o!==void 0&&(h[o]="{0}([{1}]):::last");for(let[g,v]of Object.entries(t)){let y=v.name.split(":").pop()??"",w=llr.some(S=>y.startsWith(S)&&y.endsWith(S))?`<p>${y}</p>`:y;Object.keys(v.metadata??{}).length&&(w+=`<hr/><small><em>${Object.entries(v.metadata??{}).map(([S,I])=>`${S} = ${I}`).join(`
`)}</em></small>`);let _=(h[g]??h[m]).replace("{0}",R3e(g)).replace("{1}",w);c+=` ${_}
`}}let u={};for(let m of e){let h=m.source.split(":"),g=m.target.split(":"),v=h.filter((y,w)=>y===g[w]).join(":");u[v]||(u[v]=[]),u[v].push(m)}let d=new Set;function f(m){return[...m].sort((h,g)=>h.split(":").length-g.split(":").length)}function p(m,h){let g=m.length===1&&m[0].source===m[0].target;if(h&&!g){let y=h.split(":").pop();if(d.has(h))throw new Error(`Found duplicate subgraph '${y}' at '${h} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(h),c+=` subgraph ${y}
`}let v=f(Object.keys(u).filter(y=>y.startsWith(`${h}:`)&&y!==h&&y.split(":").length===h.split(":").length+1));for(let y of v)p(u[y],y);for(let y of m){let{source:w,target:_,data:S,conditional:I}=y,C="";if(S!==void 0){let k=S,T=k.split(" ");T.length>l&&(k=Array.from({length:Math.ceil(T.length/l)},(P,E)=>T.slice(E*l,(E+1)*l).join(" ")).join("&nbsp;<br>&nbsp;")),C=I?` -. &nbsp;${k}&nbsp; .-> `:` -- &nbsp;${k}&nbsp; --> `}else C=I?" -.-> ":" --> ";c+=` ${R3e(w)}${C}${R3e(_)};
`}h&&!g&&(c+=` end
`)}p(u[""]??[],"");for(let m in u)!m.includes(":")&&m!==""&&p(u[m],m);return s&&(c+=clr(i??{})),c}async function QWt(t,e){let n=e?.backgroundColor??"white",r=e?.imageType??"png",o=JWt(t);n!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(n)||(n=`!${n}`));let i=`https://mermaid.ink/img/${o}?bgColor=${n}&type=${r}`,s=await fetch(i);if(!s.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${s.status}`,`Status text: ${s.statusText}`].join(`
`));return await s.blob()}var llr,e6t=b(()=>{lge();llr=["*","_","`"]});function ulr(t,e){if(t!==void 0&&!OY(t))return t;if(lJ(e))try{let n=e.getName();return n=n.startsWith("Runnable")?n.slice(8):n,n}catch{return e.getName()}else return e.name??"UnknownSchema"}function dlr(t){return lJ(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{...Ki(t.data.schema),title:t.data.name}}}function t6t(t,e=[]){let n=new Set(t.edges.filter(o=>!e.includes(o.source)).map(o=>o.target)),r=[];for(let o of Object.values(t.nodes))!e.includes(o.id)&&!n.has(o.id)&&r.push(o);return r.length===1?r[0]:void 0}function n6t(t,e=[]){let n=new Set(t.edges.filter(o=>!e.includes(o.target)).map(o=>o.source)),r=[];for(let o of Object.values(t.nodes))!e.includes(o.id)&&!n.has(o.id)&&r.push(o);return r.length===1?r[0]:void 0}var L3e,o6t=b(()=>{br();TL();lge();e6t();tg();L3e=class r6t{constructor(e){M(this,"nodes",{});M(this,"edges",[]);this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){let e={};return Object.values(this.nodes).forEach((n,r)=>{e[n.id]=OY(n.id)?r:n.id}),{nodes:Object.values(this.nodes).map(n=>({id:e[n.id],...dlr(n)})),edges:this.edges.map(n=>{let r={source:e[n.source],target:e[n.target]};return typeof n.data<"u"&&(r.data=n.data),typeof n.conditional<"u"&&(r.conditional=n.conditional),r})}}addNode(e,n,r){if(n!==void 0&&this.nodes[n]!==void 0)throw new Error(`Node with id ${n} already exists`);let o=n??IL(),i={id:o,data:e,name:ulr(n,e),metadata:r};return this.nodes[o]=i,i}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(n=>n.source!==e.id&&n.target!==e.id)}addEdge(e,n,r,o){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[n.id]===void 0)throw new Error(`Target node ${n.id} not in graph`);let i={source:e.id,target:n.id,data:r,conditional:o};return this.edges.push(i),i}firstNode(){return t6t(this)}lastNode(){return n6t(this)}extend(e,n=""){let r=n;Object.values(e.nodes).map(l=>l.id).every(OY)&&(r="");let o=l=>r?`${r}:${l}`:l;Object.entries(e.nodes).forEach(([l,c])=>{this.nodes[o(l)]={...c,id:o(l)}});let i=e.edges.map(l=>({...l,source:o(l.source),target:o(l.target)}));this.edges=[...this.edges,...i];let s=e.firstNode(),a=e.lastNode();return[s?{id:o(s.id),data:s.data}:void 0,a?{id:o(a.id),data:a.data}:void 0]}trimFirstNode(){let e=this.firstNode();e&&t6t(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&n6t(this,[e.id])&&this.removeNode(e)}reid(){let e=Object.fromEntries(Object.values(this.nodes).map(o=>[o.id,o.name])),n=new Map;Object.values(e).forEach(o=>{n.set(o,(n.get(o)||0)+1)});let r=o=>{let i=e[o];return OY(o)&&n.get(i)===1?i:o};return new r6t({nodes:Object.fromEntries(Object.entries(this.nodes).map(([o,i])=>[r(o),{...i,id:r(o)}])),edges:this.edges.map(o=>({...o,source:r(o.source),target:r(o.target)}))})}drawMermaid(e){let{withStyles:n,curveStyle:r,nodeColors:o={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:i}=e??{},s=this.reid(),a=s.firstNode(),l=s.lastNode();return XWt(s.nodes,s.edges,{firstNode:a?.id,lastNode:l?.id,withStyles:n,curveStyle:r,nodeColors:o,wrapLabelNWords:i})}async drawMermaidPng(e){return QWt(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}}});function i6t(t){let e=new TextEncoder,n=new ReadableStream({async start(r){for await(let o of t)r.enqueue(e.encode(`event: data
data: ${JSON.stringify(o)}
`));r.enqueue(e.encode(`event: end
`)),r.close()}});return Dm.fromReadableStream(n)}var s6t=b(()=>{Kx()});function $3e(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}function cge(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function D3e(t){return t!=null&&typeof t=="object"&&typeof t.next=="function"}async function l6t(t,e){try{let n=await t.next();for(;!n.done;)await e?.(n.value),n=await t.next();return n.value}finally{await t.return?.(void 0)}}function*F3e(t,e){for(;;){let{value:n,done:r}=xd.runWithConfig($m(t),e.next.bind(e),!0);if(r)break;yield n}}async function*uge(t,e){let n=e[Symbol.asyncIterator]();for(;;){let{value:r,done:o}=await xd.runWithConfig($m(t),n.next.bind(e),!0);if(o)break;yield r}}var a6t,U3e=b(()=>{XL();QL();qx();a6t=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function"});function Vc(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function plr(t){if(lhe(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}function tI(t){if(typeof t=="function")return new nI({func:t});if(Uo.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=tI(r);return new n4({steps:e})}else throw new Error(`Expected a Runnable, function or object.
Instead got an unsupported type.`)}function mlr(t,e){let n=e.name??t.getName(),r=e.description??Fk(e.schema);return fY(e.schema)?new j3e({name:n,description:r,schema:Qh.object({input:Qh.string()}).transform(o=>o.input),bound:t}):new j3e({name:n,description:r,schema:e.schema,bound:t})}var Uo,n1,B3e,r1,n4,flr,nI,p6t,dge,m6t,j3e,Lu=b(()=>{Vme();SL();TL();XL();QL();qx();Qz();Kx();$Wt();BWt();E3e();aJ();ZWt();lge();Px();o6t();s6t();U3e();f3e();Ox();Uo=class extends av{constructor(){super(...arguments);M(this,"lc_runnable",!0);M(this,"name")}getName(e){let n=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${n}${e}`:n}withRetry(e){return new B3e({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new n1({bound:this,config:e,kwargs:{}})}withFallbacks(e){let n=Array.isArray(e)?e:e.fallbacks;return new p6t({runnable:this,fallbacks:n})}_getOptionsList(e,n=0){if(Array.isArray(e)&&e.length!==n)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${n} inputs`);if(Array.isArray(e))return e.map(wo);if(n>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");let r=Object.fromEntries(Object.entries(e).filter(([o])=>o!=="runId"));return Array.from({length:n},(o,i)=>wo(i===0?e:r))}return Array.from({length:n},()=>wo(e))}async batch(e,n,r){let o=this._getOptionsList(n??{},e.length),i=new RA({maxConcurrency:o[0]?.maxConcurrency??r?.maxConcurrency,onFailedAttempt:a=>{throw a}}),s=e.map((a,l)=>i.call(async()=>{try{return await this.invoke(a,o[l])}catch(c){if(r?.returnExceptions)return c;throw c}}));return Promise.all(s)}async*_streamIterator(e,n){yield this.invoke(e,n)}async stream(e,n){let r=wo(n),o=new e1({generator:this._streamIterator(e,r),config:r});return await o.setup,Dm.fromAsyncGenerator(o)}_separateRunnableConfigFromCallOptions(e){let n;e===void 0?n=wo(e):n=wo({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});let r={...e};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[n,r]}async _callWithConfig(e,n,r){let o=wo(r),i=await(await Lm(o))?.handleChainStart(this.toJSON(),Vc(n,"input"),o.runId,o?.runType,void 0,void 0,o?.runName??this.getName());delete o.runId;let s;try{s=await fv(e.call(this,n,o,i),o.signal)}catch(a){throw await i?.handleChainError(a),a}return await i?.handleChainEnd(Vc(s,"output")),s}async _batchWithConfig(e,n,r,o){let i=this._getOptionsList(r??{},n.length),s=await Promise.all(i.map(Lm)),a=await Promise.all(s.map(async(c,u)=>{let d=await c?.handleChainStart(this.toJSON(),Vc(n[u],"input"),i[u].runId,i[u].runType,void 0,void 0,i[u].runName??this.getName());return delete i[u].runId,d})),l;try{l=await fv(e.call(this,n,i,a,o),i?.[0]?.signal)}catch(c){throw await Promise.all(a.map(u=>u?.handleChainError(c))),c}return await Promise.all(a.map(c=>c?.handleChainEnd(Vc(l,"output")))),l}_concatOutputChunks(e,n){return _b(e,n)}async*_transformStreamWithConfig(e,n,r){let o,i=!0,s,a=!0,l=wo(r),c=await Lm(l),u=this;async function*d(){for await(let p of e){if(i)if(o===void 0)o=p;else try{o=u._concatOutputChunks(o,p)}catch{o=void 0,i=!1}yield p}}let f;try{let p=await IWt(n.bind(this),d(),async()=>c?.handleChainStart(this.toJSON(),{input:""},l.runId,l.runType,void 0,void 0,l.runName??this.getName(),void 0,{lc_defers_inputs:!0}),l.signal,l);delete l.runId,f=p.setup;let m=f?.handlers.find(UWt),h=p.output;m!==void 0&&f!==void 0&&(h=m.tapOutputIterable(f.runId,h));let g=f?.handlers.find(LWt);g!==void 0&&f!==void 0&&(h=g.tapOutputIterable(f.runId,h));for await(let v of h)if(yield v,a)if(s===void 0)s=v;else try{s=this._concatOutputChunks(s,v)}catch{s=void 0,a=!1}}catch(p){throw await f?.handleChainError(p,void 0,void 0,void 0,{inputs:Vc(o,"input")}),p}await f?.handleChainEnd(s??{},void 0,void 0,void 0,{inputs:Vc(o,"input")})}getGraph(e){let n=new L3e,r=n.addNode({name:`${this.getName()}Input`,schema:Qh.any()}),o=n.addNode(this),i=n.addNode({name:`${this.getName()}Output`,schema:Qh.any()});return n.addEdge(r,o),n.addEdge(o,i),n}pipe(e){return new r1({first:this,last:tI(e)})}pick(e){return this.pipe(new m6t(e))}assign(e){return this.pipe(new dge(new n4({steps:e})))}async*transform(e,n){let r;for await(let o of e)r===void 0?r=o:r=this._concatOutputChunks(r,o);yield*this._streamIterator(r,wo(n))}async*streamLog(e,n,r){let o=new A3e({...r,autoClose:!1,_schemaFormat:"original"}),i=wo(n);yield*this._streamLog(e,o,i)}async*_streamLog(e,n,r){let{callbacks:o}=r;if(o===void 0)r.callbacks=[n];else if(Array.isArray(o))r.callbacks=o.concat([n]);else{let l=o.copy();l.addHandler(n,!0),r.callbacks=l}let i=this.stream(e,r);async function s(){try{let l=await i;for await(let c of l){let u=new Qk({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await n.writer.write(u)}}finally{await n.writer.close()}}let a=s();try{for await(let l of n)yield l}finally{await a}}streamEvents(e,n,r){let o;if(n.version==="v1")o=this._streamEventsV1(e,n,r);else if(n.version==="v2")o=this._streamEventsV2(e,n,r);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return n.encoding==="text/event-stream"?i6t(o):Dm.fromAsyncGenerator(o)}async*_streamEventsV2(e,n,r){let o=new jWt({...r,autoClose:!1}),i=wo(n),s=i.runId??yb();i.runId=s;let a=i.callbacks;if(a===void 0)i.callbacks=[o];else if(Array.isArray(a))i.callbacks=a.concat(o);else{let m=a.copy();m.addHandler(o,!0),i.callbacks=m}let l=new AbortController,c=this;async function u(){let m;try{if(i.signal)if("any"in AbortSignal)m=AbortSignal.any([l.signal,i.signal]);else{let v=new AbortController;i.signal.addEventListener("abort",()=>v.abort(),{once:!0}),l.signal.addEventListener("abort",()=>v.abort(),{once:!0}),m=v.signal}else m=l.signal;let h=await c.stream(e,{...i,signal:m}),g=o.tapOutputIterable(s,h);for await(let v of g)if(l.signal.aborted)break}finally{await o.finish()}}let d=u(),f=!1,p;try{for await(let m of o){if(!f){m.data.input=e,f=!0,p=m.run_id,yield m;continue}m.run_id===p&&m.event.endsWith("_end")&&m.data?.input&&delete m.data.input,yield m}}finally{l.abort(),await d}}async*_streamEventsV1(e,n,r){let o,i=!1,s=wo(n),a=s.tags??[],l=s.metadata??{},c=s.runName??this.getName(),u=new A3e({...r,autoClose:!1,_schemaFormat:"streaming_events"}),d=new YWt({...r}),f=this._streamLog(e,u,s);for await(let m of f){if(o?o=o.concat(m):o=P3e.fromRunLogPatch(m),o.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!i){i=!0;let y={...o.state},w={run_id:y.id,event:`on_${y.type}_start`,name:c,tags:a,metadata:l,data:{input:e}};d.includeEvent(w,y.type)&&(yield w)}let h=m.ops.filter(y=>y.path.startsWith("/logs/")).map(y=>y.path.split("/")[2]),g=[...new Set(h)];for(let y of g){let w,_={},S=o.state.logs[y];if(S.end_time===void 0?S.streamed_output.length>0?w="stream":w="start":w="end",w==="start")S.inputs!==void 0&&(_.input=S.inputs);else if(w==="end")S.inputs!==void 0&&(_.input=S.inputs),_.output=S.final_output;else if(w==="stream"){let I=S.streamed_output.length;if(I!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${I} instead. Encountered in: "${S.name}"`);_={chunk:S.streamed_output[0]},S.streamed_output=[]}yield{event:`on_${S.type}_${w}`,name:S.name,run_id:S.id,tags:S.tags,metadata:S.metadata,data:_}}let{state:v}=o;if(v.streamed_output.length>0){let y=v.streamed_output.length;if(y!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${y} instead. Encountered in: "${v.name}"`);let w={chunk:v.streamed_output[0]};v.streamed_output=[];let _={event:`on_${v.type}_stream`,run_id:v.id,tags:a,metadata:l,name:c,data:w};d.includeEvent(_,v.type)&&(yield _)}}let p=o?.state;if(p!==void 0){let m={event:`on_${p.type}_end`,name:c,run_id:p.id,tags:a,metadata:l,data:{output:p.final_output}};d.includeEvent(m,p.type)&&(yield m)}}static isRunnable(e){return lJ(e)}withListeners({onStart:e,onEnd:n,onError:r}){return new n1({bound:this,config:{},configFactories:[o=>({callbacks:[new N3e({config:o,onStart:e,onEnd:n,onError:r})]})]})}asTool(e){return mlr(this,e)}},n1=class c6t extends Uo{constructor(n){super(n);M(this,"lc_namespace",["langchain_core","runnables"]);M(this,"lc_serializable",!0);M(this,"bound");M(this,"config");M(this,"kwargs");M(this,"configFactories");this.bound=n.bound,this.kwargs=n.kwargs,this.config=n.config,this.configFactories=n.configFactories}static lc_name(){return"RunnableBinding"}getName(n){return this.bound.getName(n)}async _mergeConfig(...n){let r=Xz(this.config,...n);return Xz(r,...this.configFactories?await Promise.all(this.configFactories.map(async o=>await o(r))):[])}withConfig(n){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...n}})}withRetry(n){return new B3e({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:n?.stopAfterAttempt,...n})}async invoke(n,r){return this.bound.invoke(n,await this._mergeConfig(r,this.kwargs))}async batch(n,r,o){let i=Array.isArray(r)?await Promise.all(r.map(async s=>this._mergeConfig(wo(s),this.kwargs))):await this._mergeConfig(wo(r),this.kwargs);return this.bound.batch(n,i,o)}_concatOutputChunks(n,r){return this.bound._concatOutputChunks(n,r)}async*_streamIterator(n,r){yield*this.bound._streamIterator(n,await this._mergeConfig(wo(r),this.kwargs))}async stream(n,r){return this.bound.stream(n,await this._mergeConfig(wo(r),this.kwargs))}async*transform(n,r){yield*this.bound.transform(n,await this._mergeConfig(wo(r),this.kwargs))}streamEvents(n,r,o){let i=this,s=async function*(){yield*i.bound.streamEvents(n,{...await i._mergeConfig(wo(r),i.kwargs),version:r.version},o)};return Dm.fromAsyncGenerator(s())}static isRunnableBinding(n){return n.bound&&Uo.isRunnable(n.bound)}withListeners({onStart:n,onEnd:r,onError:o}){return new c6t({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[i=>({callbacks:[new N3e({config:i,onStart:n,onEnd:r,onError:o})]})]})}},B3e=class extends n1{constructor(e){super(e);M(this,"lc_namespace",["langchain_core","runnables"]);M(this,"maxAttemptNumber",3);M(this,"onFailedAttempt",()=>{});this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}static lc_name(){return"RunnableRetry"}_patchConfigForRetry(e,n,r){let o=e>1?`retry:attempt:${e}`:void 0;return Ja(n,{callbacks:r?.getChild(o)})}async _invoke(e,n,r){return sJ(o=>super.invoke(e,this._patchConfigForRetry(o,n,r)),{onFailedAttempt:({error:o})=>this.onFailedAttempt(o,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,n){return this._callWithConfig(this._invoke.bind(this),e,n)}async _batch(e,n,r,o){let i={};try{await sJ(async s=>{let a=e.map((f,p)=>p).filter(f=>i[f.toString()]===void 0||i[f.toString()]instanceof Error),l=a.map(f=>e[f]),c=a.map(f=>this._patchConfigForRetry(s,n?.[f],r?.[f])),u=await super.batch(l,c,{...o,returnExceptions:!0}),d;for(let f=0;f<u.length;f+=1){let p=u[f],m=a[f];p instanceof Error&&d===void 0&&(d=p,d.input=l[f]),i[m.toString()]=p}if(d)throw d;return u},{onFailedAttempt:({error:s})=>this.onFailedAttempt(s,s.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(s){if(o?.returnExceptions!==!0)throw s}return Object.keys(i).sort((s,a)=>parseInt(s,10)-parseInt(a,10)).map(s=>i[parseInt(s,10)])}async batch(e,n,r){return this._batchWithConfig(this._batch.bind(this),e,n,r)}},r1=class cJ extends Uo{constructor(n){super(n);M(this,"first");M(this,"middle",[]);M(this,"last");M(this,"omitSequenceTags",!1);M(this,"lc_serializable",!0);M(this,"lc_namespace",["langchain_core","runnables"]);this.first=n.first,this.middle=n.middle??this.middle,this.last=n.last,this.name=n.name,this.omitSequenceTags=n.omitSequenceTags??this.omitSequenceTags}static lc_name(){return"RunnableSequence"}get steps(){return[this.first,...this.middle,this.last]}async invoke(n,r){let o=wo(r),i=await(await Lm(o))?.handleChainStart(this.toJSON(),Vc(n,"input"),o.runId,void 0,void 0,void 0,o?.runName);delete o.runId;let s=n,a;try{let l=[this.first,...this.middle];for(let c=0;c<l.length;c+=1)s=await fv(l[c].invoke(s,Ja(o,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`)})),o.signal);if(o.signal?.aborted)throw MA(o.signal);a=await this.last.invoke(s,Ja(o,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(l){throw await i?.handleChainError(l),l}return await i?.handleChainEnd(Vc(a,"output")),a}async batch(n,r,o){let i=this._getOptionsList(r??{},n.length),s=await Promise.all(i.map(Lm)),a=await Promise.all(s.map(async(c,u)=>{let d=await c?.handleChainStart(this.toJSON(),Vc(n[u],"input"),i[u].runId,void 0,void 0,void 0,i[u].runName);return delete i[u].runId,d})),l=n;try{for(let c=0;c<this.steps.length;c+=1)l=await fv(this.steps[c].batch(l,a.map((u,d)=>{let f=u?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return Ja(i[d],{callbacks:f})}),o),i[0]?.signal)}catch(c){throw await Promise.all(a.map(u=>u?.handleChainError(c))),c}return await Promise.all(a.map(c=>c?.handleChainEnd(Vc(l,"output")))),l}_concatOutputChunks(n,r){return this.last._concatOutputChunks(n,r)}async*_streamIterator(n,r){let o=await Lm(r),{runId:i,...s}=r??{},a=await o?.handleChainStart(this.toJSON(),Vc(n,"input"),i,void 0,void 0,void 0,s?.runName),l=[this.first,...this.middle,this.last],c=!0,u;async function*d(){yield n}try{let f=l[0].transform(d(),Ja(s,{callbacks:a?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let p=1;p<l.length;p+=1)f=await l[p].transform(f,Ja(s,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${p+1}`)}));for await(let p of f)if(r?.signal?.throwIfAborted(),yield p,c)if(u===void 0)u=p;else try{u=this._concatOutputChunks(u,p)}catch{u=void 0,c=!1}}catch(f){throw await a?.handleChainError(f),f}await a?.handleChainEnd(Vc(u,"output"))}getGraph(n){let r=new L3e,o=null;return this.steps.forEach((i,s)=>{let a=i.getGraph(n);s!==0&&a.trimFirstNode(),s!==this.steps.length-1&&a.trimLastNode(),r.extend(a);let l=a.firstNode();if(!l)throw new Error(`Runnable ${i} has no first node`);o&&r.addEdge(o,l),o=a.lastNode()}),r}pipe(n){return cJ.isRunnableSequence(n)?new cJ({first:this.first,middle:this.middle.concat([this.last,n.first,...n.middle]),last:n.last,name:this.name??n.name}):new cJ({first:this.first,middle:[...this.middle,this.last],last:tI(n),name:this.name})}static isRunnableSequence(n){return Array.isArray(n.middle)&&Uo.isRunnable(n)}static from([n,...r],o){let i={};return typeof o=="string"?i.name=o:o!==void 0&&(i=o),new cJ({...i,first:tI(n),middle:r.slice(0,-1).map(tI),last:tI(r[r.length-1])})}},n4=class u6t extends Uo{constructor(n){super(n);M(this,"lc_namespace",["langchain_core","runnables"]);M(this,"lc_serializable",!0);M(this,"steps");this.steps={};for(let[r,o]of Object.entries(n.steps))this.steps[r]=tI(o)}static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}static from(n){return new u6t({steps:n})}async invoke(n,r){let o=wo(r),i=await(await Lm(o))?.handleChainStart(this.toJSON(),{input:n},o.runId,void 0,void 0,void 0,o?.runName);delete o.runId;let s={};try{let a=Object.entries(this.steps).map(async([l,c])=>{s[l]=await c.invoke(n,Ja(o,{callbacks:i?.getChild(`map:key:${l}`)}))});await fv(Promise.all(a),o.signal)}catch(a){throw await i?.handleChainError(a),a}return await i?.handleChainEnd(s),s}async*_transform(n,r,o){let i={...this.steps},s=C3e(n,Object.keys(i).length),a=new Map(Object.entries(i).map(([l,c],u)=>{let d=c.transform(s[u],Ja(o,{callbacks:r?.getChild(`map:key:${l}`)}));return[l,d.next().then(f=>({key:l,gen:d,result:f}))]}));for(;a.size;){let{key:l,result:c,gen:u}=await fv(Promise.race(a.values()),o?.signal);a.delete(l),c.done||(yield{[l]:c.value},a.set(l,u.next().then(d=>({key:l,gen:u,result:d}))))}}transform(n,r){return this._transformStreamWithConfig(n,this._transform.bind(this),r)}async stream(n,r){async function*o(){yield n}let i=wo(r),s=new e1({generator:this.transform(o(),i),config:i});return await s.setup,Dm.fromAsyncGenerator(s)}},flr=class d6t extends Uo{constructor(n){super(n);M(this,"lc_serializable",!1);M(this,"lc_namespace",["langchain_core","runnables"]);M(this,"func");if(!lhe(n.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=n.func}async invoke(n,r){let[o]=this._getOptionsList(r??{},1),i=await Lm(o);return fv(this.func(Ja(o,{callbacks:i}),n),o?.signal)}async*_streamIterator(n,r){let[o]=this._getOptionsList(r??{},1),i=await this.invoke(n,r);if(cge(i)){for await(let s of i)o?.signal?.throwIfAborted(),yield s;return}if(a6t(i)){for(;;){o?.signal?.throwIfAborted();let s=i.next();if(s.done)break;yield s.value}return}yield i}static from(n){return new d6t({func:n})}};nI=class f6t extends Uo{constructor(n){if(lhe(n.func))return flr.from(n.func);super(n);M(this,"lc_namespace",["langchain_core","runnables"]);M(this,"func");plr(n.func),this.func=n.func}static lc_name(){return"RunnableLambda"}static from(n){return new f6t({func:n})}async _invoke(n,r,o){return new Promise((i,s)=>{let a=Ja(r,{callbacks:o?.getChild(),recursionLimit:(r?.recursionLimit??25)-1});xd.runWithConfig($m(a),async()=>{try{let l=await this.func(n,{...a});if(l&&Uo.isRunnable(l)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");l=await l.invoke(n,{...a,recursionLimit:(a.recursionLimit??25)-1})}else if(cge(l)){let c;for await(let u of uge(a,l))if(r?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}l=c}else if($3e(l)){let c;for(let u of F3e(a,l))if(r?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}l=c}i(l)}catch(l){s(l)}})})}async invoke(n,r){return this._callWithConfig(this._invoke.bind(this),n,r)}async*_transform(n,r,o){let i;for await(let l of n)if(i===void 0)i=l;else try{i=this._concatOutputChunks(i,l)}catch{i=l}let s=Ja(o,{callbacks:r?.getChild(),recursionLimit:(o?.recursionLimit??25)-1}),a=await new Promise((l,c)=>{xd.runWithConfig($m(s),async()=>{try{l(await this.func(i,{...s,config:s}))}catch(u){c(u)}})});if(a&&Uo.isRunnable(a)){if(o?.recursionLimit===0)throw new Error("Recursion limit reached.");let l=await a.stream(i,s);for await(let c of l)yield c}else if(cge(a))for await(let l of uge(s,a))o?.signal?.throwIfAborted(),yield l;else if($3e(a))for(let l of F3e(s,a))o?.signal?.throwIfAborted(),yield l;else yield a}transform(n,r){return this._transformStreamWithConfig(n,this._transform.bind(this),r)}async stream(n,r){async function*o(){yield n}let i=wo(r),s=new e1({generator:this.transform(o(),i),config:i});return await s.setup,Dm.fromAsyncGenerator(s)}},p6t=class extends Uo{constructor(e){super(e);M(this,"lc_namespace",["langchain_core","runnables"]);M(this,"lc_serializable",!0);M(this,"runnable");M(this,"fallbacks");this.runnable=e.runnable,this.fallbacks=e.fallbacks}static lc_name(){return"RunnableWithFallbacks"}*runnables(){yield this.runnable;for(let e of this.fallbacks)yield e}async invoke(e,n){let r=wo(n),o=await Lm(r),{runId:i,...s}=r,a=await o?.handleChainStart(this.toJSON(),Vc(e,"input"),i,void 0,void 0,void 0,s?.runName),l=Ja(s,{callbacks:a?.getChild()});return await xd.runWithConfig(l,async()=>{let c;for(let u of this.runnables()){r?.signal?.throwIfAborted();try{let d=await u.invoke(e,l);return await a?.handleChainEnd(Vc(d,"output")),d}catch(d){c===void 0&&(c=d)}}throw c===void 0?new Error("No error stored at end of fallback."):(await a?.handleChainError(c),c)})}async*_streamIterator(e,n){let r=wo(n),o=await Lm(r),{runId:i,...s}=r,a=await o?.handleChainStart(this.toJSON(),Vc(e,"input"),i,void 0,void 0,void 0,s?.runName),l,c;for(let d of this.runnables()){r?.signal?.throwIfAborted();let f=Ja(s,{callbacks:a?.getChild()});try{c=uge(f,await d.stream(e,f));break}catch(p){l===void 0&&(l=p)}}if(c===void 0){let d=l??new Error("No error stored at end of fallback.");throw await a?.handleChainError(d),d}let u;try{for await(let d of c){yield d;try{u=u===void 0?u:this._concatOutputChunks(u,d)}catch{u=void 0}}}catch(d){throw await a?.handleChainError(d),d}await a?.handleChainEnd(Vc(u,"output"))}async batch(e,n,r){if(r?.returnExceptions)throw new Error("Not implemented.");let o=this._getOptionsList(n??{},e.length),i=await Promise.all(o.map(l=>Lm(l))),s=await Promise.all(i.map(async(l,c)=>{let u=await l?.handleChainStart(this.toJSON(),Vc(e[c],"input"),o[c].runId,void 0,void 0,void 0,o[c].runName);return delete o[c].runId,u})),a;for(let l of this.runnables()){o[0].signal?.throwIfAborted();try{let c=await l.batch(e,s.map((u,d)=>Ja(o[d],{callbacks:u?.getChild()})),r);return await Promise.all(s.map((u,d)=>u?.handleChainEnd(Vc(c[d],"output")))),c}catch(c){a===void 0&&(a=c)}}throw a?(await Promise.all(s.map(l=>l?.handleChainError(a))),a):new Error("No error stored at end of fallbacks.")}};dge=class extends Uo{constructor(e){e instanceof n4&&(e={mapper:e});super(e);M(this,"lc_namespace",["langchain_core","runnables"]);M(this,"lc_serializable",!0);M(this,"mapper");this.mapper=e.mapper}static lc_name(){return"RunnableAssign"}async invoke(e,n){let r=await this.mapper.invoke(e,n);return{...e,...r}}async*_transform(e,n,r){let o=this.mapper.getStepsKeys(),[i,s]=C3e(e),a=this.mapper.transform(s,Ja(r,{callbacks:n?.getChild()})),l=a.next();for await(let c of i){if(typeof c!="object"||Array.isArray(c))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof c}`);let u=Object.fromEntries(Object.entries(c).filter(([d])=>!o.includes(d)));Object.keys(u).length>0&&(yield u)}yield(await l).value;for await(let c of a)yield c}transform(e,n){return this._transformStreamWithConfig(e,this._transform.bind(this),n)}async stream(e,n){async function*r(){yield e}let o=wo(n),i=new e1({generator:this.transform(r(),o),config:o});return await i.setup,Dm.fromAsyncGenerator(i)}},m6t=class extends Uo{constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e});super(e);M(this,"lc_namespace",["langchain_core","runnables"]);M(this,"lc_serializable",!0);M(this,"keys");this.keys=e.keys}static lc_name(){return"RunnablePick"}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{let n=this.keys.map(r=>[r,e[r]]).filter(r=>r[1]!==void 0);return n.length===0?void 0:Object.fromEntries(n)}}async invoke(e,n){return this._callWithConfig(this._pick.bind(this),e,n)}async*_transform(e){for await(let n of e){let r=await this._pick(n);r!==void 0&&(yield r)}}transform(e,n){return this._transformStreamWithConfig(e,this._transform.bind(this),n)}async stream(e,n){async function*r(){yield e}let o=wo(n),i=new e1({generator:this.transform(r(),o),config:o});return await i.setup,Dm.fromAsyncGenerator(i)}},j3e=class extends n1{constructor(e){let n=r1.from([nI.from(async r=>{let o;if(pA(r))try{o=await iL(this.schema,r.args)}catch{throw new TY("Received tool input did not match expected schema",JSON.stringify(r.args))}else o=r;return o}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:n,config:e.config??{}});M(this,"name");M(this,"description");M(this,"schema");this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}}});var h6t=b(()=>{gf();Sz();Om();PY();qme();yA();Gme();AY();gb();Lu()});var g6t,y6t=b(()=>{g6t=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"]});var v6t,w6t=b(()=>{v6t=["image","video","audio","text-plain","file"]});var hlr,b6t=b(()=>{y6t();w6t();hlr=["text","reasoning",...g6t,...v6t]});var oi=b(()=>{br();kY();AWe();gf();Hme();Sz();Om();PY();qme();yA();Gme();AY();gb();h6t();b6t()});function z3e(t){return t!==void 0&&Array.isArray(t.lc_namespace)}function H3e(t){return t!==void 0&&Uo.isRunnable(t)&&"lc_name"in t.constructor&&typeof t.constructor.lc_name=="function"&&t.constructor.lc_name()==="RunnableToolLike"}function W3e(t){return!!t&&typeof t=="object"&&"name"in t&&"schema"in t&&(ki(t.schema)||t.schema!=null&&typeof t.schema=="object"&&"type"in t.schema&&typeof t.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(t.schema.type))}function xf(t){return W3e(t)||H3e(t)||z3e(t)}var V3e=b(()=>{Px();Lu()});function ylr(t,e){let n=typeof e=="number"?void 0:e;return{name:t.name,description:t.description,parameters:Ki(t.schema),...n?.strict!==void 0?{strict:n.strict}:{}}}function Gx(t,e){let n=typeof e=="number"?void 0:e,r;return xf(t)?r={type:"function",function:ylr(t)}:r=t,n?.strict!==void 0&&(r.function.strict=n.strict),r}var rI=b(()=>{br();tg();V3e()});function Sb(t,e){e?($u[0]=$u[16]=$u[1]=$u[2]=$u[3]=$u[4]=$u[5]=$u[6]=$u[7]=$u[8]=$u[9]=$u[10]=$u[11]=$u[12]=$u[13]=$u[14]=$u[15]=0,this.blocks=$u):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=t}var cn,vlr,xb,fge,$u,q3e,K3e=b(()=>{cn="0123456789abcdef".split(""),vlr=[-2147483648,8388608,32768,128],xb=[24,16,8,0],fge=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],$u=[];Sb.prototype.update=function(t){if(!this.finalized){var e,n=typeof t;if(n!=="string"){if(n==="object"){if(t===null)throw new Error(ERROR);if(ARRAY_BUFFER&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!Array.isArray(t)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(t)))throw new Error(ERROR)}else throw new Error(ERROR);e=!0}for(var r,o=0,i,s=t.length,a=this.blocks;o<s;){if(this.hashed&&(this.hashed=!1,a[0]=this.block,this.block=a[16]=a[1]=a[2]=a[3]=a[4]=a[5]=a[6]=a[7]=a[8]=a[9]=a[10]=a[11]=a[12]=a[13]=a[14]=a[15]=0),e)for(i=this.start;o<s&&i<64;++o)a[i>>>2]|=t[o]<<xb[i++&3];else for(i=this.start;o<s&&i<64;++o)r=t.charCodeAt(o),r<128?a[i>>>2]|=r<<xb[i++&3]:r<2048?(a[i>>>2]|=(192|r>>>6)<<xb[i++&3],a[i>>>2]|=(128|r&63)<<xb[i++&3]):r<55296||r>=57344?(a[i>>>2]|=(224|r>>>12)<<xb[i++&3],a[i>>>2]|=(128|r>>>6&63)<<xb[i++&3],a[i>>>2]|=(128|r&63)<<xb[i++&3]):(r=65536+((r&1023)<<10|t.charCodeAt(++o)&1023),a[i>>>2]|=(240|r>>>18)<<xb[i++&3],a[i>>>2]|=(128|r>>>12&63)<<xb[i++&3],a[i>>>2]|=(128|r>>>6&63)<<xb[i++&3],a[i>>>2]|=(128|r&63)<<xb[i++&3]);this.lastByteIndex=i,this.bytes+=i-this.start,i>=64?(this.block=a[16],this.start=i-64,this.hash(),this.hashed=!0):this.start=i}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};Sb.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>>2]|=vlr[e&3],this.block=t[16],e>=56&&(this.hashed||this.hash(),t[0]=this.block,t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.hBytes<<3|this.bytes>>>29,t[15]=this.bytes<<3,this.hash()}};Sb.prototype.hash=function(){var t=this.h0,e=this.h1,n=this.h2,r=this.h3,o=this.h4,i=this.h5,s=this.h6,a=this.h7,l=this.blocks,c,u,d,f,p,m,h,g,v,y,w;for(c=16;c<64;++c)p=l[c-15],u=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,p=l[c-2],d=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,l[c]=l[c-16]+u+l[c-7]+d<<0;for(w=e&n,c=0;c<64;c+=4)this.first?(this.is224?(g=300032,p=l[0]-1413257819,a=p-150054599<<0,r=p+24177077<<0):(g=704751109,p=l[0]-210244248,a=p-1521486534<<0,r=p+143694565<<0),this.first=!1):(u=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),g=t&e,f=g^t&n^w,h=o&i^~o&s,p=a+d+h+fge[c]+l[c],m=u+f,a=r+p<<0,r=p+m<<0),u=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),v=r&t,f=v^r&e^g,h=s&a^~s&o,p=i+d+h+fge[c+1]+l[c+1],m=u+f,s=n+p<<0,n=p+m<<0,u=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),y=n&r,f=y^n&t^v,h=i&s^~i&a,p=o+d+h+fge[c+2]+l[c+2],m=u+f,i=e+p<<0,e=p+m<<0,u=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),w=e&n,f=w^e&r^y,h=i&s^~i&a,p=o+d+h+fge[c+3]+l[c+3],m=u+f,o=t+p<<0,t=p+m<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+t<<0,this.h1=this.h1+e<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+o<<0,this.h5=this.h5+i<<0,this.h6=this.h6+s<<0,this.h7=this.h7+a<<0};Sb.prototype.hex=function(){this.finalize();var t=this.h0,e=this.h1,n=this.h2,r=this.h3,o=this.h4,i=this.h5,s=this.h6,a=this.h7,l=cn[t>>>28&15]+cn[t>>>24&15]+cn[t>>>20&15]+cn[t>>>16&15]+cn[t>>>12&15]+cn[t>>>8&15]+cn[t>>>4&15]+cn[t&15]+cn[e>>>28&15]+cn[e>>>24&15]+cn[e>>>20&15]+cn[e>>>16&15]+cn[e>>>12&15]+cn[e>>>8&15]+cn[e>>>4&15]+cn[e&15]+cn[n>>>28&15]+cn[n>>>24&15]+cn[n>>>20&15]+cn[n>>>16&15]+cn[n>>>12&15]+cn[n>>>8&15]+cn[n>>>4&15]+cn[n&15]+cn[r>>>28&15]+cn[r>>>24&15]+cn[r>>>20&15]+cn[r>>>16&15]+cn[r>>>12&15]+cn[r>>>8&15]+cn[r>>>4&15]+cn[r&15]+cn[o>>>28&15]+cn[o>>>24&15]+cn[o>>>20&15]+cn[o>>>16&15]+cn[o>>>12&15]+cn[o>>>8&15]+cn[o>>>4&15]+cn[o&15]+cn[i>>>28&15]+cn[i>>>24&15]+cn[i>>>20&15]+cn[i>>>16&15]+cn[i>>>12&15]+cn[i>>>8&15]+cn[i>>>4&15]+cn[i&15]+cn[s>>>28&15]+cn[s>>>24&15]+cn[s>>>20&15]+cn[s>>>16&15]+cn[s>>>12&15]+cn[s>>>8&15]+cn[s>>>4&15]+cn[s&15];return this.is224||(l+=cn[a>>>28&15]+cn[a>>>24&15]+cn[a>>>20&15]+cn[a>>>16&15]+cn[a>>>12&15]+cn[a>>>8&15]+cn[a>>>4&15]+cn[a&15]),l};Sb.prototype.toString=Sb.prototype.hex;Sb.prototype.digest=function(){this.finalize();var t=this.h0,e=this.h1,n=this.h2,r=this.h3,o=this.h4,i=this.h5,s=this.h6,a=this.h7,l=[t>>>24&255,t>>>16&255,t>>>8&255,t&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,o>>>24&255,o>>>16&255,o>>>8&255,o&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255];return this.is224||l.push(a>>>24&255,a>>>16&255,a>>>8&255,a&255),l};Sb.prototype.array=Sb.prototype.digest;Sb.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(this.is224?28:32),e=new DataView(t);return e.setUint32(0,this.h0),e.setUint32(4,this.h1),e.setUint32(8,this.h2),e.setUint32(12,this.h3),e.setUint32(16,this.h4),e.setUint32(20,this.h5),e.setUint32(24,this.h6),this.is224||e.setUint32(28,this.h7),t};q3e=(...t)=>new Sb(!1,!0).update(t.join("")).hex()});var _6t=b(()=>{br();K3e()});var wlr,blr,_lr,x6t,C6t=b(()=>{br();K3e();_6t();gb();wlr=(...t)=>q3e(t.join("_")),blr=class{constructor(){M(this,"keyEncoder",wlr)}makeDefaultKeyEncoder(t){this.keyEncoder=t}},_lr=new Map,x6t=class S6t extends blr{constructor(n){super();M(this,"cache");this.cache=n??new Map}lookup(n,r){return Promise.resolve(this.cache.get(this.keyEncoder(n,r))??null)}async update(n,r,o){this.cache.set(this.keyEncoder(n,r),o)}static global(){return new S6t(_lr)}}});var G3e,pge,mge,k6t,uJ=b(()=>{br();SL();yA();gb();G3e=class extends av{},pge=class extends G3e{constructor(e){super({value:e});M(this,"lc_namespace",["langchain_core","prompt_values"]);M(this,"lc_serializable",!0);M(this,"value");this.value=e}static lc_name(){return"StringPromptValue"}toString(){return this.value}toChatMessages(){return[new na(this.value)]}},mge=class extends G3e{constructor(e){Array.isArray(e)&&(e={messages:e});super(e);M(this,"lc_namespace",["langchain_core","prompt_values"]);M(this,"lc_serializable",!0);M(this,"messages");this.messages=e.messages}static lc_name(){return"ChatPromptValue"}toString(){return Mm(this.messages)}toChatMessages(){return this.messages}},k6t=class extends G3e{constructor(e){"imageUrl"in e||(e={imageUrl:e});super(e);M(this,"lc_namespace",["langchain_core","prompt_values"]);M(this,"lc_serializable",!0);M(this,"imageUrl");M(this,"value");this.imageUrl=e.imageUrl}static lc_name(){return"ImagePromptValue"}toString(){return this.imageUrl.url}toChatMessages(){return[new na({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}}});function klr(t,e){let n=Array.from({length:t.length},(r,o)=>({start:o,end:o+1}));for(;n.length>1;){let r=null;for(let o=0;o<n.length-1;o++){let i=t.slice(n[o].start,n[o+1].end),s=e.get(i.join(","));s!=null&&(r==null||s<r[0])&&(r=[s,o])}if(r!=null){let o=r[1];n[o]={start:n[o].start,end:n[o+1].end},n.splice(o+1,1)}else break}return n}function Ilr(t,e){return t.length===1?[e.get(t.join(","))]:klr(t,e).map(n=>e.get(t.slice(n.start,n.end).join(","))).filter(n=>n!=null)}function Tlr(t){return t.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}function Y3e(t){switch(t){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":return"o200k_base";default:throw new Error("Unknown model")}}var I6t,xlr,Slr,Clr,Z3e,hge,T6t=b(()=>{I6t=L(IAe(),1),xlr=Object.defineProperty,Slr=(t,e,n)=>e in t?xlr(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Clr=(t,e,n)=>(Slr(t,typeof e!="symbol"?e+"":e,n),n);Z3e=class{constructor(t,e){M(this,"specialTokens");M(this,"inverseSpecialTokens");M(this,"patStr");M(this,"textEncoder",new TextEncoder);M(this,"textDecoder",new TextDecoder("utf-8"));M(this,"rankMap",new Map);M(this,"textMap",new Map);this.patStr=t.pat_str;let n=t.bpe_ranks.split(`
`).filter(Boolean).reduce((r,o)=>{let[i,s,...a]=o.split(" "),l=Number.parseInt(s,10);return a.forEach((c,u)=>r[c]=l+u),r},{});for(let[r,o]of Object.entries(n)){let i=I6t.default.toByteArray(r);this.rankMap.set(i.join(","),o),this.textMap.set(o,i)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((r,[o,i])=>(r[i]=this.textEncoder.encode(o),r),{})}encode(t,e=[],n="all"){let r=new RegExp(this.patStr,"ug"),o=Z3e.specialTokenRegex(Object.keys(this.specialTokens)),i=[],s=new Set(e==="all"?Object.keys(this.specialTokens):e),a=new Set(n==="all"?Object.keys(this.specialTokens).filter(c=>!s.has(c)):n);if(a.size>0){let c=Z3e.specialTokenRegex([...a]),u=t.match(c);if(u!=null)throw new Error(`The text contains a special token that is not allowed: ${u[0]}`)}let l=0;for(;;){let c=null,u=l;for(;o.lastIndex=u,c=o.exec(t),!(c==null||s.has(c[0]));)u=c.index+1;let d=c?.index??t.length;for(let p of t.substring(l,d).matchAll(r)){let m=this.textEncoder.encode(p[0]),h=this.rankMap.get(m.join(","));if(h!=null){i.push(h);continue}i.push(...Ilr(m,this.rankMap))}if(c==null)break;let f=this.specialTokens[c[0]];i.push(f),l=c.index+c[0].length}return i}decode(t){let e=[],n=0;for(let i=0;i<t.length;++i){let s=t[i],a=this.textMap.get(s)??this.inverseSpecialTokens[s];a!=null&&(e.push(a),n+=a.length)}let r=new Uint8Array(n),o=0;for(let i of e)r.set(i,o),o+=i.length;return this.textDecoder.decode(r)}},hge=Z3e;Clr(hge,"specialTokenRegex",t=>new RegExp(t.map(e=>Tlr(e)).join("|"),"g"))});var P6t=b(()=>{T6t()});async function A6t(t){return t in gge||(gge[t]=Plr.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new hge(e)).catch(e=>{throw delete gge[t],e})),await gge[t]}async function E6t(t){return A6t(Y3e(t))}var gge,Plr,J3e=b(()=>{br();aJ();P6t();gge={},Plr=new RA({})});function Zx(t){return typeof t!="object"||!t?!1:!!("type"in t&&t.type==="function"&&"function"in t&&typeof t.function=="object"&&t.function&&"name"in t.function&&"parameters"in t.function)}var Alr,Elr,yge,r4,lg=b(()=>{br();gb();C6t();aJ();Lu();uJ();J3e();Alr=t=>t.startsWith("gpt-5")?"gpt-5":t.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":t.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":t.startsWith("gpt-4-32k")?"gpt-4-32k":t.startsWith("gpt-4-")?"gpt-4":t.startsWith("gpt-4o")?"gpt-4o":t;Elr=()=>!1,yge=class extends Uo{constructor(e){super(e);M(this,"verbose");M(this,"callbacks");M(this,"tags");M(this,"metadata");this.verbose=e.verbose??Elr(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{},this._addVersion("@langchain/core","1.2.8")}get lc_attributes(){return{callbacks:void 0,verbose:void 0}}_addVersion(e,n){let r=this.metadata?.versions;this.metadata={...this.metadata,versions:{...typeof r=="object"&&r!==null?r:{},[e]:n}}}},r4=class extends yge{constructor({callbacks:e,callbackManager:n,...r}){let{cache:o,...i}=r;super({callbacks:e??n,...i});M(this,"caller");M(this,"cache");M(this,"_encoding");typeof o=="object"?this.cache=o:o?this.cache=x6t.global():this.cache=void 0,this.caller=new RA(r??{})}get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}async getNumTokens(e){let n;typeof e=="string"?n=e:n=e.map(o=>typeof o=="string"?o:o.type==="text"&&"text"in o?o.text:"").join("");let r=Math.ceil(n.length/4);if(!this._encoding)try{this._encoding=await E6t("modelName"in this?Alr(this.modelName):"gpt2")}catch(o){console.warn("Failed to calculate number of tokens, falling back to approximate count",o)}if(this._encoding)try{r=this._encoding.encode(n).length}catch(o){console.warn("Failed to calculate number of tokens, falling back to approximate count",o)}return r}static _convertInputToPromptValue(e){return typeof e=="string"?new pge(e):Array.isArray(e)?new mge(e.map(hb)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...n}){let r={...this._identifyingParams(),...n,_type:this._llmType(),_model:this._modelType()};return Object.entries(r).filter(([o,i])=>i!==void 0).map(([o,i])=>`${o}:${JSON.stringify(i)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}get profile(){return{}}_filterInvocationParamsForTracing(e){let{tools:n,functions:r,messages:o,response_format:i,...s}=e;return s}}});function Nlr(t){return yf.isInstance(t)?t.role:t.type}function Rlr(t){switch(t){case"supervisor":case"ai":case"model":return"model";case"system":return"system";case"human":return"user";case"tool":case"function":return"function";default:throw new Error(`Unknown / unsupported author: ${t}`)}}function Llr(t){if("mimeType"in t&&"data"in t)return{inlineData:{mimeType:t.mimeType,data:t.data}};if("mimeType"in t&&"fileUri"in t)return{fileData:{mimeType:t.mimeType,fileUri:t.fileUri}};throw new Error("Invalid media content")}function $lr(t,e){return e.map(n=>cv(n)?n.tool_calls??[]:[]).flat().find(n=>n.id===t.tool_call_id)?.name}function dJ(t,e){if("data"in t&&t.data!==void 0){let n=t.data instanceof Uint8Array?btoa(String.fromCharCode(...t.data)):t.data;return{inlineData:{mimeType:t.mimeType||e,data:n}}}if("url"in t&&t.url!==void 0){let n=hf({dataUrl:t.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:t.mimeType||e,fileUri:t.url}}}throw"fileId"in t&&t.fileId!==void 0?new Error("ContentBlock.Multimodal fileId is not supported by Google Generative AI. Use a URL or base64 data instead."):new Error(`Invalid multimodal content block: must have "data", "url", or "fileId" property. Received: ${JSON.stringify(t)}`)}function Dlr(t){return{providerName:"Google Gemini",fromStandardTextBlock(e){return{text:e.text}},fromStandardImageBlock(e){if(!t)throw new Error("This model does not support images");if(e.source_type==="url"){let n=hf({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mime_type??"",fileUri:e.url}}}if(e.source_type==="base64")return{inlineData:{mimeType:e.mime_type??"",data:e.data}};throw new Error(`Unsupported source type: ${e.source_type}`)},fromStandardAudioBlock(e){if(!t)throw new Error("This model does not support audio");if(e.source_type==="url"){let n=hf({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mime_type??"",fileUri:e.url}}}if(e.source_type==="base64")return{inlineData:{mimeType:e.mime_type??"",data:e.data}};throw new Error(`Unsupported source type: ${e.source_type}`)},fromStandardFileBlock(e){if(!t)throw new Error("This model does not support files");if(e.source_type==="text")return{text:e.text};if(e.source_type==="url"){let n=hf({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mime_type??"",fileUri:e.url}}}if(e.source_type==="base64")return{inlineData:{mimeType:e.mime_type??"",data:e.data}};throw new Error(`Unsupported source type: ${e.source_type}`)}}}function M6t(t,e){if(mf(t))return qk(t,Dlr(e));if(t.type==="text")return{text:t.text};if(t.type==="executableCode")return{executableCode:t.executableCode};if(t.type==="codeExecutionResult")return{codeExecutionResult:t.codeExecutionResult};if(t.type==="image_url"){if(!e)throw new Error("This model does not support images");let n;if(typeof t.image_url=="string")n=t.image_url;else if(typeof t.image_url=="object"&&"url"in t.image_url)n=t.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");let[r,o]=n.split(",");if(!r.startsWith("data:"))throw new Error("Please provide image as base64 encoded data URL");let[i,s]=r.replace(/^data:/,"").split(";");if(s!=="base64")throw new Error("Please provide image as base64 encoded data URL");return{inlineData:{data:o,mimeType:i}}}else{if(t.type==="media")return Llr(t);if(t.type==="image")return dJ(t,"image/png");if(t.type==="video")return dJ(t,"video/mp4");if(t.type==="audio")return dJ(t,"audio/mpeg");if(t.type==="file")return dJ(t,"application/octet-stream");if(t.type==="text-plain")return"text"in t&&typeof t.text=="string"?{text:t.text}:dJ(t,"text/plain");if(t.type==="tool_use")return{functionCall:{name:t.name,args:t.input}};if(t.type==="tool_call")return{functionCall:{name:t.name,args:t.args}};if(t.type?.includes("/")&&t.type.split("/").length===2&&"data"in t&&typeof t.data=="string")return{inlineData:{mimeType:t.type,data:t.data}};if(t.type==="thinking"){let n=t;return{text:n.thinking,thought:!0,...n.signature?{thoughtSignature:n.signature}:{}}}else{if("functionCall"in t)return;throw"type"in t?new Error(`Unknown content type ${t.type}`):new Error(`Unknown content ${JSON.stringify(t)}`)}}}function Flr(t,e,n,r){if(zWe(t)){let a=t.name??$lr(t,n);if(a===void 0)throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${t.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);let l=Array.isArray(t.content)?t.content.map(c=>M6t(c,e)).filter(c=>c!==void 0):t.content;return t.status==="error"?[{functionResponse:{name:a,response:{error:{details:l}}}}]:[{functionResponse:{name:a,response:{result:l}}}]}let o=[],i=[];typeof t.content=="string"&&t.content&&i.push({text:t.content}),Array.isArray(t.content)&&i.push(...t.content.map(a=>M6t(a,e)).filter(a=>a!==void 0));let s=t.additional_kwargs?.[X3e];return cv(t)&&t.tool_calls?.length&&(o=t.tool_calls.map(a=>{let l=Olr(()=>{if(a.id){let c=s?.[a.id];if(c)return c}return r?.includes("gemini-3")?Mlr:""});return{functionCall:{name:a.name,args:a.args},...l?{thoughtSignature:l}:{}}})),[...i,...o]}function O6t(t,e,n=!1,r){return t.reduce((o,i,s)=>{if(!lv(i))throw new Error("Unsupported message input");let a=Nlr(i);if(a==="system"&&s!==0)throw new Error("System message should be the first one");let l=Rlr(a),c=o.content[o.content.length];if(!o.mergeWithPreviousContent&&c&&c.role===l)throw new Error("Google Generative AI requires alternate messages between authors");let u=Flr(i,e,t.slice(0,s),r);if(o.mergeWithPreviousContent){let p=o.content[o.content.length-1];if(!p)throw new Error("There was a problem parsing your system message. Please try a prompt without one.");return p.parts.push(...u),{mergeWithPreviousContent:!1,content:o.content}}let d=l;(d==="function"||d==="system"&&!n)&&(d="user");let f={role:d,parts:u};return{mergeWithPreviousContent:a==="system"&&!n,content:[...o.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function N6t(t,e){if(!t.candidates||t.candidates.length===0||!t.candidates[0])return{generations:[],llmOutput:{filters:t.promptFeedback}};let[n]=t.candidates,{content:r,...o}=n,i=r?.parts?.reduce((u,d)=>("functionCall"in d&&d.functionCall&&u.push({...d,id:"id"in d.functionCall&&typeof d.functionCall.id=="string"?d.functionCall.id:IL()}),u),[]),s,a=r?.parts;Array.isArray(a)&&a.length===1&&"text"in a[0]&&a[0].text&&!a[0].thought?s=a[0].text:Array.isArray(a)&&a.length>0?s=a.map(u=>u.thought&&"text"in u&&u.text?{type:"thinking",thinking:u.text,...u.thoughtSignature?{signature:u.thoughtSignature}:{}}:"text"in u?{type:"text",text:u.text}:"inlineData"in u?{type:"inlineData",inlineData:u.inlineData}:"functionCall"in u?{type:"functionCall",functionCall:u.functionCall}:"functionResponse"in u?{type:"functionResponse",functionResponse:u.functionResponse}:"fileData"in u?{type:"fileData",fileData:u.fileData}:"executableCode"in u?{type:"executableCode",executableCode:u.executableCode}:"codeExecutionResult"in u?{type:"codeExecutionResult",codeExecutionResult:u.codeExecutionResult}:u):s=[];let l=i?.reduce((u,d)=>("thoughtSignature"in d&&typeof d.thoughtSignature=="string"&&(u[d.id]=d.thoughtSignature),u),{}),c="";return typeof s=="string"?c=s:Array.isArray(s)&&s.length>0&&(c=s.find(u=>"text"in u)?.text??c),{generations:[{text:c,message:new cr({content:s??"",tool_calls:i?.map(u=>({type:"tool_call",id:u.id,name:u.functionCall.name,args:u.functionCall.args})),additional_kwargs:{...o,[X3e]:l},usage_metadata:e?.usageMetadata}),generationInfo:o}],llmOutput:{tokenUsage:{promptTokens:e?.usageMetadata?.input_tokens,completionTokens:e?.usageMetadata?.output_tokens,totalTokens:e?.usageMetadata?.total_tokens}}}}function R6t(t,e){if(!t.candidates||t.candidates.length===0)return null;let[n]=t.candidates,{content:r,...o}=n,i=r.parts?.reduce((d,f)=>("functionCall"in f&&f.functionCall&&d.push({...f,id:"id"in f.functionCall&&typeof f.functionCall.id=="string"?f.functionCall.id:IL()}),d),[]),s,a=r?.parts;Array.isArray(a)&&a.every(d=>"text"in d&&!d.thought)?s=a.map(d=>d.text).join(""):Array.isArray(a)?s=a.map(d=>d.thought&&"text"in d&&d.text?{type:"thinking",thinking:d.text,...d.thoughtSignature?{signature:d.thoughtSignature}:{}}:"text"in d?{type:"text",text:d.text}:"inlineData"in d?{type:"inlineData",inlineData:d.inlineData}:"functionCall"in d?{type:"functionCall",functionCall:d.functionCall}:"functionResponse"in d?{type:"functionResponse",functionResponse:d.functionResponse}:"fileData"in d?{type:"fileData",fileData:d.fileData}:"executableCode"in d?{type:"executableCode",executableCode:d.executableCode}:"codeExecutionResult"in d?{type:"codeExecutionResult",codeExecutionResult:d.codeExecutionResult}:d):s=[];let l="";s&&typeof s=="string"?l=s:Array.isArray(s)&&(l=s.find(d=>"text"in d)?.text??"");let c=[];i&&c.push(...i.map(d=>({type:"tool_call_chunk",id:d.id,name:d.functionCall.name,args:JSON.stringify(d.functionCall.args)})));let u=i?.reduce((d,f)=>("thoughtSignature"in f&&typeof f.thoughtSignature=="string"&&(d[f.id]=f.thoughtSignature),d),{});return new di({text:l,message:new On({content:s||"",name:r?r.role:void 0,tool_call_chunks:c,additional_kwargs:{[X3e]:u},response_metadata:{model_provider:"google-genai"},usage_metadata:e.usageMetadata}),generationInfo:o})}function L6t(t){return t.every(e=>"functionDeclarations"in e&&Array.isArray(e.functionDeclarations))?t:[{functionDeclarations:t.map(e=>{if(xf(e)){let n=xY(e.schema);return n.type==="object"&&"properties"in n&&Object.keys(n.properties).length===0?{name:e.name,description:e.description}:(xL(n,e.name),{name:e.name,description:e.description,parameters:n})}if(Zx(e)){let n=bjt(e.function.parameters);return xL(n,e.function.name),{name:e.function.name,description:e.function.description??"A function available to call.",parameters:n}}return e})}]}function fJ(t,e){let n={input_tokens:t?.promptTokenCount??0,output_tokens:t?.candidatesTokenCount??0,total_tokens:t?.totalTokenCount??0};if(t?.cachedContentTokenCount&&(n.input_token_details??(n.input_token_details={}),n.input_token_details.cache_read=t.cachedContentTokenCount),e==="gemini-3-pro-preview"){let r=Math.max(0,t?.promptTokenCount??-2e5),o=Math.max(0,t?.cachedContentTokenCount??-2e5);r&&(n.input_token_details={...n.input_token_details,over_200k:r}),o&&(n.input_token_details={...n.input_token_details,cache_read_over_200k:o})}return n}var X3e,Mlr,Olr,vge=b(()=>{Dme();_jt();oi();Sd();rI();lg();TL();X3e="__gemini_function_call_thought_signatures__",Mlr="ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==",Olr=t=>t()});function $6t(t){let e=0;for(let n of t.keys())n>=e&&(e=n+1);return e}function D6t(t){let e=t.additional_kwargs;return e!=null&&typeof e=="object"?e:{}}function Blr(t){let e=D6t(t).tool_outputs;if(!Array.isArray(e))return[];let n=[];for(let r of e){if(r==null||typeof r!="object")continue;let o=r;if(o.type!=="image_generation_call")continue;let i=typeof o.result=="string"?o.result:void 0,s=typeof o.url=="string"?o.url:void 0;if(i==null&&s==null)continue;let a=typeof o.output_format=="string"?o.output_format.toLowerCase():void 0,l=(a!=null?jlr[a]:void 0)??"image/png";n.push({type:"image",...typeof o.id=="string"?{id:o.id}:{},...s!=null?{url:s}:{},...i!=null?{data:i}:{},mimeType:l})}return n}function zlr(t){let e=D6t(t).audio;if(e==null||typeof e!="object")return;let n=e,r=typeof n.data=="string"?n.data:void 0,o=typeof n.url=="string"?n.url:void 0,i=typeof n.transcript=="string"?n.transcript:void 0;if(r==null&&o==null&&i==null)return;let s=typeof n.mime_type=="string"?n.mime_type:typeof n.mimeType=="string"?n.mimeType:void 0,a=typeof n.format=="string"?n.format.toLowerCase():void 0,l=s??(a!=null?Ulr[a]:void 0)??(r!=null?"audio/wav":"audio/pcm");return{...typeof n.id=="string"?{id:n.id}:{},...r!=null?{data:r}:{},...o!=null?{url:o}:{},...i!=null?{transcript:i}:{},mimeType:l}}async function*F6t(t,e){let n=new Map,r=!1,o,i,s=new Set;for await(let a of t){e?.signal?.throwIfAborted();let l=a.message,c=!1;if(!r){r=!0;let f={event:"message-start",id:l.id??void 0};On.isInstance(l)&&l.usage_metadata&&(f.usage=l.usage_metadata,o={...l.usage_metadata},c=!0),yield f}let u=l.content;if(typeof u=="string"){if(u!==""){if(!n.has(0)){let m={type:"text",text:""};n.set(0,{type:"text",accumulated:m}),yield{event:"content-block-start",index:0,content:m}}let p=n.get(0);p.accumulated={...p.accumulated,text:(p.accumulated.text??"")+u},yield{event:"content-block-delta",index:0,delta:{type:"text-delta",text:u}}}}else if(Array.isArray(u))for(let f of u){let p=typeof f.index=="number"?f.index:n.size;if(!n.has(p))n.set(p,{type:f.type,accumulated:{...f}}),yield{event:"content-block-start",index:p,content:{...f}};else{let m=n.get(p),h=Wlr(f);m.accumulated=Hlr(m.accumulated,h),yield{event:"content-block-delta",index:p,delta:h}}}if(On.isInstance(l)&&l.tool_call_chunks&&l.tool_call_chunks.length>0)for(let f of l.tool_call_chunks){let p=typeof f.index=="number"?f.index:n.size;if(!n.has(p)){let h={type:"tool_call_chunk",id:f.id,name:f.name,args:"",index:p};n.set(p,{type:"tool_call_chunk",accumulated:h}),yield{event:"content-block-start",index:p,content:h}}let m=n.get(p).accumulated;f.id!=null&&(m.id=f.id),f.name!=null&&(m.name=f.name),m.args=(m.args??"")+(f.args??""),yield{event:"content-block-delta",index:p,delta:{type:"block-delta",fields:{type:"tool_call_chunk",..."id"in m&&m.id!=null?{id:m.id}:{},..."name"in m&&m.name!=null?{name:m.name}:{},args:m.args}}}}let d=zlr(l);if(d!=null){if(i==null){let p=$6t(n);i={index:p,id:d.id,mimeType:d.mimeType,transcript:""};let m={type:"audio",...d.id!=null?{id:d.id}:{},...d.url!=null?{url:d.url}:{},data:"",mimeType:d.mimeType};n.set(p,{type:"audio",accumulated:m}),yield{event:"content-block-start",index:p,content:m}}let f=n.get(i.index);if(f!=null){let p=f.accumulated;d.id!=null&&i.id==null&&(i.id=d.id,p.id=d.id),d.transcript!=null&&(i.transcript+=d.transcript,p.transcript=i.transcript,yield{event:"content-block-delta",index:i.index,delta:{type:"block-delta",fields:{type:"audio",transcript:i.transcript}}}),d.data!=null&&d.data.length>0&&(p.data=(p.data??"")+d.data,yield{event:"content-block-delta",index:i.index,delta:{type:"data-delta",data:d.data,encoding:"base64"}})}}for(let f of Blr(l)){let p=f,m=p.id??p.url??(p.data!=null?`${p.data.length}:${p.data.slice(0,32)}`:void 0);if(m!=null&&s.has(m))continue;m!=null&&s.add(m);let h=$6t(n);n.set(h,{type:"image",accumulated:f}),yield{event:"content-block-start",index:h,content:f}}if(!c&&On.isInstance(l)&&l.usage_metadata){let f=l.usage_metadata;o?o={input_tokens:o.input_tokens+f.input_tokens,output_tokens:o.output_tokens+f.output_tokens,total_tokens:o.total_tokens+f.total_tokens}:o={...f},yield{event:"usage",usage:{...o}}}}for(let[a,l]of n)yield{event:"content-block-finish",index:a,content:oI(l.accumulated)};yield{event:"message-finish",reason:"stop",...o?{usage:o}:{}}}function Hlr(t,e){switch(e.type){case"text-delta":return t.type==="text"?{...t,text:(t.text??"")+e.text}:t;case"reasoning-delta":return t.type==="thinking"?{...t,thinking:(t.thinking??"")+e.reasoning}:t.type==="reasoning"?{...t,reasoning:(t.reasoning??"")+e.reasoning}:t;case"data-delta":return{...t,data:(t.data??"")+e.data};case"block-delta":return{...t,...e.fields};default:throw new Error(`Unknown delta type: ${JSON.stringify(e)}`)}}function Wlr(t){if(t.type==="text")return{type:"text-delta",text:t.text};if(t.type==="reasoning")return{type:"reasoning-delta",reasoning:t.reasoning};if(t.type==="thinking"&&typeof t.thinking=="string")return{type:"reasoning-delta",reasoning:t.thinking};if(typeof t.data=="string")return{type:"data-delta",data:t.data,encoding:"base64"};if(typeof t.type=="string")return{type:"block-delta",fields:{...t}};throw new Error(`Unsupported content block delta: ${JSON.stringify(t)}`)}function oI(t){if(t.type==="tool_call_chunk"){let e=t,n;try{n=JSON.parse(e.args??"{}")}catch{return{type:"invalid_tool_call",id:e.id,name:e.name,args:e.args,error:"Failed to parse tool call arguments as JSON"}}return{type:"tool_call",id:e.id,name:e.name,args:n}}return t}var Ulr,jlr,o4=b(()=>{br();Om();Ulr={wav:"audio/wav",mp3:"audio/mpeg",flac:"audio/flac",opus:"audio/opus",aac:"audio/aac",pcm16:"audio/pcm"},jlr={png:"image/png",jpeg:"image/jpeg",jpg:"image/jpeg",webp:"image/webp",gif:"image/gif"}});async function*U6t(t,e={}){let n=e.streamUsage??!0,r=new Map,o=new Map,i=0,s=!1,a,l="stop",c=(u,d)=>{let f=o.get(u);if(f!==void 0)return{index:f,isNew:!1};let p=i++;return o.set(u,p),r.set(p,{...d}),{index:p,isNew:!0}};for await(let u of t){s||(s=!0,yield{event:"message-start"}),n&&"usageMetadata"in u&&u.usageMetadata&&(a=fJ(u.usageMetadata,e.model??""),yield{event:"usage",usage:a});let d=u.candidates?.[0];d?.finishReason&&(l=Vlr(d.finishReason));let f=d?.content?.parts;if(!f)continue;let p=0;for(let m of f)if("text"in m&&m.text)if("thought"in m&&m.thought){let{index:h,isNew:g}=c("reasoning",{type:"reasoning",reasoning:""});g&&(yield{event:"content-block-start",index:h,content:{type:"reasoning",reasoning:""}});let v=r.get(h);v.reasoning=(v.reasoning??"")+m.text,yield{event:"content-block-delta",index:h,delta:{type:"reasoning-delta",reasoning:m.text}}}else{let{index:h,isNew:g}=c("text",{type:"text",text:""});g&&(yield{event:"content-block-start",index:h,content:{type:"text",text:""}});let v=r.get(h);v.text=(v.text??"")+m.text,yield{event:"content-block-delta",index:h,delta:{type:"text-delta",text:m.text}}}else if("functionCall"in m&&m.functionCall){let h=`tool:${p}`,g=JSON.stringify(m.functionCall.args??{}),{index:v,isNew:y}=c(h,{type:"tool_call_chunk",name:m.functionCall.name,args:"",index:p});y&&(yield{event:"content-block-start",index:v,content:{type:"tool_call_chunk",name:m.functionCall.name,args:"",index:p}});let w=r.get(v);w.args=g,yield{event:"content-block-delta",index:v,delta:{type:"block-delta",fields:{type:"tool_call_chunk",name:w.name,args:w.args}}},p+=1}}for(let[u,d]of r)yield{event:"content-block-finish",index:u,content:oI(d)};yield{event:"message-finish",reason:l,...a?{usage:a}:{},responseMetadata:{model_provider:"google-genai"}}}function Vlr(t){switch(t.toLowerCase()){case"max_tokens":case"max-token":case"max_token":return"length";case"safety":case"recitation":case"language":case"blocklist":case"prohibited_content":case"prohibited-content":case"spii":case"image_safety":case"image-safety":case"image_prohibited_content":case"image-prohibited-content":case"image_recitation":case"image-recitation":return"content_filter";default:return"stop"}}var j6t=b(()=>{vge();o4()});var pJ,wge=b(()=>{qx();Kx();Lu();pJ=class extends Uo{constructor(e){super(e);M(this,"lc_namespace",["langchain_core","runnables"]);M(this,"lc_serializable",!0);M(this,"func");e&&(this.func=e.func)}static lc_name(){return"RunnablePassthrough"}async invoke(e,n){let r=wo(n);return this.func&&await this.func(e,r),this._callWithConfig(o=>Promise.resolve(o),e,r)}async*transform(e,n){let r=wo(n),o,i=!0;for await(let s of this._transformStreamWithConfig(e,a=>a,r))if(yield s,i)if(o===void 0)o=s;else try{o=_b(o,s)}catch{o=void 0,i=!1}this.func&&o!==void 0&&await this.func(o,r)}static assign(e){return new dge(new n4({steps:e}))}}});var B6t=b(()=>{qx();Lu()});var z6t=b(()=>{qx();Kx();Lu()});var H6t=b(()=>{gf();Om();yA();Lu();oi();wge()});var LA=b(()=>{br();qx();Qz();Lu();wge();B6t();z6t();H6t()});var i4,$A,Cd,o1=b(()=>{Kk();Lu();LA();i4=class extends Uo{parseResultWithPrompt(t,e,n){return this.parseResult(t,n)}_baseMessageToString(t){return typeof t.content=="string"?t.content:this._baseMessageContentToString(t.content)}_baseMessageContentToString(t){return JSON.stringify(t)}async invoke(t,e){return typeof t=="string"?this._callWithConfig(async(n,r)=>this.parseResult([{text:n}],r?.callbacks),t,{...e,runType:"parser"}):this._callWithConfig(async(n,r)=>this.parseResult([{message:n,text:this._baseMessageToString(n)}],r?.callbacks),t,{...e,runType:"parser"})}},$A=class extends i4{parseResult(t,e){return this.parse(t[0].text,e)}async parseWithPrompt(t,e,n){return this.parse(t,n)}_type(){throw new Error("_type not implemented")}},Cd=class extends Error{constructor(e,n,r,o=!1){super(e);M(this,"llmOutput");M(this,"observation");M(this,"sendToLLM");if(this.llmOutput=n,this.observation=r,this.sendToLLM=o,o&&(r===void 0||n===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");fA(this,"OUTPUT_PARSING_FAILURE")}}});var mJ,s4,DA=b(()=>{gf();gb();Sd();o1();$me();mJ=class extends $A{async*_transform(t){for await(let e of t)typeof e=="string"?yield this.parseResult([{text:e}]):yield this.parseResult([{message:e,text:this._baseMessageToString(e)}])}async*transform(t,e){yield*this._transformStreamWithConfig(t,this._transform.bind(this),{...e,runType:"parser"})}},s4=class extends mJ{constructor(e){super(e);M(this,"diff",!1);this.diff=e?.diff??this.diff}async*_transform(e){let n,r;for await(let o of e){if(typeof o!="string"&&typeof o.content!="string")throw new Error("Cannot handle non-string output.");let i;if(zme(o)){if(typeof o.content!="string")throw new Error("Cannot handle non-string message output.");i=new di({message:o,text:o.content})}else if(lv(o)){if(typeof o.content!="string")throw new Error("Cannot handle non-string message output.");i=new di({message:Yme(o),text:o.content})}else i=new eI({text:o});r===void 0?r=i:r=r.concat(i);let s=await this.parsePartialResult([r]);s!=null&&!Hk(s,n)&&(this.diff?yield this._diff(n,s):yield s,n=s)}}getFormatInstructions(){return""}}});var W6t=b(()=>{DA()});var V6t=b(()=>{o1();DA()});var q6t=b(()=>{DA()});var Q3e=b(()=>{br();nJ();oJ();I3e()});var hJ,gJ=b(()=>{kz();oJ();DA();Q3e();hJ=class extends s4{constructor(){super(...arguments);M(this,"lc_namespace",["langchain_core","output_parsers"]);M(this,"lc_serializable",!0)}static lc_name(){return"JsonOutputParser"}_concatOutputChunks(e,n){return this.diff?super._concatOutputChunks(e,n):n}_diff(e,n){if(n)return e?rJ(e,n):[{op:"replace",path:"",value:n}]}async parsePartialResult(e){return Cz(e[0].text)}async parse(e){return Cz(e,JSON.parse)}getFormatInstructions(){return""}_baseMessageToString(e){return e.text}}});var eqe,tqe=b(()=>{kz();o1();gJ();eqe=class extends $A{constructor(e){super();M(this,"lc_namespace",["langchain","output_parsers","standard_schema"]);M(this,"schema");this.schema=e}static lc_name(){return"StandardSchemaOutputParser"}static fromSerializableSchema(e){return new this(e)}async parse(e){try{let n=Cz(e,JSON.parse),r=await this.schema["~standard"].validate(n);if(r.issues)throw new Error(`Validation failed: ${JSON.stringify(r.issues)}`);return r.value}catch(n){throw new Cd(`Failed to parse. Text: "${e}". Error: ${n}`,e)}}_baseMessageToString(e){return e.text}getFormatInstructions(){return""}}});var nqe,rqe=b(()=>{Px();tg();o1();Ox();nqe=class extends $A{constructor(e){super(e);M(this,"schema");M(this,"lc_namespace",["langchain","output_parsers","structured"]);this.schema=e}static lc_name(){return"StructuredOutputParser"}toJSON(){return this.toJSONNotImplemented()}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){let n=Qh.object(Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Qh.string().describe(o)])));return new this(n)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
\`\`\`json
${JSON.stringify(Ki(this.schema))}
\`\`\`
`}async parse(e){try{let n=e.trim(),r=(n.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||n.match(/```json\s*([\s\S]*?)```/)?.[1]||n).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(o,i)=>`"${i.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await iL(this.schema,JSON.parse(r))}catch(n){throw new Cd(`Failed to parse. Text: "${e}". Error: ${n}`,e)}}_baseMessageToString(e){return e.text}}});var qlr,Klr,K6t=b(()=>{qlr=function(){let t={};t.parser=function(N,R){return new n(N,R)},t.SAXParser=n,t.SAXStream=c,t.createStream=l,t.MAX_BUFFER_LENGTH=65536;let e=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];t.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function n(N,R){if(!(this instanceof n))return new n(N,R);var X=this;o(X),X.q=X.c="",X.bufferCheckPosition=t.MAX_BUFFER_LENGTH,X.opt=R||{},X.opt.lowercase=X.opt.lowercase||X.opt.lowercasetags,X.looseCase=X.opt.lowercase?"toLowerCase":"toUpperCase",X.tags=[],X.closed=X.closedRoot=X.sawRoot=!1,X.tag=X.error=null,X.strict=!!N,X.noscript=!!(N||X.opt.noscript),X.state=k.BEGIN,X.strictEntities=X.opt.strictEntities,X.ENTITIES=X.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),X.attribList=[],X.opt.xmlns&&(X.ns=Object.create(m)),X.trackPosition=X.opt.position!==!1,X.trackPosition&&(X.position=X.line=X.column=0),P(X,"onready")}Object.create||(Object.create=function(N){function R(){}return R.prototype=N,new R}),Object.keys||(Object.keys=function(N){var R=[];for(var X in N)N.hasOwnProperty(X)&&R.push(X);return R});function r(N){for(var R=Math.max(t.MAX_BUFFER_LENGTH,10),X=0,D=0,G=e.length;D<G;D++){var ce=N[e[D]].length;if(ce>R)switch(e[D]){case"textNode":O(N);break;case"cdata":E(N,"oncdata",N.cdata),N.cdata="";break;case"script":E(N,"onscript",N.script),N.script="";break;default:U(N,"Max buffer length exceeded: "+e[D])}X=Math.max(X,ce)}N.bufferCheckPosition=t.MAX_BUFFER_LENGTH-X+N.position}function o(N){for(var R=0,X=e.length;R<X;R++)N[e[R]]=""}function i(N){O(N),N.cdata!==""&&(E(N,"oncdata",N.cdata),N.cdata=""),N.script!==""&&(E(N,"onscript",N.script),N.script="")}n.prototype={end:function(){V(this)},write:z,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){i(this)}};var s=ReadableStream;s||(s=function(){});var a=t.EVENTS.filter(function(N){return N!=="error"&&N!=="end"});function l(N,R){return new c(N,R)}function c(N,R){if(!(this instanceof c))return new c(N,R);s.apply(this),this._parser=new n(N,R),this.writable=!0,this.readable=!0;var X=this;this._parser.onend=function(){X.emit("end")},this._parser.onerror=function(D){X.emit("error",D),X._parser.error=null},this._decoder=null,a.forEach(function(D){Object.defineProperty(X,"on"+D,{get:function(){return X._parser["on"+D]},set:function(G){if(!G)return X.removeAllListeners(D),X._parser["on"+D]=G,G;X.on(D,G)},enumerable:!0,configurable:!1})})}c.prototype=Object.create(s.prototype,{constructor:{value:c}}),c.prototype.write=function(N){return this._parser.write(N.toString()),this.emit("data",N),!0},c.prototype.end=function(N){return N&&N.length&&this.write(N),this._parser.end(),!0},c.prototype.on=function(N,R){var X=this;return!X._parser["on"+N]&&a.indexOf(N)!==-1&&(X._parser["on"+N]=function(){var D=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);D.splice(0,0,N),X.emit.apply(X,D)}),s.prototype.on.call(X,N,R)};var u="[CDATA[",d="DOCTYPE",f="http://www.w3.org/XML/1998/namespace",p="http://www.w3.org/2000/xmlns/",m={xml:f,xmlns:p},h=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,g=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,v=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,y=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function w(N){return N===" "||N===`
`||N==="\r"||N===" "}function _(N){return N==='"'||N==="'"}function S(N){return N===">"||w(N)}function I(N,R){return N.test(R)}function C(N,R){return!I(N,R)}var k=0;t.STATE={BEGIN:k++,BEGIN_WHITESPACE:k++,TEXT:k++,TEXT_ENTITY:k++,OPEN_WAKA:k++,SGML_DECL:k++,SGML_DECL_QUOTED:k++,DOCTYPE:k++,DOCTYPE_QUOTED:k++,DOCTYPE_DTD:k++,DOCTYPE_DTD_QUOTED:k++,COMMENT_STARTING:k++,COMMENT:k++,COMMENT_ENDING:k++,COMMENT_ENDED:k++,CDATA:k++,CDATA_ENDING:k++,CDATA_ENDING_2:k++,PROC_INST:k++,PROC_INST_BODY:k++,PROC_INST_ENDING:k++,OPEN_TAG:k++,OPEN_TAG_SLASH:k++,ATTRIB:k++,ATTRIB_NAME:k++,ATTRIB_NAME_SAW_WHITE:k++,ATTRIB_VALUE:k++,ATTRIB_VALUE_QUOTED:k++,ATTRIB_VALUE_CLOSED:k++,ATTRIB_VALUE_UNQUOTED:k++,ATTRIB_VALUE_ENTITY_Q:k++,ATTRIB_VALUE_ENTITY_U:k++,CLOSE_TAG:k++,CLOSE_TAG_SAW_WHITE:k++,SCRIPT:k++,SCRIPT_ENDING:k++},t.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},t.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(t.ENTITIES).forEach(function(N){var R=t.ENTITIES[N],X=typeof R=="number"?String.fromCharCode(R):R;t.ENTITIES[N]=X});for(var T in t.STATE)t.STATE[t.STATE[T]]=T;k=t.STATE;function P(N,R,X){N[R]&&N[R](X)}function E(N,R,X){N.textNode&&O(N),P(N,R,X)}function O(N){N.textNode=$(N.opt,N.textNode),N.textNode&&P(N,"ontext",N.textNode),N.textNode=""}function $(N,R){return N.trim&&(R=R.trim()),N.normalize&&(R=R.replace(/\s+/g," ")),R}function U(N,R){return O(N),N.trackPosition&&(R+=`
Line: `+N.line+`
Column: `+N.column+`
Char: `+N.c),R=new Error(R),N.error=R,P(N,"onerror",R),N}function V(N){return N.sawRoot&&!N.closedRoot&&K(N,"Unclosed root tag"),N.state!==k.BEGIN&&N.state!==k.BEGIN_WHITESPACE&&N.state!==k.TEXT&&U(N,"Unexpected end"),O(N),N.c="",N.closed=!0,P(N,"onend"),n.call(N,N.strict,N.opt),N}function K(N,R){if(typeof N!="object"||!(N instanceof n))throw new Error("bad call to strictFail");N.strict&&U(N,R)}function se(N){N.strict||(N.tagName=N.tagName[N.looseCase]());var R=N.tags[N.tags.length-1]||N,X=N.tag={name:N.tagName,attributes:{}};N.opt.xmlns&&(X.ns=R.ns),N.attribList.length=0,E(N,"onopentagstart",X)}function le(N,R){var X=N.indexOf(":")<0?["",N]:N.split(":"),D=X[0],G=X[1];return R&&N==="xmlns"&&(D="xmlns",G=""),{prefix:D,local:G}}function Q(N){if(N.strict||(N.attribName=N.attribName[N.looseCase]()),N.attribList.indexOf(N.attribName)!==-1||N.tag.attributes.hasOwnProperty(N.attribName)){N.attribName=N.attribValue="";return}if(N.opt.xmlns){var R=le(N.attribName,!0),X=R.prefix,D=R.local;if(X==="xmlns")if(D==="xml"&&N.attribValue!==f)K(N,"xml: prefix must be bound to "+f+`
Actual: `+N.attribValue);else if(D==="xmlns"&&N.attribValue!==p)K(N,"xmlns: prefix must be bound to "+p+`
Actual: `+N.attribValue);else{var G=N.tag,ce=N.tags[N.tags.length-1]||N;G.ns===ce.ns&&(G.ns=Object.create(ce.ns)),G.ns[D]=N.attribValue}N.attribList.push([N.attribName,N.attribValue])}else N.tag.attributes[N.attribName]=N.attribValue,E(N,"onattribute",{name:N.attribName,value:N.attribValue});N.attribName=N.attribValue=""}function ne(N,R){if(N.opt.xmlns){var X=N.tag,D=le(N.tagName);X.prefix=D.prefix,X.local=D.local,X.uri=X.ns[D.prefix]||"",X.prefix&&!X.uri&&(K(N,"Unbound namespace prefix: "+JSON.stringify(N.tagName)),X.uri=D.prefix);var G=N.tags[N.tags.length-1]||N;X.ns&&G.ns!==X.ns&&Object.keys(X.ns).forEach(function(Xt){E(N,"onopennamespace",{prefix:Xt,uri:X.ns[Xt]})});for(var ce=0,Z=N.attribList.length;ce<Z;ce++){var te=N.attribList[ce],fe=te[0],de=te[1],ye=le(fe,!0),Te=ye.prefix,Be=ye.local,qe=Te===""?"":X.ns[Te]||"",Ae={name:fe,value:de,prefix:Te,local:Be,uri:qe};Te&&Te!=="xmlns"&&!qe&&(K(N,"Unbound namespace prefix: "+JSON.stringify(Te)),Ae.uri=Te),N.tag.attributes[fe]=Ae,E(N,"onattribute",Ae)}N.attribList.length=0}N.tag.isSelfClosing=!!R,N.sawRoot=!0,N.tags.push(N.tag),E(N,"onopentag",N.tag),R||(!N.noscript&&N.tagName.toLowerCase()==="script"?N.state=k.SCRIPT:N.state=k.TEXT,N.tag=null,N.tagName=""),N.attribName=N.attribValue="",N.attribList.length=0}function ee(N){if(!N.tagName){K(N,"Weird empty close tag."),N.textNode+="</>",N.state=k.TEXT;return}if(N.script){if(N.tagName!=="script"){N.script+="</"+N.tagName+">",N.tagName="",N.state=k.SCRIPT;return}E(N,"onscript",N.script),N.script=""}var R=N.tags.length,X=N.tagName;N.strict||(X=X[N.looseCase]());for(var D=X;R--&&N.tags[R].name!==D;)K(N,"Unexpected close tag");if(R<0){K(N,"Unmatched closing tag: "+N.tagName),N.textNode+="</"+N.tagName+">",N.state=k.TEXT;return}N.tagName=X;for(var G=N.tags.length;G-- >R;){var ce=N.tag=N.tags.pop();N.tagName=N.tag.name,E(N,"onclosetag",N.tagName);var Z={};for(var te in ce.ns)Z[te]=ce.ns[te];var fe=N.tags[N.tags.length-1]||N;N.opt.xmlns&&ce.ns!==fe.ns&&Object.keys(ce.ns).forEach(function(de){var ye=ce.ns[de];E(N,"onclosenamespace",{prefix:de,uri:ye})})}R===0&&(N.closedRoot=!0),N.tagName=N.attribValue=N.attribName="",N.attribList.length=0,N.state=k.TEXT}function ae(N){var R=N.entity,X=R.toLowerCase(),D,G="";return N.ENTITIES[R]?N.ENTITIES[R]:N.ENTITIES[X]?N.ENTITIES[X]:(R=X,R.charAt(0)==="#"&&(R.charAt(1)==="x"?(R=R.slice(2),D=parseInt(R,16),G=D.toString(16)):(R=R.slice(1),D=parseInt(R,10),G=D.toString(10))),R=R.replace(/^0+/,""),isNaN(D)||G.toLowerCase()!==R?(K(N,"Invalid character entity"),"&"+N.entity+";"):String.fromCodePoint(D))}function q(N,R){R==="<"?(N.state=k.OPEN_WAKA,N.startTagPosition=N.position):w(R)||(K(N,"Non-whitespace before first tag."),N.textNode=R,N.state=k.TEXT)}function F(N,R){var X="";return R<N.length&&(X=N.charAt(R)),X}function z(N){var R=this;if(this.error)throw this.error;if(R.closed)return U(R,"Cannot write after close. Assign an onready handler.");if(N===null)return V(R);typeof N=="object"&&(N=N.toString());for(var X=0,D="";D=F(N,X++),R.c=D,!!D;)switch(R.trackPosition&&(R.position++,D===`
`?(R.line++,R.column=0):R.column++),R.state){case k.BEGIN:if(R.state=k.BEGIN_WHITESPACE,D==="\uFEFF")continue;q(R,D);continue;case k.BEGIN_WHITESPACE:q(R,D);continue;case k.TEXT:if(R.sawRoot&&!R.closedRoot){for(var G=X-1;D&&D!=="<"&&D!=="&";)D=F(N,X++),D&&R.trackPosition&&(R.position++,D===`
`?(R.line++,R.column=0):R.column++);R.textNode+=N.substring(G,X-1)}D==="<"&&!(R.sawRoot&&R.closedRoot&&!R.strict)?(R.state=k.OPEN_WAKA,R.startTagPosition=R.position):(!w(D)&&(!R.sawRoot||R.closedRoot)&&K(R,"Text data outside of root node."),D==="&"?R.state=k.TEXT_ENTITY:R.textNode+=D);continue;case k.SCRIPT:D==="<"?R.state=k.SCRIPT_ENDING:R.script+=D;continue;case k.SCRIPT_ENDING:D==="/"?R.state=k.CLOSE_TAG:(R.script+="<"+D,R.state=k.SCRIPT);continue;case k.OPEN_WAKA:if(D==="!")R.state=k.SGML_DECL,R.sgmlDecl="";else if(!w(D))if(I(h,D))R.state=k.OPEN_TAG,R.tagName=D;else if(D==="/")R.state=k.CLOSE_TAG,R.tagName="";else if(D==="?")R.state=k.PROC_INST,R.procInstName=R.procInstBody="";else{if(K(R,"Unencoded <"),R.startTagPosition+1<R.position){var ce=R.position-R.startTagPosition;D=new Array(ce).join(" ")+D}R.textNode+="<"+D,R.state=k.TEXT}continue;case k.SGML_DECL:(R.sgmlDecl+D).toUpperCase()===u?(E(R,"onopencdata"),R.state=k.CDATA,R.sgmlDecl="",R.cdata=""):R.sgmlDecl+D==="--"?(R.state=k.COMMENT,R.comment="",R.sgmlDecl=""):(R.sgmlDecl+D).toUpperCase()===d?(R.state=k.DOCTYPE,(R.doctype||R.sawRoot)&&K(R,"Inappropriately located doctype declaration"),R.doctype="",R.sgmlDecl=""):D===">"?(E(R,"onsgmldeclaration",R.sgmlDecl),R.sgmlDecl="",R.state=k.TEXT):(_(D)&&(R.state=k.SGML_DECL_QUOTED),R.sgmlDecl+=D);continue;case k.SGML_DECL_QUOTED:D===R.q&&(R.state=k.SGML_DECL,R.q=""),R.sgmlDecl+=D;continue;case k.DOCTYPE:D===">"?(R.state=k.TEXT,E(R,"ondoctype",R.doctype),R.doctype=!0):(R.doctype+=D,D==="["?R.state=k.DOCTYPE_DTD:_(D)&&(R.state=k.DOCTYPE_QUOTED,R.q=D));continue;case k.DOCTYPE_QUOTED:R.doctype+=D,D===R.q&&(R.q="",R.state=k.DOCTYPE);continue;case k.DOCTYPE_DTD:R.doctype+=D,D==="]"?R.state=k.DOCTYPE:_(D)&&(R.state=k.DOCTYPE_DTD_QUOTED,R.q=D);continue;case k.DOCTYPE_DTD_QUOTED:R.doctype+=D,D===R.q&&(R.state=k.DOCTYPE_DTD,R.q="");continue;case k.COMMENT:D==="-"?R.state=k.COMMENT_ENDING:R.comment+=D;continue;case k.COMMENT_ENDING:D==="-"?(R.state=k.COMMENT_ENDED,R.comment=$(R.opt,R.comment),R.comment&&E(R,"oncomment",R.comment),R.comment=""):(R.comment+="-"+D,R.state=k.COMMENT);continue;case k.COMMENT_ENDED:D!==">"?(K(R,"Malformed comment"),R.comment+="--"+D,R.state=k.COMMENT):R.state=k.TEXT;continue;case k.CDATA:D==="]"?R.state=k.CDATA_ENDING:R.cdata+=D;continue;case k.CDATA_ENDING:D==="]"?R.state=k.CDATA_ENDING_2:(R.cdata+="]"+D,R.state=k.CDATA);continue;case k.CDATA_ENDING_2:D===">"?(R.cdata&&E(R,"oncdata",R.cdata),E(R,"onclosecdata"),R.cdata="",R.state=k.TEXT):D==="]"?R.cdata+="]":(R.cdata+="]]"+D,R.state=k.CDATA);continue;case k.PROC_INST:D==="?"?R.state=k.PROC_INST_ENDING:w(D)?R.state=k.PROC_INST_BODY:R.procInstName+=D;continue;case k.PROC_INST_BODY:if(!R.procInstBody&&w(D))continue;D==="?"?R.state=k.PROC_INST_ENDING:R.procInstBody+=D;continue;case k.PROC_INST_ENDING:D===">"?(E(R,"onprocessinginstruction",{name:R.procInstName,body:R.procInstBody}),R.procInstName=R.procInstBody="",R.state=k.TEXT):(R.procInstBody+="?"+D,R.state=k.PROC_INST_BODY);continue;case k.OPEN_TAG:I(g,D)?R.tagName+=D:(se(R),D===">"?ne(R):D==="/"?R.state=k.OPEN_TAG_SLASH:(w(D)||K(R,"Invalid character in tag name"),R.state=k.ATTRIB));continue;case k.OPEN_TAG_SLASH:D===">"?(ne(R,!0),ee(R)):(K(R,"Forward-slash in opening tag not followed by >"),R.state=k.ATTRIB);continue;case k.ATTRIB:if(w(D))continue;D===">"?ne(R):D==="/"?R.state=k.OPEN_TAG_SLASH:I(h,D)?(R.attribName=D,R.attribValue="",R.state=k.ATTRIB_NAME):K(R,"Invalid attribute name");continue;case k.ATTRIB_NAME:D==="="?R.state=k.ATTRIB_VALUE:D===">"?(K(R,"Attribute without value"),R.attribValue=R.attribName,Q(R),ne(R)):w(D)?R.state=k.ATTRIB_NAME_SAW_WHITE:I(g,D)?R.attribName+=D:K(R,"Invalid attribute name");continue;case k.ATTRIB_NAME_SAW_WHITE:if(D==="=")R.state=k.ATTRIB_VALUE;else{if(w(D))continue;K(R,"Attribute without value"),R.tag.attributes[R.attribName]="",R.attribValue="",E(R,"onattribute",{name:R.attribName,value:""}),R.attribName="",D===">"?ne(R):I(h,D)?(R.attribName=D,R.state=k.ATTRIB_NAME):(K(R,"Invalid attribute name"),R.state=k.ATTRIB)}continue;case k.ATTRIB_VALUE:if(w(D))continue;_(D)?(R.q=D,R.state=k.ATTRIB_VALUE_QUOTED):(K(R,"Unquoted attribute value"),R.state=k.ATTRIB_VALUE_UNQUOTED,R.attribValue=D);continue;case k.ATTRIB_VALUE_QUOTED:if(D!==R.q){D==="&"?R.state=k.ATTRIB_VALUE_ENTITY_Q:R.attribValue+=D;continue}Q(R),R.q="",R.state=k.ATTRIB_VALUE_CLOSED;continue;case k.ATTRIB_VALUE_CLOSED:w(D)?R.state=k.ATTRIB:D===">"?ne(R):D==="/"?R.state=k.OPEN_TAG_SLASH:I(h,D)?(K(R,"No whitespace between attributes"),R.attribName=D,R.attribValue="",R.state=k.ATTRIB_NAME):K(R,"Invalid attribute name");continue;case k.ATTRIB_VALUE_UNQUOTED:if(!S(D)){D==="&"?R.state=k.ATTRIB_VALUE_ENTITY_U:R.attribValue+=D;continue}Q(R),D===">"?ne(R):R.state=k.ATTRIB;continue;case k.CLOSE_TAG:if(R.tagName)D===">"?ee(R):I(g,D)?R.tagName+=D:R.script?(R.script+="</"+R.tagName,R.tagName="",R.state=k.SCRIPT):(w(D)||K(R,"Invalid tagname in closing tag"),R.state=k.CLOSE_TAG_SAW_WHITE);else{if(w(D))continue;C(h,D)?R.script?(R.script+="</"+D,R.state=k.SCRIPT):K(R,"Invalid tagname in closing tag."):R.tagName=D}continue;case k.CLOSE_TAG_SAW_WHITE:if(w(D))continue;D===">"?ee(R):K(R,"Invalid characters in closing tag");continue;case k.TEXT_ENTITY:case k.ATTRIB_VALUE_ENTITY_Q:case k.ATTRIB_VALUE_ENTITY_U:var Z,te;switch(R.state){case k.TEXT_ENTITY:Z=k.TEXT,te="textNode";break;case k.ATTRIB_VALUE_ENTITY_Q:Z=k.ATTRIB_VALUE_QUOTED,te="attribValue";break;case k.ATTRIB_VALUE_ENTITY_U:Z=k.ATTRIB_VALUE_UNQUOTED,te="attribValue";break}if(D===";")if(R.opt.unparsedEntities){var fe=ae(R);R.entity="",R.state=Z,R.write(fe)}else R[te]+=ae(R),R.entity="",R.state=Z;else I(R.entity.length?y:v,D)?R.entity+=D:(K(R,"Invalid character in entity name"),R[te]+="&"+R.entity+D,R.entity="",R.state=Z);continue;default:throw new Error(R,"Unknown state: "+R.state)}return R.position>=R.bufferCheckPosition&&r(R),R}return String.fromCodePoint||function(){var N=String.fromCharCode,R=Math.floor,X=function(){var D=16384,G=[],ce,Z,te=-1,fe=arguments.length;if(!fe)return"";for(var de="";++te<fe;){var ye=Number(arguments[te]);if(!isFinite(ye)||ye<0||ye>1114111||R(ye)!==ye)throw RangeError("Invalid code point: "+ye);ye<=65535?G.push(ye):(ye-=65536,ce=(ye>>10)+55296,Z=ye%1024+56320,G.push(ce,Z)),(te+1===fe||G.length>D)&&(de+=N.apply(null,G),G.length=0)}return de};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:X,configurable:!0,writable:!0}):String.fromCodePoint=X}(),t},Klr=qlr()});var G6t=b(()=>{oJ();DA();Q3e();K6t()});var a4=b(()=>{br();kz();o1();DA();W6t();V6t();q6t();gJ();tqe();rqe();G6t()});var Z6t,Y6t=b(()=>{tv();a4();Z6t=class extends i4{constructor(e){super(e);M(this,"lc_namespace",["langchain","google_genai","output_parsers"]);M(this,"returnId",!1);M(this,"keyName");M(this,"returnSingle",!1);M(this,"zodSchema");M(this,"serializableSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema,this.serializableSchema=e.serializableSchema}static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}async _validateResult(e){if(this.serializableSchema!==void 0){let r=await this.serializableSchema["~standard"].validate(e);if(r.issues)throw new Cd(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.issues)}`,JSON.stringify(e,null,2));return r.value}if(this.zodSchema===void 0)return e;let n=await oL(this.zodSchema,e);if(n.success)return n.data;throw new Cd(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){let n=e.flatMap(o=>{let{message:i}=o;return!("tool_calls"in i)||!Array.isArray(i.tool_calls)?[]:i.tool_calls});if(n[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");let[r]=n;return await this._validateResult(r.args)}}});function Xlr(t){let e=[];return t?.apiClient&&e.push(t.apiClient),e.push(`${Jlr}/${Ylr}`),e.join(" ")}async function Qlr(t){var e;let n=new Headers;n.append("Content-Type","application/json"),n.append("x-goog-api-client",Xlr(t.requestOptions)),n.append("x-goog-api-key",t.apiKey);let r=(e=t.requestOptions)===null||e===void 0?void 0:e.customHeaders;if(r){if(!(r instanceof Headers))try{r=new Headers(r)}catch(o){throw new Yx(`unable to convert customHeaders value ${JSON.stringify(r)} to Headers: ${o.message}`)}for(let[o,i]of r.entries()){if(o==="x-goog-api-key")throw new Yx(`Cannot set reserved header name ${o}`);if(o==="x-goog-api-client")throw new Yx(`Header name ${o} can only be set using the apiClient field`);n.append(o,i)}}return n}async function ecr(t,e,n,r,o,i){let s=new oqe(t,e,n,r,i);return{url:s.toString(),fetchOptions:Object.assign(Object.assign({},ocr(i)),{method:"POST",headers:await Qlr(s),body:o})}}async function bJ(t,e,n,r,o,i={},s=fetch){let{url:a,fetchOptions:l}=await ecr(t,e,n,r,o,i);return tcr(a,l,s)}async function tcr(t,e,n=fetch){let r;try{r=await n(t,e)}catch(o){ncr(o,t)}return r.ok||await rcr(r,t),r}function ncr(t,e){let n=t;throw n.name==="AbortError"?(n=new xge(`Request aborted when fetching ${e.toString()}: ${t.message}`),n.stack=t.stack):t instanceof _ge||t instanceof Yx||(n=new Du(`Error fetching from ${e.toString()}: ${t.message}`),n.stack=t.stack),n}async function rcr(t,e){let n="",r;try{let o=await t.json();n=o.error.message,o.error.details&&(n+=` ${JSON.stringify(o.error.details)}`,r=o.error.details)}catch{}throw new _ge(`Error fetching from ${e.toString()}: [${t.status} ${t.statusText}] ${n}`,t.status,t.statusText,r)}function ocr(t){let e={};if(t?.signal!==void 0||t?.timeout>=0){let n=new AbortController;t?.timeout>=0&&setTimeout(()=>n.abort(),t.timeout),t?.signal&&t.signal.addEventListener("abort",()=>{n.abort()}),e.signal=n.signal}return e}function sqe(t){return t.text=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),bge(t.candidates[0]))throw new FA(`${UA(t)}`,t);return icr(t)}else if(t.promptFeedback)throw new FA(`Text not available. ${UA(t)}`,t);return""},t.functionCall=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),bge(t.candidates[0]))throw new FA(`${UA(t)}`,t);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),aVt(t)[0]}else if(t.promptFeedback)throw new FA(`Function call not available. ${UA(t)}`,t)},t.functionCalls=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),bge(t.candidates[0]))throw new FA(`${UA(t)}`,t);return aVt(t)}else if(t.promptFeedback)throw new FA(`Function call not available. ${UA(t)}`,t)},t}function icr(t){var e,n,r,o;let i=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(let s of(o=(r=t.candidates)===null||r===void 0?void 0:r[0].content)===null||o===void 0?void 0:o.parts)s.text&&i.push(s.text),s.executableCode&&i.push("\n```"+s.executableCode.language+`
`+s.executableCode.code+"\n```\n"),s.codeExecutionResult&&i.push("\n```\n"+s.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function aVt(t){var e,n,r,o;let i=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(let s of(o=(r=t.candidates)===null||r===void 0?void 0:r[0].content)===null||o===void 0?void 0:o.parts)s.functionCall&&i.push(s.functionCall);if(i.length>0)return i}function bge(t){return!!t.finishReason&&scr.includes(t.finishReason)}function UA(t){var e,n,r;let o="";if((!t.candidates||t.candidates.length===0)&&t.promptFeedback)o+="Response was blocked",!((e=t.promptFeedback)===null||e===void 0)&&e.blockReason&&(o+=` due to ${t.promptFeedback.blockReason}`),!((n=t.promptFeedback)===null||n===void 0)&&n.blockReasonMessage&&(o+=`: ${t.promptFeedback.blockReasonMessage}`);else if(!((r=t.candidates)===null||r===void 0)&&r[0]){let i=t.candidates[0];bge(i)&&(o+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(o+=`: ${i.finishMessage}`))}return o}function vJ(t){return this instanceof vJ?(this.v=t,this):new vJ(t)}function acr(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),o,i=[];return o={},s("next"),s("throw"),s("return"),o[Symbol.asyncIterator]=function(){return this},o;function s(f){r[f]&&(o[f]=function(p){return new Promise(function(m,h){i.push([f,p,m,h])>1||a(f,p)})})}function a(f,p){try{l(r[f](p))}catch(m){d(i[0][3],m)}}function l(f){f.value instanceof vJ?Promise.resolve(f.value.v).then(c,u):d(i[0][2],f)}function c(f){a("next",f)}function u(f){a("throw",f)}function d(f,p){f(p),i.shift(),i.length&&a(i[0][0],i[0][1])}}function lcr(t){let e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),n=dcr(e),[r,o]=n.tee();return{stream:ucr(r),response:ccr(o)}}async function ccr(t){let e=[],n=t.getReader();for(;;){let{done:r,value:o}=await n.read();if(r)return sqe(fcr(e));e.push(o)}}function ucr(t){return acr(this,arguments,function*(){let n=t.getReader();for(;;){let{value:r,done:o}=yield vJ(n.read());if(o)break;yield yield vJ(sqe(r))}})}function dcr(t){let e=t.getReader();return new ReadableStream({start(r){let o="";return i();function i(){return e.read().then(({value:s,done:a})=>{if(a){if(o.trim()){r.error(new Du("Failed to parse stream"));return}r.close();return}o+=s;let l=o.match(lVt),c;for(;l;){try{c=JSON.parse(l[1])}catch{r.error(new Du(`Error parsing JSON response: "${l[1]}"`));return}r.enqueue(c),o=o.substring(l[0].length),l=o.match(lVt)}return i()}).catch(s=>{let a=s;throw a.stack=s.stack,a.name==="AbortError"?a=new xge("Request aborted when reading from the stream"):a=new Du("Error reading from the stream"),a})}}})}function fcr(t){let e=t[t.length-1],n={promptFeedback:e?.promptFeedback};for(let r of t){if(r.candidates){let o=0;for(let i of r.candidates)if(n.candidates||(n.candidates=[]),n.candidates[o]||(n.candidates[o]={index:o}),n.candidates[o].citationMetadata=i.citationMetadata,n.candidates[o].groundingMetadata=i.groundingMetadata,n.candidates[o].finishReason=i.finishReason,n.candidates[o].finishMessage=i.finishMessage,n.candidates[o].safetyRatings=i.safetyRatings,i.content&&i.content.parts){n.candidates[o].content||(n.candidates[o].content={role:i.content.role||"user",parts:[]});let s={};for(let a of i.content.parts)a.text&&(s.text=a.text),a.functionCall&&(s.functionCall=a.functionCall),a.executableCode&&(s.executableCode=a.executableCode),a.codeExecutionResult&&(s.codeExecutionResult=a.codeExecutionResult),Object.keys(s).length===0&&(s.text=""),n.candidates[o].content.parts.push(s)}o++}r.usageMetadata&&(n.usageMetadata=r.usageMetadata)}return n}async function pVt(t,e,n,r){let o=await bJ(e,s1.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(n),r);return lcr(o)}async function mVt(t,e,n,r){let i=await(await bJ(e,s1.GENERATE_CONTENT,t,!1,JSON.stringify(n),r)).json();return{response:sqe(i)}}function hVt(t){if(t!=null){if(typeof t=="string")return{role:"system",parts:[{text:t}]};if(t.text)return{role:"system",parts:[t]};if(t.parts)return t.role?t:{role:"system",parts:t.parts}}}function wJ(t){let e=[];if(typeof t=="string")e=[{text:t}];else for(let n of t)typeof n=="string"?e.push({text:n}):e.push(n);return pcr(e)}function pcr(t){let e={role:"user",parts:[]},n={role:"function",parts:[]},r=!1,o=!1;for(let i of t)"functionResponse"in i?(n.parts.push(i),o=!0):(e.parts.push(i),r=!0);if(r&&o)throw new Du("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!r&&!o)throw new Du("No content is provided for sending chat message.");return r?e:n}function mcr(t,e){var n;let r={model:e?.model,generationConfig:e?.generationConfig,safetySettings:e?.safetySettings,tools:e?.tools,toolConfig:e?.toolConfig,systemInstruction:e?.systemInstruction,cachedContent:(n=e?.cachedContent)===null||n===void 0?void 0:n.name,contents:[]},o=t.generateContentRequest!=null;if(t.contents){if(o)throw new Yx("CountTokensRequest must have one of contents or generateContentRequest, not both.");r.contents=t.contents}else if(o)r=Object.assign(Object.assign({},r),t.generateContentRequest);else{let i=wJ(t);r.contents=[i]}return{generateContentRequest:r}}function cVt(t){let e;return t.contents?e=t:e={contents:[wJ(t)]},t.systemInstruction&&(e.systemInstruction=hVt(t.systemInstruction)),e}function hcr(t){return typeof t=="string"||Array.isArray(t)?{content:wJ(t)}:t}function ycr(t){let e=!1;for(let n of t){let{role:r,parts:o}=n;if(!e&&r!=="user")throw new Du(`First content should be with role 'user', got ${r}`);if(!eVt.includes(r))throw new Du(`Each item should include role field. Got ${r} but valid roles are: ${JSON.stringify(eVt)}`);if(!Array.isArray(o))throw new Du("Content should have 'parts' property with an array of Parts");if(o.length===0)throw new Du("Each Content should have at least one part");let i={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(let a of o)for(let l of uVt)l in a&&(i[l]+=1);let s=gcr[r];for(let a of uVt)if(!s.includes(a)&&i[a]>0)throw new Du(`Content with role '${r}' can't contain '${a}' part`);e=!0}}function dVt(t){var e;if(t.candidates===void 0||t.candidates.length===0)return!1;let n=(e=t.candidates[0])===null||e===void 0?void 0:e.content;if(n===void 0||n.parts===void 0||n.parts.length===0)return!1;for(let r of n.parts)if(r===void 0||Object.keys(r).length===0||r.text!==void 0&&r.text==="")return!1;return!0}async function vcr(t,e,n,r){return(await bJ(e,s1.COUNT_TOKENS,t,!1,JSON.stringify(n),r)).json()}async function wcr(t,e,n,r){return(await bJ(e,s1.EMBED_CONTENT,t,!1,JSON.stringify(n),r)).json()}async function bcr(t,e,n,r){let o=n.requests.map(s=>Object.assign(Object.assign({},s),{model:e}));return(await bJ(e,s1.BATCH_EMBED_CONTENTS,t,!1,JSON.stringify({requests:o}),r)).json()}var J6t,X6t,Q6t,eVt,tVt,nVt,rVt,oVt,yJ,iVt,i1,sVt,Du,FA,_ge,Yx,xge,Glr,Zlr,Ylr,Jlr,s1,oqe,scr,lVt,uVt,gcr,fVt,iqe,Sge,a1,Cge=b(()=>{(function(t){t.STRING="string",t.NUMBER="number",t.INTEGER="integer",t.BOOLEAN="boolean",t.ARRAY="array",t.OBJECT="object"})(J6t||(J6t={}));(function(t){t.LANGUAGE_UNSPECIFIED="language_unspecified",t.PYTHON="python"})(X6t||(X6t={}));(function(t){t.OUTCOME_UNSPECIFIED="outcome_unspecified",t.OUTCOME_OK="outcome_ok",t.OUTCOME_FAILED="outcome_failed",t.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(Q6t||(Q6t={}));eVt=["user","model","function","system"];(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",t.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(tVt||(tVt={}));(function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"})(nVt||(nVt={}));(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(rVt||(rVt={}));(function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER"})(oVt||(oVt={}));(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.SPII="SPII",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.OTHER="OTHER"})(yJ||(yJ={}));(function(t){t.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",t.RETRIEVAL_QUERY="RETRIEVAL_QUERY",t.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",t.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",t.CLASSIFICATION="CLASSIFICATION",t.CLUSTERING="CLUSTERING"})(iVt||(iVt={}));(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE"})(i1||(i1={}));(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(sVt||(sVt={}));Du=class extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}},FA=class extends Du{constructor(e,n){super(e),this.response=n}},_ge=class extends Du{constructor(e,n,r,o){super(e),this.status=n,this.statusText=r,this.errorDetails=o}},Yx=class extends Du{},xge=class extends Du{};Glr="https://generativelanguage.googleapis.com",Zlr="v1beta",Ylr="0.24.1",Jlr="genai-js";(function(t){t.GENERATE_CONTENT="generateContent",t.STREAM_GENERATE_CONTENT="streamGenerateContent",t.COUNT_TOKENS="countTokens",t.EMBED_CONTENT="embedContent",t.BATCH_EMBED_CONTENTS="batchEmbedContents"})(s1||(s1={}));oqe=class{constructor(e,n,r,o,i){this.model=e,this.task=n,this.apiKey=r,this.stream=o,this.requestOptions=i}toString(){var e,n;let r=((e=this.requestOptions)===null||e===void 0?void 0:e.apiVersion)||Zlr,i=`${((n=this.requestOptions)===null||n===void 0?void 0:n.baseUrl)||Glr}/${r}/${this.model}:${this.task}`;return this.stream&&(i+="?alt=sse"),i}};scr=[yJ.RECITATION,yJ.SAFETY,yJ.LANGUAGE];lVt=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;uVt=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],gcr={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};fVt="SILENT_ERROR",iqe=class{constructor(e,n,r,o={}){this.model=n,this.params=r,this._requestOptions=o,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,r?.history&&(ycr(r.history),this._history=r.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,n={}){var r,o,i,s,a,l;await this._sendPromise;let c=wJ(e),u={safetySettings:(r=this.params)===null||r===void 0?void 0:r.safetySettings,generationConfig:(o=this.params)===null||o===void 0?void 0:o.generationConfig,tools:(i=this.params)===null||i===void 0?void 0:i.tools,toolConfig:(s=this.params)===null||s===void 0?void 0:s.toolConfig,systemInstruction:(a=this.params)===null||a===void 0?void 0:a.systemInstruction,cachedContent:(l=this.params)===null||l===void 0?void 0:l.cachedContent,contents:[...this._history,c]},d=Object.assign(Object.assign({},this._requestOptions),n),f;return this._sendPromise=this._sendPromise.then(()=>mVt(this._apiKey,this.model,u,d)).then(p=>{var m;if(dVt(p.response)){this._history.push(c);let h=Object.assign({parts:[],role:"model"},(m=p.response.candidates)===null||m===void 0?void 0:m[0].content);this._history.push(h)}else{let h=UA(p.response);h&&console.warn(`sendMessage() was unsuccessful. ${h}. Inspect response object for details.`)}f=p}).catch(p=>{throw this._sendPromise=Promise.resolve(),p}),await this._sendPromise,f}async sendMessageStream(e,n={}){var r,o,i,s,a,l;await this._sendPromise;let c=wJ(e),u={safetySettings:(r=this.params)===null||r===void 0?void 0:r.safetySettings,generationConfig:(o=this.params)===null||o===void 0?void 0:o.generationConfig,tools:(i=this.params)===null||i===void 0?void 0:i.tools,toolConfig:(s=this.params)===null||s===void 0?void 0:s.toolConfig,systemInstruction:(a=this.params)===null||a===void 0?void 0:a.systemInstruction,cachedContent:(l=this.params)===null||l===void 0?void 0:l.cachedContent,contents:[...this._history,c]},d=Object.assign(Object.assign({},this._requestOptions),n),f=pVt(this._apiKey,this.model,u,d);return this._sendPromise=this._sendPromise.then(()=>f).catch(p=>{throw new Error(fVt)}).then(p=>p.response).then(p=>{if(dVt(p)){this._history.push(c);let m=Object.assign({},p.candidates[0].content);m.role||(m.role="model"),this._history.push(m)}else{let m=UA(p);m&&console.warn(`sendMessageStream() was unsuccessful. ${m}. Inspect response object for details.`)}}).catch(p=>{p.message!==fVt&&console.error(p)}),f}};Sge=class{constructor(e,n,r={}){this.apiKey=e,this._requestOptions=r,n.model.includes("/")?this.model=n.model:this.model=`models/${n.model}`,this.generationConfig=n.generationConfig||{},this.safetySettings=n.safetySettings||[],this.tools=n.tools,this.toolConfig=n.toolConfig,this.systemInstruction=hVt(n.systemInstruction),this.cachedContent=n.cachedContent}async generateContent(e,n={}){var r;let o=cVt(e),i=Object.assign(Object.assign({},this._requestOptions),n);return mVt(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(r=this.cachedContent)===null||r===void 0?void 0:r.name},o),i)}async generateContentStream(e,n={}){var r;let o=cVt(e),i=Object.assign(Object.assign({},this._requestOptions),n);return pVt(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(r=this.cachedContent)===null||r===void 0?void 0:r.name},o),i)}startChat(e){var n;return new iqe(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(n=this.cachedContent)===null||n===void 0?void 0:n.name},e),this._requestOptions)}async countTokens(e,n={}){let r=mcr(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),o=Object.assign(Object.assign({},this._requestOptions),n);return vcr(this.apiKey,this.model,r,o)}async embedContent(e,n={}){let r=hcr(e),o=Object.assign(Object.assign({},this._requestOptions),n);return wcr(this.apiKey,this.model,r,o)}async batchEmbedContents(e,n={}){let r=Object.assign(Object.assign({},this._requestOptions),n);return bcr(this.apiKey,this.model,e,r)}};a1=class{constructor(e){this.apiKey=e}getGenerativeModel(e,n){if(!e.model)throw new Du("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new Sge(this.apiKey,e,n)}getGenerativeModelFromCachedContent(e,n,r){if(!e.name)throw new Yx("Cached content must contain a `name` field.");if(!e.model)throw new Yx("Cached content must contain a `model` field.");let o=["model","systemInstruction"];for(let s of o)if(n?.[s]&&e[s]&&n?.[s]!==e[s]){if(s==="model"){let a=n.model.startsWith("models/")?n.model.replace("models/",""):n.model,l=e.model.startsWith("models/")?e.model.replace("models/",""):e.model;if(a===l)continue}throw new Yx(`Different value for "${s}" specified in modelParams (${n[s]}) and cachedContent (${e[s]})`)}let i=Object.assign(Object.assign({},n),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new Sge(this.apiKey,i,r)}}});function aqe(t,e){let n=_cr(t);return{tools:n,toolConfig:Scr(n,e)}}function _cr(t){let e=[],n=[];return t.forEach(r=>{if(xf(r)){let[o]=L6t([r]);o.functionDeclarations&&e.push(...o.functionDeclarations)}else if(Zx(r)){let{functionDeclarations:o}=xcr(r);if(o)e.push(...o);else throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool")}else n.push(r)}),n.find(r=>"functionDeclarations"in r)?n.map(r=>{if(e?.length>0&&"functionDeclarations"in r){let o={functionDeclarations:[...r.functionDeclarations||[],...e]};return e=[],o}return r}):[...n,...e.length>0?[{functionDeclarations:e}]:[]]}function xcr(t){return{functionDeclarations:[{name:t.function.name,description:t.function.description,parameters:Vk(t.function.parameters)}]}}function Scr(t,e){if(!t.length||!e)return;let{toolChoice:n,allowedFunctionNames:r}=e,o={any:i1.ANY,auto:i1.AUTO,none:i1.NONE};if(n&&["any","auto","none"].includes(n))return{functionCallingConfig:{mode:o[n]??"MODE_UNSPECIFIED",allowedFunctionNames:r}};if(typeof n=="string"||r)return{functionCallingConfig:{mode:i1.ANY,allowedFunctionNames:[...r??[],...n&&typeof n=="string"?[n]:[]]}}}var gVt=b(()=>{Dme();vge();Cge();rI();lg()});var yVt,vVt=b(()=>{yVt={"gemini-embedding-001":{maxInputTokens:2048,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-lite-preview-09-2025":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro-preview-06-05":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-04-17":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-preview-09-2025":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro-preview-05-06":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-05-20":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-live-2.5-flash":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-3-flash-preview":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-live-2.5-flash-preview-native-audio":{maxInputTokens:131072,imageInputs:!1,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-lite":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-tts":{maxInputTokens:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-flash-latest":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-lite-preview-06-17":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-image":{maxInputTokens:32768,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-pro-preview-tts":{maxInputTokens:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-image-preview":{maxInputTokens:32768,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-1.5-flash-8b":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-3-pro-preview":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.0-flash-lite":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-1.5-flash":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-flash-lite-latest":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.0-flash":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-1.5-pro":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1}}});function _J(t){let e=t.constructor;return new e({...t,content:t.contentBlocks,response_metadata:{...t.response_metadata,output_version:"v1"}})}var wVt,bVt=b(()=>{wVt=t=>t()});function jA(t,e){if(t.function===void 0)return;let n;if(e?.partial)try{n=kL(t.function.arguments??"{}")}catch{return}else try{n=JSON.parse(t.function.arguments)}catch(o){throw new Cd([`Function "${t.function.name}" arguments:`,"",t.function.arguments,"","are not valid JSON.",`Error: ${o.message}`].join(`
`))}let r={name:t.function.name,args:n,type:"tool_call"};return e?.returnId&&(r.id=t.id),r}function l4(t){if(t.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:t.id,type:"function",function:{name:t.name,arguments:JSON.stringify(t.args)}}}function iI(t,e){return{name:t.function?.name,args:t.function?.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var _Vt,lqe,cqe=b(()=>{kz();Om();Px();o1();DA();gJ();_Vt=class extends s4{constructor(e){super(e);M(this,"returnId",!1);M(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);M(this,"lc_serializable",!0);this.returnId=e?.returnId??this.returnId}static lc_name(){return"JsonOutputToolsParser"}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,n=!0){let r=e[0].message,o;if(cv(r)&&r.tool_calls?.length?o=r.tool_calls.map(s=>{let{id:a,...l}=s;return this.returnId?{id:a,...l}:l}):r.additional_kwargs.tool_calls!==void 0&&(o=JSON.parse(JSON.stringify(r.additional_kwargs.tool_calls)).map(s=>jA(s,{returnId:this.returnId,partial:n}))),!o)return[];let i=[];for(let s of o)if(s!==void 0){let a={type:s.name,args:s.args,id:s.id};i.push(a)}return i}},lqe=class extends _Vt{constructor(e){super(e);M(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);M(this,"lc_serializable",!0);M(this,"returnId",!1);M(this,"keyName");M(this,"returnSingle",!1);M(this,"zodSchema");M(this,"serializableSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,"zodSchema"in e&&(this.zodSchema=e.zodSchema),"serializableSchema"in e&&(this.serializableSchema=e.serializableSchema)}static lc_name(){return"JsonOutputKeyToolsParser"}async _validateResult(e){if(this.serializableSchema!==void 0){let r=await this.serializableSchema["~standard"].validate(e);if(r.issues)throw new Cd(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.issues)}`,JSON.stringify(e,null,2));return r.value}if(this.zodSchema===void 0)return e;let n=await oL(this.zodSchema,e);if(n.success)return n.data;throw new Cd(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error?.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){let n=(await super.parsePartialResult(e)).filter(o=>o.type===this.keyName),r=n;if(n.length)return this.returnId||(r=n.map(o=>o.args)),this.returnSingle?r[0]:r}async parseResult(e){let n=(await super.parsePartialResult(e,!1)).filter(o=>o.type===this.keyName),r=n;if(n.length)return this.returnId||(r=n.map(o=>o.args)),this.returnSingle?this._validateResult(r[0]):await Promise.all(r.map(o=>this._validateResult(o)))}}});function pv(t){return ki(t)?nqe.fromZodSchema(t):Ya(t)?eqe.fromSerializableSchema(t):new hJ}function Jx(t,e,n){let r=n??lqe;return ki(t)?new r({returnSingle:!0,keyName:e,zodSchema:t}):Ya(t)?new r({returnSingle:!0,keyName:e,serializableSchema:t}):new r({returnSingle:!0,keyName:e})}function mv(t,e,n,r){if(!n){let l=t.pipe(e);return r?l.withConfig({runName:r}):l}let o=pJ.assign({parsed:(l,c)=>e.invoke(l.raw,c)}),i=pJ.assign({parsed:()=>null}),s=o.withFallbacks({fallbacks:[i]}),a=r1.from([{raw:t},s]);return r?a.withConfig({runName:r}):a}var l1=b(()=>{br();Px();Nx();Lu();wge();LA();gJ();tqe();rqe();a4();cqe();tv()});function kcr(t,e){switch(e.type){case"text-delta":return t.type==="text"?{...t,text:(t.text??"")+e.text}:t;case"reasoning-delta":return t.type==="thinking"?{...t,thinking:(t.thinking??"")+e.reasoning}:t.type==="reasoning"?{...t,reasoning:(t.reasoning??"")+e.reasoning}:t;case"data-delta":return{...t,data:(t.data??"")+e.data};case"block-delta":return{...t,...e.fields};default:throw new Error(`Unknown delta type: ${JSON.stringify(e)}`)}}function xJ(t){if(t.event!=="content-block-delta")return;if("delta"in t&&t.delta)return t.delta;let e=t.content;if(e==null||typeof e!="object")return;let n=e;if(n.type==="text"&&typeof n.text=="string")return{type:"text-delta",text:n.text};if(n.type==="reasoning"&&typeof n.reasoning=="string")return{type:"reasoning-delta",reasoning:n.reasoning};if(n.type==="thinking"&&typeof n.thinking=="string")return{type:"reasoning-delta",reasoning:n.thinking};if(typeof n.data=="string")return{type:"data-delta",data:n.data,encoding:"base64"};if(typeof n.type=="string")return{type:"block-delta",fields:{...n,type:n.type}}}function xVt(t){if(t==null||typeof t!="object")return;let e=t;if(e.type==="reasoning"&&typeof e.reasoning=="string")return e.reasoning;if(e.type==="thinking"&&typeof e.thinking=="string")return e.thinking}function kge(t){if(t==null||typeof t!="object")return!1;let e=t.type;return e==="reasoning"||e==="thinking"}function c4(t){if(t)return{...t,input_tokens:t.input_tokens??0,output_tokens:t.output_tokens??0,total_tokens:t.total_tokens??0}}function Icr(t){if(t!=null&&typeof t=="object"&&!Array.isArray(t))return t;if(typeof t!="string"||t.length===0)return{};try{let e=JSON.parse(t);return e!=null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Tcr(t){let e=t;if(t.type==="tool_call"||t.type!=="tool_call_chunk"&&t.type!=="tool_use"&&t.type!=="input_json_delta")return t;let n=typeof e.name=="string"?e.name:void 0;if(n==null)return t;let r=e.args??e.input;return{...e,type:"tool_call",name:n,args:Icr(r)}}var Ccr,Pcr,Acr,Ecr,Mcr,uqe,SVt=b(()=>{br();Om();Ccr=class{constructor(){M(this,"events",[]);M(this,"finished",!1);M(this,"waiters",[]);M(this,"error",null)}push(t){this.events.push(t);let e=this.waiters.splice(0);for(let n of e)n()}finish(){this.finished=!0;let t=this.waiters.splice(0);for(let e of t)e()}setError(t){this.error=t,this.finished=!0;let e=this.waiters.splice(0);for(let n of e)n()}async*iterate(){if(this.finished){if(this.error)throw this.error;yield*this.events;return}let t=0;for(;;){for(;t<this.events.length;)yield this.events[t],t++;if(this.finished){if(this.error)throw this.error;return}await new Promise(e=>{if(t<this.events.length||this.finished){e();return}this.waiters.push(e)})}}};Pcr=class{constructor(t){M(this,"_buffer");this._buffer=t}get full(){let t=this._buffer;return{async*[Symbol.asyncIterator](){let e="";for await(let n of t.iterate()){let r=xJ(n);r?.type==="text-delta"&&(e+=r.text,yield e)}}}}[Symbol.asyncIterator](){let t=this._buffer;async function*e(){for await(let n of t.iterate()){let r=xJ(n);r?.type==="text-delta"&&(yield r.text)}}return e()}then(t,e){return(async()=>{let n="";for await(let r of this)n+=r;return n})().then(t,e)}},Acr=class{constructor(t){M(this,"_buffer");this._buffer=t}get full(){let t=this._buffer;return{async*[Symbol.asyncIterator](){let e=[];for await(let n of t.iterate())n.event==="content-block-finish"&&n.content.type==="tool_call"&&(e.push(n.content),yield[...e])}}}[Symbol.asyncIterator](){let t=this._buffer;async function*e(){for await(let n of t.iterate())n.event==="content-block-finish"&&n.content.type==="tool_call"&&(yield n.content)}return e()}then(t,e){return(async()=>{let n=[];for await(let r of this)n.push(r);return n})().then(t,e)}},Ecr=class{constructor(t){M(this,"_buffer");this._buffer=t}get full(){let t=this._buffer;return{async*[Symbol.asyncIterator](){let e="",n=!1;for await(let r of t.iterate())if(r.event==="content-block-start"){if(!kge(r.content)){if(n)return;continue}n=!0;let o=xVt(r.content);if(o==null||o.length===0)continue;e+=o,yield e}else if(r.event==="content-block-delta"){let o=xJ(r);if(o?.type!=="reasoning-delta")continue;n=!0;let i=o.reasoning;if(i==null||i.length===0)continue;e+=i,yield e}else{if(r.event==="content-block-finish"&&kge(r.content))return;if(r.event==="message-finish")return}}}}[Symbol.asyncIterator](){let t=this._buffer;async function*e(){let n=!1;for await(let r of t.iterate())if(r.event==="content-block-start"){if(!kge(r.content)){if(n)return;continue}n=!0;let o=xVt(r.content);o!=null&&o.length>0&&(yield o)}else if(r.event==="content-block-delta"){let o=xJ(r);if(o?.type!=="reasoning-delta")continue;n=!0;let i=o.reasoning;i!=null&&i.length>0&&(yield i)}else{if(r.event==="content-block-finish"&&kge(r.content))return;if(r.event==="message-finish")return}}return e()}then(t,e){return(async()=>{let n="";for await(let r of this)n+=r;return n})().then(t,e)}},Mcr=class{constructor(t){M(this,"_buffer");this._buffer=t}[Symbol.asyncIterator](){let t=this._buffer;async function*e(){for await(let n of t.iterate())if(n.event==="usage"){let r=c4(n.usage);r&&(yield r)}else if(n.event==="message-start"&&n.usage){let r=c4(n.usage);r&&(yield r)}else if(n.event==="message-finish"&&n.usage){let r=c4(n.usage);r&&(yield r)}}return e()}then(t,e){return(async()=>{let n;for await(let r of this)n=r;return n})().then(t,e)}},uqe=class{constructor(t){M(this,"_buffer");this._buffer=new Ccr,this._consume(t)}async _consume(t){try{for await(let e of t)this._buffer.push(e);this._buffer.finish()}catch(e){this._buffer.setError(e instanceof Error?e:new Error(String(e)))}}[Symbol.asyncIterator](){return this._buffer.iterate()}get text(){return new Pcr(this._buffer)}get toolCalls(){return new Acr(this._buffer)}get reasoning(){return new Ecr(this._buffer)}get usage(){return new Mcr(this._buffer)}get output(){return this._assembleMessage()}then(t,e){return this._assembleMessage().then(t,e)}async _assembleMessage(){let t=[],e,n,r={},o;for await(let s of this._buffer.iterate())switch(s.event){case"message-start":e=s.id??e,s.usage&&(n=c4(s.usage));break;case"content-block-start":t[s.index]=s.content;break;case"content-block-delta":{let a=t[s.index],l=xJ(s);a&&l&&(t[s.index]=kcr(a,l));break}case"content-block-finish":t[s.index]=s.content;break;case"usage":n=c4(s.usage);break;case"message-finish":o=s.reason,s.usage&&(n=c4(s.usage)),s.responseMetadata&&(r={...r,...s.responseMetadata});break;default:break}let i=t.filter(s=>s!=null).map(Tcr);return new cr({id:e,content:i,usage_metadata:n,response_metadata:{...r,...o?{finish_reason:o}:{},output_version:"v1"}})}}});function dqe(t){let e=[];for(let n of t){let r=n;if(Array.isArray(n.content))for(let o=0;o<n.content.length;o++){let i=n.content[o];(SY(i)||CY(i))&&r===n&&(r=new n.constructor({...r,content:[...n.content.slice(0,o),TWe(i),...n.content.slice(o+1)]}))}e.push(r)}return e}var Cb,c1=b(()=>{br();Kk();kY();gf();Om();gb();ys();RY();EA();Kx();Sd();Px();Nx();tg();Lu();oi();lg();bVt();l1();SVt();o4();Cb=class Xx extends r4{constructor(n){super(n);M(this,"lc_namespace",["langchain","chat_models",this._llmType()]);M(this,"disableStreaming",!1);M(this,"outputVersion");this.outputVersion=wVt(()=>{let r=n.outputVersion??Nn("LC_OUTPUT_VERSION");return r&&["v0","v1"].includes(r)?r:"v0"})}get callKeys(){return[...super.callKeys,"outputVersion"]}_separateRunnableConfigFromCallOptionsCompat(n){let[r,o]=super._separateRunnableConfigFromCallOptions(n);return o.signal=r.signal,[r,o]}async invoke(n,r){let o=Xx._convertInputToPromptValue(n);return(await this.generatePrompt([o],r,r?.callbacks)).generations[0][0].message}async*_streamResponseChunks(n,r,o){throw new Error("Not implemented.")}async*_streamChatModelEvents(n,r,o){yield*F6t(this._streamResponseChunks(n,r,o),{signal:r.signal})}streamEvents(n,r,o){if(r?.version==="v1"||r?.version==="v2")return super.streamEvents(n,r,o);let i=Xx._convertInputToPromptValue(n).toChatMessages(),[,s]=this._separateRunnableConfigFromCallOptionsCompat(r);return new uqe(this._streamChatModelEvents(i,s))}streamV2(n,r){return this.streamEvents(n,r)}async*_streamIterator(n,r){if(this._streamResponseChunks===Xx.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(n,r);else{let o=Xx._convertInputToPromptValue(n).toChatMessages(),[i,s]=this._separateRunnableConfigFromCallOptionsCompat(r),a={...i.metadata,...this.getLsParamsWithDefaults(s)},l=this._getInvocationParamsForTracing(s),c=await Ru.configure(i.callbacks,this.callbacks,i.tags,this.tags,a,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(l)}),u={options:this._getCallOptionsForTracing(s,l),invocation_params:l,batch_size:1},d=s.outputVersion??this.outputVersion,f=await c?.handleChatModelStart(this.toJSON(),[dqe(o)],i.runId,void 0,u,void 0,void 0,i.runName),p,m;try{for await(let h of this._streamResponseChunks(o,s,f?.[0])){if(s.signal?.throwIfAborted(),h.message.id==null){let g=f?.at(0)?.runId;g!=null&&h.message._updateId(`run-${g}`)}h.message.response_metadata={...h.generationInfo,...h.message.response_metadata},d==="v1"?yield _J(h.message):yield h.message,p?p=p.concat(h):p=h,Jme(h.message)&&h.message.usage_metadata!==void 0&&(m={tokenUsage:{promptTokens:h.message.usage_metadata.input_tokens,completionTokens:h.message.usage_metadata.output_tokens,totalTokens:h.message.usage_metadata.total_tokens}})}s.signal?.throwIfAborted()}catch(h){throw await Promise.all((f??[]).map(g=>g?.handleLLMError(h))),h}await Promise.all((f??[]).map(h=>h?.handleLLMEnd({generations:[[p]],llmOutput:m})))}}getLsParams(n){let r=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:n.stop,ls_provider:r}}getLsParamsWithDefaults(n){return{...this.getLsParams(n),ls_integration:"langchain_chat_model"}}async _generateUncached(n,r,o,i){let s=n.map(m=>m.map(hb)),a;if(i!==void 0&&i.length===s.length)a=i;else{let m={...o.metadata,...this.getLsParamsWithDefaults(r)},h=this._getInvocationParamsForTracing(r),g=await Ru.configure(o.callbacks,this.callbacks,o.tags,this.tags,m,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(h)}),v={options:this._getCallOptionsForTracing(r,h),invocation_params:h,batch_size:1};a=await g?.handleChatModelStart(this.toJSON(),s.map(dqe),o.runId,void 0,v,void 0,void 0,o.runName)}let l=r.outputVersion??this.outputVersion,c=[],u=[],d=!!a?.[0].handlers.find(ezt),f=!!a?.[0].handlers.find(r6e);if(d&&!this.disableStreaming&&s.length===1&&(this._streamChatModelEvents!==Xx.prototype._streamChatModelEvents||this._streamResponseChunks!==Xx.prototype._streamResponseChunks))try{let m=!1,h=a?.[0],g=this._streamChatModelEvents(s[0],r),v=await new uqe({async*[Symbol.asyncIterator](){for await(let _ of g){r.signal?.throwIfAborted(),m=!0;let S=_.event==="message-start"&&_.id==null&&h?.runId!=null?{..._,id:`run-${h.runId}`}:_;await h?.handleChatModelStreamEvent(S),yield S}}});if(r.signal?.throwIfAborted(),!m)throw new Error("Received empty response from chat model call.");if(v.id==null){let _=a?.at(0)?.runId;_!=null&&v._updateId(`run-${_}`)}let y={text:v.text,message:v};c.push([y]);let w=v.usage_metadata!==void 0?{tokenUsage:{promptTokens:v.usage_metadata.input_tokens,completionTokens:v.usage_metadata.output_tokens,totalTokens:v.usage_metadata.total_tokens}}:void 0;await a?.[0].handleLLMEnd({generations:c,llmOutput:w})}catch(m){throw await a?.[0].handleLLMError(m),m}else if(f&&!this.disableStreaming&&s.length===1&&this._streamResponseChunks!==Xx.prototype._streamResponseChunks)try{let m=await this._streamResponseChunks(s[0],r,a?.[0]),h,g;for await(let v of m){if(r.signal?.aborted){let y=h?.message;throw new qWe("Model invocation was aborted.",y)}if(v.message.id==null){let y=a?.at(0)?.runId;y!=null&&v.message._updateId(`run-${y}`)}h===void 0?h=v:h=_b(h,v),Jme(v.message)&&v.message.usage_metadata!==void 0&&(g={tokenUsage:{promptTokens:v.message.usage_metadata.input_tokens,completionTokens:v.message.usage_metadata.output_tokens,totalTokens:v.message.usage_metadata.total_tokens}})}if(r.signal?.aborted){let v=h?.message;throw new qWe("Model invocation was aborted.",v)}if(h===void 0)throw new Error("Received empty response from chat model call.");l==="v1"&&(h.message=_J(h.message)),c.push([h]),await a?.[0].handleLLMEnd({generations:c,llmOutput:g})}catch(m){throw await a?.[0].handleLLMError(m),m}else{let m=await Promise.allSettled(s.map(async(h,g)=>{let v=await this._generate(h,{...r,promptIndex:g},a?.[g]);if(l==="v1")for(let y of v.generations)y.message=_J(y.message);return v}));await Promise.all(m.map(async(h,g)=>{if(h.status==="fulfilled"){let v=h.value;for(let y of v.generations){if(y.message.id==null){let w=a?.at(0)?.runId;w!=null&&y.message._updateId(`run-${w}`)}y.message.response_metadata={...y.generationInfo,...y.message.response_metadata}}return v.generations.length===1&&(v.generations[0].message.response_metadata={...v.llmOutput,...v.generations[0].message.response_metadata}),c[g]=v.generations,u[g]=v.llmOutput,a?.[g]?.handleLLMEnd({generations:[v.generations],llmOutput:v.llmOutput})}else return await a?.[g]?.handleLLMError(h.reason),Promise.reject(h.reason)}))}let p={generations:c,llmOutput:u.length?this._combineLLMOutput?.(...u):void 0};return Object.defineProperty(p,iJ,{value:a?{runIds:a?.map(m=>m.runId)}:void 0,configurable:!0}),p}async _generateCached({messages:n,cache:r,llmStringKey:o,parsedOptions:i,handledOptions:s}){let a=n.map(y=>y.map(hb)),l={...s.metadata,...this.getLsParamsWithDefaults(i)},c=this._getInvocationParamsForTracing(i),u=await Ru.configure(s.callbacks,this.callbacks,s.tags,this.tags,l,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(c)}),d={options:this._getCallOptionsForTracing(i,c),invocation_params:c,batch_size:1},f=await u?.handleChatModelStart(this.toJSON(),a.map(dqe),s.runId,void 0,d,void 0,void 0,s.runName),p=[],m=(await Promise.allSettled(a.map(async(y,w)=>{let _=Xx._convertInputToPromptValue(y).toString(),S=await r.lookup(_,o);return S==null&&p.push(w),S}))).map((y,w)=>({result:y,runManager:f?.[w]})).filter(({result:y})=>y.status==="fulfilled"&&y.value!=null||y.status==="rejected"),h=i.outputVersion??this.outputVersion,g=[];await Promise.all(m.map(async({result:y,runManager:w},_)=>{if(y.status==="fulfilled"){let S=y.value;return g[_]=S.map(I=>("message"in I&&lv(I.message)&&cv(I.message)&&(I.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},h==="v1"&&(I.message=_J(I.message))),I.generationInfo={...I.generationInfo,tokenUsage:{}},I)),S.length&&await w?.handleLLMNewToken(S[0].text),w?.handleLLMEnd({generations:[S]},void 0,void 0,void 0,{cached:!0})}else return await w?.handleLLMError(y.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(y.reason)}));let v={generations:g,missingPromptIndices:p,startedRunManagers:f};return Object.defineProperty(v,iJ,{value:f?{runIds:f?.map(y=>y.runId)}:void 0,configurable:!0}),v}async generate(n,r,o){let i;Array.isArray(r)?i={stop:r}:i=r;let s=n.map(h=>h.map(hb)),[a,l]=this._separateRunnableConfigFromCallOptionsCompat(i);if(a.callbacks=a.callbacks??o,!this.cache)return this._generateUncached(s,l,a);let{cache:c}=this,u=this._getSerializedCacheKeyParametersForCall(l),{generations:d,missingPromptIndices:f,startedRunManagers:p}=await this._generateCached({messages:s,cache:c,llmStringKey:u,parsedOptions:l,handledOptions:a}),m={};if(f.length>0){let h=await this._generateUncached(f.map(g=>s[g]),l,a,p!==void 0?f.map(g=>p?.[g]):void 0);await Promise.all(h.generations.map(async(g,v)=>{let y=f[v];d[y]=g;let w=Xx._convertInputToPromptValue(s[y]).toString();return c.update(w,u,g)})),m=h.llmOutput??{}}return{generations:d,llmOutput:m}}_getInvocationParamsForTracing(n){return this.invocationParams(n)}_getCallOptionsForTracing(n,r){return n}invocationParams(n){return{}}_modelType(){return"base_chat_model"}async generatePrompt(n,r,o){let i=n.map(s=>s.toChatMessages());return this.generate(i,r,o)}withStructuredOutput(n,r){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(r?.strict)throw new Error('"strict" mode is not supported for this model by default.');let o=n,i=r?.name,s=Fk(o)??"A function available to call.",a=r?.method,l=r?.includeRaw;if(a==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let c=i??"extract";!ki(o)&&!Ya(o)&&"name"in o&&(c=o.name);let u=ki(o)||Ya(o)?Ki(o):o,d=[{type:"function",function:{name:c,description:s,parameters:u}}];return mv(this.bindTools(d),nI.from(f=>{if(!On.isInstance(f))throw new Error("Input is not an AIMessageChunk.");if(!f.tool_calls||f.tool_calls.length===0)throw new Error("No tool calls found in the response.");let p=f.tool_calls.find(m=>m.name===c);if(!p)throw new Error(`No tool call found with name ${c}.`);return p.args}),l,l?"StructuredOutputRunnable":"StructuredOutput")}}});var fqe,CVt=b(()=>{Dme();vge();j6t();Y6t();gVt();vVt();Cge();tv();Nx();ys();c1();l1();fqe=class extends Cb{constructor(e,n){let r=typeof e=="string"?{...n??{},model:e}:e;super(r);M(this,"lc_serializable",!0);M(this,"lc_namespace",["langchain","chat_models","google_genai"]);M(this,"model");M(this,"temperature");M(this,"maxOutputTokens");M(this,"topP");M(this,"topK");M(this,"stopSequences",[]);M(this,"safetySettings");M(this,"apiKey");M(this,"streaming",!1);M(this,"json");M(this,"streamUsage",!0);M(this,"convertSystemMessageToHumanContent");M(this,"thinkingConfig");M(this,"client");if(this._addVersion("@langchain/google-genai","2.2.0"),this.model=r.model.replace(/^models\//,""),this.maxOutputTokens=r.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw new Error("`maxOutputTokens` must be a positive integer");if(this.temperature=r.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw new Error("`temperature` must be in the range of [0.0,2.0]");if(this.topP=r.topP??this.topP,this.topP&&this.topP<0)throw new Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw new Error("`topP` must be below 1.");if(this.topK=r.topK??this.topK,this.topK&&this.topK<0)throw new Error("`topK` must be a positive integer");if(this.stopSequences=r.stopSequences??this.stopSequences,this.apiKey=r.apiKey??Nn("GOOGLE_API_KEY"),!this.apiKey)throw new Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor");if(this.safetySettings=r.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0&&new Set(this.safetySettings.map(o=>o.category)).size!==this.safetySettings.length)throw new Error("The categories in `safetySettings` array must be unique");this.streaming=r.streaming??this.streaming,this.json=r.json,this.thinkingConfig=r.thinkingConfig??this.thinkingConfig,this.client=new a1(this.apiKey).getGenerativeModel({model:this.model,safetySettings:this.safetySettings,generationConfig:{stopSequences:this.stopSequences,maxOutputTokens:this.maxOutputTokens,temperature:this.temperature,topP:this.topP,topK:this.topK,...this.json?{responseMimeType:"application/json"}:{},...this.thinkingConfig?{thinkingConfig:this.thinkingConfig}:{}}},{apiVersion:r.apiVersion,baseUrl:r.baseUrl,customHeaders:r.customHeaders}),this.streamUsage=r.streamUsage??this.streamUsage}static lc_name(){return"ChatGoogleGenerativeAI"}get lc_secrets(){return{apiKey:"GOOGLE_API_KEY"}}get lc_aliases(){return{apiKey:"google_api_key"}}get _isMultimodalModel(){return this.model.includes("vision")||this.model.startsWith("gemini-1.5")||this.model.startsWith("gemini-2")||this.model.startsWith("gemma-3-")&&!this.model.startsWith("gemma-3-1b")||this.model.startsWith("gemini-3")}useCachedContent(e,n,r){this.apiKey&&(this.client=new a1(this.apiKey).getGenerativeModelFromCachedContent(e,n,r))}get useSystemInstruction(){return typeof this.convertSystemMessageToHumanContent=="boolean"?!this.convertSystemMessageToHumanContent:this.computeUseSystemInstruction}get computeUseSystemInstruction(){return this.model==="gemini-1.0-pro-001"||this.model.startsWith("gemini-pro-vision")||this.model.startsWith("gemini-1.0-pro-vision")?!1:this.model!=="gemini-pro"}getLsParams(e){return{ls_provider:"google_genai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:this.client.generationConfig.temperature,ls_max_tokens:this.client.generationConfig.maxOutputTokens,ls_stop:e.stop}}_combineLLMOutput(){return[]}_llmType(){return"googlegenerativeai"}bindTools(e,n){return this.withConfig({tools:aqe(e)?.tools,...n})}invocationParams(e){let n=e?.tools?.length?aqe(e.tools,{toolChoice:e.tool_choice,allowedFunctionNames:e.allowedFunctionNames}):void 0;return{...n?.tools?{tools:n.tools}:{},...n?.toolConfig?{toolConfig:n.toolConfig}:{},generationConfig:{stopSequences:this.stopSequences,maxOutputTokens:this.maxOutputTokens,temperature:this.temperature,topP:this.topP,topK:this.topK,...this.json?{responseMimeType:"application/json"}:{},...this.thinkingConfig?{thinkingConfig:this.thinkingConfig}:{},...e?.responseSchema?{responseSchema:e.responseSchema,responseMimeType:"application/json"}:{}}}}_buildGenerateContentRequest(e,n){let r=O6t(e,this._isMultimodalModel,this.useSystemInstruction,this.model),o=r,i;return r[0]?.role==="system"&&([i,...o]=r),{...this.invocationParams(n),...i?{systemInstruction:i}:{},contents:o}}async _generate(e,n,r){if(n.signal?.throwIfAborted(),this.streaming){let a={},l=this._streamResponseChunks(e,n,r),c=[];for await(let u of l){let d=u.generationInfo?.completion??0;c[d]===void 0?c[d]=u:c[d]=c[d].concat(u)}return{generations:c.filter(u=>u!==void 0),llmOutput:{estimatedTokenUsage:a}}}let o=await this.completionWithRetry(this._buildGenerateContentRequest(e,n)),i;"usageMetadata"in o.response&&(i=fJ(o.response.usageMetadata,this.model));let s=N6t(o.response,{usageMetadata:i});return s.generations?.length>0&&await r?.handleLLMNewToken(s.generations[0]?.text??""),s}async*_streamChatModelEvents(e,n,r){let o=this._buildGenerateContentRequest(e,n),i=await this.caller.callWithOptions({signal:n?.signal},async()=>{let{stream:l}=await this.client.generateContentStream(o,{signal:n?.signal});return l}),s=this.streamUsage!==!1&&n.streamUsage!==!1;yield*U6t(async function*(l,c){for await(let u of l){if(c?.aborted)return;yield u}}(i,n.signal),{streamUsage:s,model:this.model})}async*_streamResponseChunks(e,n,r){let o=this._buildGenerateContentRequest(e,n),i=await this.caller.callWithOptions({signal:n?.signal},async()=>{let{stream:d}=await this.client.generateContentStream(o,{signal:n?.signal});return d}),s,a=0,l=0,c=0,u=0;for await(let d of i){if(n.signal?.aborted)return;if("usageMetadata"in d&&d.usageMetadata!==void 0&&this.streamUsage!==!1&&n.streamUsage!==!1){s=fJ(d.usageMetadata,this.model);let p=d.usageMetadata.promptTokenCount??0;s.input_tokens=Math.max(0,p-a),a=p;let m=d.usageMetadata.candidatesTokenCount??0;s.output_tokens=Math.max(0,m-l),l=m;let h=d.usageMetadata.totalTokenCount??0;s.total_tokens=Math.max(0,h-c),c=h}let f=R6t(d,{usageMetadata:s,index:u});u+=1,f&&(yield f,await r?.handleLLMNewToken(f.text??""))}}async completionWithRetry(e,n){return this.caller.callWithOptions({signal:n?.signal},async()=>{try{return await this.client.generateContent(e,{signal:n?.signal})}catch(r){throw r.message?.includes("400 Bad Request")&&(r.status=400),r}})}get profile(){return yVt[this.model]??{}}withStructuredOutput(e,n){let r=e,o=n?.name,i=n?.method,s=n?.includeRaw;if(i==="jsonMode")throw new Error('ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.');let a,l;if(i==="functionCalling"){let c=o??"extract",u;if(ki(r)||Ya(r)){let f=xY(r);u={name:c,description:f.description??"A function available to call.",parameters:f}}else typeof r.name=="string"&&typeof r.parameters=="object"&&r.parameters!=null?(u=r,u.parameters=Vk(r.parameters),c=r.name):u={name:c,description:r.description??"",parameters:Vk(r)};let d=[{functionDeclarations:[u]}];a=this.bindTools(d).withConfig({allowedFunctionNames:[c]}),l=Jx(r,c,Z6t)}else{let c=xY(r);a=this.withConfig({responseSchema:c}),l=pv(r)}return mv(a,l,s,s?"StructuredOutputRunnable":"ChatGoogleGenerativeAIStructuredOutput")}}});var BA,SJ=b(()=>{br();aJ();BA=class{constructor(t){M(this,"caller");this.caller=new RA(t??{})}}});var u1,CJ=b(()=>{br();u1=(t,e)=>t.reduce((n,r,o)=>{let i=Math.floor(o/e);return n[i]=(n[i]||[]).concat([r]),n},[])});var pqe,kVt=b(()=>{Cge();ys();SJ();CJ();pqe=class extends BA{constructor(e){super(e??{});M(this,"apiKey");M(this,"modelName","embedding-001");M(this,"model","embedding-001");M(this,"taskType");M(this,"title");M(this,"stripNewLines",!0);M(this,"maxBatchSize",100);M(this,"client");if(this.modelName=e?.model?.replace(/^models\//,"")??e?.modelName?.replace(/^models\//,"")??this.modelName,this.model=this.modelName,this.taskType=e?.taskType??this.taskType,this.title=e?.title??this.title,this.title&&this.taskType!=="RETRIEVAL_DOCUMENT")throw new Error("title can only be sepcified with TaskType.RETRIEVAL_DOCUMENT");if(this.apiKey=e?.apiKey??Nn("GOOGLE_API_KEY"),!this.apiKey)throw new Error("Please set an API key for Google GenerativeAI in the environmentb variable GOOGLE_API_KEY or in the `apiKey` field of the GoogleGenerativeAIEmbeddings constructor");this.client=new a1(this.apiKey).getGenerativeModel({model:this.model},{baseUrl:e?.baseUrl})}_convertToContent(e){return{content:{role:"user",parts:[{text:this.stripNewLines?e.replace(/\n/g," "):e}]},taskType:this.taskType,title:this.title}}async _embedQueryContent(e){let n=this._convertToContent(e);return(await this.client.embedContent(n)).embedding.values??[]}async _embedDocumentsContent(e){let n=u1(e,this.maxBatchSize),r=n.map(o=>({requests:o.map(i=>this._convertToContent(i))}));return(await Promise.allSettled(r.map(o=>this.client.batchEmbedContents(o)))).flatMap((o,i)=>o.status==="fulfilled"?o.value.embeddings.map(s=>s.values||[]):Array(n[i].length).fill([]))}embedQuery(e){return this.caller.call(this._embedQueryContent.bind(this),e)}embedDocuments(e){return this.caller.call(this._embedDocumentsContent.bind(this),e)}}});var mqe=b(()=>{CVt();kVt()});async function*IVt(t,e={}){let n=e.streamUsage??!0,r=e.think??!1,o=new Map,i=new Map,s=0,a=!1,l,c,u=(d,f)=>{let p=i.get(d);if(p!==void 0)return{index:p,isNew:!1};let m=s++;return i.set(d,m),o.set(m,{...f}),{index:m,isNew:!0}};for await(let d of t){if(a||(a=!0,yield{event:"message-start"}),n){let p=d.prompt_eval_count??0,m=d.eval_count??0;(p>0||m>0)&&(l={input_tokens:p,output_tokens:m,total_tokens:p+m},yield{event:"usage",usage:l})}d.done_reason&&(c=Ocr(d.done_reason));let{message:f}=d;if(r&&f.thinking){let{index:p,isNew:m}=u("reasoning",{type:"reasoning",reasoning:""});m&&(yield{event:"content-block-start",index:p,content:{type:"reasoning",reasoning:""}});let h=o.get(p);h.reasoning=(h.reasoning??"")+f.thinking,yield{event:"content-block-delta",index:p,delta:{type:"reasoning-delta",reasoning:f.thinking}}}if(f.content){let{index:p,isNew:m}=u("text",{type:"text",text:""});m&&(yield{event:"content-block-start",index:p,content:{type:"text",text:""}});let h=o.get(p);h.text=(h.text??"")+f.content,yield{event:"content-block-delta",index:p,delta:{type:"text-delta",text:f.content}}}if(f.tool_calls?.length)for(let p=0;p<f.tool_calls.length;p++){let m=f.tool_calls[p],h=`tool:${p}`,g=typeof m.function.arguments=="string"?m.function.arguments:JSON.stringify(m.function.arguments),{index:v,isNew:y}=u(h,{type:"tool_call_chunk",name:m.function.name,args:"",index:p});y&&(yield{event:"content-block-start",index:v,content:{type:"tool_call_chunk",name:m.function.name,args:"",index:p}});let w=o.get(v);w.name=m.function.name,w.args=g,yield{event:"content-block-delta",index:v,delta:{type:"block-delta",fields:{type:"tool_call_chunk",name:w.name,args:w.args}}}}}for(let[d,f]of o)yield{event:"content-block-finish",index:d,content:oI(f)};yield{event:"message-finish",reason:c,...l?{usage:l}:{},responseMetadata:{model_provider:"ollama"}}}function Ocr(t){switch(t){case"stop":return"stop";case"length":return"length";default:return"stop"}}var TVt=b(()=>{o4()});function AVt(t,e){return new On({content:t.content??"",additional_kwargs:t.thinking&&t.thinking!==""?{reasoning_content:t.thinking}:{},tool_call_chunks:t.tool_calls?.map(n=>({name:n.function.name,args:JSON.stringify(n.function.arguments),type:"tool_call_chunk",index:0,id:IL()})),response_metadata:{...e?.responseMetadata,model_provider:"ollama"},usage_metadata:e?.usageMetadata})}function PVt(t){let e=t.match(/^data:.*?;base64,(.*)$/);return e?e[1]:""}function Ncr(t){if(typeof t.content=="string"){if(t.tool_calls?.length){let r=t.tool_calls.map(o=>({id:o.id,type:"function",function:{name:o.name,arguments:o.args}}));return[{role:"assistant",content:t.content,tool_calls:r}]}return[{role:"assistant",content:t.content}]}let e=t.content.filter(r=>r.type==="text"&&typeof r.text=="string").map(r=>({role:"assistant",content:r.text})),n;if(t.content.find(r=>r.type==="tool_use")&&t.tool_calls?.length){let r=t.tool_calls?.map(o=>({id:o.id,type:"function",function:{name:o.name,arguments:o.args}}));r&&(n={role:"assistant",tool_calls:r,content:""})}else if(t.content.find(r=>r.type==="tool_use")&&!t.tool_calls?.length)throw new Error("'tool_use' content type is not supported without tool calls.");return[...e,...n?[n]:[]]}function Rcr(t){return typeof t.content=="string"?[{role:"user",content:t.content}]:t.content.map(e=>{if(e.type==="text")return{role:"user",content:e.text};if(e.type==="image_url"){if(typeof e.image_url=="string")return{role:"user",content:"",images:[PVt(e.image_url)]};if(e.image_url.url&&typeof e.image_url.url=="string")return{role:"user",content:"",images:[PVt(e.image_url.url)]}}throw new Error(`Unsupported content type: ${e.type}`)})}function Lcr(t){if(typeof t.content=="string")return[{role:"system",content:t.content}];if(t.content.every(e=>e.type==="text"&&typeof e.text=="string"))return t.content.map(e=>({role:"system",content:e.text}));throw new Error(`Unsupported content type(s): ${t.content.map(e=>e.type).join(", ")}`)}function $cr(t){if(typeof t.content!="string")throw new Error("Non string tool message content is not supported");return[{role:"tool",content:t.content}]}function hqe(t){return t.flatMap(e=>{if(["human","generic"].includes(e._getType()))return Rcr(e);if(e._getType()==="ai")return Ncr(e);if(e._getType()==="system")return Lcr(e);if(e._getType()==="tool")return $cr(e);throw new Error(`Unsupported message type: ${e._getType()}`)})}var EVt=b(()=>{oi();TL()});function Dcr(t){return t&&DataView.prototype.isPrototypeOf(t)}function u4(t){if(typeof t!="string"&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(t)||t==="")throw new TypeError('Invalid character in header field name: "'+t+'"');return t.toLowerCase()}function yqe(t){return typeof t!="string"&&(t=String(t)),t}function vqe(t){var e={next:function(){var n=t.shift();return{done:n===void 0,value:n}}};return Ap.iterable&&(e[Symbol.iterator]=function(){return e}),e}function qc(t){this.map={},t instanceof qc?t.forEach(function(e,n){this.append(n,e)},this):Array.isArray(t)?t.forEach(function(e){if(e.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])},this):t&&Object.getOwnPropertyNames(t).forEach(function(e){this.append(e,t[e])},this)}function gqe(t){if(!t._noBody){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}}function RVt(t){return new Promise(function(e,n){t.onload=function(){e(t.result)},t.onerror=function(){n(t.error)}})}function Fcr(t){var e=new FileReader,n=RVt(e);return e.readAsArrayBuffer(t),n}function Ucr(t){var e=new FileReader,n=RVt(e),r=/charset=([A-Za-z0-9_-]+)/.exec(t.type),o=r?r[1]:"utf-8";return e.readAsText(t,o),n}function jcr(t){for(var e=new Uint8Array(t),n=new Array(e.length),r=0;r<e.length;r++)n[r]=String.fromCharCode(e[r]);return n.join("")}function OVt(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function LVt(){return this.bodyUsed=!1,this._initBody=function(t){this.bodyUsed=this.bodyUsed,this._bodyInit=t,t?typeof t=="string"?this._bodyText=t:Ap.blob&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:Ap.formData&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:Ap.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():Ap.arrayBuffer&&Ap.blob&&Dcr(t)?(this._bodyArrayBuffer=OVt(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):Ap.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(t)||NVt(t))?this._bodyArrayBuffer=OVt(t):this._bodyText=t=Object.prototype.toString.call(t):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof t=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):Ap.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},Ap.blob&&(this.blob=function(){var t=gqe(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var t=gqe(this);return t||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(Ap.blob)return this.blob().then(Fcr);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var t=gqe(this);if(t)return t;if(this._bodyBlob)return Ucr(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(jcr(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},Ap.formData&&(this.formData=function(){return this.text().then(Hcr)}),this.json=function(){return this.text().then(JSON.parse)},this}function zcr(t){var e=t.toUpperCase();return Bcr.indexOf(e)>-1?e:t}function f1(t,e){if(!(this instanceof f1))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');e=e||{};var n=e.body;if(t instanceof f1){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new qc(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,!n&&t._bodyInit!=null&&(n=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"same-origin",(e.headers||!this.headers)&&(this.headers=new qc(e.headers)),this.method=zcr(e.method||this.method||"GET"),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal||function(){if("AbortController"in kd){var i=new AbortController;return i.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&n)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(n),(this.method==="GET"||this.method==="HEAD")&&(e.cache==="no-store"||e.cache==="no-cache")){var r=/([?&])_=[^&]*/;if(r.test(this.url))this.url=this.url.replace(r,"$1_="+new Date().getTime());else{var o=/\?/;this.url+=(o.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}function Hcr(t){var e=new FormData;return t.trim().split("&").forEach(function(n){if(n){var r=n.split("="),o=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");e.append(decodeURIComponent(o),decodeURIComponent(i))}}),e}function Wcr(t){var e=new qc,n=t.replace(/\r?\n[\t ]+/g," ");return n.split("\r").map(function(r){return r.indexOf(`
`)===0?r.substr(1,r.length):r}).forEach(function(r){var o=r.split(":"),i=o.shift().trim();if(i){var s=o.join(":").trim();try{e.append(i,s)}catch(a){console.warn("Response "+a.message)}}}),e}function Qx(t,e){if(!(this instanceof Qx))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(e||(e={}),this.type="default",this.status=e.status===void 0?200:e.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=e.statusText===void 0?"":""+e.statusText,this.headers=new qc(e.headers),this.url=e.url||"",this._initBody(t)}function $Vt(t,e){return new Promise(function(n,r){var o=new f1(t,e);if(o.signal&&o.signal.aborted)return r(new d1("Aborted","AbortError"));var i=new XMLHttpRequest;function s(){i.abort()}i.onload=function(){var c={statusText:i.statusText,headers:Wcr(i.getAllResponseHeaders()||"")};o.url.indexOf("file://")===0&&(i.status<200||i.status>599)?c.status=200:c.status=i.status,c.url="responseURL"in i?i.responseURL:c.headers.get("X-Request-URL");var u="response"in i?i.response:i.responseText;setTimeout(function(){n(new Qx(u,c))},0)},i.onerror=function(){setTimeout(function(){r(new TypeError("Network request failed"))},0)},i.ontimeout=function(){setTimeout(function(){r(new TypeError("Network request timed out"))},0)},i.onabort=function(){setTimeout(function(){r(new d1("Aborted","AbortError"))},0)};function a(c){try{return c===""&&kd.location.href?kd.location.href:c}catch{return c}}if(i.open(o.method,a(o.url),!0),o.credentials==="include"?i.withCredentials=!0:o.credentials==="omit"&&(i.withCredentials=!1),"responseType"in i&&(Ap.blob?i.responseType="blob":Ap.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof qc||kd.Headers&&e.headers instanceof kd.Headers)){var l=[];Object.getOwnPropertyNames(e.headers).forEach(function(c){l.push(u4(c)),i.setRequestHeader(c,yqe(e.headers[c]))}),o.headers.forEach(function(c,u){l.indexOf(u)===-1&&i.setRequestHeader(u,c)})}else o.headers.forEach(function(c,u){i.setRequestHeader(u,c)});o.signal&&(o.signal.addEventListener("abort",s),i.onreadystatechange=function(){i.readyState===4&&o.signal.removeEventListener("abort",s)}),i.send(typeof o._bodyInit>"u"?null:o._bodyInit)})}var kd,Ap,MVt,NVt,Bcr,Vcr,d1,DVt=b(()=>{kd=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof window<"u"&&window||{},Ap={searchParams:"URLSearchParams"in kd,iterable:"Symbol"in kd&&"iterator"in Symbol,blob:"FileReader"in kd&&"Blob"in kd&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in kd,arrayBuffer:"ArrayBuffer"in kd};Ap.arrayBuffer&&(MVt=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],NVt=ArrayBuffer.isView||function(t){return t&&MVt.indexOf(Object.prototype.toString.call(t))>-1});qc.prototype.append=function(t,e){t=u4(t),e=yqe(e);var n=this.map[t];this.map[t]=n?n+", "+e:e};qc.prototype.delete=function(t){delete this.map[u4(t)]};qc.prototype.get=function(t){return t=u4(t),this.has(t)?this.map[t]:null};qc.prototype.has=function(t){return this.map.hasOwnProperty(u4(t))};qc.prototype.set=function(t,e){this.map[u4(t)]=yqe(e)};qc.prototype.forEach=function(t,e){for(var n in this.map)this.map.hasOwnProperty(n)&&t.call(e,this.map[n],n,this)};qc.prototype.keys=function(){var t=[];return this.forEach(function(e,n){t.push(n)}),vqe(t)};qc.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),vqe(t)};qc.prototype.entries=function(){var t=[];return this.forEach(function(e,n){t.push([n,e])}),vqe(t)};Ap.iterable&&(qc.prototype[Symbol.iterator]=qc.prototype.entries);Bcr=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];f1.prototype.clone=function(){return new f1(this,{body:this._bodyInit})};LVt.call(f1.prototype);LVt.call(Qx.prototype);Qx.prototype.clone=function(){return new Qx(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new qc(this.headers),url:this.url})};Qx.error=function(){var t=new Qx(null,{status:200,statusText:""});return t.ok=!1,t.status=0,t.type="error",t};Vcr=[301,302,303,307,308];Qx.redirect=function(t,e){if(Vcr.indexOf(e)===-1)throw new RangeError("Invalid status code");return new Qx(null,{status:e,headers:{location:t}})};d1=kd.DOMException;try{new d1}catch{d1=function(e,n){this.message=e,this.name=n;var r=Error(e);this.stack=r.stack},d1.prototype=Object.create(Error.prototype),d1.prototype.constructor=d1}$Vt.polyfill=!0;kd.fetch||(kd.fetch=$Vt,kd.Headers=qc,kd.Request=f1,kd.Response=Qx)});function Zcr(){if(typeof window<"u"&&window.navigator){let t=navigator;return"userAgentData"in t&&t.userAgentData?.platform?`${t.userAgentData.platform.toLowerCase()} Browser/${navigator.userAgent};`:navigator.platform?`${navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`:`unknown Browser/${navigator.userAgent};`}else if(typeof process<"u")return`${process.arch} ${process.platform} Node.js/${process.version}`;return""}function Ycr(t){if(t instanceof Headers){let e={};return t.forEach((n,r)=>{e[r]=n}),e}else return Array.isArray(t)?Object.fromEntries(t):t||{}}var FVt,UVt,qcr,Kcr,Gcr,wqe,xqe,Sqe,Cqe,Jcr,kqe,bqe,zA,Xcr,Qcr,eur,tur,nur,_qe,d4,I1o,Ige=b(()=>{DVt();FVt="11434",UVt=`http://127.0.0.1:${FVt}`,qcr="0.6.3",Kcr=Object.defineProperty,Gcr=(t,e,n)=>e in t?Kcr(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,wqe=(t,e,n)=>(Gcr(t,typeof e!="symbol"?e+"":e,n),n),xqe=class t extends Error{constructor(e,n){super(e),this.error=e,this.status_code=n,this.name="ResponseError",Error.captureStackTrace&&Error.captureStackTrace(this,t)}},Sqe=class{constructor(e,n,r){wqe(this,"abortController"),wqe(this,"itr"),wqe(this,"doneCallback"),this.abortController=e,this.itr=n,this.doneCallback=r}abort(){this.abortController.abort()}async*[Symbol.asyncIterator](){for await(let e of this.itr){if("error"in e)throw new Error(e.error);if(yield e,e.done||e.status==="success"){this.doneCallback();return}}throw new Error("Did not receive done or success response in stream.")}},Cqe=async t=>{if(t.ok)return;let e=`Error ${t.status}: ${t.statusText}`,n=null;if(t.headers.get("content-type")?.includes("application/json"))try{n=await t.json(),e=n.error||e}catch{console.log("Failed to parse error response as JSON")}else try{console.log("Getting text from response"),e=await t.text()||e}catch{console.log("Failed to get text from error response")}throw new xqe(e,t.status)};Jcr=(t,e)=>t[e],kqe=async(t,e,n={})=>{let r={"Content-Type":"application/json",Accept:"application/json","User-Agent":`ollama-js/${qcr} (${Zcr()})`};n.headers=Ycr(n.headers);try{let i=new URL(e);if(i.protocol==="https:"&&i.hostname==="ollama.com"){let s=typeof process=="object"&&process!==null&&typeof process.env=="object"&&process.env!==null?Jcr(process.env,"OLLAMA_API_KEY"):void 0;!(n.headers.authorization||n.headers.Authorization)&&s&&(n.headers.Authorization=`Bearer ${s}`)}}catch(i){console.error("error parsing url",i)}let o=Object.fromEntries(Object.entries(n.headers).filter(([i])=>!Object.keys(r).some(s=>s.toLowerCase()===i.toLowerCase())));return n.headers={...r,...o},t(e,n)},bqe=async(t,e,n)=>{let r=await kqe(t,e,{headers:n?.headers});return await Cqe(r),r},zA=async(t,e,n,r)=>{let i=(a=>a!==null&&typeof a=="object"&&!Array.isArray(a))(n)?JSON.stringify(n):n,s=await kqe(t,e,{method:"POST",body:i,signal:r?.signal,headers:r?.headers});return await Cqe(s),s},Xcr=async(t,e,n,r)=>{let o=await kqe(t,e,{method:"DELETE",body:JSON.stringify(n),headers:r?.headers});return await Cqe(o),o},Qcr=async function*(t){let e=new TextDecoder("utf-8"),n="",r=t.getReader();for(;;){let{done:o,value:i}=await r.read();if(o)break;n+=e.decode(i,{stream:!0});let s=n.split(`
`);n=s.pop()??"";for(let a of s)try{yield JSON.parse(a)}catch{console.warn("invalid json: ",a)}}n+=e.decode();for(let o of n.split(`
`).filter(i=>i!==""))try{yield JSON.parse(o)}catch{console.warn("invalid json: ",o)}},eur=t=>{if(!t)return UVt;let e=t.includes("://");t.startsWith(":")&&(t=`http://127.0.0.1${t}`,e=!0),e||(t=`http://${t}`);let n=new URL(t),r=n.port;r||(e?r=n.protocol==="https:"?"443":"80":r=FVt);let o="";n.username&&(o=n.username,n.password&&(o+=`:${n.password}`),o+="@");let i=`${n.protocol}//${o}${n.hostname}:${r}${n.pathname}`;return i.endsWith("/")&&(i=i.slice(0,-1)),i},tur=Object.defineProperty,nur=(t,e,n)=>e in t?tur(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,_qe=(t,e,n)=>(nur(t,typeof e!="symbol"?e+"":e,n),n),d4=class{constructor(e){_qe(this,"config"),_qe(this,"fetch"),_qe(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=eur(e?.host??UVt)),this.fetch=e?.fetch??fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,n){n.stream=n.stream??!1;let r=`${this.config.host}/api/${e}`;if(n.stream){let i=new AbortController,s=await zA(this.fetch,r,n,{signal:i.signal,headers:this.config.headers});if(!s.body)throw new Error("Missing body");let a=Qcr(s.body),l=new Sqe(i,a,()=>{let c=this.ongoingStreamedRequests.indexOf(l);c>-1&&this.ongoingStreamedRequests.splice(c,1)});return this.ongoingStreamedRequests.push(l),l}return await(await zA(this.fetch,r,n,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!="string"){let n=new Uint8Array(e),r="",o=n.byteLength;for(let i=0;i<o;i++)r+=String.fromCharCode(n[i]);return btoa(r)}return e}async generate(e){return e.images&&(e.images=await Promise.all(e.images.map(this.encodeImage.bind(this)))),this.processStreamableRequest("generate",e)}async chat(e){if(e.messages)for(let n of e.messages)n.images&&(n.images=await Promise.all(n.images.map(this.encodeImage.bind(this))));return this.processStreamableRequest("chat",e)}async create(e){return this.processStreamableRequest("create",{...e})}async pull(e){return this.processStreamableRequest("pull",{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest("push",{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await Xcr(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await zA(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await bqe(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await zA(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await zA(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await zA(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await bqe(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await bqe(this.fetch,`${this.config.host}/api/version`,{headers:this.config.headers})).json()}async webSearch(e){if(!e.query||e.query.length===0)throw new Error("Query is required");return await(await zA(this.fetch,"https://ollama.com/api/web_search",{...e},{headers:this.config.headers})).json()}async webFetch(e){if(!e.url||e.url.length===0)throw new Error("URL is required");return await(await zA(this.fetch,"https://ollama.com/api/web_fetch",{...e},{headers:this.config.headers})).json()}},I1o=new d4});var Iqe,jVt=b(()=>{TVt();EVt();oi();c1();Ige();Sd();rI();Kx();ys();tv();tg();Nx();l1();Iqe=class extends Cb{constructor(e,n){let r=typeof e=="string"?{...n??{},model:e}:e??{};super(r);M(this,"model","llama3");M(this,"numa");M(this,"numCtx");M(this,"numBatch");M(this,"numGpu");M(this,"mainGpu");M(this,"lowVram");M(this,"f16Kv");M(this,"logitsAll");M(this,"vocabOnly");M(this,"useMmap");M(this,"useMlock");M(this,"embeddingOnly");M(this,"numThread");M(this,"numKeep");M(this,"seed");M(this,"numPredict");M(this,"topK");M(this,"topP");M(this,"tfsZ");M(this,"typicalP");M(this,"repeatLastN");M(this,"temperature");M(this,"repeatPenalty");M(this,"presencePenalty");M(this,"frequencyPenalty");M(this,"mirostat");M(this,"mirostatTau");M(this,"mirostatEta");M(this,"penalizeNewline");M(this,"streaming");M(this,"format");M(this,"keepAlive");M(this,"client");M(this,"checkOrPullModel",!1);M(this,"baseUrl","http://127.0.0.1:11434");M(this,"think");this._addVersion("@langchain/ollama","1.3.0"),this.baseUrl=r.baseUrl??Nn("OLLAMA_BASE_URL")??this.baseUrl,this.client=new d4({fetch:r.fetch,host:this.baseUrl,headers:r.headers}),this.model=r.model??this.model,this.numa=r.numa,this.numCtx=r.numCtx,this.numBatch=r.numBatch,this.numGpu=r.numGpu,this.mainGpu=r.mainGpu,this.lowVram=r.lowVram,this.f16Kv=r.f16Kv,this.logitsAll=r.logitsAll,this.vocabOnly=r.vocabOnly,this.useMmap=r.useMmap,this.useMlock=r.useMlock,this.embeddingOnly=r.embeddingOnly,this.numThread=r.numThread,this.numKeep=r.numKeep,this.seed=r.seed,this.numPredict=r.numPredict,this.topK=r.topK,this.topP=r.topP,this.tfsZ=r.tfsZ,this.typicalP=r.typicalP,this.repeatLastN=r.repeatLastN,this.temperature=r.temperature,this.repeatPenalty=r.repeatPenalty,this.presencePenalty=r.presencePenalty,this.frequencyPenalty=r.frequencyPenalty,this.mirostat=r.mirostat,this.mirostatTau=r.mirostatTau,this.mirostatEta=r.mirostatEta,this.penalizeNewline=r.penalizeNewline,this.streaming=r.streaming,this.format=r.format,this.keepAlive=r.keepAlive,this.think=r.think,this.checkOrPullModel=r.checkOrPullModel??this.checkOrPullModel}static lc_name(){return"ChatOllama"}_llmType(){return"ollama"}async pull(e,n){let{stream:r,insecure:o,logProgress:i}={stream:!0,...n};if(r)for await(let s of await this.client.pull({model:e,insecure:o,stream:r}))i&&console.log(s);else{let s=await this.client.pull({model:e,insecure:o});i&&console.log(s)}}bindTools(e,n){return this.withConfig({tools:e.map(r=>Gx(r)),...n})}getLsParams(e){let n=this.invocationParams(e);return{ls_provider:"ollama",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:n.options?.temperature??void 0,ls_max_tokens:n.options?.num_predict??void 0,ls_stop:e.stop}}invocationParams(e){return{model:this.model,format:e?.format??this.format,keep_alive:this.keepAlive,think:this.think,options:{numa:this.numa,num_ctx:this.numCtx,num_batch:this.numBatch,num_gpu:this.numGpu,main_gpu:this.mainGpu,low_vram:this.lowVram,f16_kv:this.f16Kv,logits_all:this.logitsAll,vocab_only:this.vocabOnly,use_mmap:this.useMmap,use_mlock:this.useMlock,embedding_only:this.embeddingOnly,num_thread:this.numThread,num_keep:this.numKeep,seed:this.seed,num_predict:this.numPredict,top_k:this.topK,top_p:this.topP,tfs_z:this.tfsZ,typical_p:this.typicalP,repeat_last_n:this.repeatLastN,temperature:this.temperature,repeat_penalty:this.repeatPenalty,presence_penalty:this.presencePenalty,frequency_penalty:this.frequencyPenalty,mirostat:this.mirostat,mirostat_tau:this.mirostatTau,mirostat_eta:this.mirostatEta,penalize_newline:this.penalizeNewline,stop:e?.stop},tools:e?.tools?.length?e.tools.map(n=>Gx(n)):void 0}}async checkModelExistsOnMachine(e){let{models:n}=await this.client.list();return!!n.find(r=>r.name===e||r.name===`${e}:latest`)}async ensureModelAvailable(){this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}))}async _generate(e,n,r){n.signal?.throwIfAborted(),await this.ensureModelAvailable();let o;for await(let s of this._streamResponseChunks(e,n,r))o?o=_b(o,s.message):o=s.message;let i=new cr({id:o?.id,content:o?.content??"",additional_kwargs:o?.additional_kwargs,tool_calls:o?.tool_calls,response_metadata:o?.response_metadata,usage_metadata:o?.usage_metadata});return{generations:[{text:typeof i.content=="string"?i.content:"",message:i}]}}async*_streamChatModelEvents(e,n,r){await this.ensureModelAvailable();let o=this.invocationParams(n),i=hqe(e),s=await this.client.chat({...o,messages:i,stream:!0}),a=n.streamUsage??!0;yield*IVt(async function*(c,u){for await(let d of c){if(u?.aborted)return;yield d}}(s,n.signal),{streamUsage:a,think:this.think})}async*_streamResponseChunks(e,n,r){await this.ensureModelAvailable();let o=this.invocationParams(n),i=hqe(e),s={input_tokens:0,output_tokens:0,total_tokens:0},a=await this.client.chat({...o,messages:i,stream:!0}),l;for await(let c of a){if(n.signal?.aborted){this.client.abort();return}let{message:u,...d}=c;s.input_tokens+=d.prompt_eval_count??0,s.output_tokens+=d.eval_count??0,s.total_tokens=s.input_tokens+s.output_tokens,l=d;let f=this.think?u.thinking??u.content??"":u.content??"",p=new di({text:f,message:AVt(u)});yield p,await r?.handleLLMNewToken(f,void 0,void 0,void 0,void 0,{chunk:p})}yield new di({text:"",message:new On({content:"",response_metadata:{...l,model_provider:"ollama"},usage_metadata:s})})}withStructuredOutput(e,n){let r,o,{schema:i,name:s,includeRaw:a}={...n,schema:e},l=n?.method??"jsonSchema";if(l==="functionCalling"){let c=s??"extract",u,d=Ki(i);ki(i)||Ya(i)?u={name:c,description:d.description,parameters:d}:typeof i.name=="string"&&typeof i.parameters=="object"&&i.parameters!=null?(u=i,c=i.name):u={name:c,description:i.description??"",parameters:i},r=this.bindTools([{type:"function",function:u}]).withConfig({ls_structured_output_format:{kwargs:{method:l},schema:ki(i)||Ya(i)?d:i}}),o=Jx(i,c)}else if(l==="jsonMode"||l==="jsonSchema"){o=pv(i);let c=Ki(i);r=this.withConfig({format:l==="jsonMode"?"json":c,ls_structured_output_format:{kwargs:{method:l},schema:c}})}else throw new TypeError(`Unrecognized structured output method '${l}'. Expected one of 'functionCalling', 'jsonMode', or 'jsonSchema'`);return mv(r,o,a,a?"StructuredOutputRunnable":"ChatOllamaStructuredOutput")}}});var Tqe,BVt=b(()=>{Ige();ys();SJ();Tqe=class extends BA{constructor(e){super({maxConcurrency:1,...e});M(this,"model","mxbai-embed-large");M(this,"baseUrl","http://localhost:11434");M(this,"dimensions");M(this,"keepAlive");M(this,"requestOptions");M(this,"client");M(this,"truncate",!1);this.baseUrl=e?.baseUrl??Nn("OLLAMA_BASE_URL")??this.baseUrl,this.client=new d4({fetch:e?.fetch,host:this.baseUrl,headers:e?.headers?new Headers(e.headers):void 0}),this.model=e?.model??this.model,this.dimensions=e?.dimensions,this.keepAlive=e?.keepAlive,this.truncate=e?.truncate??this.truncate,this.requestOptions=e?.requestOptions?this._convertOptions(e?.requestOptions):void 0}_convertOptions(e){let n={},r={embeddingOnly:"embedding_only",frequencyPenalty:"frequency_penalty",keepAlive:"keep_alive",logitsAll:"logits_all",lowVram:"low_vram",mainGpu:"main_gpu",mirostat:"mirostat",mirostatEta:"mirostat_eta",mirostatTau:"mirostat_tau",numBatch:"num_batch",numCtx:"num_ctx",numGpu:"num_gpu",numKeep:"num_keep",numPredict:"num_predict",numThread:"num_thread",penalizeNewline:"penalize_newline",presencePenalty:"presence_penalty",repeatLastN:"repeat_last_n",repeatPenalty:"repeat_penalty",temperature:"temperature",stop:"stop",tfsZ:"tfs_z",topK:"top_k",topP:"top_p",typicalP:"typical_p",useMlock:"use_mlock",useMmap:"use_mmap",vocabOnly:"vocab_only",f16Kv:"f16_kv",numa:"numa",seed:"seed"};for(let[o,i]of Object.entries(e)){let s=r[o];s?n[s]=i:n[o]=i}return n}async embedDocuments(e){return this.embeddingWithRetry(e)}async embedQuery(e){return(await this.embeddingWithRetry([e]))[0]}async embeddingWithRetry(e){return(await this.caller.call(()=>this.client.embed({model:this.model,input:e,dimensions:this.dimensions,keep_alive:this.keepAlive,options:this.requestOptions,truncate:this.truncate}))).embeddings}}});var Pqe=b(()=>{br();RY();EA();Kx();Sd();lg()});var zVt=b(()=>{Ige();Sd();ys();Pqe()});var Aqe=b(()=>{jVt();BVt();zVt()});function kJ(t,e){return t.lc_error_code=e,t.message=`${t.message}
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
`,t}var HVt=b(()=>{});function Tn(t,e,n,r,o){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(t,n):o?o.value=n:e.set(t,n),n}function be(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)}var hv=b(()=>{});var p1,IJ=b(()=>{p1=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return p1=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))}});function TJ(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var PJ,Tge=b(()=>{PJ=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)}});var pt,Qa,Ra,HA,eS,f4,p4,m4,h4,g4,y4,v4,w4,b4,_4,tS,m1,AJ,gv=b(()=>{Tge();pt=class extends Error{},Qa=class t extends pt{constructor(e,n,r,o){super(`${t.makeMessage(e,n,r)}`),this.status=e,this.headers=o,this.requestID=o?.get("x-request-id"),this.error=n;let i=n;this.code=i?.code,this.param=i?.param,this.type=i?.type}static makeMessage(e,n,r){let o=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,n,r,o){if(!e||!o)return new HA({message:r,cause:PJ(n)});let i=n?.error;return e===400?new f4(e,i,r,o):e===401?new p4(e,i,r,o):e===403?new m4(e,i,r,o):e===404?new h4(e,i,r,o):e===409?new g4(e,i,r,o):e===422?new y4(e,i,r,o):e===429?new v4(e,i,r,o):e>=500?new w4(e,i,r,o):new t(e,i,r,o)}},Ra=class extends Qa{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},HA=class extends Qa{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}},eS=class extends HA{constructor({message:e}={}){super({message:e??"Request timed out."})}},f4=class extends Qa{},p4=class extends Qa{},m4=class extends Qa{},h4=class extends Qa{},g4=class extends Qa{},y4=class extends Qa{},v4=class extends Qa{},w4=class extends Qa{},b4=class extends pt{constructor(){super("Could not parse response content as the length limit was reached")}},_4=class extends pt{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},tS=class extends Error{constructor(e){super(e)}},m1=class extends Qa{constructor(e,n,r){let o="OAuth2 authentication error",i;if(n&&typeof n=="object"){let s=n;i=s.error;let a=s.error_description;a&&typeof a=="string"?o=a:i&&(o=i)}super(e,n,o,r),this.error_code=i}},AJ=class extends pt{constructor(e,n,r){super(e),this.provider=n,this.cause=r}}});function Pge(t){return typeof t!="object"?{}:t??{}}function Mqe(t){if(!t)return!0;for(let e in t)return!1;return!0}function VVt(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function x4(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var our,WVt,Sf,Eqe,qVt,KVt,sI=b(()=>{gv();our=/^[a-z][a-z0-9+.-]*:/i,WVt=t=>our.test(t),Sf=t=>(Sf=Array.isArray,Sf(t)),Eqe=Sf;qVt=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new pt(`${t} must be an integer`);if(e<0)throw new pt(`${t} must be a positive integer`);return e},KVt=t=>{try{return JSON.parse(t)}catch{return}}});var nS,S4=b(()=>{nS=t=>new Promise(e=>setTimeout(e,t))});var WA,Oqe=b(()=>{WA="6.49.0"});function iur(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function aur(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:n}of t){let r=n.exec(navigator.userAgent);if(r){let o=r[1]||0,i=r[2]||0,s=r[3]||0;return{browser:e,version:`${o}.${i}.${s}`}}}return null}var JVt,sur,GVt,ZVt,YVt,XVt,Nqe=b(()=>{Oqe();JVt=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";sur=()=>{let t=iur();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":WA,"X-Stainless-OS":ZVt(Deno.build.os),"X-Stainless-Arch":GVt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":WA,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":WA,"X-Stainless-OS":ZVt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":GVt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=aur();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":WA,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":WA,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};GVt=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",ZVt=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),XVt=()=>YVt??(YVt=sur())});function Age(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Rqe(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function EJ(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Rqe({start(){},async pull(n){let{done:r,value:o}=await e.next();r?n.close():n.enqueue(o)},async cancel(){await e.return?.()}})}function Ege(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){let n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Lqe(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),n=e.cancel();e.releaseLock(),await n}var C4=b(()=>{});var e3t,t3t=b(()=>{e3t=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)})});var $qe,Dqe,Fqe,n3t,Uqe=b(()=>{$qe="RFC3986",Dqe=t=>String(t),Fqe={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:Dqe},n3t="RFC1738"});function o3t(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function Bqe(t,e){if(Sf(t)){let n=[];for(let r=0;r<t.length;r+=1)n.push(e(t[r]));return n}return e(t)}var Mge,rS,jqe,r3t,i3t=b(()=>{Uqe();sI();Mge=(t,e)=>(Mge=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Mge(t,e)),rS=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})(),jqe=1024,r3t=(t,e,n,r,o)=>{if(t.length===0)return t;let i=t;if(typeof t=="symbol"?i=Symbol.prototype.toString.call(t):typeof t!="string"&&(i=String(t)),n==="iso-8859-1")return escape(i).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let s="";for(let a=0;a<i.length;a+=jqe){let l=i.length>=jqe?i.slice(a,a+jqe):i,c=[];for(let u=0;u<l.length;++u){let d=l.charCodeAt(u);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||o===n3t&&(d===40||d===41)){c[c.length]=l.charAt(u);continue}if(d<128){c[c.length]=rS[d];continue}if(d<2048){c[c.length]=rS[192|d>>6]+rS[128|d&63];continue}if(d<55296||d>=57344){c[c.length]=rS[224|d>>12]+rS[128|d>>6&63]+rS[128|d&63];continue}u+=1,d=65536+((d&1023)<<10|l.charCodeAt(u)&1023),c[c.length]=rS[240|d>>18]+rS[128|d>>12&63]+rS[128|d>>6&63]+rS[128|d&63]}s+=c.join("")}return s}});function cur(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}function c3t(t,e,n,r,o,i,s,a,l,c,u,d,f,p,m,h,g,v){let y=t,w=v,_=0,S=!1;for(;(w=w.get(zqe))!==void 0&&!S;){let P=w.get(t);if(_+=1,typeof P<"u"){if(P===_)throw new RangeError("Cyclic object value");S=!0}typeof w.get(zqe)>"u"&&(_=0)}if(typeof c=="function"?y=c(e,y):y instanceof Date?y=f?.(y):n==="comma"&&Sf(y)&&(y=Bqe(y,function(P){return P instanceof Date?f?.(P):P})),y===null){if(i)return l&&!h?l(e,Kc.encoder,g,"key",p):e;y=""}if(cur(y)||o3t(y)){if(l){let P=h?e:l(e,Kc.encoder,g,"key",p);return[m?.(P)+"="+m?.(l(y,Kc.encoder,g,"value",p))]}return[m?.(e)+"="+m?.(String(y))]}let I=[];if(typeof y>"u")return I;let C;if(n==="comma"&&Sf(y))h&&l&&(y=Bqe(y,l)),C=[{value:y.length>0?y.join(",")||null:void 0}];else if(Sf(c))C=c;else{let P=Object.keys(y);C=u?P.sort(u):P}let k=a?String(e).replace(/\./g,"%2E"):String(e),T=r&&Sf(y)&&y.length===1?k+"[]":k;if(o&&Sf(y)&&y.length===0)return T+"[]";for(let P=0;P<C.length;++P){let E=C[P],O=typeof E=="object"&&typeof E.value<"u"?E.value:y[E];if(s&&O===null)continue;let $=d&&a?E.replace(/\./g,"%2E"):E,U=Sf(y)?typeof n=="function"?n(T,$):T:T+(d?"."+$:"["+$+"]");v.set(t,_);let V=new WeakMap;V.set(zqe,v),l3t(I,c3t(O,U,n,r,o,i,s,a,n==="comma"&&h&&Sf(y)?null:l,c,u,d,f,p,m,h,g,V))}return I}function uur(t=Kc){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||Kc.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=$qe;if(typeof t.format<"u"){if(!Mge(Fqe,t.format))throw new TypeError("Unknown format option provided.");n=t.format}let r=Fqe[n],o=Kc.filter;(typeof t.filter=="function"||Sf(t.filter))&&(o=t.filter);let i;if(t.arrayFormat&&t.arrayFormat in a3t?i=t.arrayFormat:"indices"in t?i=t.indices?"indices":"repeat":i=Kc.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let s=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:Kc.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:Kc.addQueryPrefix,allowDots:s,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:Kc.allowEmptyArrays,arrayFormat:i,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:Kc.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?Kc.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:Kc.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:Kc.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:Kc.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:Kc.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:Kc.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:Kc.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:Kc.strictNullHandling}}function u3t(t,e={}){let n=t,r=uur(e),o,i;typeof r.filter=="function"?(i=r.filter,n=i("",n)):Sf(r.filter)&&(i=r.filter,o=i);let s=[];if(typeof n!="object"||n===null)return"";let a=a3t[r.arrayFormat],l=a==="comma"&&r.commaRoundTrip;o||(o=Object.keys(n)),r.sort&&o.sort(r.sort);let c=new WeakMap;for(let f=0;f<o.length;++f){let p=o[f];r.skipNulls&&n[p]===null||l3t(s,c3t(n[p],p,a,l,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,c))}let u=s.join(r.delimiter),d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}var a3t,l3t,s3t,Kc,zqe,d3t=b(()=>{i3t();Uqe();sI();a3t={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},l3t=function(t,e){Array.prototype.push.apply(t,Sf(e)?e:[e])},Kc={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:r3t,encodeValuesOnly:!1,format:$qe,formatter:Dqe,indices:!1,serializeDate(t){return(s3t??(s3t=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};zqe={}});function f3t(t){return u3t(t,{arrayFormat:"brackets"})}var Hqe=b(()=>{d3t()});function h3t(t){let e=0;for(let o of t)e+=o.length;let n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.length;return n}function cg(t){let e;return(p3t??(e=new globalThis.TextEncoder,p3t=e.encode.bind(e)))(t)}function Wqe(t){let e;return(m3t??(e=new globalThis.TextDecoder,m3t=e.decode.bind(e)))(t)}var p3t,m3t,MJ=b(()=>{});function fur(t,e){for(let o=e??0;o<t.length;o++){if(t[o]===10)return{preceding:o,index:o+1,carriage:!1};if(t[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function g3t(t){for(let r=0;r<t.length-1;r++){if(t[r]===10&&t[r+1]===10||t[r]===13&&t[r+1]===13)return r+2;if(t[r]===13&&t[r+1]===10&&r+3<t.length&&t[r+2]===13&&t[r+3]===10)return r+4}return-1}var ug,dg,h1,y3t=b(()=>{hv();MJ();h1=class{constructor(){ug.set(this,void 0),dg.set(this,void 0),Tn(this,ug,new Uint8Array,"f"),Tn(this,dg,null,"f")}decode(e){if(e==null)return[];let n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?cg(e):e;Tn(this,ug,h3t([be(this,ug,"f"),n]),"f");let r=[],o;for(;(o=fur(be(this,ug,"f"),be(this,dg,"f")))!=null;){if(o.carriage&&be(this,dg,"f")==null){Tn(this,dg,o.index,"f");continue}if(be(this,dg,"f")!=null&&(o.index!==be(this,dg,"f")+1||o.carriage)){r.push(Wqe(be(this,ug,"f").subarray(0,be(this,dg,"f")-1))),Tn(this,ug,be(this,ug,"f").subarray(be(this,dg,"f")),"f"),Tn(this,dg,null,"f");continue}let i=be(this,dg,"f")!==null?o.preceding-1:o.preceding,s=Wqe(be(this,ug,"f").subarray(0,i));r.push(s),Tn(this,ug,be(this,ug,"f").subarray(o.index),"f"),Tn(this,dg,null,"f")}return r}flush(){return be(this,ug,"f").length?this.decode(`
`):[]}};ug=new WeakMap,dg=new WeakMap;h1.NEWLINE_CHARS=new Set([`
`,"\r"]);h1.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function OJ(){}function Oge(t,e,n){return!e||Nge[t]>Nge[n]?OJ:e[t].bind(e)}function _l(t){let e=t.logger,n=t.logLevel??"off";if(!e)return pur;let r=v3t.get(e);if(r&&r[0]===n)return r[1];let o={error:Oge("error",e,n),warn:Oge("warn",e,n),info:Oge("info",e,n),debug:Oge("debug",e,n)};return v3t.set(e,[n,o]),o}var Nge,Vqe,pur,v3t,aI,NJ=b(()=>{sI();Nge={off:0,error:200,warn:300,info:400,debug:500},Vqe=(t,e,n)=>{if(t){if(VVt(Nge,t))return t;_l(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(Nge))}`)}};pur={error:OJ,warn:OJ,info:OJ,debug:OJ},v3t=new WeakMap;aI=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="x-amz-security-token"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t)});async function*mur(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new pt("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new pt("Attempted to iterate over a response with no body");let n=new qqe,r=new h1,o=Ege(t.body);for await(let i of hur(o))for(let s of r.decode(i)){let a=n.decode(s);a&&(yield a)}for(let i of r.flush()){let s=n.decode(i);s&&(yield s)}}async function*hur(t){let e=new Uint8Array;for await(let n of t){if(n==null)continue;let r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?cg(n):n,o=new Uint8Array(e.length+r.length);o.set(e),o.set(r,e.length),e=o;let i;for(;(i=g3t(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function gur(t,e){let n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}var RJ,Fm,qqe,Kqe=b(()=>{hv();gv();C4();y3t();C4();Tge();MJ();NJ();gv();Fm=class t{constructor(e,n,r){this.iterator=e,RJ.set(this,void 0),this.controller=n,Tn(this,RJ,r,"f")}static fromSSEResponse(e,n,r,o){let i=!1,s=r?_l(r):console;async function*a(){if(i)throw new pt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let l=!1;try{for await(let c of mur(e,n))if(!l){if(c.data.startsWith("[DONE]")){l=!0;continue}if(c.event===null||!c.event.startsWith("thread.")){let u;try{u=JSON.parse(c.data)}catch(d){throw s.error("Could not parse message into JSON:",c.data),s.error("From chunk:",c.raw),d}if(u&&u.error)throw new Qa(void 0,u.error,void 0,e.headers);yield o?{event:c.event,data:u}:u}else{let u;try{u=JSON.parse(c.data)}catch(d){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),d}if(c.event=="error")throw new Qa(void 0,u.error,u.message,void 0);yield{event:c.event,data:u}}}l=!0}catch(c){if(TJ(c))return;throw c}finally{l||n.abort()}}return new t(a,n,r)}static fromReadableStream(e,n,r){let o=!1;async function*i(){let a=new h1,l=e.getReader(),c=!1,u,d=()=>{u??(u=l.cancel()),u.catch(()=>{})};n.signal.addEventListener("abort",d,{once:!0});try{if(n.signal.aborted){d();return}for(;;){let{value:f,done:p}=await l.read();if(p){c=!0;break}if(n.signal.aborted)return;for(let m of a.decode(f)){if(n.signal.aborted)return;yield m}}if(n.signal.aborted)return;for(let f of a.flush()){if(n.signal.aborted)return;yield f}}finally{n.signal.removeEventListener("abort",d),c||d(),l.releaseLock()}}async function*s(){if(o)throw new pt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of i())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(n.signal.aborted||TJ(l))return;throw l}finally{a||n.abort()}}return new t(s,n,r)}[(RJ=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],n=[],r=this.iterator(),o=i=>({next:()=>{if(i.length===0){let s=r.next();e.push(s),n.push(s)}return i.shift()}});return[new t(()=>o(e),this.controller,be(this,RJ,"f")),new t(()=>o(n),this.controller,be(this,RJ,"f"))]}toReadableStream(){let e=this,n;return Rqe({async start(){n=e[Symbol.asyncIterator]()},async pull(r){try{let{value:o,done:i}=await n.next();if(i)return r.close();let s=cg(JSON.stringify(o)+`
`);r.enqueue(s)}catch(o){r.error(o)}},async cancel(){await n.return?.()}})}};qqe=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,o]=gur(e,":");return o.startsWith(" ")&&(o=o.substring(1)),n==="event"?this.event=o:n==="data"&&this.data.push(o),null}}});async function Rge(t,e){let{response:n,requestLogID:r,retryOfRequestLogID:o,startTime:i}=e,s=await(async()=>{if(e.options.stream)return _l(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller,t,e.options.__synthesizeEventData):Fm.fromSSEResponse(n,e.controller,t,e.options.__synthesizeEventData);if(n.status===204)return null;if(e.options.__binaryResponse)return n;let l=n.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){if(n.headers.get("content-length")==="0")return;let f=await n.json();return Gqe(f,n)}return await n.text()})();return _l(t).debug(`[${r}] response parsed`,aI({retryOfRequestLogID:o,url:n.url,status:n.status,body:s,durationMs:Date.now()-i})),s}function Gqe(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Zqe=b(()=>{Kqe();NJ()});var LJ,g1,Lge=b(()=>{hv();Zqe();g1=class t extends Promise{constructor(e,n,r=Rge){super(o=>{o(null)}),this.responsePromise=n,this.parseResponse=r,LJ.set(this,void 0),Tn(this,LJ,e,"f")}_thenUnwrap(e){return new t(be(this,LJ,"f"),this.responsePromise,async(n,r)=>Gqe(e(await this.parseResponse(n,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(be(this,LJ,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};LJ=new WeakMap});var $ge,k4,$J,Cf,pr,jo,Zl,Kn=b(()=>{hv();gv();Zqe();Lge();sI();k4=class{constructor(e,n,r,o){$ge.set(this,void 0),Tn(this,$ge,e,"f"),this.options=o,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new pt("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await be(this,$ge,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[($ge=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let n of e.getPaginatedItems())yield n}},$J=class extends g1{constructor(e,n,r){super(e,n,async(o,i)=>new r(o,i.response,await Rge(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let n of e)yield n}},Cf=class extends k4{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},pr=class extends k4{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),n=e[e.length-1]?.id;return n?{...this.options,query:{...Pge(this.options.query),after:n}}:null}},jo=class extends k4{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...Pge(this.options.query),after:e}}:null}},Zl=class extends k4{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.has_more=r.has_more||!1,this.next=r.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...Pge(this.options.query),after:e}}:null}}});var vur,wur,Dge,w3t=b(()=>{C4();gv();vur={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},wur="urn:ietf:params:oauth:grant-type:token-exchange",Dge=class{constructor(e,n){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=n??Age()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e=await this.config.provider.getToken(),n={grant_type:wur,subject_token:e,subject_token_type:vur[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(n.client_id=this.config.clientId);let r=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let l=await r.text(),c;try{c=JSON.parse(l)}catch{}throw r.status===400||r.status===401||r.status===403?new m1(r.status,c,r.headers):Qa.generate(r.status,c,`Token exchange failed with status ${r.status}`,r.headers)}let o=await r.json();if(typeof o!="object"||o===null||!("access_token"in o)||typeof o.access_token!="string"||o.access_token.trim().length===0)throw new pt("Token exchange response missing 'access_token' field");let i=o.access_token,s=o.expires_in??3600,a=Date.now()+s*1e3;return this.cachedToken={token:i,expiresAt:a},i}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let r=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-r}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}}});function*_ur(t){if(!t)return;if(b3t in t){let{values:r,nulls:o}=t;yield*r.entries();for(let i of o)yield[i,null];return}let e=!1,n;t instanceof Headers?n=t.entries():Eqe(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let r of n){let o=r[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let i=Eqe(r[1])?r[1]:[r[1]],s=!1;for(let a of i)a!==void 0&&(e&&!s&&(s=!0,yield[o,null]),yield[o,a])}}var b3t,bur,We,Ii=b(()=>{sI();b3t=Symbol("brand.privateNullableHeaders"),bur=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;We=t=>{let e=new Headers,n=new Set;for(let r of t){let o=new Set;for(let[i,s]of _ur(r)){if(!bur.test(i))throw new TypeError(`Header name must be a valid HTTP token ["${i}"]`);let a=i.toLowerCase();o.has(a)||(e.delete(a),o.add(a)),s===null?(e.delete(a),n.add(a)):(e.append(a,s),n.delete(a))}}return{[b3t]:!0,values:e,nulls:n}}});function Uge(t,e,n){if(!e)throw new TypeError("toStreamingFile requires a non-empty file name");return{[x3t]:!0,data:t,name:e,...n?.type?{type:n.type}:{}}}function P4(t,e,n){return e5e(),new File(t,e??"unknown_file",n)}function T4(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}function xur(t){let e=typeof t=="function"?t:t.fetch,n=_3t.get(e);if(n)return n;let r=(async()=>{try{let o="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new o(i).text()}catch{return!0}})();return _3t.set(e,r),r}async function*Sur(t,e){for await(let{key:n,value:r}of Cur(t)){if(yield cg(`--${e}\r
`),n5e(r)){let o=kur(r),i=Iur(r);yield cg(`Content-Disposition: form-data; name="${Yqe(n)}"; filename="${Yqe(o)}"\r
Content-Type: ${i}\r
\r
`),yield*I4(Tur(r))}else yield cg(`Content-Disposition: form-data; name="${Yqe(n)}"\r
\r
${String(r)}`);yield cg(`\r
`)}yield cg(`--${e}--\r
`)}async function*Cur(t){if(!(!t||typeof t!="object"))for(let[e,n]of Object.entries(t))yield*Xqe(e,n)}async function*Xqe(t,e){if(e!==void 0){if(e==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||n5e(e))yield{key:t,value:e};else if(Array.isArray(e))for(let n of e)yield*Xqe(t+"[]",n);else if(typeof e=="object")for(let[n,r]of Object.entries(e))yield*Xqe(`${t}[${n}]`,r);else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${e} instead`)}}function kur(t){return DJ(t)?t.name:T4(t)??"unknown_file"}function Iur(t){return DJ(t)?t.type||"application/octet-stream":jge(t)&&t.type?t.type:t instanceof Response&&t.headers.get("content-type")||"application/octet-stream"}function Tur(t){return DJ(t)?t.data:t}async function*I4(t){if(typeof t=="string")yield cg(t);else if(ArrayBuffer.isView(t))yield new Uint8Array(t.buffer,t.byteOffset,t.byteLength);else if(t instanceof ArrayBuffer)yield new Uint8Array(t);else if(t instanceof Response)t.body?yield*I4(t.body):yield*I4(await t.blob());else if(t instanceof Blob)typeof t.stream=="function"?yield*I4(t.stream()):yield new Uint8Array(await t.arrayBuffer());else if(t5e(t))for await(let e of Ege(t))yield*I4(e);else if(A4(t))for await(let e of t)yield*I4(e);else throw new TypeError(`Invalid streaming file chunk: ${String(t)}`)}function Yqe(t){return t.replace(/["\\\r\n]/g,e=>encodeURIComponent(e))}var x3t,e5e,A4,VA,kf,_3t,S3t,jge,t5e,DJ,n5e,Fge,Jqe,C3t,Qqe,fg=b(()=>{Ii();C4();MJ();x3t=Symbol("brand.privateStreamingFile");e5e=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};A4=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",VA=async(t,e)=>Jqe(t.body)?Fge(t.body)?C3t(t):{...t,body:await S3t(t.body,e)}:t,kf=async(t,e)=>Fge(t.body)?C3t(t):{...t,body:await S3t(t.body,e)},_3t=new WeakMap;S3t=async(t,e)=>{if(!await xur(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let n=new FormData;return await Promise.all(Object.entries(t||{}).map(([r,o])=>Qqe(n,r,o))),n},jge=t=>t instanceof Blob&&"name"in t,t5e=t=>typeof t=="object"&&t!==null&&"getReader"in t&&typeof t.getReader=="function",DJ=t=>typeof t=="object"&&t!==null&&x3t in t,n5e=t=>typeof t=="object"&&t!==null&&(t instanceof Response||A4(t)||t5e(t)||DJ(t)||jge(t)),Fge=t=>{if(DJ(t)||A4(t)||t5e(t))return!0;if(Array.isArray(t))return t.some(Fge);if(t&&typeof t=="object"&&!jge(t)&&!(t instanceof Response)){for(let e in t)if(Fge(t[e]))return!0}return!1},Jqe=t=>{if(n5e(t))return!0;if(Array.isArray(t))return t.some(Jqe);if(t&&typeof t=="object"){for(let e in t)if(Jqe(t[e]))return!0}return!1},C3t=t=>{let e=`openai-${Math.random().toString(36).slice(2)}`,n=EJ(Sur(t.body,e));return{...t,body:n,headers:We([{"content-type":`multipart/form-data; boundary=${e}`},t.headers])}};Qqe=async(t,e,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response)t.append(e,P4([await n.blob()],T4(n)));else if(A4(n))t.append(e,P4([await new Response(EJ(n)).blob()],T4(n)));else if(jge(n))t.append(e,n,T4(n));else if(Array.isArray(n))await Promise.all(n.map(r=>Qqe(t,e+"[]",r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([r,o])=>Qqe(t,`${e}[${r}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}}});async function FJ(t,e,n){if(e5e(),t=await t,Pur(t))return t instanceof File?t:P4([await t.arrayBuffer()],t.name);if(Aur(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),P4(await r5e(o),e,n)}let r=await r5e(t);if(e||(e=T4(t)),!n?.type){let o=r.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof o=="string"&&(n={...n,type:o})}return P4(r,e,n)}async function r5e(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(k3t(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(A4(t))for await(let n of t)e.push(...await r5e(n));else{let n=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${n?`; constructor: ${n}`:""}${Eur(t)}`)}return e}function Eur(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}var k3t,Pur,Aur,I3t=b(()=>{fg();fg();k3t=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",Pur=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&k3t(t),Aur=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function"});var o5e=b(()=>{fg();I3t()});var ge,ot=b(()=>{ge=class{constructor(e){this._client=e}}});function P3t(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var T3t,Our,ue,sn=b(()=>{gv();T3t=Object.freeze(Object.create(null)),Our=(t=P3t)=>function(n,...r){if(n.length===1)return n[0];let o=!1,i=[],s=n.reduce((u,d,f)=>{/[?#]/.test(d)&&(o=!0);let p=r[f],m=(o?encodeURIComponent:t)(""+p);return f!==r.length&&(p==null||typeof p=="object"&&p.toString===Object.getPrototypeOf(Object.getPrototypeOf(p.hasOwnProperty??T3t)??T3t)?.toString)&&(m=p+"",i.push({start:u.length+d.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(p).slice(8,-1)} is not a valid path parameter`})),u+d+(f===r.length?"":m)},""),a=s.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=l.exec(a))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(i.sort((u,d)=>u.start-d.start),i.length>0){let u=0,d=i.reduce((f,p)=>{let m=" ".repeat(p.start-u),h="^".repeat(p.length);return u=p.start+p.length,f+m+h},"");throw new pt(`Path parameters result in path with invalid segments:
${i.map(f=>f.error).join(`
`)}
${s}
${d}`)}return s},ue=Our(P3t)});var y1,Bge=b(()=>{ot();Kn();sn();y1=class extends ge{list(e,n={},r){return this._client.getAPIList(ue`/chat/completions/${e}/messages`,pr,{query:n,...r,__security:{bearerAuth:!0}})}}});var Um=b(()=>{gv()});function UJ(t){return t!==void 0&&"function"in t&&t.function!==void 0}function E3t(t,e){let n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function jJ(t){return t?.$brand==="auto-parseable-response-format"}function v1(t){return t?.$brand==="auto-parseable-tool"}function M3t(t,e){return!e||!i5e(e)?{...t,choices:t.choices.map(n=>(N3t(n.message.tool_calls),{...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:BJ(t,e)}function BJ(t,e){let n=t.choices.map(r=>{if(r.finish_reason==="length")throw new b4;if(r.finish_reason==="content_filter")throw new _4;return N3t(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(o=>Lur(e,o))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?Rur(e,r.message.content):null}}});return{...t,choices:n}}function Rur(t,e){return t.response_format?.type!=="json_schema"?null:t.response_format?.type==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function Lur(t,e){let n=t.tools?.find(r=>UJ(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:v1(n)?n.$parseRaw(e.function.arguments):n?.function.strict?JSON.parse(e.function.arguments):null}}}function O3t(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let n=t.tools?.find(r=>UJ(r)&&r.function?.name===e.function.name);return UJ(n)&&(v1(n)||n?.function.strict||!1)}function i5e(t){return jJ(t.response_format)?!0:t.tools?.some(e=>v1(e)||e.type==="function"&&e.function.strict===!0)??!1}function N3t(t){for(let e of t||[])if(e.type!=="function")throw new pt(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function R3t(t){for(let e of t??[]){if(e.type!=="function")throw new pt(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new pt(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var E4=b(()=>{Um()});var lI,zJ,zge=b(()=>{lI=t=>t?.role==="assistant",zJ=t=>t?.role==="tool"});var HJ,Hge,Wge,WJ,VJ,Vge,qJ,cI,qge,KJ,Kge,Gge,M4,L3t,s5e,qA,Zge=b(()=>{hv();Um();qA=class{constructor(){HJ.add(this),this.controller=new AbortController,Hge.set(this,void 0),Wge.set(this,()=>{}),WJ.set(this,()=>{}),VJ.set(this,void 0),Vge.set(this,()=>{}),qJ.set(this,()=>{}),cI.set(this,{}),qge.set(this,[]),KJ.set(this,!1),Kge.set(this,!1),Gge.set(this,!1),M4.set(this,!1),Tn(this,Hge,new Promise((e,n)=>{Tn(this,Wge,e,"f"),Tn(this,WJ,n,"f")}),"f"),Tn(this,VJ,new Promise((e,n)=>{Tn(this,Vge,e,"f"),Tn(this,qJ,n,"f")}),"f"),be(this,Hge,"f").catch(()=>{}),be(this,VJ,"f").catch(()=>{})}_run(e){setTimeout(()=>{Promise.resolve().then(e).then(()=>{try{this._emitFinal()}catch(n){be(this,HJ,"m",s5e).call(this,n);return}this._emit("end")},be(this,HJ,"m",s5e).bind(this))},0)}_connected(){this.ended||(be(this,Wge,"f").call(this),this._emit("connect"))}get ended(){return be(this,KJ,"f")}get errored(){return be(this,Kge,"f")}get aborted(){return be(this,Gge,"f")}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let n=()=>this.controller.abort();e.addEventListener("abort",n,{once:!0}),be(this,qge,"f").push({signal:e,listener:n})}on(e,n){return(be(this,cI,"f")[e]||(be(this,cI,"f")[e]=[])).push({listener:n}),this}off(e,n){let r=be(this,cI,"f")[e];if(!r)return this;let o=r.findIndex(i=>i.listener===n);return o>=0&&r.splice(o,1),this}once(e,n){return(be(this,cI,"f")[e]||(be(this,cI,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,r)=>{Tn(this,M4,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,n)})}events(e){let n=[],r=[],o=this.ended,i,s=!1,a=()=>({value:void 0,done:!0}),l=()=>{for(;r.length;)r.shift().resolve(a())},c=()=>{!i||s||!r.length||(s=!0,r.shift().reject(i))},u=()=>{this.off(e,d),this.off("end",p),e!=="error"&&this.off("error",f),e!=="abort"&&this.off("abort",f)},d=(...m)=>{if(o)return;let h=r.shift();h?h.resolve({value:m,done:!1}):n.push(m)},f=m=>{i=m,n.length||c()},p=()=>{o=!0,u(),n.length||(c(),l())};return o||(this.on(e,d),this.on("end",p),e!=="error"&&this.on("error",f),e!=="abort"&&this.on("abort",f)),{next:()=>{let m=n.shift();return m?Promise.resolve({value:m,done:!1}):i&&!s?(s=!0,Promise.reject(i)):o?Promise.resolve(a()):new Promise((h,g)=>{r.push({resolve:h,reject:g})})},return:()=>(o=!0,n.length=0,u(),l(),Promise.resolve(a())),[Symbol.asyncIterator](){return this}}}async done(){Tn(this,M4,!0,"f"),await be(this,VJ,"f")}_emit(e,...n){if(be(this,KJ,"f"))return;e==="end"&&(be(this,HJ,"m",L3t).call(this),Tn(this,KJ,!0,"f"),be(this,Vge,"f").call(this));let r=be(this,cI,"f")[e];if(r&&(be(this,cI,"f")[e]=r.filter(o=>!o.once),r.forEach(({listener:o})=>o(...n))),e==="abort"){let o=n[0];!be(this,M4,"f")&&!r?.length&&Promise.reject(o),be(this,WJ,"f").call(this,o),be(this,qJ,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=n[0];!be(this,M4,"f")&&!r?.length&&Promise.reject(o),be(this,WJ,"f").call(this,o),be(this,qJ,"f").call(this,o),this._emit("end")}}_emitFinal(){}};Hge=new WeakMap,Wge=new WeakMap,WJ=new WeakMap,VJ=new WeakMap,Vge=new WeakMap,qJ=new WeakMap,cI=new WeakMap,qge=new WeakMap,KJ=new WeakMap,Kge=new WeakMap,Gge=new WeakMap,M4=new WeakMap,HJ=new WeakSet,L3t=function(){for(let{signal:e,listener:n}of be(this,qge,"f").splice(0))e.removeEventListener("abort",n)},s5e=function(e){if(Tn(this,Kge,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new Ra),e instanceof Ra)return Tn(this,Gge,!0,"f"),this._emit("abort",e);if(e instanceof pt)return this._emit("error",e);if(e instanceof Error){let n=new pt(e.message);return n.cause=e,this._emit("error",n)}return this._emit("error",new pt(String(e)))}});function $3t(t){return typeof t.parse=="function"}var a5e=b(()=>{});function Dur(t){for(let e of t.choices)for(let n of e.message.tool_calls??[])n.id||(n.id=`call_${p1()}`)}function Fur(t){if(!lI(t))return t;let e={role:"assistant"};return t.audio!=null&&(e.audio={id:t.audio.id}),t.content!==void 0&&(e.content=t.content),t.function_call!=null&&(e.function_call=t.function_call),t.name!==void 0&&(e.name=t.name),t.refusal!=null&&(e.refusal=t.refusal),t.tool_calls!==void 0&&(e.tool_calls=t.tool_calls.map(n=>n.type==="custom"?{id:n.id,type:n.type,custom:{input:n.custom.input,name:n.custom.name}}:{id:n.id,type:n.type,function:{arguments:n.function.arguments,name:n.function.name}})),e}var Ep,l5e,Yge,c5e,u5e,d5e,D3t,F3t,$ur,O4,f5e=b(()=>{hv();Um();IJ();E4();zge();Zge();a5e();$ur=10;O4=class extends qA{constructor(){super(...arguments),Ep.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){Dur(e),this._chatCompletions.push(e),this._emit("chatCompletion",e);let n=e.choices[0]?.message;return n&&this._addMessage(n),e}_addMessage(e,n=!0){if("content"in e||(e.content=null),this.messages.push(e),n){if(this._emit("message",e),zJ(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(lI(e)&&e.tool_calls)for(let r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new pt("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),be(this,Ep,"m",l5e).call(this)}async finalMessage(){return await this.done(),be(this,Ep,"m",Yge).call(this)}async finalFunctionToolCall(){return await this.done(),be(this,Ep,"m",c5e).call(this)}async finalFunctionToolCallResult(){return await this.done(),be(this,Ep,"m",u5e).call(this)}async totalUsage(){return await this.done(),be(this,Ep,"m",d5e).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let n=be(this,Ep,"m",Yge).call(this);n&&this._emit("finalMessage",n);let r=be(this,Ep,"m",l5e).call(this);r&&this._emit("finalContent",r);let o=be(this,Ep,"m",c5e).call(this);o&&this._emit("finalFunctionToolCall",o);let i=be(this,Ep,"m",u5e).call(this);i!=null&&this._emit("finalFunctionToolCallResult",i),this._chatCompletions.some(s=>s.usage)&&this._emit("totalUsage",be(this,Ep,"m",d5e).call(this))}async _createChatCompletion(e,n,r){this._listenForAbort(r?.signal),be(this,Ep,"m",D3t).call(this,n);let o=await e.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(BJ(o,n))}async _runChatCompletion(e,n,r){for(let o of n.messages)this._addMessage(o,!1);return await this._createChatCompletion(e,n,r)}async _runTools(e,n,r,o){let i="tool",{tool_choice:s="auto",stream:a,toolContext:l,...c}=n,u=l,d=typeof s!="string"&&s.type==="function"&&s?.function?.name,{maxChatCompletions:f=$ur,afterCompletion:p}=o||{},m=n.tools.map(y=>{if(v1(y)){if(!y.$callback)throw new pt("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:y.$callback,name:y.function.name,description:y.function.description||"",parameters:y.function.parameters,parse:y.$parseRaw,strict:!0}}}return y}),h={};for(let y of m)y.type==="function"&&(h[y.function.name||y.function.function.name]=y.function);let g="tools"in n?m.map(y=>y.type==="function"?{type:"function",function:{name:y.function.name||y.function.function.name,parameters:y.function.parameters,description:y.function.description,strict:y.function.strict}}:y):void 0;for(let y of n.messages)this._addMessage(y,!1);let v=async y=>{if(y.type!=="function")return{message:void 0,functionCalled:!1};let w=y.id,{name:_,arguments:S}=y.function,I=h[_];if(!I){let T=`Invalid tool_call: ${JSON.stringify(_)}. Available options are: ${Object.keys(h).map(P=>JSON.stringify(P)).join(", ")}. Please try again`;return{message:{role:i,tool_call_id:w,content:T},functionCalled:!1}}if(d&&d!==_){let T=`Invalid tool_call: ${JSON.stringify(_)}. ${JSON.stringify(d)} requested. Please try again`;return{message:{role:i,tool_call_id:w,content:T},functionCalled:!1}}let C;if($3t(I)){let T;try{T=await I.parse(S)}catch(P){let E=P instanceof Error?P.message:String(P);return{message:{role:i,tool_call_id:w,content:E},functionCalled:!1}}C=await I.function(T,r,u)}else C=await I.function(S,r,u);let k=be(this,Ep,"m",F3t).call(this,C);return{message:{role:i,tool_call_id:w,content:k},functionCalled:!0}};for(let y=0;y<f;++y){let w=await this._createChatCompletion(e,{...c,tool_choice:s,tools:g,messages:this.messages.map(Fur)},o),_=w.choices[0]?.message;if(!_)throw new pt("missing message in ChatCompletion response");if(!_.tool_calls?.length){await p?.(w,r);return}if(d||n.parallel_tool_calls===!1)for(let S of _.tool_calls){let I=await v(S);if(I.message&&this._addMessage(I.message),d&&I.functionCalled){await p?.(w,r);return}}else{let S=await Promise.allSettled(_.tool_calls.map(v));for(let I of S)if(I.status==="rejected")throw I.reason;for(let I of S)I.status==="fulfilled"&&I.value.message&&this._addMessage(I.value.message)}await p?.(w,r)}}};Ep=new WeakSet,l5e=function(){return be(this,Ep,"m",Yge).call(this).content??null},Yge=function(){let e=this.messages.length;for(;e-- >0;){let n=this.messages[e];if(lI(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new pt("stream ended without producing a ChatCompletionMessage with role=assistant")},c5e=function(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(lI(n)&&n?.tool_calls?.length)for(let r=n.tool_calls.length-1;r>=0;r--){let o=n.tool_calls[r];if(o?.type==="function")return o.function}}},u5e=function(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(zJ(n)&&n.content!=null&&typeof n.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(o=>o.type==="function"&&o.id===n.tool_call_id)))return n.content}},d5e=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:n}of this._chatCompletions)n&&(e.completion_tokens+=n.completion_tokens,e.prompt_tokens+=n.prompt_tokens,e.total_tokens+=n.total_tokens);return e},D3t=function(e){if(e.n!=null&&e.n>1)throw new pt("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},F3t=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)}});var GJ,p5e=b(()=>{f5e();zge();GJ=class t extends O4{static runTools(e,n,r){let o=new t,i={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,n,o,i)),o}_addMessage(e,n=!0){super._addMessage(e,n),lI(e)&&e.content&&this._emit("content",e.content)}}});function Uur(t,e=Fu.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return jur(t.trim(),e)}var Fu,m5e,h5e,jur,g5e,U3t=b(()=>{Fu={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},m5e=class extends Error{},h5e=class extends Error{};jur=(t,e)=>{let n=t.length,r=0,o=f=>{throw new m5e(`${f} at position ${r}`)},i=f=>{throw new h5e(`${f} at position ${r}`)},s=()=>(d(),r>=n&&o("Unexpected end of input"),t[r]==='"'?a():t[r]==="{"?l():t[r]==="["?c():t.substring(r,r+4)==="null"||Fu.NULL&e&&n-r<4&&"null".startsWith(t.substring(r))?(r+=4,null):t.substring(r,r+4)==="true"||Fu.BOOL&e&&n-r<4&&"true".startsWith(t.substring(r))?(r+=4,!0):t.substring(r,r+5)==="false"||Fu.BOOL&e&&n-r<5&&"false".startsWith(t.substring(r))?(r+=5,!1):t.substring(r,r+8)==="Infinity"||Fu.INFINITY&e&&n-r<8&&"Infinity".startsWith(t.substring(r))?(r+=8,1/0):t.substring(r,r+9)==="-Infinity"||Fu.MINUS_INFINITY&e&&1<n-r&&n-r<9&&"-Infinity".startsWith(t.substring(r))?(r+=9,-1/0):t.substring(r,r+3)==="NaN"||Fu.NAN&e&&n-r<3&&"NaN".startsWith(t.substring(r))?(r+=3,NaN):u()),a=()=>{let f=r,p=!1;for(r++;r<n&&(t[r]!=='"'||p&&t[r-1]==="\\");)p=t[r]==="\\"?!p:!1,r++;if(t.charAt(r)=='"')try{return JSON.parse(t.substring(f,++r-Number(p)))}catch(m){i(String(m))}else if(Fu.STR&e)try{return JSON.parse(t.substring(f,r-Number(p))+'"')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},l=()=>{r++,d();let f={};try{for(;t[r]!=="}";){if(d(),r>=n&&Fu.OBJ&e)return f;let p=a();d(),r++;try{let m=s();Object.defineProperty(f,p,{value:m,writable:!0,enumerable:!0,configurable:!0})}catch(m){if(Fu.OBJ&e)return f;throw m}d(),t[r]===","&&r++}}catch{if(Fu.OBJ&e)return f;o("Expected '}' at end of object")}return r++,f},c=()=>{r++;let f=[];try{for(;t[r]!=="]";)f.push(s()),d(),t[r]===","&&r++}catch{if(Fu.ARR&e)return f;o("Expected ']' at end of array")}return r++,f},u=()=>{if(r===0){t==="-"&&Fu.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t)}catch(p){if(Fu.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}i(String(p))}}let f=r;for(t[r]==="-"&&r++;t[r]&&!",]}".includes(t[r]);)r++;r==n&&!(Fu.NUM&e)&&o("Unterminated number literal");try{return JSON.parse(t.substring(f,r))}catch{t.substring(f,r)==="-"&&Fu.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t.substring(f,t.lastIndexOf("e")))}catch(m){i(String(m))}}},d=()=>{for(;r<n&&`
\r `.includes(t[r]);)r++};return s()},g5e=t=>Uur(t,Fu.ALL^Fu.NUM)});var ZJ=b(()=>{Kqe()});function B3t(t,e,n){let r={type:"message",message:e,...n?{tool_call_ids:n}:{}};return{id:t.id,choices:[],created:t.created,model:t.model,object:`${S5e}${JSON.stringify(r)}`}}function Bur(t){return"type"in t&&t.type==="message"&&"message"in t||"object"in t&&typeof t.object=="string"&&t.object.startsWith(S5e)}function zur(t){return"type"in t?t:JSON.parse(t.object.slice(S5e.length))}function Hur(t,e,n){let{id:r,choices:o,created:i,model:s,system_fingerprint:a,...l}=t,c={...l,id:r,choices:o.map(({message:u,finish_reason:d,index:f,logprobs:p,...m})=>{let{content:h=null,function_call:g,tool_calls:v,audio:y,...w}=u,_=d??(n.has(f)&&Wur(y)?"stop":null);if(!_)throw new pt(`missing finish_reason for choice ${f}`);let S=y?{audio:y}:{},I=u.role;if(!I)throw new pt(`missing role for choice ${f}`);if(g){let{arguments:C,name:k}=g;if(C==null)throw new pt(`missing function_call.arguments for choice ${f}`);if(!k)throw new pt(`missing function_call.name for choice ${f}`);return{...m,message:{...S,content:h,function_call:{arguments:C,name:k},role:I,refusal:u.refusal??null},finish_reason:_,index:f,logprobs:p}}return v?{...m,index:f,finish_reason:_,logprobs:p,message:{...w,...S,role:I,content:h,refusal:u.refusal??null,tool_calls:v.map((C,k)=>{let{function:T,type:P,id:E,...O}=C,{arguments:$,name:U,...V}=T||{};if(P==null)throw new pt(`missing choices[${f}].tool_calls[${k}].type
${x5e(t)}`);if(U==null)throw new pt(`missing choices[${f}].tool_calls[${k}].function.name
${x5e(t)}`);if($==null)throw new pt(`missing choices[${f}].tool_calls[${k}].function.arguments
${x5e(t)}`);return{...O,id:E||`call_${p1()}`,type:P,function:{...V,name:U,arguments:$}}})}}:{...m,message:{...w,...S,content:h,role:I,refusal:u.refusal??null},finish_reason:_,index:f,logprobs:p}}),created:i,model:s,object:"chat.completion",...a?{system_fingerprint:a}:{}};return M3t(c,e)}function Wur(t){return t?.id!=null&&t.data!=null&&t.transcript!=null&&t.expires_at!=null}function x5e(t){return JSON.stringify(t)}var Yl,uI,KA,N4,kb,y5e,Jge,v5e,w5e,b5e,YJ,_5e,j3t,S5e,w1,Xge=b(()=>{hv();U3t();Um();IJ();E4();ZJ();f5e();S5e="chat.completion.chunk.message:";w1=class t extends O4{constructor(e){super(),Yl.add(this),uI.set(this,void 0),KA.set(this,void 0),N4.set(this,void 0),kb.set(this,void 0),Tn(this,uI,e,"f"),Tn(this,KA,new Set,"f"),Tn(this,N4,[],"f")}get currentChatCompletionSnapshot(){return be(this,kb,"f")}static fromReadableStream(e){let n=new t(null);return n._run(()=>n._fromReadableStream(e)),n}static createChatCompletion(e,n,r){let o=new t(n);return o._run(()=>o._runChatCompletion(e,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(e,n,r){super._createChatCompletion,this._listenForAbort(r?.signal),be(this,Yl,"m",y5e).call(this);let o=await e.chat.completions.create({...n,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let i of o)be(this,Yl,"m",v5e).call(this,i);if(o.controller.signal?.aborted)throw new Ra;return this._addChatCompletion(be(this,Yl,"m",YJ).call(this))}async _fromReadableStream(e,n){this._listenForAbort(n?.signal),be(this,Yl,"m",y5e).call(this),this._connected();let r=Fm.fromReadableStream(e,this.controller),o;for await(let s of r){if(Bur(s)){let l=zur(s);if(be(this,kb,"f")){let c=be(this,kb,"f").choices[0]?.message.tool_calls;for(let[u,d]of l.tool_call_ids?.entries()??[]){let f=c?.[u];f&&d&&(f.id=d)}this._addChatCompletion(be(this,Yl,"m",YJ).call(this)),o=void 0}this._addMessage(l.message);continue}let a=s;o&&a.id&&o!==a.id&&this._addChatCompletion(be(this,Yl,"m",YJ).call(this)),be(this,Yl,"m",v5e).call(this,a),a.id&&(o=a.id)}if(r.controller.signal?.aborted)throw new Ra;if(be(this,kb,"f"))return this._addChatCompletion(be(this,Yl,"m",YJ).call(this));let i=this._chatCompletions[this._chatCompletions.length-1];if(i)return i;throw new pt("request ended without sending any chunks")}[(uI=new WeakMap,KA=new WeakMap,N4=new WeakMap,kb=new WeakMap,Yl=new WeakSet,y5e=function(){this.ended||(Tn(this,KA,new Set,"f"),Tn(this,kb,void 0,"f"))},Jge=function(n){let r=be(this,N4,"f")[n.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},be(this,N4,"f")[n.index]=r,r)},v5e=function(n){if(this.ended)return;let r=be(this,Yl,"m",j3t).call(this,n);this._emit("chunk",n,r);for(let o of n.choices){let i=r.choices[o.index],{delta:s}=o;s?.content!=null&&i.message?.role==="assistant"&&i.message?.content&&(this._emit("content",s.content,i.message.content),this._emit("content.delta",{delta:s.content,snapshot:i.message.content,parsed:i.message.parsed})),s?.refusal!=null&&i.message?.role==="assistant"&&i.message?.refusal&&this._emit("refusal.delta",{delta:s.refusal,snapshot:i.message.refusal}),o.logprobs?.content!=null&&i.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:o.logprobs?.content,snapshot:i.logprobs?.content??[]}),o.logprobs?.refusal!=null&&i.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:o.logprobs?.refusal,snapshot:i.logprobs?.refusal??[]});let a=be(this,Yl,"m",Jge).call(this,i);i.finish_reason&&(be(this,Yl,"m",b5e).call(this,i),a.current_tool_call_index!=null&&be(this,Yl,"m",w5e).call(this,i,a.current_tool_call_index));for(let l of s?.tool_calls??[])a.current_tool_call_index!==l.index&&(be(this,Yl,"m",b5e).call(this,i),a.current_tool_call_index!=null&&be(this,Yl,"m",w5e).call(this,i,a.current_tool_call_index)),a.current_tool_call_index=l.index;for(let l of s?.tool_calls??[]){let c=i.message.tool_calls?.[l.index];c?.type&&(c?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:c.function?.name,index:l.index,arguments:c.function.arguments,parsed_arguments:c.function.parsed_arguments,arguments_delta:l.function?.arguments??""}):(c?.type,void 0))}}},w5e=function(n,r){if(be(this,Yl,"m",Jge).call(this,n).done_tool_calls.has(r))return;let i=n.message.tool_calls?.[r];if(!i)throw new Error("no tool call snapshot");if(!i.type)throw new Error("tool call snapshot missing `type`");if(i.type==="function"){let s=be(this,uI,"f")?.tools?.find(a=>UJ(a)&&a.function.name===i.function.name);this._emit("tool_calls.function.arguments.done",{name:i.function.name,index:r,arguments:i.function.arguments,parsed_arguments:v1(s)?s.$parseRaw(i.function.arguments):s?.function.strict?JSON.parse(i.function.arguments):null})}else i.type},b5e=function(n){let r=be(this,Yl,"m",Jge).call(this,n);if(n.message.content&&!r.content_done){r.content_done=!0;let o=be(this,Yl,"m",_5e).call(this);this._emit("content.done",{content:n.message.content,parsed:o?o.$parseRaw(n.message.content):null})}n.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:n.message.refusal})),n.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:n.logprobs.content})),n.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:n.logprobs.refusal}))},YJ=function(){if(this.ended)throw new pt("stream has ended, this shouldn't happen");let n=be(this,kb,"f");if(!n)throw new pt("request ended without sending any chunks");let r=be(this,KA,"f");return Tn(this,KA,new Set,"f"),Tn(this,kb,void 0,"f"),Tn(this,N4,[],"f"),Hur(n,be(this,uI,"f"),r)},_5e=function(){let n=be(this,uI,"f")?.response_format;return jJ(n)?n:null},j3t=function(n){var r,o,i,s,a;let l=be(this,kb,"f"),{choices:c,...u}=n;l?n.id&&Object.assign(l,u):l=Tn(this,kb,{...u,choices:[]},"f");for(let{delta:d,finish_reason:f,index:p,logprobs:m=null,...h}of n.choices){let g=l.choices[p];if(g||(g=l.choices[p]={finish_reason:f,index:p,message:{},logprobs:m,...h}),m)if(!g.logprobs)g.logprobs=Object.assign({},m);else{let{content:k,refusal:T,...P}=m;Object.assign(g.logprobs,P),k&&((r=g.logprobs).content??(r.content=[]),g.logprobs.content.push(...k)),T&&((o=g.logprobs).refusal??(o.refusal=[]),g.logprobs.refusal.push(...T))}if(f&&(g.finish_reason=f,be(this,uI,"f")&&i5e(be(this,uI,"f")))){if(f==="length")throw new b4;if(f==="content_filter")throw new _4}if(Object.assign(g,h),!d)continue;be(this,KA,"f").delete(p);let{audio:v,content:y,refusal:w,function_call:_,role:S,tool_calls:I,...C}=d;if(Object.assign(g.message,C),v?.expires_at!=null&&v.id==null&&v.data==null&&v.transcript==null&&y==null&&w==null&&_==null&&S==null&&I==null&&Object.keys(C).length===0&&be(this,KA,"f").add(p),w&&(g.message.refusal=(g.message.refusal||"")+w),S&&(g.message.role=S),v){let k=(i=g.message).audio??(i.audio={});v.id!=null&&(k.id=v.id),v.data!=null&&(k.data=(k.data??"")+v.data),v.transcript!=null&&(k.transcript=(k.transcript??"")+v.transcript),v.expires_at!=null&&(k.expires_at=v.expires_at)}if(_&&(g.message.function_call?(_.name&&(g.message.function_call.name=_.name),_.arguments&&((s=g.message.function_call).arguments??(s.arguments=""),g.message.function_call.arguments+=_.arguments)):g.message.function_call=_),y&&(g.message.content=(g.message.content||"")+y,!g.message.refusal&&be(this,Yl,"m",_5e).call(this)&&(g.message.parsed=g.message.content.trim()?g5e(g.message.content):null)),I){g.message.tool_calls||(g.message.tool_calls=[]);for(let{index:k,id:T,type:P,function:E,...O}of I){let $=(a=g.message.tool_calls)[k]??(a[k]={});Object.assign($,O),T&&($.id=T),P&&($.type=P),E&&($.function??($.function={name:E.name??"",arguments:""})),E?.name&&($.function.name=E.name),E?.arguments&&($.function.arguments+=E.arguments,O3t(be(this,uI,"f"),$)&&($.function.parsed_arguments=g5e($.function.arguments)))}}}return l},Symbol.asyncIterator)](){let e=[],n=[],r=!1;return this.on("chunk",o=>{let i=n.shift();i?i.resolve(o):e.push(o)}),this.on("end",()=>{r=!0;for(let o of n)o.resolve(void 0);n.length=0}),this.on("abort",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),this.on("error",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,s)=>n.push({resolve:i,reject:s})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Fm(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}});var JJ,C5e=b(()=>{Xge();Um();ZJ();zge();JJ=class t extends w1{static fromReadableStream(e){let n=new t(null);return n._run(()=>n._fromReadableStream(e)),n}toReadableStream(){let e=[],n=[],r=!1,o,i,s=c=>{let u=n.shift();u?u.resolve(c):e.push(c)};this.on("chunk",c=>{o=c,s(c)}),this.on("message",c=>{if(lI(c)){i=c.tool_calls?.map(u=>u.id);return}if(zJ(c)){if(!o)throw new pt("cannot serialize a tool message before receiving any chunks");s(B3t(o,c,i))}}),this.on("end",()=>{r=!0;for(let c of n)c.resolve(void 0);n.length=0}),this.on("abort",c=>{r=!0;for(let u of n)u.reject(c);n.length=0}),this.on("error",c=>{r=!0;for(let u of n)u.reject(c);n.length=0});let a=()=>({next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise((u,d)=>n.push({resolve:u,reject:d})).then(u=>u?{value:u,done:!1}:{value:void 0,done:!0});let c=e.shift();return c?{value:c,done:!1}:{value:void 0,done:!0}},return:async()=>(this.abort(),{value:void 0,done:!0})});return new Fm(a,this.controller).toReadableStream()}static runTools(e,n,r){let o=new t(n),i={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,n,o,i)),o}}});var dI,XJ=b(()=>{ot();Bge();Bge();Kn();sn();p5e();C5e();Xge();E4();C5e();a5e();Xge();p5e();dI=class extends ge{constructor(){super(...arguments),this.messages=new y1(this._client)}create(e,n){return this._client.post("/chat/completions",{body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(ue`/chat/completions/${e}`,{...n,__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(ue`/chat/completions/${e}`,{body:n,...r,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/chat/completions",pr,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(ue`/chat/completions/${e}`,{...n,__security:{bearerAuth:!0}})}parse(e,n){return R3t(e.tools),this._client.chat.completions.create(e,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>BJ(r,e))}runTools(e,n){return e.stream?JJ.runTools(this._client,e,n):GJ.runTools(this._client,e,n)}stream(e,n){return w1.createChatCompletion(this._client,e,n)}};dI.Messages=y1});var GA,k5e=b(()=>{ot();XJ();XJ();GA=class extends ge{constructor(){super(...arguments),this.completions=new dI(this._client)}};GA.Completions=dI});var z3t=b(()=>{XJ();XJ();Bge()});var H3t=b(()=>{k5e();z3t()});var W3t=b(()=>{});var R4,I5e=b(()=>{ot();Kn();sn();R4=class extends ge{create(e,n){return this._client.post("/organization/admin_api_keys",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(ue`/organization/admin_api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/admin_api_keys",pr,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(ue`/organization/admin_api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}});var L4,T5e=b(()=>{ot();Kn();L4=class extends ge{list(e={},n){return this._client.getAPIList("/organization/audit_logs",jo,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}}});var $4,P5e=b(()=>{ot();Kn();sn();$4=class extends ge{create(e,n){return this._client.post("/organization/certificates",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n={},r){return this._client.get(ue`/organization/certificates/${e}`,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(ue`/organization/certificates/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/certificates",jo,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(ue`/organization/certificates/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}activate(e,n){return this._client.getAPIList("/organization/certificates/activate",Cf,{body:e,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,n){return this._client.getAPIList("/organization/certificates/deactivate",Cf,{body:e,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}}});var D4,A5e=b(()=>{ot();D4=class extends ge{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,n){return this._client.post("/organization/data_retention",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}}});var F4,E5e=b(()=>{ot();Kn();sn();F4=class extends ge{create(e,n){return this._client.post("/organization/invites",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(ue`/organization/invites/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/invites",jo,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(ue`/organization/invites/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}});var U4,M5e=b(()=>{ot();Kn();sn();U4=class extends ge{create(e,n){return this._client.post("/organization/roles",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(ue`/organization/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(ue`/organization/roles/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/roles",Zl,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(ue`/organization/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}});var j4,O5e=b(()=>{ot();Kn();sn();j4=class extends ge{create(e,n){return this._client.post("/organization/spend_alerts",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(ue`/organization/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(ue`/organization/spend_alerts/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/spend_alerts",jo,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(ue`/organization/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}});var B4,N5e=b(()=>{ot();B4=class extends ge{retrieve(e){return this._client.get("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,n){return this._client.post("/organization/spend_limit",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e){return this._client.delete("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}}});var z4,R5e=b(()=>{ot();z4=class extends ge{audioSpeeches(e,n){return this._client.get("/organization/usage/audio_speeches",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,n){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,n){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}completions(e,n){return this._client.get("/organization/usage/completions",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}costs(e,n){return this._client.get("/organization/costs",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}embeddings(e,n){return this._client.get("/organization/usage/embeddings",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,n){return this._client.get("/organization/usage/file_search_calls",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}images(e,n){return this._client.get("/organization/usage/images",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}moderations(e,n){return this._client.get("/organization/usage/moderations",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,n){return this._client.get("/organization/usage/vector_stores",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,n){return this._client.get("/organization/usage/web_search_calls",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}}});var H4,L5e=b(()=>{ot();Kn();sn();H4=class extends ge{create(e,n,r){return this._client.post(ue`/organization/groups/${e}/roles`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{group_id:o}=n;return this._client.get(ue`/organization/groups/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(ue`/organization/groups/${e}/roles`,Zl,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{group_id:o}=n;return this._client.delete(ue`/organization/groups/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}});var W4,$5e=b(()=>{ot();Kn();sn();W4=class extends ge{create(e,n,r){return this._client.post(ue`/organization/groups/${e}/users`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{group_id:o}=n;return this._client.get(ue`/organization/groups/${o}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(ue`/organization/groups/${e}/users`,Zl,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{group_id:o}=n;return this._client.delete(ue`/organization/groups/${o}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}});var ZA,D5e=b(()=>{ot();L5e();L5e();$5e();$5e();Kn();sn();ZA=class extends ge{constructor(){super(...arguments),this.users=new W4(this._client),this.roles=new H4(this._client)}create(e,n){return this._client.post("/organization/groups",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(ue`/organization/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(ue`/organization/groups/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/groups",Zl,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(ue`/organization/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};ZA.Users=W4;ZA.Roles=H4});var V4,F5e=b(()=>{ot();Kn();sn();V4=class extends ge{retrieve(e,n,r){let{project_id:o}=n;return this._client.get(ue`/organization/projects/${o}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(ue`/organization/projects/${e}/api_keys`,jo,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:o}=n;return this._client.delete(ue`/organization/projects/${o}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}});var q4,U5e=b(()=>{ot();Kn();sn();q4=class extends ge{list(e,n={},r){return this._client.getAPIList(ue`/organization/projects/${e}/certificates`,jo,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}activate(e,n,r){return this._client.getAPIList(ue`/organization/projects/${e}/certificates/activate`,Cf,{body:n,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,n,r){return this._client.getAPIList(ue`/organization/projects/${e}/certificates/deactivate`,Cf,{body:n,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}}});var K4,j5e=b(()=>{ot();sn();K4=class extends ge{retrieve(e,n){return this._client.get(ue`/organization/projects/${e}/data_retention`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(ue`/organization/projects/${e}/data_retention`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}}});var G4,B5e=b(()=>{ot();sn();G4=class extends ge{retrieve(e,n){return this._client.get(ue`/organization/projects/${e}/hosted_tool_permissions`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(ue`/organization/projects/${e}/hosted_tool_permissions`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}}});var Z4,z5e=b(()=>{ot();sn();Z4=class extends ge{retrieve(e,n){return this._client.get(ue`/organization/projects/${e}/model_permissions`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(ue`/organization/projects/${e}/model_permissions`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(ue`/organization/projects/${e}/model_permissions`,{...n,__security:{adminAPIKeyAuth:!0}})}}});var Y4,H5e=b(()=>{ot();Kn();sn();Y4=class extends ge{listRateLimits(e,n={},r){return this._client.getAPIList(ue`/organization/projects/${e}/rate_limits`,jo,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,n,r){let{project_id:o,...i}=n;return this._client.post(ue`/organization/projects/${o}/rate_limits/${e}`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}}});var J4,W5e=b(()=>{ot();Kn();sn();J4=class extends ge{create(e,n,r){return this._client.post(ue`/projects/${e}/roles`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{project_id:o}=n;return this._client.get(ue`/projects/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){let{project_id:o,...i}=n;return this._client.post(ue`/projects/${o}/roles/${e}`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(ue`/projects/${e}/roles`,Zl,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:o}=n;return this._client.delete(ue`/projects/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}});var X4,V5e=b(()=>{ot();Kn();sn();X4=class extends ge{create(e,n,r){return this._client.post(ue`/organization/projects/${e}/spend_alerts`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{project_id:o}=n;return this._client.get(ue`/organization/projects/${o}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){let{project_id:o,...i}=n;return this._client.post(ue`/organization/projects/${o}/spend_alerts/${e}`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(ue`/organization/projects/${e}/spend_alerts`,jo,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:o}=n;return this._client.delete(ue`/organization/projects/${o}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}});var Q4,q5e=b(()=>{ot();sn();Q4=class extends ge{retrieve(e,n){return this._client.get(ue`/organization/projects/${e}/spend_limit`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(ue`/organization/projects/${e}/spend_limit`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(ue`/organization/projects/${e}/spend_limit`,{...n,__security:{adminAPIKeyAuth:!0}})}}});var eH,K5e=b(()=>{ot();Kn();sn();eH=class extends ge{create(e,n,r){let{project_id:o,...i}=n;return this._client.post(ue`/projects/${o}/groups/${e}/roles`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{project_id:o,group_id:i}=n;return this._client.get(ue`/projects/${o}/groups/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n,r){let{project_id:o,...i}=n;return this._client.getAPIList(ue`/projects/${o}/groups/${e}/roles`,Zl,{query:i,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:o,group_id:i}=n;return this._client.delete(ue`/projects/${o}/groups/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}});var b1,G5e=b(()=>{ot();K5e();K5e();Kn();sn();b1=class extends ge{constructor(){super(...arguments),this.roles=new eH(this._client)}create(e,n,r){return this._client.post(ue`/organization/projects/${e}/groups`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{project_id:o,...i}=n;return this._client.get(ue`/organization/projects/${o}/groups/${e}`,{query:i,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(ue`/organization/projects/${e}/groups`,Zl,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:o}=n;return this._client.delete(ue`/organization/projects/${o}/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};b1.Roles=eH});var tH,Z5e=b(()=>{ot();sn();tH=class extends ge{create(e,n,r){let{project_id:o,...i}=n;return this._client.post(ue`/organization/projects/${o}/service_accounts/${e}/api_keys`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}}});var _1,Y5e=b(()=>{ot();Z5e();Z5e();Kn();sn();_1=class extends ge{constructor(){super(...arguments),this.apiKeys=new tH(this._client)}create(e,n,r){return this._client.post(ue`/organization/projects/${e}/service_accounts`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{project_id:o}=n;return this._client.get(ue`/organization/projects/${o}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){let{project_id:o,...i}=n;return this._client.post(ue`/organization/projects/${o}/service_accounts/${e}`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(ue`/organization/projects/${e}/service_accounts`,jo,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:o}=n;return this._client.delete(ue`/organization/projects/${o}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};_1.APIKeys=tH});var nH,J5e=b(()=>{ot();Kn();sn();nH=class extends ge{create(e,n,r){let{project_id:o,...i}=n;return this._client.post(ue`/projects/${o}/users/${e}/roles`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{project_id:o,user_id:i}=n;return this._client.get(ue`/projects/${o}/users/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n,r){let{project_id:o,...i}=n;return this._client.getAPIList(ue`/projects/${o}/users/${e}/roles`,Zl,{query:i,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:o,user_id:i}=n;return this._client.delete(ue`/projects/${o}/users/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}});var x1,X5e=b(()=>{ot();J5e();J5e();Kn();sn();x1=class extends ge{constructor(){super(...arguments),this.roles=new nH(this._client)}create(e,n,r){return this._client.post(ue`/organization/projects/${e}/users`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{project_id:o}=n;return this._client.get(ue`/organization/projects/${o}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){let{project_id:o,...i}=n;return this._client.post(ue`/organization/projects/${o}/users/${e}`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(ue`/organization/projects/${e}/users`,jo,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:o}=n;return this._client.delete(ue`/organization/projects/${o}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};x1.Roles=nH});var Uu,Q5e=b(()=>{ot();F5e();F5e();U5e();U5e();j5e();j5e();B5e();B5e();z5e();z5e();H5e();H5e();W5e();W5e();V5e();V5e();q5e();q5e();G5e();G5e();Y5e();Y5e();X5e();X5e();Kn();sn();Uu=class extends ge{constructor(){super(...arguments),this.users=new x1(this._client),this.serviceAccounts=new _1(this._client),this.apiKeys=new V4(this._client),this.rateLimits=new Y4(this._client),this.modelPermissions=new Z4(this._client),this.hostedToolPermissions=new G4(this._client),this.groups=new b1(this._client),this.roles=new J4(this._client),this.dataRetention=new K4(this._client),this.spendLimit=new Q4(this._client),this.spendAlerts=new X4(this._client),this.certificates=new q4(this._client)}create(e,n){return this._client.post("/organization/projects",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(ue`/organization/projects/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(ue`/organization/projects/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/projects",jo,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}archive(e,n){return this._client.post(ue`/organization/projects/${e}/archive`,{...n,__security:{adminAPIKeyAuth:!0}})}};Uu.Users=x1;Uu.ServiceAccounts=_1;Uu.APIKeys=V4;Uu.RateLimits=Y4;Uu.ModelPermissions=Z4;Uu.HostedToolPermissions=G4;Uu.Groups=b1;Uu.Roles=J4;Uu.DataRetention=K4;Uu.SpendLimit=Q4;Uu.SpendAlerts=X4;Uu.Certificates=q4});var rH,eKe=b(()=>{ot();Kn();sn();rH=class extends ge{create(e,n,r){return this._client.post(ue`/organization/users/${e}/roles`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{user_id:o}=n;return this._client.get(ue`/organization/users/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(ue`/organization/users/${e}/roles`,Zl,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{user_id:o}=n;return this._client.delete(ue`/organization/users/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}});var S1,tKe=b(()=>{ot();eKe();eKe();Kn();sn();S1=class extends ge{constructor(){super(...arguments),this.roles=new rH(this._client)}retrieve(e,n){return this._client.get(ue`/organization/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(ue`/organization/users/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/users",jo,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(ue`/organization/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};S1.Roles=rH});var ju,nKe=b(()=>{ot();I5e();I5e();T5e();T5e();P5e();P5e();A5e();A5e();E5e();E5e();M5e();M5e();O5e();O5e();N5e();N5e();R5e();R5e();D5e();D5e();Q5e();Q5e();tKe();tKe();ju=class extends ge{constructor(){super(...arguments),this.auditLogs=new L4(this._client),this.adminAPIKeys=new R4(this._client),this.usage=new z4(this._client),this.invites=new F4(this._client),this.users=new S1(this._client),this.groups=new ZA(this._client),this.roles=new U4(this._client),this.dataRetention=new D4(this._client),this.spendLimit=new B4(this._client),this.spendAlerts=new j4(this._client),this.certificates=new $4(this._client),this.projects=new Uu(this._client)}};ju.AuditLogs=L4;ju.AdminAPIKeys=R4;ju.Usage=z4;ju.Invites=F4;ju.Users=S1;ju.Groups=ZA;ju.Roles=U4;ju.DataRetention=D4;ju.SpendLimit=B4;ju.SpendAlerts=j4;ju.Certificates=$4;ju.Projects=Uu});var YA,rKe=b(()=>{ot();nKe();nKe();YA=class extends ge{constructor(){super(...arguments),this.organization=new ju(this._client)}};YA.Organization=ju});var oH,oKe=b(()=>{ot();Ii();oH=class extends ge{create(e,n){return this._client.post("/audio/speech",{body:e,...n,headers:We([{Accept:"application/octet-stream"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}});var iH,iKe=b(()=>{ot();fg();iH=class extends ge{create(e,n){return this._client.post("/audio/transcriptions",kf({body:e,...n,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}});var sH,sKe=b(()=>{ot();fg();sH=class extends ge{create(e,n){return this._client.post("/audio/translations",kf({body:e,...n,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}});var oS,aKe=b(()=>{ot();oKe();oKe();iKe();iKe();sKe();sKe();oS=class extends ge{constructor(){super(...arguments),this.transcriptions=new iH(this._client),this.translations=new sH(this._client),this.speech=new oH(this._client)}};oS.Transcriptions=iH;oS.Translations=sH;oS.Speech=oH});var C1,lKe=b(()=>{ot();Kn();sn();C1=class extends ge{create(e,n){return this._client.post("/batches",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(ue`/batches/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/batches",pr,{query:e,...n,__security:{bearerAuth:!0}})}cancel(e,n){return this._client.post(ue`/batches/${e}/cancel`,{...n,__security:{bearerAuth:!0}})}}});var aH,cKe=b(()=>{ot();Kn();Ii();sn();aH=class extends ge{create(e,n){return this._client.post("/assistants",{body:e,...n,headers:We([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(ue`/assistants/${e}`,{...n,headers:We([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(ue`/assistants/${e}`,{body:n,...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/assistants",pr,{query:e,...n,headers:We([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(ue`/assistants/${e}`,{...n,headers:We([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}}});var lH,uKe=b(()=>{ot();Ii();lH=class extends ge{create(e,n){return this._client.post("/realtime/sessions",{body:e,...n,headers:We([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}}});var cH,dKe=b(()=>{ot();Ii();cH=class extends ge{create(e,n){return this._client.post("/realtime/transcription_sessions",{body:e,...n,headers:We([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}}});var JA,fKe=b(()=>{ot();uKe();uKe();dKe();dKe();JA=class extends ge{constructor(){super(...arguments),this.sessions=new lH(this._client),this.transcriptionSessions=new cH(this._client)}};JA.Sessions=lH;JA.TranscriptionSessions=cH});var uH,pKe=b(()=>{ot();Ii();sn();uH=class extends ge{create(e,n){return this._client.post("/chatkit/sessions",{body:e,...n,headers:We([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,n){return this._client.post(ue`/chatkit/sessions/${e}/cancel`,{...n,headers:We([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}}});var dH,mKe=b(()=>{ot();Kn();Ii();sn();dH=class extends ge{retrieve(e,n){return this._client.get(ue`/chatkit/threads/${e}`,{...n,headers:We([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/chatkit/threads",jo,{query:e,...n,headers:We([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(ue`/chatkit/threads/${e}`,{...n,headers:We([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}listItems(e,n={},r){return this._client.getAPIList(ue`/chatkit/threads/${e}/items`,jo,{query:n,...r,headers:We([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}}});var XA,hKe=b(()=>{ot();pKe();pKe();mKe();mKe();XA=class extends ge{constructor(){super(...arguments),this.sessions=new uH(this._client),this.threads=new dH(this._client)}};XA.Sessions=uH;XA.Threads=dH});var fH,gKe=b(()=>{ot();Kn();Ii();sn();fH=class extends ge{list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(ue`/responses/${e}/input_items?beta=true`,pr,{query:i,...r,headers:We([{...o?.toString()!=null?{"openai-beta":o?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}}});var pH,yKe=b(()=>{ot();Ii();pH=class extends ge{count(e={},n){let{betas:r,...o}=e??{};return this._client.post("/responses/input_tokens?beta=true",{body:o,...n,headers:We([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},n?.headers]),__security:{bearerAuth:!0}})}}});var QA,vKe=b(()=>{ot();gKe();gKe();yKe();yKe();Ii();sn();QA=class extends ge{constructor(){super(...arguments),this.inputItems=new fH(this._client),this.inputTokens=new pH(this._client)}create(e,n){let{betas:r,...o}=e;return this._client.post("/responses?beta=true",{body:o,...n,headers:We([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},n?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,n={},r){let{betas:o,...i}=n??{};return this._client.get(ue`/responses/${e}?beta=true`,{query:i,...r,headers:We([{...o?.toString()!=null?{"openai-beta":o?.toString()}:void 0},r?.headers]),stream:n?.stream??!1,__security:{bearerAuth:!0}})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(ue`/responses/${e}?beta=true`,{...r,headers:We([{Accept:"*/*",...o?.toString()!=null?{"openai-beta":o?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,n={},r){let{betas:o}=n??{};return this._client.post(ue`/responses/${e}/cancel?beta=true`,{...r,headers:We([{...o?.toString()!=null?{"openai-beta":o?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}compact(e,n){let{betas:r,...o}=e;return this._client.post("/responses/compact?beta=true",{body:o,...n,headers:We([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},n?.headers]),__security:{bearerAuth:!0}})}};QA.InputItems=fH;QA.InputTokens=pH});var mH,wKe=b(()=>{ot();Kn();Ii();sn();mH=class extends ge{create(e,n,r){return this._client.post(ue`/threads/${e}/messages`,{body:n,...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,n,r){let{thread_id:o}=n;return this._client.get(ue`/threads/${o}/messages/${e}`,{...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,n,r){let{thread_id:o,...i}=n;return this._client.post(ue`/threads/${o}/messages/${e}`,{body:i,...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(ue`/threads/${e}/messages`,pr,{query:n,...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,n,r){let{thread_id:o}=n;return this._client.delete(ue`/threads/${o}/messages/${e}`,{...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}}});var hH,bKe=b(()=>{ot();Kn();Ii();sn();hH=class extends ge{retrieve(e,n,r){let{thread_id:o,run_id:i,...s}=n;return this._client.get(ue`/threads/${o}/runs/${i}/steps/${e}`,{query:s,...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,n,r){let{thread_id:o,...i}=n;return this._client.getAPIList(ue`/threads/${o}/runs/${e}/steps`,pr,{query:i,...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}}});var V3t,q3t=b(()=>{gv();MJ();V3t=t=>{if(typeof Buffer<"u"){let e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(t),n=e.length,r=new Uint8Array(n);for(let o=0;o<n;o++)r[o]=e.charCodeAt(o);return Array.from(new Float32Array(r.buffer))}}});var jm,_Ke=b(()=>{jm=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0}});var gH=b(()=>{sI();q3t();_Ke();NJ();IJ();S4();Hqe()});var Id,I1,xKe,iS,Qge,Ib,T1,yH,k1,nye,pg,eye,tye,tX,QJ,eX,K3t,G3t,Z3t,Y3t,J3t,X3t,Q3t,fI,SKe=b(()=>{hv();ZJ();Um();Zge();gH();fI=class extends qA{constructor(){super(...arguments),Id.add(this),xKe.set(this,[]),iS.set(this,{}),Qge.set(this,{}),Ib.set(this,void 0),T1.set(this,void 0),yH.set(this,void 0),k1.set(this,void 0),nye.set(this,void 0),pg.set(this,void 0),eye.set(this,void 0),tye.set(this,void 0),tX.set(this,void 0)}[(xKe=new WeakMap,iS=new WeakMap,Qge=new WeakMap,Ib=new WeakMap,T1=new WeakMap,yH=new WeakMap,k1=new WeakMap,nye=new WeakMap,pg=new WeakMap,eye=new WeakMap,tye=new WeakMap,tX=new WeakMap,Id=new WeakSet,Symbol.asyncIterator)](){let e=[],n=[],r=!1;return this.on("event",o=>{let i=structuredClone(o),s=n.shift();s?s.resolve(i):e.push(i)}),this.on("end",()=>{r=!0;for(let o of n)o.resolve(void 0);n.length=0}),this.on("abort",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),this.on("error",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,s)=>n.push({resolve:i,reject:s})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let n=new I1;return n._run(()=>n._fromReadableStream(e)),n}async _fromReadableStream(e,n){this._listenForAbort(n?.signal),this._connected();let r=Fm.fromReadableStream(e,this.controller);for await(let o of r)be(this,Id,"m",QJ).call(this,o);if(r.controller.signal?.aborted)throw new Ra;return this._addRun(be(this,Id,"m",eX).call(this))}toReadableStream(){return new Fm(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,n,r,o){let i=new I1;return i._run(()=>i._runToolAssistantStream(e,n,r,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,n,r,o){this._listenForAbort(o?.signal);let i={...r,stream:!0},s=await e.submitToolOutputs(n,i,{...o,signal:this.controller.signal});this._connected();for await(let a of s)be(this,Id,"m",QJ).call(this,a);if(s.controller.signal?.aborted)throw new Ra;return this._addRun(be(this,Id,"m",eX).call(this))}static createThreadAssistantStream(e,n,r){let o=new I1;return o._run(()=>o._threadAssistantStream(e,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),o}static createAssistantStream(e,n,r,o){let i=new I1;return i._run(()=>i._runAssistantStream(e,n,r,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),i}currentEvent(){return be(this,eye,"f")}currentRun(){return be(this,tye,"f")}currentMessageSnapshot(){return be(this,Ib,"f")}currentRunStepSnapshot(){return be(this,tX,"f")}async finalRunSteps(){return await this.done(),Object.values(be(this,iS,"f"))}async finalMessages(){return await this.done(),Object.values(be(this,Qge,"f"))}async finalRun(){if(await this.done(),!be(this,T1,"f"))throw Error("Final run was not received.");return be(this,T1,"f")}async _createThreadAssistantStream(e,n,r){this._listenForAbort(r?.signal);let o={...n,stream:!0},i=await e.createAndRun(o,{...r,signal:this.controller.signal});this._connected();for await(let s of i)be(this,Id,"m",QJ).call(this,s);if(i.controller.signal?.aborted)throw new Ra;return this._addRun(be(this,Id,"m",eX).call(this))}async _createAssistantStream(e,n,r,o){this._listenForAbort(o?.signal);let i={...r,stream:!0},s=await e.create(n,i,{...o,signal:this.controller.signal});this._connected();for await(let a of s)be(this,Id,"m",QJ).call(this,a);if(s.controller.signal?.aborted)throw new Ra;return this._addRun(be(this,Id,"m",eX).call(this))}static accumulateDelta(e,n){for(let[r,o]of Object.entries(n)){if(!e.hasOwnProperty(r)){e[r]=o;continue}let i=e[r];if(i==null){e[r]=o;continue}if(r==="index"||r==="type"){e[r]=o;continue}if(typeof i=="string"&&typeof o=="string")i+=o;else if(typeof i=="number"&&typeof o=="number")i+=o;else if(x4(i)&&x4(o))i=this.accumulateDelta(i,o);else if(Array.isArray(i)&&Array.isArray(o)){if(i.every(s=>typeof s=="string"||typeof s=="number")){i.push(...o);continue}for(let s of o){if(!x4(s))throw new Error(`Expected array delta entry to be an object but got: ${s}`);let a=s.index;if(a==null)throw console.error(s),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let l=i[a];l==null?i[a]=s:i[a]=this.accumulateDelta(l,s)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${o}, accValue: ${i}`);e[r]=i}return e}_addRun(e){return e}async _threadAssistantStream(e,n,r){return await this._createThreadAssistantStream(n,e,r)}async _runAssistantStream(e,n,r,o){return await this._createAssistantStream(n,e,r,o)}async _runToolAssistantStream(e,n,r,o){return await this._createToolAssistantStream(n,e,r,o)}};I1=fI,QJ=function(e){if(!this.ended)switch(Tn(this,eye,e,"f"),be(this,Id,"m",Z3t).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":be(this,Id,"m",Q3t).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":be(this,Id,"m",G3t).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":be(this,Id,"m",K3t).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},eX=function(){if(this.ended)throw new pt("stream has ended, this shouldn't happen");if(!be(this,T1,"f"))throw Error("Final run has not been received");return be(this,T1,"f")},K3t=function(e){let[n,r]=be(this,Id,"m",J3t).call(this,e,be(this,Ib,"f"));Tn(this,Ib,n,"f"),be(this,Qge,"f")[n.id]=n;for(let o of r){let i=n.content[o.index];i?.type=="text"&&this._emit("textCreated",i.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,n),e.data.delta.content)for(let o of e.data.delta.content){if(o.type=="text"&&o.text){let i=o.text,s=n.content[o.index];if(s&&s.type=="text")this._emit("textDelta",i,s.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(o.index!=be(this,yH,"f")){if(be(this,k1,"f"))switch(be(this,k1,"f").type){case"text":this._emit("textDone",be(this,k1,"f").text,be(this,Ib,"f"));break;case"image_file":this._emit("imageFileDone",be(this,k1,"f").image_file,be(this,Ib,"f"));break}Tn(this,yH,o.index,"f")}Tn(this,k1,n.content[o.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(be(this,yH,"f")!==void 0){let o=e.data.content[be(this,yH,"f")];if(o)switch(o.type){case"image_file":this._emit("imageFileDone",o.image_file,be(this,Ib,"f"));break;case"text":this._emit("textDone",o.text,be(this,Ib,"f"));break}}be(this,Ib,"f")&&this._emit("messageDone",e.data),Tn(this,Ib,void 0,"f")}},G3t=function(e){let n=be(this,Id,"m",Y3t).call(this,e);switch(Tn(this,tX,n,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&n.step_details.type=="tool_calls")for(let i of r.step_details.tool_calls)i.index==be(this,nye,"f")?this._emit("toolCallDelta",i,n.step_details.tool_calls[i.index]):(be(this,pg,"f")&&this._emit("toolCallDone",be(this,pg,"f")),Tn(this,nye,i.index,"f"),Tn(this,pg,n.step_details.tool_calls[i.index],"f"),be(this,pg,"f")&&this._emit("toolCallCreated",be(this,pg,"f")));this._emit("runStepDelta",e.data.delta,n);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":Tn(this,tX,void 0,"f"),e.data.step_details.type=="tool_calls"&&be(this,pg,"f")&&(this._emit("toolCallDone",be(this,pg,"f")),Tn(this,pg,void 0,"f")),this._emit("runStepDone",e.data,n);break;case"thread.run.step.in_progress":break}},Z3t=function(e){be(this,xKe,"f").push(e),this._emit("event",e)},Y3t=function(e){switch(e.event){case"thread.run.step.created":return be(this,iS,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let n=be(this,iS,"f")[e.data.id];if(!n)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let o=I1.accumulateDelta(n,r.delta);be(this,iS,"f")[e.data.id]=o}return be(this,iS,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":be(this,iS,"f")[e.data.id]=e.data;break}if(be(this,iS,"f")[e.data.id])return be(this,iS,"f")[e.data.id];throw new Error("No snapshot available")},J3t=function(e,n){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!n)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let o=e.data;if(o.delta.content)for(let i of o.delta.content)if(i.index in n.content){let s=n.content[i.index];n.content[i.index]=be(this,Id,"m",X3t).call(this,i,s)}else n.content[i.index]=i,r.push(i);return[n,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(n)return[n,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},X3t=function(e,n){return I1.accumulateDelta(n,e)},Q3t=function(e){switch(Tn(this,tye,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":Tn(this,T1,e.data,"f"),be(this,pg,"f")&&(this._emit("toolCallDone",be(this,pg,"f")),Tn(this,pg,void 0,"f"));break;case"thread.run.cancelling":break}}});var P1,CKe=b(()=>{ot();bKe();bKe();Kn();Ii();SKe();S4();sn();P1=class extends ge{constructor(){super(...arguments),this.steps=new hH(this._client)}create(e,n,r){let{include:o,...i}=n;return this._client.post(ue`/threads/${e}/runs`,{query:{include:o},body:i,...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:n.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,n,r){let{thread_id:o}=n;return this._client.get(ue`/threads/${o}/runs/${e}`,{...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,n,r){let{thread_id:o,...i}=n;return this._client.post(ue`/threads/${o}/runs/${e}`,{body:i,...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(ue`/threads/${e}/runs`,pr,{query:n,...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,n,r){let{thread_id:o}=n;return this._client.post(ue`/threads/${o}/runs/${e}/cancel`,{...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,n,r){let o=await this.create(e,n,r);return await this.poll(o.id,{thread_id:e},r)}createAndStream(e,n,r){return fI.createAssistantStream(e,this._client.beta.threads.runs,n,r)}async poll(e,n,r){let o=We([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:s}=await this.retrieve(e,n,{...r,headers:{...r?.headers,...o}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let l=s.headers.get("openai-poll-after-ms");if(l){let c=parseInt(l);isNaN(c)||(a=c)}}await nS(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,n,r){return fI.createAssistantStream(e,this._client.beta.threads.runs,n,r)}submitToolOutputs(e,n,r){let{thread_id:o,...i}=n;return this._client.post(ue`/threads/${o}/runs/${e}/submit_tool_outputs`,{body:i,...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:n.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,n,r){let o=await this.submitToolOutputs(e,n,r);return await this.poll(o.id,n,r)}submitToolOutputsStream(e,n,r){return fI.createToolAssistantStream(e,this._client.beta.threads.runs,n,r)}};P1.Steps=hH});var eE,kKe=b(()=>{ot();wKe();wKe();CKe();CKe();Ii();SKe();sn();eE=class extends ge{constructor(){super(...arguments),this.runs=new P1(this._client),this.messages=new mH(this._client)}create(e={},n){return this._client.post("/threads",{body:e,...n,headers:We([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(ue`/threads/${e}`,{...n,headers:We([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(ue`/threads/${e}`,{body:n,...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(ue`/threads/${e}`,{...n,headers:We([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,n){return this._client.post("/threads/runs",{body:e,...n,headers:We([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,n){let r=await this.createAndRun(e,n);return await this.runs.poll(r.id,{thread_id:r.thread_id},n)}createAndRunStream(e,n){return fI.createThreadAssistantStream(e,this._client.beta.threads,n)}};eE.Runs=P1;eE.Messages=mH});var yv,IKe=b(()=>{ot();cKe();cKe();fKe();fKe();hKe();hKe();vKe();vKe();kKe();kKe();yv=class extends ge{constructor(){super(...arguments),this.realtime=new JA(this._client),this.responses=new QA(this._client),this.chatkit=new XA(this._client),this.assistants=new aH(this._client),this.threads=new eE(this._client)}};yv.Realtime=JA;yv.Responses=QA;yv.ChatKit=XA;yv.Assistants=aH;yv.Threads=eE});var A1,TKe=b(()=>{ot();A1=class extends ge{create(e,n){return this._client.post("/completions",{body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}})}}});var vH,PKe=b(()=>{ot();Ii();sn();vH=class extends ge{retrieve(e,n,r){let{container_id:o}=n;return this._client.get(ue`/containers/${o}/files/${e}/content`,{...r,headers:We([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}});var E1,AKe=b(()=>{ot();PKe();PKe();Kn();Ii();fg();sn();E1=class extends ge{constructor(){super(...arguments),this.content=new vH(this._client)}create(e,n,r){return this._client.post(ue`/containers/${e}/files`,VA({body:n,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,n,r){let{container_id:o}=n;return this._client.get(ue`/containers/${o}/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(ue`/containers/${e}/files`,pr,{query:n,...r,__security:{bearerAuth:!0}})}delete(e,n,r){let{container_id:o}=n;return this._client.delete(ue`/containers/${o}/files/${e}`,{...r,headers:We([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};E1.Content=vH});var tE,EKe=b(()=>{ot();AKe();AKe();Kn();Ii();sn();tE=class extends ge{constructor(){super(...arguments),this.files=new E1(this._client)}create(e,n){return this._client.post("/containers",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(ue`/containers/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/containers",pr,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(ue`/containers/${e}`,{...n,headers:We([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};tE.Files=E1});var wH,MKe=b(()=>{ot();Kn();sn();wH=class extends ge{create(e,n,r){let{include:o,...i}=n;return this._client.post(ue`/conversations/${e}/items`,{query:{include:o},body:i,...r,__security:{bearerAuth:!0}})}retrieve(e,n,r){let{conversation_id:o,...i}=n;return this._client.get(ue`/conversations/${o}/items/${e}`,{query:i,...r,__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(ue`/conversations/${e}/items`,jo,{query:n,...r,__security:{bearerAuth:!0}})}delete(e,n,r){let{conversation_id:o}=n;return this._client.delete(ue`/conversations/${o}/items/${e}`,{...r,__security:{bearerAuth:!0}})}}});var nE,OKe=b(()=>{ot();MKe();MKe();sn();nE=class extends ge{constructor(){super(...arguments),this.items=new wH(this._client)}create(e={},n){return this._client.post("/conversations",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(ue`/conversations/${e}`,{...n,__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(ue`/conversations/${e}`,{body:n,...r,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(ue`/conversations/${e}`,{...n,__security:{bearerAuth:!0}})}};nE.Items=wH});var M1,NKe=b(()=>{ot();gH();M1=class extends ge{create(e,n){let r=!!e.encoding_format,o=r?e.encoding_format:"base64";r&&_l(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let i=this._client.post("/embeddings",{body:{...e,encoding_format:o},...n,__security:{bearerAuth:!0}});return r?i:(_l(this._client).debug("embeddings/decoding base64 embeddings from base64"),i._thenUnwrap(s=>(s&&s.data&&s.data.forEach(a=>{let l=a.embedding;a.embedding=V3t(l)}),s)))}}});var bH,RKe=b(()=>{ot();Kn();sn();bH=class extends ge{retrieve(e,n,r){let{eval_id:o,run_id:i}=n;return this._client.get(ue`/evals/${o}/runs/${i}/output_items/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,n,r){let{eval_id:o,...i}=n;return this._client.getAPIList(ue`/evals/${o}/runs/${e}/output_items`,pr,{query:i,...r,__security:{bearerAuth:!0}})}}});var O1,LKe=b(()=>{ot();RKe();RKe();Kn();sn();O1=class extends ge{constructor(){super(...arguments),this.outputItems=new bH(this._client)}create(e,n,r){return this._client.post(ue`/evals/${e}/runs`,{body:n,...r,__security:{bearerAuth:!0}})}retrieve(e,n,r){let{eval_id:o}=n;return this._client.get(ue`/evals/${o}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(ue`/evals/${e}/runs`,pr,{query:n,...r,__security:{bearerAuth:!0}})}delete(e,n,r){let{eval_id:o}=n;return this._client.delete(ue`/evals/${o}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}cancel(e,n,r){let{eval_id:o}=n;return this._client.post(ue`/evals/${o}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}};O1.OutputItems=bH});var rE,$Ke=b(()=>{ot();LKe();LKe();Kn();sn();rE=class extends ge{constructor(){super(...arguments),this.runs=new O1(this._client)}create(e,n){return this._client.post("/evals",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(ue`/evals/${e}`,{...n,__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(ue`/evals/${e}`,{body:n,...r,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/evals",pr,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(ue`/evals/${e}`,{...n,__security:{bearerAuth:!0}})}};rE.Runs=O1});var N1,DKe=b(()=>{ot();Kn();Ii();S4();Um();fg();sn();N1=class extends ge{create(e,n){return this._client.post("/files",kf({body:e,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,n){return this._client.get(ue`/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/files",pr,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(ue`/files/${e}`,{...n,__security:{bearerAuth:!0}})}content(e,n){return this._client.get(ue`/files/${e}/content`,{...n,headers:We([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:n=5e3,maxWait:r=30*60*1e3}={}){let o=new Set(["processed","error","deleted"]),i=Date.now(),s=await this.retrieve(e);for(;!s.status||!o.has(s.status);)if(await nS(n),s=await this.retrieve(e),Date.now()-i>r)throw new eS({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return s}}});var _H,FKe=b(()=>{ot();_H=class extends ge{}});var xH,UKe=b(()=>{ot();xH=class extends ge{run(e,n){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...n,__security:{bearerAuth:!0}})}validate(e,n){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...n,__security:{bearerAuth:!0}})}}});var R1,jKe=b(()=>{ot();UKe();UKe();R1=class extends ge{constructor(){super(...arguments),this.graders=new xH(this._client)}};R1.Graders=xH});var SH,BKe=b(()=>{ot();Kn();sn();SH=class extends ge{create(e,n,r){return this._client.getAPIList(ue`/fine_tuning/checkpoints/${e}/permissions`,Cf,{body:n,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n={},r){return this._client.get(ue`/fine_tuning/checkpoints/${e}/permissions`,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(ue`/fine_tuning/checkpoints/${e}/permissions`,jo,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{fine_tuned_model_checkpoint:o}=n;return this._client.delete(ue`/fine_tuning/checkpoints/${o}/permissions/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}});var L1,zKe=b(()=>{ot();BKe();BKe();L1=class extends ge{constructor(){super(...arguments),this.permissions=new SH(this._client)}};L1.Permissions=SH});var CH,HKe=b(()=>{ot();Kn();sn();CH=class extends ge{list(e,n={},r){return this._client.getAPIList(ue`/fine_tuning/jobs/${e}/checkpoints`,pr,{query:n,...r,__security:{bearerAuth:!0}})}}});var $1,WKe=b(()=>{ot();HKe();HKe();Kn();sn();$1=class extends ge{constructor(){super(...arguments),this.checkpoints=new CH(this._client)}create(e,n){return this._client.post("/fine_tuning/jobs",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(ue`/fine_tuning/jobs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/fine_tuning/jobs",pr,{query:e,...n,__security:{bearerAuth:!0}})}cancel(e,n){return this._client.post(ue`/fine_tuning/jobs/${e}/cancel`,{...n,__security:{bearerAuth:!0}})}listEvents(e,n={},r){return this._client.getAPIList(ue`/fine_tuning/jobs/${e}/events`,pr,{query:n,...r,__security:{bearerAuth:!0}})}pause(e,n){return this._client.post(ue`/fine_tuning/jobs/${e}/pause`,{...n,__security:{bearerAuth:!0}})}resume(e,n){return this._client.post(ue`/fine_tuning/jobs/${e}/resume`,{...n,__security:{bearerAuth:!0}})}};$1.Checkpoints=CH});var Tb,VKe=b(()=>{ot();FKe();FKe();jKe();jKe();zKe();zKe();WKe();WKe();Tb=class extends ge{constructor(){super(...arguments),this.methods=new _H(this._client),this.jobs=new $1(this._client),this.checkpoints=new L1(this._client),this.alpha=new R1(this._client)}};Tb.Methods=_H;Tb.Jobs=$1;Tb.Checkpoints=L1;Tb.Alpha=R1});var kH,qKe=b(()=>{ot();kH=class extends ge{}});var oE,KKe=b(()=>{ot();qKe();qKe();oE=class extends ge{constructor(){super(...arguments),this.graderModels=new kH(this._client)}};oE.GraderModels=kH});var D1,GKe=b(()=>{ot();fg();D1=class extends ge{createVariation(e,n){return this._client.post("/images/variations",kf({body:e,...n,__security:{bearerAuth:!0}},this._client))}edit(e,n){return this._client.post("/images/edits",kf({body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,n){return this._client.post("/images/generations",{body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}})}}});var F1,ZKe=b(()=>{ot();Kn();sn();F1=class extends ge{retrieve(e,n){return this._client.get(ue`/models/${e}`,{...n,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",Cf,{...e,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(ue`/models/${e}`,{...n,__security:{bearerAuth:!0}})}}});var U1,YKe=b(()=>{ot();U1=class extends ge{create(e,n){return this._client.post("/moderations",{body:e,...n,__security:{bearerAuth:!0}})}}});var IH,JKe=b(()=>{ot();Ii();sn();IH=class extends ge{accept(e,n,r){return this._client.post(ue`/realtime/calls/${e}/accept`,{body:n,...r,headers:We([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}hangup(e,n){return this._client.post(ue`/realtime/calls/${e}/hangup`,{...n,headers:We([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}refer(e,n,r){return this._client.post(ue`/realtime/calls/${e}/refer`,{body:n,...r,headers:We([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}reject(e,n={},r){return this._client.post(ue`/realtime/calls/${e}/reject`,{body:n,...r,headers:We([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}}});var TH,XKe=b(()=>{ot();TH=class extends ge{create(e,n){return this._client.post("/realtime/client_secrets",{body:e,...n,__security:{bearerAuth:!0}})}}});var pI,QKe=b(()=>{ot();JKe();JKe();XKe();XKe();pI=class extends ge{constructor(){super(...arguments),this.clientSecrets=new TH(this._client),this.calls=new IH(this._client)}};pI.ClientSecrets=TH;pI.Calls=IH});function eqt(t,e){if(!e||!nfr(e)){let n={...t,output_parsed:null,output:t.output.map(r=>r.type==="function_call"?{...r,parsed_arguments:null}:r.type==="message"?{...r,content:r.content.map(o=>({...o,parsed:null}))}:r)};return nqt(t,n)&&mg(n),n}return eGe(t,e)}function eGe(t,e){let n=!t.status||t.status==="completed",r=t.output.map(i=>{if(i.type==="function_call")return n?ofr(e,i):{...i,parsed_arguments:null};if(i.type==="message"){let s=i.content.map(a=>a.type==="output_text"?{...a,parsed:n?tfr(e,a.text):null}:a);return{...i,content:s}}return i}),o=Object.assign({},t,{output:r});return nqt(t,o)&&mg(o),Object.defineProperty(o,"output_parsed",{enumerable:!0,get(){for(let i of o.output)if(i.type==="message"){for(let s of i.content)if(s.type==="output_text"&&s.parsed!==null)return s.parsed}return null}}),o}function tfr(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function nfr(t){return jJ(t.text?.format)?!0:Array.isArray(t.tools)&&t.tools.some(e=>tqt(e)||e.type==="function"&&e.strict===!0)}function tqt(t){return t?.$brand==="auto-parseable-tool"}function rfr(t,e){return t.find(n=>n.type==="function"&&n.name===e)}function ofr(t,e){let n=rfr(t.tools??[],e.name);return{...e,...e,parsed_arguments:tqt(n)?n.$parseRaw(e.arguments):n?.strict?JSON.parse(e.arguments):null}}function nqt(t,e){return!Object.getOwnPropertyDescriptor(t,"output_text")||e.output_text==null}function mg(t){let e=[];for(let n of t.output)if(n.type==="message")for(let r of n.content)r.type==="output_text"&&e.push(r.text);t.output_text=e.join("")}var PH=b(()=>{Um();E4()});function oqt(t,e){if(!e){if(t.type!=="response.created")throw new pt(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return rqt(t.response)}switch(t.type){case"response.output_item.added":{e.output.push(structuredClone(t.item)),t.item.type==="message"&&mg(e);break}case"response.output_item.done":{Po(e,t.output_index),e.output[t.output_index]=structuredClone(t.item),t.item.type==="message"&&mg(e);break}case"response.content_part.added":{let n=Po(e,t.output_index),r=n.type,o=t.part;r==="message"&&o.type!=="reasoning_text"?(n.content.push(structuredClone(o)),o.type==="output_text"&&mg(e)):r==="reasoning"&&o.type==="reasoning_text"&&(n.content||(n.content=[]),n.content.push(structuredClone(o)));break}case"response.content_part.done":{let n=Po(e,t.output_index),r=t.part;if(n.type==="message"&&r.type!=="reasoning_text")vv(n.content,t.content_index),n.content[t.content_index]=structuredClone(r),r.type==="output_text"&&mg(e);else if(n.type==="reasoning"&&r.type==="reasoning_text"){let o=n.content;if(!o)throw new pt(`missing content at index ${t.content_index}`);vv(o,t.content_index),o[t.content_index]=structuredClone(r)}break}case"response.output_text.delta":{let n=Po(e,t.output_index);if(n.type==="message"){let r=vv(n.content,t.content_index);if(r.type!=="output_text")throw new pt(`expected content to be 'output_text', got ${r.type}`);r.text+=t.delta,e.output_text+=t.delta}break}case"response.output_text.done":{let n=Po(e,t.output_index);if(n.type==="message"){let r=vv(n.content,t.content_index);if(r.type!=="output_text")throw new pt(`expected content to be 'output_text', got ${r.type}`);r.text=t.text,mg(e)}break}case"response.output_text.annotation.added":{let n=Po(e,t.output_index);if(n.type==="message"){let r=vv(n.content,t.content_index);if(r.type!=="output_text")throw new pt(`expected content to be 'output_text', got ${r.type}`);r.annotations[t.annotation_index]=structuredClone(t.annotation)}break}case"response.refusal.delta":{let n=Po(e,t.output_index);if(n.type==="message"){let r=vv(n.content,t.content_index);if(r.type!=="refusal")throw new pt(`expected content to be 'refusal', got ${r.type}`);r.refusal+=t.delta}break}case"response.refusal.done":{let n=Po(e,t.output_index);if(n.type==="message"){let r=vv(n.content,t.content_index);if(r.type!=="refusal")throw new pt(`expected content to be 'refusal', got ${r.type}`);r.refusal=t.refusal}break}case"response.function_call_arguments.delta":{let n=Po(e,t.output_index);n.type==="function_call"&&(n.arguments+=t.delta);break}case"response.function_call_arguments.done":{let n=Po(e,t.output_index);n.type==="function_call"&&(n.arguments=t.arguments);break}case"response.reasoning_text.delta":{let n=Po(e,t.output_index);if(n.type==="reasoning"){if(!n.content)throw new pt(`missing content at index ${t.content_index}`);let r=vv(n.content,t.content_index);if(r.type!=="reasoning_text")throw new pt(`expected content to be 'reasoning_text', got ${r.type}`);r.text+=t.delta}break}case"response.reasoning_text.done":{let n=Po(e,t.output_index);if(n.type==="reasoning"){if(!n.content)throw new pt(`missing content at index ${t.content_index}`);let r=vv(n.content,t.content_index);if(r.type!=="reasoning_text")throw new pt(`expected content to be 'reasoning_text', got ${r.type}`);r.text=t.text}break}case"response.reasoning_summary_part.added":{let n=Po(e,t.output_index);n.type==="reasoning"&&n.summary.push(structuredClone(t.part));break}case"response.reasoning_summary_part.done":{let n=Po(e,t.output_index);n.type==="reasoning"&&(vv(n.summary,t.summary_index),n.summary[t.summary_index]=structuredClone(t.part));break}case"response.reasoning_summary_text.delta":{let n=Po(e,t.output_index);if(n.type==="reasoning"){let r=vv(n.summary,t.summary_index);r.text+=t.delta}break}case"response.reasoning_summary_text.done":{let n=Po(e,t.output_index);if(n.type==="reasoning"){let r=vv(n.summary,t.summary_index);r.text=t.text}break}case"response.custom_tool_call_input.delta":{let n=Po(e,t.output_index);n.type==="custom_tool_call"&&(n.input+=t.delta);break}case"response.custom_tool_call_input.done":{let n=Po(e,t.output_index);n.type==="custom_tool_call"&&(n.input=t.input);break}case"response.mcp_call_arguments.delta":{let n=Po(e,t.output_index);n.type==="mcp_call"&&(n.arguments+=t.delta);break}case"response.mcp_call_arguments.done":{let n=Po(e,t.output_index);n.type==="mcp_call"&&(n.arguments=t.arguments);break}case"response.code_interpreter_call_code.delta":{let n=Po(e,t.output_index);n.type==="code_interpreter_call"&&(n.code=(n.code??"")+t.delta);break}case"response.code_interpreter_call_code.done":{let n=Po(e,t.output_index);n.type==="code_interpreter_call"&&(n.code=t.code);break}case"response.code_interpreter_call.in_progress":{let n=Po(e,t.output_index);n.type==="code_interpreter_call"&&(n.status="in_progress");break}case"response.code_interpreter_call.interpreting":{let n=Po(e,t.output_index);n.type==="code_interpreter_call"&&(n.status="interpreting");break}case"response.code_interpreter_call.completed":{let n=Po(e,t.output_index);n.type==="code_interpreter_call"&&(n.status="completed");break}case"response.file_search_call.in_progress":{let n=Po(e,t.output_index);n.type==="file_search_call"&&(n.status="in_progress");break}case"response.file_search_call.searching":{let n=Po(e,t.output_index);n.type==="file_search_call"&&(n.status="searching");break}case"response.file_search_call.completed":{let n=Po(e,t.output_index);n.type==="file_search_call"&&(n.status="completed");break}case"response.web_search_call.in_progress":{let n=Po(e,t.output_index);n.type==="web_search_call"&&(n.status="in_progress");break}case"response.web_search_call.searching":{let n=Po(e,t.output_index);n.type==="web_search_call"&&(n.status="searching");break}case"response.web_search_call.completed":{let n=Po(e,t.output_index);n.type==="web_search_call"&&(n.status="completed");break}case"response.image_generation_call.in_progress":{let n=Po(e,t.output_index);n.type==="image_generation_call"&&(n.status="in_progress");break}case"response.image_generation_call.generating":{let n=Po(e,t.output_index);n.type==="image_generation_call"&&(n.status="generating");break}case"response.image_generation_call.completed":{let n=Po(e,t.output_index);n.type==="image_generation_call"&&(n.status="completed");break}case"response.mcp_call.in_progress":{let n=Po(e,t.output_index);n.type==="mcp_call"&&(n.status="in_progress");break}case"response.mcp_call.completed":{let n=Po(e,t.output_index);n.type==="mcp_call"&&(n.status="completed");break}case"response.mcp_call.failed":{let n=Po(e,t.output_index);n.type==="mcp_call"&&(n.status="failed");break}case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":{e=rqt(t.response);break}case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":case"response.image_generation_call.partial_image":case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":case"keepalive":case"error":break;default:ifr(t)}return e}function rqt(t){let e=structuredClone(t);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&mg(e),e}function Po(t,e){let n=t.output[e];if(!n)throw new pt(`missing output at index ${e}`);return n}function vv(t,e){let n=t[e];if(!n)throw new pt(`missing content at index ${e}`);return n}function ifr(t){throw new pt(`Unhandled response stream event: ${JSON.stringify(t)}`)}var iqt=b(()=>{Um();PH()});function sfr(t,e){return eqt(t,e)}var iE,rye,j1,oye,tGe,nGe,rGe,iye,sqt=b(()=>{hv();Um();Zge();iqt();PH();ZJ();iye=class t extends qA{constructor(e){super(),iE.add(this),rye.set(this,void 0),j1.set(this,void 0),oye.set(this,void 0),Tn(this,rye,e,"f")}static createResponse(e,n,r){let o=new t(n);return o._run(()=>o._createOrRetrieveResponse(e,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),o}static fromReadableStream(e){let n=new t(null);return n._run(()=>n._fromReadableStream(e)),n}async _createOrRetrieveResponse(e,n,r){this._listenForAbort(r?.signal),be(this,iE,"m",tGe).call(this);let o,i=null;"response_id"in n?(o=await e.responses.retrieve(n.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=n.starting_after??null):o=await e.responses.create({...n,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let s of o)be(this,iE,"m",nGe).call(this,s,i);if(o.controller.signal?.aborted)throw new Ra;return be(this,iE,"m",rGe).call(this)}async _fromReadableStream(e,n){this._listenForAbort(n?.signal),be(this,iE,"m",tGe).call(this),this._connected();let r=Fm.fromReadableStream(e,this.controller);for await(let o of r)be(this,iE,"m",nGe).call(this,o,null);if(r.controller.signal?.aborted)throw new Ra;return be(this,iE,"m",rGe).call(this)}[(rye=new WeakMap,j1=new WeakMap,oye=new WeakMap,iE=new WeakSet,tGe=function(){this.ended||Tn(this,j1,void 0,"f")},nGe=function(n,r){if(this.ended)return;let o=(s,a)=>{(r==null||a.sequence_number>r)&&this._emit(s,a)},i=oqt(n,be(this,j1,"f"));switch(Tn(this,j1,i,"f"),o("event",n),n.type){case"response.output_text.delta":{let s=i.output[n.output_index];if(!s)throw new pt(`missing output at index ${n.output_index}`);if(s.type==="message"){let a=s.content[n.content_index];if(!a)throw new pt(`missing content at index ${n.content_index}`);if(a.type!=="output_text")throw new pt(`expected content to be 'output_text', got ${a.type}`);o("response.output_text.delta",{...n,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let s=i.output[n.output_index];if(!s)throw new pt(`missing output at index ${n.output_index}`);s.type==="function_call"&&o("response.function_call_arguments.delta",{...n,snapshot:s.arguments});break}default:o(n.type,n);break}},rGe=function(){if(this.ended)throw new pt("stream has ended, this shouldn't happen");let n=be(this,j1,"f");if(!n)throw new pt("request ended without sending any events");Tn(this,j1,void 0,"f");let r=sfr(n,be(this,rye,"f"));return Tn(this,oye,r,"f"),r},Symbol.asyncIterator)](){let e=[],n=[],r=!1;return this.on("event",o=>{let i=n.shift();i?i.resolve(o):e.push(o)}),this.on("end",()=>{r=!0;for(let o of n)o.resolve(void 0);n.length=0}),this.on("abort",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),this.on("error",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,s)=>n.push({resolve:i,reject:s})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=be(this,oye,"f");if(!e)throw new pt("stream ended without producing a ChatCompletion");return e}}});var AH,oGe=b(()=>{ot();Kn();sn();AH=class extends ge{list(e,n={},r){return this._client.getAPIList(ue`/responses/${e}/input_items`,pr,{query:n,...r,__security:{bearerAuth:!0}})}}});var EH,iGe=b(()=>{ot();EH=class extends ge{count(e={},n){return this._client.post("/responses/input_tokens",{body:e,...n,__security:{bearerAuth:!0}})}}});var sS,sGe=b(()=>{PH();sqt();ot();oGe();oGe();iGe();iGe();Ii();sn();sS=class extends ge{constructor(){super(...arguments),this.inputItems=new AH(this._client),this.inputTokens=new EH(this._client)}create(e,n){return this._client.post("/responses",{body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(r=>("object"in r&&r.object==="response"&&mg(r),r))}retrieve(e,n={},r){return this._client.get(ue`/responses/${e}`,{query:n,...r,stream:n?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(o=>("object"in o&&o.object==="response"&&mg(o),o))}delete(e,n){return this._client.delete(ue`/responses/${e}`,{...n,headers:We([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}parse(e,n){return this._client.responses.create(e,n)._thenUnwrap(r=>eGe(r,e))}stream(e,n){return iye.createResponse(this._client,e,n)}cancel(e,n){return this._client.post(ue`/responses/${e}/cancel`,{...n,__security:{bearerAuth:!0}})}compact(e,n){return this._client.post("/responses/compact",{body:e,...n,__security:{bearerAuth:!0}})}};sS.InputItems=AH;sS.InputTokens=EH});var MH,aGe=b(()=>{ot();Ii();sn();MH=class extends ge{retrieve(e,n){return this._client.get(ue`/skills/${e}/content`,{...n,headers:We([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}});var OH,lGe=b(()=>{ot();Ii();sn();OH=class extends ge{retrieve(e,n,r){let{skill_id:o}=n;return this._client.get(ue`/skills/${o}/versions/${e}/content`,{...r,headers:We([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}});var B1,cGe=b(()=>{ot();lGe();lGe();Kn();fg();sn();B1=class extends ge{constructor(){super(...arguments),this.content=new OH(this._client)}create(e,n={},r){return this._client.post(ue`/skills/${e}/versions`,VA({body:n,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,n,r){let{skill_id:o}=n;return this._client.get(ue`/skills/${o}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(ue`/skills/${e}/versions`,pr,{query:n,...r,__security:{bearerAuth:!0}})}delete(e,n,r){let{skill_id:o}=n;return this._client.delete(ue`/skills/${o}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}};B1.Content=OH});var mI,uGe=b(()=>{ot();aGe();aGe();cGe();cGe();Kn();fg();sn();mI=class extends ge{constructor(){super(...arguments),this.content=new MH(this._client),this.versions=new B1(this._client)}create(e={},n){return this._client.post("/skills",VA({body:e,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,n){return this._client.get(ue`/skills/${e}`,{...n,__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(ue`/skills/${e}`,{body:n,...r,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/skills",pr,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(ue`/skills/${e}`,{...n,__security:{bearerAuth:!0}})}};mI.Content=MH;mI.Versions=B1});var NH,dGe=b(()=>{ot();fg();sn();NH=class extends ge{create(e,n,r){return this._client.post(ue`/uploads/${e}/parts`,kf({body:n,...r,__security:{bearerAuth:!0}},this._client))}}});var sE,fGe=b(()=>{ot();dGe();dGe();sn();sE=class extends ge{constructor(){super(...arguments),this.parts=new NH(this._client)}create(e,n){return this._client.post("/uploads",{body:e,...n,__security:{bearerAuth:!0}})}cancel(e,n){return this._client.post(ue`/uploads/${e}/cancel`,{...n,__security:{bearerAuth:!0}})}complete(e,n,r){return this._client.post(ue`/uploads/${e}/complete`,{body:n,...r,__security:{bearerAuth:!0}})}};sE.Parts=NH});var aqt,lqt=b(()=>{aqt=async t=>{let e=await Promise.allSettled(t),n=e.filter(o=>o.status==="rejected");if(n.length){for(let o of n)console.error(o.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}let r=[];for(let o of e)o.status==="fulfilled"&&r.push(o.value);return r}});var RH,pGe=b(()=>{ot();Kn();Ii();S4();lqt();sn();RH=class extends ge{create(e,n,r){return this._client.post(ue`/vector_stores/${e}/file_batches`,{body:n,...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,n,r){let{vector_store_id:o}=n;return this._client.get(ue`/vector_stores/${o}/file_batches/${e}`,{...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,n,r){let{vector_store_id:o}=n;return this._client.post(ue`/vector_stores/${o}/file_batches/${e}/cancel`,{...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,n,r){let o=await this.create(e,n);return await this.poll(e,o.id,r)}listFiles(e,n,r){let{vector_store_id:o,...i}=n;return this._client.getAPIList(ue`/vector_stores/${o}/file_batches/${e}/files`,pr,{query:i,...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async poll(e,n,r){let o=We([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:s}=await this.retrieve(n,{vector_store_id:e},{...r,headers:o}).withResponse();switch(i.status){case"in_progress":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let l=s.headers.get("openai-poll-after-ms");if(l){let c=parseInt(l);isNaN(c)||(a=c)}}await nS(a);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(e,{files:n,fileIds:r=[]},o){if(n==null||n.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=o?.maxConcurrency??5,s=Math.min(i,n.length),a=this._client,l=n.values(),c=[...r];async function u(f){for(let p of f){let m=await a.files.create({file:p,purpose:"assistants"},o);c.push(m.id)}}let d=Array(s).fill(l).map(u);return await aqt(d),await this.createAndPoll(e,{file_ids:c})}}});var LH,mGe=b(()=>{ot();Kn();Ii();gH();sn();LH=class extends ge{create(e,n,r){return this._client.post(ue`/vector_stores/${e}/files`,{body:n,...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,n,r){let{vector_store_id:o}=n;return this._client.get(ue`/vector_stores/${o}/files/${e}`,{...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,n,r){let{vector_store_id:o,...i}=n;return this._client.post(ue`/vector_stores/${o}/files/${e}`,{body:i,...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(ue`/vector_stores/${e}/files`,pr,{query:n,...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,n,r){let{vector_store_id:o}=n;return this._client.delete(ue`/vector_stores/${o}/files/${e}`,{...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,n,r){let o=await this.create(e,n,r);return await this.poll(e,o.id,r)}async poll(e,n,r){let o=We([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let i=await this.retrieve(n,{vector_store_id:e},{...r,headers:o}).withResponse(),s=i.data;switch(s.status){case"in_progress":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let l=i.response.headers.get("openai-poll-after-ms");if(l){let c=parseInt(l);isNaN(c)||(a=c)}}await nS(a);break;case"failed":case"completed":return s}}}async upload(e,n,r){let o=await this._client.files.create({file:n,purpose:"assistants"},r);return this.create(e,{file_id:o.id},r)}async uploadAndPoll(e,n,r){let o=await this.upload(e,n,r);return await this.poll(e,o.id,r)}content(e,n,r){let{vector_store_id:o}=n;return this._client.getAPIList(ue`/vector_stores/${o}/files/${e}/content`,Cf,{...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}}});var hI,hGe=b(()=>{ot();pGe();pGe();mGe();mGe();Kn();Ii();sn();hI=class extends ge{constructor(){super(...arguments),this.files=new LH(this._client),this.fileBatches=new RH(this._client)}create(e,n){return this._client.post("/vector_stores",{body:e,...n,headers:We([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(ue`/vector_stores/${e}`,{...n,headers:We([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(ue`/vector_stores/${e}`,{body:n,...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/vector_stores",pr,{query:e,...n,headers:We([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(ue`/vector_stores/${e}`,{...n,headers:We([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}search(e,n,r){return this._client.getAPIList(ue`/vector_stores/${e}/search`,Cf,{body:n,method:"post",...r,headers:We([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};hI.Files=LH;hI.FileBatches=RH});var z1,gGe=b(()=>{ot();Kn();Ii();fg();sn();z1=class extends ge{create(e,n){return this._client.post("/videos",kf({body:e,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,n){return this._client.get(ue`/videos/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/videos",jo,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(ue`/videos/${e}`,{...n,__security:{bearerAuth:!0}})}createCharacter(e,n){return this._client.post("/videos/characters",kf({body:e,...n,__security:{bearerAuth:!0}},this._client))}downloadContent(e,n={},r){return this._client.get(ue`/videos/${e}/content`,{query:n,...r,headers:We([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,n){return this._client.post("/videos/edits",kf({body:e,...n,__security:{bearerAuth:!0}},this._client))}extend(e,n){return this._client.post("/videos/extensions",kf({body:e,...n,__security:{bearerAuth:!0}},this._client))}getCharacter(e,n){return this._client.get(ue`/videos/characters/${e}`,{...n,__security:{bearerAuth:!0}})}remix(e,n,r){return this._client.post(ue`/videos/${e}/remix`,VA({body:n,...r,__security:{bearerAuth:!0}},this._client))}}});var $H,cqt,sye,H1,yGe=b(()=>{hv();Um();ot();Ii();H1=class extends ge{constructor(){super(...arguments),$H.add(this)}async unwrap(e,n,r=this._client.webhookSecret,o=300){return await this.verifySignature(e,n,r,o),JSON.parse(e)}async verifySignature(e,n,r=this._client.webhookSecret,o=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");be(this,$H,"m",cqt).call(this,r);let i=We([n]).values,s=be(this,$H,"m",sye).call(this,i,"webhook-signature"),a=be(this,$H,"m",sye).call(this,i,"webhook-timestamp"),l=be(this,$H,"m",sye).call(this,i,"webhook-id"),c=parseInt(a,10);if(isNaN(c))throw new tS("Invalid webhook timestamp format");let u=Math.floor(Date.now()/1e3);if(u-c>o)throw new tS("Webhook timestamp is too old");if(c>u+o)throw new tS("Webhook timestamp is too new");let d=s.split(" ").map(h=>h.startsWith("v1,")?h.substring(3):h),f=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),p=l?`${l}.${a}.${e}`:`${a}.${e}`,m=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let h of d)try{let g=Buffer.from(h,"base64");if(await crypto.subtle.verify("HMAC",m,g,new TextEncoder().encode(p)))return}catch{continue}throw new tS("The given webhook signature does not match the expected signature")}};$H=new WeakSet,cqt=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},sye=function(e,n){if(!e)throw new Error("Headers are required");let r=e.get(n);if(r==null)throw new Error(`Missing required header: ${n}`);return r}});var uqt=b(()=>{yGe()});var dqt=b(()=>{uqt()});var vGe=b(()=>{H3t();W3t();rKe();aKe();lKe();IKe();TKe();EKe();OKe();NKe();$Ke();DKe();VKe();KKe();GKe();ZKe();YKe();QKe();sGe();uGe();fGe();hGe();gGe();dqt()});function yqt(t){let e=gqt.get(t);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var pqt,mqt,hqt,gqt,vqt=b(()=>{pqt=Symbol.for("openai.node.providerDefinitions.v1"),mqt=globalThis,hqt=mqt[pqt],gqt=hqt??new WeakMap;hqt||Object.defineProperty(mqt,pqt,{value:gqt})});function gfr(t){if(yfr(t))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });"}function yfr(t){let e=t;for(let n=0;n<8&&e&&typeof e=="object";n++){let r=e;if(r.code==="UND_ERR_INVALID_ARG"&&typeof r.message=="string"&&r.message.includes("invalid onRequestStart method"))return!0;e=r.cause}return!1}var wGe,bGe,nX,wqt,hfr,Rn,rX=b(()=>{hv();IJ();sI();S4();Tge();Nqe();C4();t3t();Hqe();Oqe();gv();Kn();w3t();gv();o5e();vGe();Lge();lKe();TKe();NKe();DKe();GKe();ZKe();YKe();gGe();rKe();aKe();IKe();k5e();EKe();OKe();$Ke();VKe();KKe();QKe();sGe();uGe();fGe();hGe();yGe();Nqe();Ii();vqt();_Ke();NJ();sI();hfr="workload-identity-auth",Rn=class{constructor(e={}){wGe.add(this),nX.set(this,void 0),this.completions=new A1(this),this.chat=new GA(this),this.embeddings=new M1(this),this.files=new N1(this),this.images=new D1(this),this.audio=new oS(this),this.moderations=new U1(this),this.models=new F1(this),this.fineTuning=new Tb(this),this.graders=new oE(this),this.vectorStores=new hI(this),this.webhooks=new H1(this),this.beta=new yv(this),this.batches=new C1(this),this.uploads=new sE(this),this.admin=new YA(this),this.responses=new sS(this),this.realtime=new pI(this),this.conversations=new nE(this),this.evals=new rE(this),this.containers=new tE(this),this.skills=new mI(this),this.videos=new z1(this);let n=e.provider;if(n){let h=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(g=>e[g]!=null);if(h.length)throw new pt(`The \`provider\` option cannot be used with ${h.map(g=>`\`${g}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:r=n?null:jm("OPENAI_BASE_URL"),apiKey:o=n?null:jm("OPENAI_API_KEY")??null,adminAPIKey:i=n?null:jm("OPENAI_ADMIN_KEY")??null,organization:s=n?null:jm("OPENAI_ORG_ID")??null,project:a=n?null:jm("OPENAI_PROJECT_ID")??null,webhookSecret:l=jm("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:c,...u}=e,d=n?yqt(n):void 0,f={apiKey:o,adminAPIKey:i,organization:s,project:a,webhookSecret:l,workloadIdentity:c,provider:n,...u,baseURL:d?.baseURL??(r||"https://api.openai.com/v1")};if(o&&c)throw new pt("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!d&&!o&&!i&&!c)throw new pt("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!f.dangerouslyAllowBrowser&&JVt())throw new pt(`It looks like you're running in a browser-like environment.
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
`);this.baseURL=f.baseURL,this.timeout=f.timeout??bGe.DEFAULT_TIMEOUT,this.logger=f.logger??console;let p="warn";this.logLevel=p,this.logLevel=Vqe(f.logLevel,"ClientOptions.logLevel",this)??Vqe(jm("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??p,this.fetchOptions=f.fetchOptions,this.maxRetries=f.maxRetries??2,this.fetch=f.fetch??Age(),Tn(this,nX,e3t,"f");let m=n?void 0:jm("OPENAI_CUSTOM_HEADERS");if(m){let h={};for(let g of m.split(`
`)){let v=g.indexOf(":");v>=0&&(h[g.substring(0,v).trim()]=g.substring(v+1).trim())}f.defaultHeaders=We([h,f.defaultHeaders])}this._options=f,this._provider=d,c&&(this._workloadIdentityAuth=new Dge(c,this.fetch)),this.apiKey=typeof o=="string"?o:null,this.adminAPIKey=i,this.organization=s,this.project=a,this.webhookSecret=l}withOptions(e){let n=this._options.provider,r=e.provider??n,o={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return r&&(delete o.apiKey,delete o.adminAPIKey,delete o.workloadIdentity,delete o.baseURL,r!==n&&(delete o.organization,delete o.project,delete o.defaultHeaders)),new this.constructor({...o,...e,provider:r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n},r={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(n.has("authorization")||n.has("api-key"))&&!(this._workloadIdentityAuth&&r.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,n={bearerAuth:!0,adminAPIKeyAuth:!0}){return We([n.bearerAuth?await this.bearerAuth(e):null,n.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return We([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return We([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return We([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return f3t(e)}getUserAgent(){return`${this.constructor.name}/JS ${WA}`}defaultIdempotencyKey(){return`stainless-node-retry-${p1()}`}makeStatusError(e,n,r,o){return Qa.generate(e,n,r,o)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!="function")return!1;let n;try{n=await e()}catch(r){throw r instanceof pt?r:new pt(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof n!="string"||!n)throw new pt(`Expected 'apiKey' function argument to return a string but it returned ${n}`);return this.apiKey=n,!0}buildURL(e,n,r){let o=!be(this,wGe,"m",wqt).call(this)&&r||this.baseURL,i=WVt(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery(),a=Object.fromEntries(i.searchParams);return(!Mqe(s)||!Mqe(a))&&(n={...a,...s,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(i.search=this.stringifyQuery(n)),i.toString()}async prepareOptions(e){if(this._provider)return;(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:n,options:r}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(o=>({method:e,path:n,...o})))}request(e,n=null){return new g1(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){let o=await e,i=o.maxRetries??this.maxRetries;n==null&&(n=i),await this.prepareOptions(o);let{req:s,url:a,timeout:l}=await this.buildRequest(o,{retryCount:i-n}),c=o.__metadata?.hasStreamingBody===!0;await this.prepareRequest(s,{url:a,options:o}),await this._provider?.prepareRequest?.(s,{url:a,options:o});let u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=r===void 0?"":`, retryOf: ${r}`,f=Date.now();if(_l(this).debug(`[${u}] sending request`,aI({retryOfRequestLogID:r,method:o.method,url:a,options:o,headers:s.headers})),o.signal?.aborted)throw new Ra;let p=o.__security??{bearerAuth:!0},m=new AbortController,h=await this.fetchWithAuth(a,s,l,m,p).catch(PJ),g=Date.now();if(h instanceof globalThis.Error){let w=`retrying, ${n} attempts remaining`;if(o.signal?.aborted)throw new Ra;let _=TJ(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(n&&!c)return _l(this).info(`[${u}] connection ${_?"timed out":"failed"} - ${w}`),_l(this).debug(`[${u}] connection ${_?"timed out":"failed"} (${w})`,aI({retryOfRequestLogID:r,url:a,durationMs:g-f,message:h.message})),this.retryRequest(o,n,r??u);let S=c?"error; streaming body cannot be retried":"error; no more retries left";throw _l(this).info(`[${u}] connection ${_?"timed out":"failed"} - ${S}`),_l(this).debug(`[${u}] connection ${_?"timed out":"failed"} (${S})`,aI({retryOfRequestLogID:r,url:a,durationMs:g-f,message:h.message})),h instanceof m1||h instanceof AJ?h:_?new eS:new HA({message:gfr(h),cause:h})}let v=[...h.headers.entries()].filter(([w])=>w==="x-request-id").map(([w,_])=>", "+w+": "+JSON.stringify(_)).join(""),y=`[${u}${d}${v}] ${s.method} ${a} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${g-f}ms`;if(!h.ok){if(h.status===401&&this._workloadIdentityAuth&&p.bearerAuth&&!o.__metadata?.hasStreamingBody&&!o.__metadata?.workloadIdentityTokenRefreshed)return await Lqe(h.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...o,__metadata:{...o.__metadata,workloadIdentityTokenRefreshed:!0}},n,r??u);let w=await this.shouldRetry(h);if(n&&w&&!c){let T=`retrying, ${n} attempts remaining`;return await Lqe(h.body),_l(this).info(`${y} - ${T}`),_l(this).debug(`[${u}] response error (${T})`,aI({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:g-f})),this.retryRequest(o,n,r??u,h.headers)}let _=w?c?"error; streaming body cannot be retried":"error; no more retries left":"error; not retryable";_l(this).info(`${y} - ${_}`);let S=await h.text().catch(T=>PJ(T).message),I=KVt(S),C=I?void 0:S;throw _l(this).debug(`[${u}] response error (${_})`,aI({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,message:C,durationMs:Date.now()-f})),this.makeStatusError(h.status,I,C,h.headers)}return _l(this).info(y),_l(this).debug(`[${u}] response start`,aI({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:g-f})),{response:h,options:o,controller:m,requestLogID:u,retryOfRequestLogID:r,startTime:f}}getAPIList(e,n,r){return this.requestAPIList(n,r&&"then"in r?r.then(o=>({method:"get",path:e,...o})):{method:"get",path:e,...r})}requestAPIList(e,n){let r=this.makeRequest(n,null,void 0);return new $J(this,r,e)}async fetchWithAuth(e,n,r,o,i={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&i.bearerAuth){let a=n.headers,l=a.get("Authorization");if(!l||l===`Bearer ${hfr}`){let c=await this._workloadIdentityAuth.getToken();a.set("Authorization",`Bearer ${c}`)}}return await this.fetchWithTimeout(e,n,r,o)}async fetchWithTimeout(e,n,r,o){let{signal:i,method:s,...a}=n||{},l=this._makeAbort(o);i&&i.addEventListener("abort",l,{once:!0});let c=setTimeout(l,r),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:o.signal,...u?{duplex:"half"}:{},method:"GET",...a};s&&(d.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(c)}}async shouldRetry(e){let n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,r,o){let i,s=o?.get("retry-after-ms");if(s){let l=parseFloat(s);Number.isNaN(l)||(i=l)}let a=o?.get("retry-after");if(a&&!i){let l=parseFloat(a);Number.isNaN(l)?i=Date.parse(a)-Date.now():i=l*1e3}if(i===void 0){let l=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(n,l)}return await nS(i),this.makeRequest(e,n-1,r)}calculateDefaultRetryTimeoutMillis(e,n){let i=n-e,s=Math.min(.5*Math.pow(2,i),8),a=1-Math.random()*.25;return s*a*1e3}async buildRequest(e,{retryCount:n=0}={}){let r={...e},{method:o,path:i,query:s,defaultBaseURL:a}=r,l=this.buildURL(i,s,a);"timeout"in r&&qVt("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:c,body:u,isStreamingBody:d}=this.buildBody({options:r});d&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let f=await this.buildHeaders({options:e,method:o,bodyHeaders:c,retryCount:n});return{req:{method:o,headers:f,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...r.fetchOptions??{}},url:l,timeout:r.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:r,retryCount:o}){let i={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);let s=We([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...XVt(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,r,e.headers]);return this._provider||this.validateHeaders(s,e.__security??{bearerAuth:!0}),s.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:n,headers:r}=e;if(!n)return n===void 0&&"body"in e?{...be(this,nX,"f").call(this,{body:n,headers:We([r])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let o=We([r]),i=typeof globalThis.ReadableStream<"u"&&n instanceof globalThis.ReadableStream,s=!i&&(typeof n=="string"||n instanceof ArrayBuffer||ArrayBuffer.isView(n)||typeof globalThis.Blob<"u"&&n instanceof globalThis.Blob||n instanceof URLSearchParams||n instanceof FormData);return ArrayBuffer.isView(n)||n instanceof ArrayBuffer||n instanceof DataView||typeof n=="string"&&o.values.has("content-type")||globalThis.Blob&&n instanceof globalThis.Blob||n instanceof FormData||n instanceof URLSearchParams||i?{bodyHeaders:void 0,body:n,isStreamingBody:!s}:typeof n=="object"&&(Symbol.asyncIterator in n||Symbol.iterator in n&&"next"in n&&typeof n.next=="function")?{bodyHeaders:void 0,body:EJ(n),isStreamingBody:!0}:typeof n=="object"&&o.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(n),isStreamingBody:!1}:{...be(this,nX,"f").call(this,{body:n,headers:o}),isStreamingBody:!1}}};bGe=Rn,nX=new WeakMap,wGe=new WeakSet,wqt=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};Rn.OpenAI=bGe;Rn.DEFAULT_TIMEOUT=6e5;Rn.OpenAIError=pt;Rn.APIError=Qa;Rn.APIConnectionError=HA;Rn.APIConnectionTimeoutError=eS;Rn.APIUserAbortError=Ra;Rn.NotFoundError=h4;Rn.ConflictError=g4;Rn.RateLimitError=v4;Rn.BadRequestError=f4;Rn.AuthenticationError=p4;Rn.InternalServerError=w4;Rn.PermissionDeniedError=m4;Rn.UnprocessableEntityError=y4;Rn.InvalidWebhookSignatureError=tS;Rn.toFile=FJ;Rn.toStreamingFile=Uge;Rn.Completions=A1;Rn.Chat=GA;Rn.Embeddings=M1;Rn.Files=N1;Rn.Images=D1;Rn.Audio=oS;Rn.Moderations=U1;Rn.Models=F1;Rn.FineTuning=Tb;Rn.Graders=oE;Rn.VectorStores=hI;Rn.Webhooks=H1;Rn.Beta=yv;Rn.Batches=C1;Rn.Uploads=sE;Rn.Admin=YA;Rn.Responses=sS;Rn.Realtime=pI;Rn.Conversations=nE;Rn.Evals=rE;Rn.Containers=tE;Rn.Skills=mI;Rn.Videos=z1});var W1,vfr,bqt=b(()=>{Ii();Um();gH();rX();W1=class extends Rn{constructor({baseURL:e=jm("OPENAI_BASE_URL"),apiKey:n=jm("AZURE_OPENAI_API_KEY"),apiVersion:r=jm("OPENAI_API_VERSION"),endpoint:o,deployment:i,azureADTokenProvider:s,dangerouslyAllowBrowser:a,...l}={}){if(!r)throw new pt("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof s=="function"&&(a=!0),!s&&!n)throw new pt("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(s&&n)throw new pt("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(l.defaultQuery={...l.defaultQuery,"api-version":r},e){if(o)throw new pt("baseURL and endpoint are mutually exclusive")}else{if(o||(o=process.env.AZURE_OPENAI_ENDPOINT),!o)throw new pt("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");let c=o.length;for(;c>0&&o[c-1]==="/";)c--;e=`${o.slice(0,c)}/openai`}super({apiKey:s??n,baseURL:e,...l,...a!==void 0?{dangerouslyAllowBrowser:a}:{}}),this.apiVersion="",this.apiVersion=r,this.deploymentName=i}async buildRequest(e,n={}){if(vfr.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!x4(e.body))throw new Error("Expected request body to be an object");let r=this.deploymentName||e.body.model||e.__metadata?.model;r!==void 0&&!this.baseURL.includes("/deployments")&&(e.path=`/deployments/${r}${e.path}`)}return super.buildRequest(e,n)}async authHeaders(e,n){let r=n??{bearerAuth:!0,adminAPIKeyAuth:!0};return r.bearerAuth&&typeof this._options.apiKey=="string"?We([{"api-key":this.apiKey}]):super.authHeaders(e,r)}},vfr=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"])});var _qt=b(()=>{Um();rX();Ii();gH();PH();vGe()});var Pb=b(()=>{rX();o5e();Lge();rX();Kn();gv();bqt();_qt()});function wfr(t){return!!(String(t).includes("context_length_exceeded")||"message"in t&&typeof t.message=="string"&&(t.message.includes("Input tokens exceed the configured limit")||t.message.includes("exceeds the context window")||t.message.includes("maximum context length")))}function hg(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===eS.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError",Gl(e,!0)):t.constructor.name===Ra.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError",Gl(e,!1)):wfr(t)?e=Wme.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=Gl(kJ(t,"INVALID_TOOL_RESULTS"),!1):"status"in t&&t.status===401?e=Gl(kJ(t,"MODEL_AUTHENTICATION"),!1):"status"in t&&t.status===429?e=Gl(kJ(t,"MODEL_RATE_LIMIT"),!0):"status"in t&&t.status===404?e=Gl(kJ(t,"MODEL_NOT_FOUND"),!1):e=t,e}var aE=b(()=>{HVt();Pb();Kk()});function gI(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function bfr(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function aye(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}function V1(t){let e=t.metadata?.filename??t.metadata?.name??t.metadata?.title;return e||(console.warn("OpenAI may require a filename for file uploads. Specify a filename in the content block metadata, e.g.: { type: 'file', mimeType: '...', data: '...', metadata: { filename: 'my-file.pdf' } }. Using placeholder filename 'LC_AUTOGENERATED'."),_fr)}function yI(t){let e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!yf.isInstance(t))throw new Error("Invalid generic chat message");return bfr(t);default:throw new Error(`Unknown message type: ${e}`)}}function xqt(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-pro")||t.includes("codex"))}var Ab,_fr,lE=b(()=>{oi();Ab=t=>t();_fr="LC_AUTOGENERATED"});function aS(t){let{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:n,azureOpenAIApiKey:r,azureOpenAIBasePath:o,baseURL:i,azureADTokenProvider:s,azureOpenAIEndpoint:a}=t;if((r||s)&&o&&e)return`${o}/${e}`;if((r||s)&&a&&e)return`${a}/openai/deployments/${e}`;if(r||s){if(!n)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${n}.openai.azure.com/openai/deployments/${e}`}return i}function _Ge(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function Sqt(t){let e=Ab(()=>{if(_Ge(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&_Ge(t.values))return t.values;if(typeof t=="object"&&t!==null){let n=Object.entries(t).filter(([,r])=>typeof r=="string").map(([r,o])=>[r,o]);return new Headers(n)}return new Headers});return Object.fromEntries(e.entries())}function Cqt(){let t=n6e();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function lS(t,e=!1,n="1.0.0"){let r=Sqt(t),o=Cqt(),i=`langchainjs${e?"-azure":""}-openai`;return{...r,"User-Agent":r["User-Agent"]?`${i}/${n} (${o})${r["User-Agent"]}`:`${i}/${n} (${o})`}}var cE=b(()=>{lE();ys()});function kqt(t,e){let n;return xf(t)?n=Gx(t):n=t,e?.strict!==void 0&&(n.function.strict=e.strict),n}function xfr(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Iqt(t){let e=["namespace functions {",""];for(let n of t)n.description&&e.push(`// ${n.description}`),Object.keys(n.parameters.properties??{}).length>0?(e.push(`type ${n.name} = (_: {`),e.push(Tqt(n.parameters,0)),e.push("}) => any;")):e.push(`type ${n.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
`)}function Tqt(t,e){let n=[];for(let[r,o]of Object.entries(t.properties??{}))o.description&&e<2&&n.push(`// ${o.description}`),t.required?.includes(r)?n.push(`${r}: ${lye(o,e)},`):n.push(`${r}?: ${lye(o,e)},`);return n.map(r=>" ".repeat(e)+r).join(`
`)}function lye(t,e){if(xfr(t))return t.anyOf.map(n=>lye(n,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(n=>`"${n}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",Tqt(t,e+2),"}"].join(`
`);case"array":return t.items?`${lye(t.items,e)}[]`:"any[]";default:return""}}function cye(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}function DH(t){return"type"in t&&t.type!=="function"}function Pqt(t){return typeof t=="object"&&t!==null&&"extras"in t&&typeof t.extras=="object"&&t.extras!==null&&"providerToolDefinition"in t.extras&&typeof t.extras.providerToolDefinition=="object"&&t.extras.providerToolDefinition!==null}function Aqt(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function q1(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function uye(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function Eqt(t){if(t.type==="custom_tool_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:t.name,isCustomTool:!0,args:{input:t.input}}}function Mqt(t){if(t.type==="computer_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:"computer_use",isComputerTool:!0,args:{action:t.action}}}function Oqt(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function Nqt(t,e){return typeof t!="object"||t===null||!("type"in t)||t.type!=="tool_call"?!1:!!("isCustomTool"in t&&t.isCustomTool===!0||e&&"id"in t&&typeof t.id=="string"&&t.id in e)}function Rqt(t){let e=()=>{if(t.custom.format){if(t.custom.format.type==="grammar")return{type:"grammar",definition:t.custom.format.grammar.definition,syntax:t.custom.format.grammar.syntax};if(t.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:t.custom.name,description:t.custom.description,format:e()}}function Lqt(t){let e=()=>{if(t.format){if(t.format.type==="grammar")return{type:"grammar",grammar:{definition:t.format.definition,syntax:t.format.syntax}};if(t.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:t.name,description:t.description,format:e()}}}var FH=b(()=>{rI();tv();tg()});var $qt=b(()=>{B8();B8()});var Eb=b(()=>{$qt()});var Uqt,Fqt,jqt,dye=b(()=>{Uqt=Symbol("Let zodToJsonSchema decide on which parser to use"),Fqt={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},jqt=t=>typeof t=="string"?{...Fqt,basePath:["#"],definitions:{},name:t}:{...Fqt,basePath:["#"],definitions:{},...t}});function Bqt(t){if(!t)return!0;for(let e in t)return!1;return!0}var oX,xGe=b(()=>{oX=t=>"_def"in t?t._def:t});var zqt,SGe=b(()=>{dye();xGe();zqt=t=>{let e=jqt(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:n,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([r,o])=>[oX(o),{def:oX(o),path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}}});function CGe(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function Bo(t,e,n,r,o){t[e]=n,CGe(t,e,r,o)}var uE=b(()=>{});function Hqt(){return{}}var kGe=b(()=>{});function Wqt(t,e){let n={type:"array"};return t.type?._def?.typeName!==Ie.ZodAny&&(n.items=ur(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Bo(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Bo(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Bo(n,"minItems",t.exactLength.value,t.exactLength.message,e),Bo(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}var IGe=b(()=>{Ox();uE();Jl()});function Vqt(t,e){let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?Bo(n,"minimum",r.value,r.message,e):Bo(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),Bo(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?Bo(n,"maximum",r.value,r.message,e):Bo(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),Bo(n,"maximum",r.value,r.message,e));break;case"multipleOf":Bo(n,"multipleOf",r.value,r.message,e);break}return n}var TGe=b(()=>{uE()});function qqt(){return{type:"boolean"}}var PGe=b(()=>{});function Kqt(t,e,n){return ur(t.type._def,e,n)}var AGe=b(()=>{Jl()});var Gqt,EGe=b(()=>{Jl();Gqt=(t,e,n)=>ur(t.innerType._def,e,n)});function MGe(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,i)=>MGe(t,e,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Sfr(t,e)}}var Sfr,OGe=b(()=>{uE();Sfr=(t,e)=>{let n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(let r of t.checks)switch(r.kind){case"min":Bo(n,"minimum",r.value,r.message,e);break;case"max":Bo(n,"maximum",r.value,r.message,e);break}return n}});function Zqt(t,e,n){return{...ur(t.innerType._def,e,n),default:t.defaultValue()}}var NGe=b(()=>{Jl()});function Yqt(t,e,n){return e.effectStrategy==="input"?ur(t.schema._def,e,n):{}}var RGe=b(()=>{Jl()});function Jqt(t){return{type:"string",enum:[...t.values]}}var LGe=b(()=>{});function Xqt(t,e){let n=[ur(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ur(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return n.forEach(i=>{if(Cfr(i))o.push(...i.allOf),i.unevaluatedProperties===void 0&&(r=void 0);else{let s=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:a,...l}=i;s=l}else r=void 0;o.push(s)}}),o.length?{allOf:o,...r}:void 0}var Cfr,$Ge=b(()=>{Jl();Cfr=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Qqt(t,e){let n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}var DGe=b(()=>{});function fye(t,e){let n={type:"string"};function r(o){return e.patternStrategy==="escape"?kfr(o):o}if(t.checks)for(let o of t.checks)switch(o.kind){case"min":Bo(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,o.value):o.value,o.message,e);break;case"max":Bo(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,o.value):o.value,o.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Mb(n,"email",o.message,e);break;case"format:idn-email":Mb(n,"idn-email",o.message,e);break;case"pattern:zod":Ob(n,K1.email,o.message,e);break}break;case"url":Mb(n,"uri",o.message,e);break;case"uuid":Mb(n,"uuid",o.message,e);break;case"regex":Ob(n,o.regex,o.message,e);break;case"cuid":Ob(n,K1.cuid,o.message,e);break;case"cuid2":Ob(n,K1.cuid2,o.message,e);break;case"startsWith":Ob(n,RegExp(`^${r(o.value)}`),o.message,e);break;case"endsWith":Ob(n,RegExp(`${r(o.value)}$`),o.message,e);break;case"datetime":Mb(n,"date-time",o.message,e);break;case"date":Mb(n,"date",o.message,e);break;case"time":Mb(n,"time",o.message,e);break;case"duration":Mb(n,"duration",o.message,e);break;case"length":Bo(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,o.value):o.value,o.message,e),Bo(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,o.value):o.value,o.message,e);break;case"includes":{Ob(n,RegExp(r(o.value)),o.message,e);break}case"ip":{o.version!=="v6"&&Mb(n,"ipv4",o.message,e),o.version!=="v4"&&Mb(n,"ipv6",o.message,e);break}case"emoji":Ob(n,K1.emoji,o.message,e);break;case"ulid":{Ob(n,K1.ulid,o.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Mb(n,"binary",o.message,e);break}case"contentEncoding:base64":{Bo(n,"contentEncoding","base64",o.message,e);break}case"pattern:zod":{Ob(n,K1.base64,o.message,e);break}}break}case"nanoid":Ob(n,K1.nanoid,o.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}var FGe,K1,kfr,Mb,Ob,e5t,pye=b(()=>{uE();K1={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(FGe===void 0&&(FGe=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),FGe),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};kfr=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Mb=(t,e,n,r)=>{t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&r.errorMessages&&{errorMessage:{format:n}}})):Bo(t,"format",e,n,r)},Ob=(t,e,n,r)=>{t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:e5t(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Bo(t,"pattern",e5t(e,r),n,r)},e5t=(t,e)=>{let n=typeof t=="function"?t():t;if(!e.applyRegexFlags||!n.flags)return n.source;let r={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},o=r.i?n.source.toLowerCase():n.source,i="",s=!1,a=!1,l=!1;for(let c=0;c<o.length;c++){if(s){i+=o[c],s=!1;continue}if(r.i){if(a){if(o[c].match(/[a-z]/)){l?(i+=o[c],i+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&o[c+2]?.match(/[a-z]/)?(i+=o[c],l=!0):i+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){i+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(r.m){if(o[c]==="^"){i+=`(^|(?<=[\r
]))`;continue}else if(o[c]==="$"){i+=`($|(?=[\r
]))`;continue}}if(r.s&&o[c]==="."){i+=a?`${o[c]}\r
`:`[${o[c]}\r
]`;continue}i+=o[c],o[c]==="\\"?s=!0:a&&o[c]==="]"?a=!1:!a&&o[c]==="["&&(a=!0)}try{let c=new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return i}});function mye(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===Ie.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,o)=>({...r,[o]:ur(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let n={type:"object",additionalProperties:ur(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===Ie.ZodString&&t.keyType._def.checks?.length){let r=Object.entries(fye(t.keyType._def,e)).reduce((o,[i,s])=>i==="type"?o:{...o,[i]:s},{});return{...n,propertyNames:r}}else if(t.keyType?._def.typeName===Ie.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};return n}var hye=b(()=>{Ox();Jl();pye()});function t5t(t,e){if(e.mapStrategy==="record")return mye(t,e);let n=ur(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=ur(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}var UGe=b(()=>{Jl();hye()});function n5t(t){let e=t.values,r=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(r.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}var jGe=b(()=>{});function r5t(){return{not:{}}}var BGe=b(()=>{});function o5t(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var zGe=b(()=>{});function s5t(t,e){if(e.target==="openApi3")return i5t(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in iX&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((o,i)=>{let s=iX[i._def.typeName];return s&&!o.includes(s)?[...o,s]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.reduce((o,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(r.length===n.length){let o=r.filter((i,s,a)=>a.indexOf(i)===s);return{type:o.length>1?o:o[0],enum:n.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(i=>!r.includes(i))],[])};return i5t(t,e)}var iX,i5t,gye=b(()=>{Jl();iX={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};i5t=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,o)=>ur(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0}});function a5t(t,e,n){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:iX[t.innerType._def.typeName],nullable:!0}:{type:[iX[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let o=ur(t.innerType._def,{...e,currentPath:[...e.currentPath]},n);return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}let r=ur(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var HGe=b(()=>{Jl();gye()});function l5t(t,e){let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",CGe(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?Bo(n,"minimum",r.value,r.message,e):Bo(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),Bo(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?Bo(n,"maximum",r.value,r.message,e):Bo(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),Bo(n,"maximum",r.value,r.message,e));break;case"multipleOf":Bo(n,"multipleOf",r.value,r.message,e);break}return n}var WGe=b(()=>{uE()});function Ifr(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":ur(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":ur(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function c5t(t,e){let n={type:"object",...Object.entries(t.shape()).reduce((r,[o,i])=>{if(i===void 0||i._def===void 0)return r;let s=[...e.currentPath,"properties",o],a=ur(i._def,{...e,currentPath:s,propertyPath:s});if(a===void 0)return r;if(e.openaiStrictMode&&i.isOptional()&&!i.isNullable()&&typeof i._def?.defaultValue>"u")throw new Error(`Zod field at \`${s.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...r.properties,[o]:a},required:i.isOptional()&&!e.openaiStrictMode?r.required:[...r.required,o]}},{properties:{},required:[]}),additionalProperties:Ifr(t,e)};return n.required.length||delete n.required,n}var VGe=b(()=>{Jl()});var u5t,qGe=b(()=>{Jl();u5t=(t,e,n)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return ur(t.innerType._def,{...e,currentPath:e.currentPath},n);let r=ur(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]},n);return r?{anyOf:[{not:{}},r]}:{}}});var d5t,KGe=b(()=>{Jl();d5t=(t,e,n)=>{if(e.pipeStrategy==="input")return ur(t.in._def,e,n);if(e.pipeStrategy==="output")return ur(t.out._def,e,n);let r=ur(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),o=ur(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,o].filter(i=>i!==void 0)}}});function f5t(t,e,n){return ur(t.type._def,e,n)}var GGe=b(()=>{Jl()});function p5t(t,e){let r={type:"array",uniqueItems:!0,items:ur(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&Bo(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&Bo(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}var ZGe=b(()=>{uE();Jl()});function m5t(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>ur(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:ur(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>ur(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}var YGe=b(()=>{Jl()});function h5t(){return{not:{}}}var JGe=b(()=>{});function g5t(){return{}}var XGe=b(()=>{});var y5t,QGe=b(()=>{Jl();y5t=(t,e,n)=>ur(t.innerType._def,e,n)});function ur(t,e,n=!1){let r=e.seen.get(t);if(e.override){let i=e.override?.(t,e,r,n);if(i!==Uqt)return i}if(r&&!n){let i=Tfr(r,e);if(i!==void 0)return"$ref"in i&&e.seenRefs.add(i.$ref),i}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);try{let i=Efr(t,t.typeName,e,n);return i&&Mfr(t,e,i),o.jsonSchema=i,i}finally{n&&r&&e.seen.set(t,r)}}var Tfr,v5t,Pfr,Afr,Efr,Mfr,Jl=b(()=>{Ox();kGe();IGe();TGe();PGe();AGe();EGe();OGe();NGe();RGe();LGe();$Ge();DGe();UGe();jGe();BGe();zGe();HGe();WGe();VGe();qGe();KGe();GGe();hye();ZGe();pye();YGe();JGe();gye();XGe();QGe();dye();Tfr=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":let n=t.path.slice(e.basePath.length+1).map((r,o)=>o===0?r:Pfr(r)).join("_");return n!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[n]=t.def),{$ref:[...e.basePath,e.definitionPath,n].join("/")};case"relative":return{$ref:Afr(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,o)=>e.currentPath[o]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},v5t="_x_",Pfr=t=>{if(/^[A-Za-z0-9_-]*$/.test(t)&&!t.startsWith(v5t))return t;let e=v5t;for(let n=0;n<t.length;n++)e+=t.charCodeAt(n).toString(16).padStart(4,"0");return e},Afr=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")},Efr=(t,e,n,r)=>{switch(e){case Ie.ZodString:return fye(t,n);case Ie.ZodNumber:return l5t(t,n);case Ie.ZodObject:return c5t(t,n);case Ie.ZodBigInt:return Vqt(t,n);case Ie.ZodBoolean:return qqt();case Ie.ZodDate:return MGe(t,n);case Ie.ZodUndefined:return h5t();case Ie.ZodNull:return o5t(n);case Ie.ZodArray:return Wqt(t,n);case Ie.ZodUnion:case Ie.ZodDiscriminatedUnion:return s5t(t,n);case Ie.ZodIntersection:return Xqt(t,n);case Ie.ZodTuple:return m5t(t,n);case Ie.ZodRecord:return mye(t,n);case Ie.ZodLiteral:return Qqt(t,n);case Ie.ZodEnum:return Jqt(t);case Ie.ZodNativeEnum:return n5t(t);case Ie.ZodNullable:return a5t(t,n,r);case Ie.ZodOptional:return u5t(t,n,r);case Ie.ZodMap:return t5t(t,n);case Ie.ZodSet:return p5t(t,n);case Ie.ZodLazy:return ur(t.getter()._def,n,r);case Ie.ZodPromise:return f5t(t,n,r);case Ie.ZodNaN:case Ie.ZodNever:return r5t();case Ie.ZodEffects:return Yqt(t,n,r);case Ie.ZodAny:return Hqt();case Ie.ZodUnknown:return g5t();case Ie.ZodDefault:return Zqt(t,n,r);case Ie.ZodBranded:return Kqt(t,n,r);case Ie.ZodReadonly:return y5t(t,n,r);case Ie.ZodCatch:return Gqt(t,n,r);case Ie.ZodPipeline:return d5t(t,n,r);case Ie.ZodFunction:case Ie.ZodVoid:case Ie.ZodSymbol:return;default:return(o=>{})(e)}},Mfr=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n)});var e9e,t9e=b(()=>{Jl();SGe();xGe();e9e=(t,e)=>{let n=zqt(e),r=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=ur(t._def,r===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??{},i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.title=i);let s=(()=>{if(Bqt(n.definitions))return;let l={},c=new Set;for(let u=0;u<500;u++){let d=Object.entries(n.definitions).filter(([f])=>!c.has(f));if(d.length===0)break;for(let[f,p]of d)l[f]=ur(oX(p),{...n,currentPath:[...n.basePath,n.definitionPath,f]},!0)??{},c.add(f)}return l})(),a=r===void 0?s?{...o,[n.definitionPath]:s}:o:n.nameStrategy==="duplicate-ref"?{...o,...s||n.seenRefs.size?{[n.definitionPath]:{...s,...n.seenRefs.size?{[r]:o}:void 0}}:void 0}:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,r].join("/"),[n.definitionPath]:{...s,[r]:o}};return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":n.target==="jsonSchema2019-09"&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),a}});var w5t=b(()=>{dye();SGe();uE();Jl();kGe();IGe();TGe();PGe();AGe();EGe();OGe();NGe();RGe();LGe();$Ge();DGe();UGe();jGe();BGe();zGe();HGe();WGe();VGe();qGe();KGe();GGe();QGe();hye();ZGe();pye();YGe();JGe();gye();XGe();t9e();t9e()});function wv(t,e,n){let r=t;for(let o of x5t)o in r&&n(r[o],[...e,o],o);for(let o of S5t){let i=r[o];if(Array.isArray(i))for(let[s,a]of i.entries())n(a,[...e,o,String(s)],o);else i!==void 0&&n(i,[...e,o],o)}for(let o of C5t){let i=r[o];if(bo(i))for(let[s,a]of Object.entries(i))o==="dependencies"&&!UH(a)||n(a,[...e,o,s],o)}}function k5t(t){let e=structuredClone(t);if(I5t(e),T5t(e),qfr(e),Nfr(e),e.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${e.type?`'${e.type}'`:"undefined"}`);if(e.anyOf!==void 0)throw new Error("Root schema must not use `anyOf` because strict Structured Outputs requires a root object without a union.");vye(e,[],e),E5t(e),vye(e,[],e),Gfr(e),bye(e,[],e);let n=yye(e,[],e);return vye(n,[],n),n}function I5t(t,e=new Set){if(typeof t=="boolean"||!bo(t)||e.has(t))return;e.add(t);let n=t;for(let r of Object.keys(n))n[r]===void 0&&delete n[r];wv(t,[],r=>{I5t(r,e)})}function Nfr(t){let e=new Set;for(;;){if(typeof t.$ref=="string"){if(e.has(t.$ref))throw new Error("Cyclic local $ref at `<root>` is not supported: "+JSON.stringify(t.$ref));e.add(t.$ref)}Rfr(t),E5t(t,!0),Lfr(t);let n=$fr(t);if(t.$ref===void 0&&!n)return}}function Rfr(t){let e=t.$ref;if(e===void 0)return;if(_5t(e),!Ufr(t))throw new Error("Schema $ref at `<root>` has non-metadata siblings that Draft 7 ignores and cannot be represented in strict Structured Outputs.");let n=new Set,r=Object.fromEntries(Object.entries(t).filter(([u])=>Nb.has(u))),o;for(;;){if(n.has(e))throw new Error("Cyclic local $ref at `<root>` is not supported: "+JSON.stringify(e));n.add(e);let u=dE(t,e);if(u===void 0)throw new Error("Local $ref at `<root>` does not resolve to an object or boolean schema: "+JSON.stringify(e));if(typeof u=="boolean")throw new TypeError("Expected object schema but got boolean; path=<root>");let d=u.$ref;if(d===void 0){o=u;break}if(_5t(d),n.has(d))throw new Error("Cyclic local $ref at `<root>` is not supported: "+JSON.stringify(d));if(!jH(u))throw new Error("Schema $ref in root chain has non-annotation siblings that Draft 7 ignores and cannot be represented in strict Structured Outputs.");for(let f of Nb)!(f in r)&&f in u&&(r[f]=u[f]);e=d}let i=t.$defs,s=t.definitions,a=Object.fromEntries(Object.entries(t).filter(([u])=>Nb.has(u)||Z1.has(u))),l=structuredClone(o);for(let u of["$defs","definitions"])t[u]!==void 0&&l[u]!==void 0&&delete l[u];let c=t;for(let u of Object.keys(t))delete c[u];Object.assign(t,l,r,a),i!==void 0&&(t.$defs=i),s!==void 0&&(t.definitions=s)}function Lfr(t){for(;t.allOf!==void 0;){if(Array.isArray(t.allOf))for(let[s,a]of t.allOf.entries())bye(a,["allOf",String(s)],t);if(l9e(t,[],t))continue;let e=t.allOf;if(!Array.isArray(e)||e.length!==1||!jfr(t))return;let n=e[0];if(typeof n=="boolean"||!bo(n))return;let r={...t};delete r.allOf;let o=structuredClone(n),i=t;for(let s of Object.keys(t))delete i[s];Object.assign(t,o,r)}}function $fr(t){let e=t.anyOf;if(!Array.isArray(e)||!Bfr(t))return!1;let n=e.map((c,u)=>({branch:c,index:u})).filter(({branch:c})=>c!==!1);if(n.length!==1)return!1;let{branch:r,index:o}=n[0];if(typeof r=="boolean"||!bo(r)||!wye(r,t))return!1;let i=Dfr(t,r);Ffr(t,o,i);let s={...t};delete s.anyOf;let a=structuredClone(r);for(let c of["$defs","definitions"]){let u=t[c],d=a[c];if(!bo(u)||!bo(d))continue;let f=i.get(c),p={...u};for(let[m,h]of Object.entries(d))p[f?.get(m)??m]=h;a[c]=p,delete s[c]}let l=t;for(let c of Object.keys(t))delete l[c];return Object.assign(t,a,s),!0}function Dfr(t,e){let n=new Map;for(let r of["$defs","definitions"]){let o=t[r],i=e[r];if(!bo(o)||!bo(i))continue;let s=new Set([...Object.keys(o),...Object.keys(i)]),a=new Map,l=0;for(let[c,u]of Object.entries(i)){if(!Object.prototype.hasOwnProperty.call(o,c)||aX(o[c],u))continue;let d="__openai_strict_anyOf_definition_"+l++;for(;s.has(d);)d="__openai_strict_anyOf_definition_"+l++;s.add(d),a.set(c,d)}a.size>0&&n.set(r,a)}return n}function Ffr(t,e,n){let r=i=>{let s=Y1(i);if(s===void 0||s[0]!=="anyOf"||s[1]!==String(e))return i;let a=s.slice(2),l=a[0];if(a.length>1&&(l==="$defs"||l==="definitions")){let c=n.get(l)?.get(a[1]);c!==void 0&&(a[1]=c)}return a.length===0?"#":"#/"+a.map(A5t).join("/")},o=i=>{typeof i=="boolean"||!bo(i)||(typeof i.$ref=="string"&&(i.$ref=r(i.$ref)),wv(i,[],s=>{o(s)}))};o(t)}function _5t(t){if(typeof t!="string")throw new TypeError("Received non-string $ref - "+String(t)+"; path=<root>");if(!t.startsWith("#"))throw new Error("External $ref at `<root>` is not supported in strict Structured Outputs: "+JSON.stringify(t))}function Ufr(t){return Object.keys(t).every(e=>e==="$ref"||e==="$defs"||e==="definitions"||Z1.has(e)||Nb.has(e))}function T5t(t){typeof t=="boolean"||!bo(t)||(Array.isArray(t.type)&&t.type.length===1&&(t.type=t.type[0]),wv(t,[],e=>{T5t(e)}))}function sX(t,e,n=new Set){if(typeof t=="boolean")return t;let r=t.$ref;if(r!==void 0){if(typeof r!="string"||!jH(t)||n.has(r))return!1;let o=dE(e,r);return o===void 0?!1:sX(o,e,new Set([...n,r]))}return!(t.type!==void 0&&t.type!=="null"&&!(Array.isArray(t.type)&&t.type.includes("null"))||"const"in t&&t.const!==null||t.enum!==void 0&&(!Array.isArray(t.enum)||!t.enum.includes(null))||t.allOf!==void 0&&(!Array.isArray(t.allOf)||!t.allOf.every(o=>sX(o,e)))||t.anyOf!==void 0&&(!Array.isArray(t.anyOf)||!t.anyOf.some(o=>sX(o,e)))||t.oneOf!==void 0&&(!Array.isArray(t.oneOf)||t.oneOf.filter(o=>sX(o,e)).length!==1)||t.not!==void 0||t.if!==void 0||t.then!==void 0||t.else!==void 0)}function yye(t,e,n){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!bo(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);if(l9e(t,e,n))return yye(t,e,n);if(Vfr(t),Hfr(t,e,n),o9e(t)){if(!("additionalProperties"in t))t.additionalProperties=!1;else if(t.additionalProperties!==!1)throw new Error(`Object schema at \`${e.join("/")||"<root>"}\` must set \`additionalProperties: false\` to be compatible with strict Structured Outputs.`)}let r=t.required??[];if(!Array.isArray(r)||r.some(d=>typeof d!="string"))throw new TypeError(`Expected \`required\` to be an array of strings; path=${e.join("/")||"<root>"}`);let o=t.properties;if(o9e(t)){for(let d of r)if(!bo(o)||!Object.prototype.hasOwnProperty.call(o,d))throw new Error(`Object schema at \`${e.join("/")||"<root>"}\` requires property \`${d}\` but does not declare it in \`properties\`.`)}if(bo(o)){for(let[d,f]of Object.entries(o))if(!sX(f,n)&&!r.includes(d))throw new Error(`Schema field at \`${[...e,"properties",d].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(o)}let i=t.items,s=t.additionalItems;if(Array.isArray(i))throw new Error(`Schema at \`${e.join("/")||"<root>"}\` uses tuple-form \`items\`, which cannot be represented in strict Structured Outputs.`);if(s!==void 0)throw new Error(`Schema at \`${e.join("/")||"<root>"}\` uses unsupported keyword \`additionalItems\` and cannot be represented in strict Structured Outputs.`);let a=t.allOf;if(Array.isArray(a)&&a.length===1&&s9e(t,"allOf")){let d=a[0];if(d===!1)throw new Error(`Schema at \`${e.join("/")||"<root>"}\` uses \`allOf: [false]\`, which cannot be represented in strict Structured Outputs.`);if(d===!0)delete t.allOf;else{let f=yye(d,[...e,"allOf","0"],n),p={...t};delete p.allOf,Object.assign(t,f,p),delete t.allOf}}Wfr(t,n);let l=t;for(let d of Ofr){if(l[d]!==void 0)throw new Error(`Schema at \`${e.join("/")||"<root>"}\` uses unsupported keyword \`${d}\` and cannot be represented in strict Structured Outputs.`);delete l[d]}let c=t.type,u=t.items;if((c==="array"||Array.isArray(c)&&c.includes("array"))&&u===void 0)throw new Error(`Schema at \`${e.join("/")||"<root>"}\` declares an array without \`items\`, which cannot be represented in strict Structured Outputs.`);return wv(t,e,(d,f,p)=>{typeof d=="boolean"&&(p==="additionalProperties"||p==="additionalItems")||yye(d,f,n)}),t.default===null&&delete t.default,t}function Y1(t){if(!t.startsWith("#"))return;let e;try{e=decodeURIComponent(t.slice(1))}catch{return}if(e==="")return[];if(!e.startsWith("/"))return;let n=[];for(let r of e.slice(1).split("/")){if(/~(?:[^01]|$)/.test(r))return;n.push(r.replace(/~1/g,"/").replace(/~0/g,"~"))}return n}function G1(t,e){if(Array.isArray(t)){if(!/^(?:0|[1-9]\d*)$/.test(e))return;let n=Number(e);return Object.prototype.hasOwnProperty.call(t,n)?t[n]:void 0}if(!(!bo(t)||!Object.prototype.hasOwnProperty.call(t,e)))return t[e]}function dE(t,e){let n=Y1(e);if(n===void 0)return;let r=t;for(let o=0;o<n.length;){if(!bo(r))return;let i=n[o];if(x5t.includes(i)){r=G1(r,i),o+=1;continue}if(S5t.includes(i)){if(r=G1(r,i),o+=1,Array.isArray(r)){if(o>=n.length)return;r=G1(r,n[o]),o+=1}continue}if(C5t.includes(i)){let s=G1(r,i);if(o+=1,!bo(s)||o>=n.length||(r=G1(s,n[o]),i==="dependencies"&&!UH(r)))return;o+=1;continue}return}return UH(r)?r:void 0}function bo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function UH(t){return typeof t=="boolean"||bo(t)}function wye(t,e,n=new Set){if(typeof t=="boolean"||!bo(t))return!1;if(t.$ref!==void 0){if(typeof t.$ref!="string"||!jH(t)||n.has(t.$ref))return!1;let r=dE(e,t.$ref);return r===void 0?!1:wye(r,e,new Set([...n,t.$ref]))}if(t.allOf!==void 0){if(!Array.isArray(t.allOf)||t.allOf.length!==1||!s9e(t,"allOf"))return!1;let r=t.allOf[0];return r!==void 0&&r!==!0&&r!==!1?wye(r,e,n):!1}return t.type==="object"||Array.isArray(t.type)&&t.type.length===1&&t.type[0]==="object"}function r9e(t,e,n=new Set){if(typeof t=="boolean"||!bo(t))return!1;if(t.$ref!==void 0){if(typeof t.$ref!="string"||!jH(t)||n.has(t.$ref))return!1;let r=dE(e,t.$ref);return r===void 0?!1:r9e(r,e,new Set([...n,t.$ref]))}if(t.allOf!==void 0){if(!Array.isArray(t.allOf)||t.allOf.length!==1||!s9e(t,"allOf"))return!1;let r=t.allOf[0];return r!==void 0&&r!==!0&&r!==!1?r9e(r,e,n):!1}return t.type==="array"||Array.isArray(t.type)&&t.type.length===1&&t.type[0]==="array"}function jH(t){return Object.keys(t).every(e=>e==="$ref"||e==="$defs"||e==="definitions"||Nb.has(e))}function s9e(t,e){let n=t;return Object.keys(t).every(r=>r===e||(r==="$defs"||r==="definitions")&&bo(n[r])||Nb.has(r))}function jfr(t){return Object.keys(t).every(e=>e==="allOf"||e==="$defs"||e==="definitions"||Z1.has(e)||Nb.has(e))}function Bfr(t){return Object.keys(t).every(e=>e==="anyOf"||e==="$defs"||e==="definitions"||e==="type"&&t.type==="object"||Z1.has(e)||Nb.has(e))}function zfr(t){return Object.keys(t).some(e=>i9e.has(e))}function o9e(t){let e=t.type;return e==="object"||Array.isArray(e)&&e.includes("object")||e===void 0&&zfr(t)}function P5t(t,e){return t===e||Array.isArray(t)&&t.length===2&&t.includes(e)&&t.includes("null")}function Hfr(t,e,n){if(t.anyOf===void 0)return;let r=bo(t.properties)&&Object.keys(t.properties).length===0,o=Array.isArray(t.required)&&t.required.length===0;if(r&&delete t.properties,o&&delete t.required,!o9e(t))return;let i=Object.keys(t).some(s=>i9e.has(s));if(P5t(t.type,"object")&&!i&&Array.isArray(t.anyOf)&&t.anyOf.every(s=>wye(s,n))){delete t.type;return}throw new Error("Object anyOf schema at `"+(e.join("/")||"<root>")+"` cannot be represented in strict Structured Outputs without changing Draft 7 validation.")}function Wfr(t,e){P5t(t.type,"array")&&t.items===void 0&&Array.isArray(t.anyOf)&&t.anyOf.every(n=>r9e(n,e))&&delete t.type}function Vfr(t){if(!Array.isArray(t.anyOf))return;let e=t.anyOf.filter(n=>n!==!1);e.length>0&&e.length!==t.anyOf.length&&(t.anyOf=e)}function qfr(t){let e=(n,r)=>{if(!(typeof n=="boolean"||!bo(n))){if(r.length>0&&n.$id!==void 0)throw new Error("Nested $id at "+JSON.stringify(r.join("/"))+" establishes a separate JSON Schema resource scope and cannot be represented in strict Structured Outputs.");wv(n,r,(o,i)=>{e(o,i)})}};e(t,[])}function Kfr(t,e){let n=Y1(e);if(n===void 0)return!1;let r=t;for(let[o,i]of n.entries()){if(i==="allOf"&&bo(r)&&Array.isArray(r.allOf)&&o<n.length-1)return!0;if(r=G1(r,i),r===void 0)return!1}return!1}function a9e(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function A5t(t){return encodeURIComponent(a9e(t)).replace(/%24/g,"$")}function Gfr(t){let e=r=>{let o=Y1(r);if(o===void 0||o.length===0)return r;let i=[...o],s=t,a=!1;for(let[l,c]of o.entries()){let u=typeof s=="object"&&s!==null&&!Array.isArray(s)?s:void 0;if(c==="anyOf"&&l<o.length-1&&u!==void 0&&Array.isArray(u.anyOf)){let d=u.anyOf,f=o[l+1];if(!/^(?:0|[1-9]\d*)$/.test(f))return r;let p=Number(f);if(!Object.prototype.hasOwnProperty.call(d,p))return r;let m=d.filter(h=>h!==!1);if(m.length>0&&m.length!==d.length){if(d[p]===!1)return r;let h=d.slice(0,p).filter(g=>g!==!1).length;h!==p&&(i[l+1]=String(h),a=!0)}}if(s=G1(s,c),s===void 0)return r}return a?"#/"+i.map(A5t).join("/"):r},n=r=>{typeof r=="boolean"||!bo(r)||(typeof r.$ref=="string"&&(r.$ref=e(r.$ref)),wv(r,[],o=>{n(o)}))};n(t)}function E5t(t,e=!1){let n=new Set,r=l=>{if(!(typeof l=="boolean"||!bo(l))){if(typeof l.$ref=="string"&&Kfr(t,l.$ref)){let c=Y1(l.$ref);(!e||c?.[0]==="allOf")&&n.add(l.$ref)}wv(l,[],c=>{r(c)})}};if(r(t),n.size===0)return;if(t.$defs!==void 0&&!bo(t.$defs))throw new Error("Root schema has invalid $defs and cannot preserve local allOf references.");let o=t.$defs??(t.$defs={}),i=new Map,s=0;for(let l of n){let c=dE(t,l);if(!UH(c)){if(e)continue;throw new Error("Local $ref cannot be preserved before allOf flattening: "+JSON.stringify(l))}let u="__openai_strict_allOf_ref_"+s++;for(;Object.prototype.hasOwnProperty.call(o,u);)u="__openai_strict_allOf_ref_"+s++;o[u]=structuredClone(c),i.set(l,"#/$defs/"+a9e(u))}let a=l=>{typeof l=="boolean"||!bo(l)||(typeof l.$ref=="string"&&(l.$ref=i.get(l.$ref)??l.$ref),wv(l,[],c=>{a(c)}))};a(t)}function Zfr(t,e){if(e.length===0)return;let n=new Set,r=l=>{if(!(typeof l=="boolean"||!bo(l))){if(typeof l.$ref=="string"){let c=Y1(l.$ref);c!==void 0&&e.some(u=>c.length>=u.length&&u.every((d,f)=>c[f]===d))&&n.add(l.$ref)}wv(l,[],c=>{r(c)})}};if(r(t),n.size===0)return;if(t.$defs!==void 0&&!bo(t.$defs))throw new Error("Root schema has invalid $defs and cannot preserve discarded allOf properties.");let o=t.$defs??(t.$defs={}),i=new Map,s=0;for(let l of n){let c=dE(t,l);if(!UH(c))throw new Error("Local $ref cannot be preserved before allOf property removal: "+JSON.stringify(l));let u="__openai_strict_allOf_property_ref_"+s++;for(;Object.prototype.hasOwnProperty.call(o,u);)u="__openai_strict_allOf_property_ref_"+s++;o[u]=structuredClone(c),i.set(l,"#/$defs/"+a9e(u))}let a=l=>{typeof l=="boolean"||!bo(l)||(typeof l.$ref=="string"&&(l.$ref=i.get(l.$ref)??l.$ref),wv(l,[],c=>{a(c)}))};a(t)}function vye(t,e,n){if(typeof t=="boolean"||!bo(t))return;let r=t.$ref;if(r!==void 0){if(typeof r!="string")throw new TypeError(`Received non-string $ref - ${r}; path=${e.join("/")}`);if(!r.startsWith("#"))throw new Error(`External $ref at \`${e.join("/")||"<root>"}\` is not supported in strict Structured Outputs: ${JSON.stringify(r)}`);let o=dE(n,r);if(o===void 0||!UH(o))throw new Error(`Local $ref at \`${e.join("/")||"<root>"}\` does not resolve to an object or boolean schema: ${JSON.stringify(r)}`);if(typeof o=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!jH(t))throw new Error(`Schema $ref at \`${e.join("/")||"<root>"}\` has non-annotation siblings that Draft 7 ignores and cannot be represented in strict Structured Outputs.`)}wv(t,e,(o,i)=>{vye(o,i,n)})}function Yfr(t,e,n){let r=[t],o=new Set,i=t,s=[];for(;;){for(;i.$ref!==void 0;){let a=i.$ref;if(typeof a!="string"||!jH(i)||o.has(a))return;o.add(a);let l=dE(e,a);if(typeof l=="boolean"||!bo(l))return;let c=Y1(a);if(c===void 0)return;i=l,s=c,r.push(i)}if(i.allOf!==void 0&&!n.has(i)){let a=i.allOf;if(bye(i,s,e,n),i.$ref!==void 0||i.allOf!==a)continue}return{schema:i,refChain:r}}}function bye(t,e,n,r=new Set){if(!(typeof t=="boolean"||!bo(t))&&!r.has(t)){r.add(t);try{for(;;)if(wv(t,e,(o,i)=>{bye(o,i,n,r)}),!l9e(t,e,n,r))return}finally{r.delete(t)}}}function l9e(t,e,n,r=new Set){let o=t.allOf;if(!Array.isArray(o)||o.length===0)return!1;let i=o.filter((P,E)=>!o.slice(0,E).some(O=>aX(O,P)));if(i.length!==o.length)return t.allOf=i,!0;let s=o.filter(P=>P!==!0);if(s.length!==o.length)return s.length===0?delete t.allOf:t.allOf=s,!0;let a=n9e(t),l=o.map(P=>bo(P)?Yfr(P,n,r):void 0),c=l.map(P=>P?.schema).filter(P=>P!==void 0&&n9e(P));if(!a&&c.length===0||!a&&o.length===1)return!1;let u=()=>{throw new Error(`Object allOf at \`${e.join("/")||"<root>"}\` cannot be merged without changing Draft 7 validation.`)};!a&&["additionalProperties","properties","required","type"].some(P=>P in t)&&u();for(let P of Object.keys(t))P!=="allOf"&&P!=="$defs"&&P!=="definitions"&&!(e.length===0&&Z1.has(P))&&!b5t.has(P)&&u();let d=[];a&&d.push({schema:t,sourcePath:e});for(let[P,E]of o.entries()){bo(E)||u();let O=l[P];if(O===void 0)return u();let $=O.schema;n9e($)?d.push({schema:$,sourcePath:$===E?[...e,"allOf",String(P)]:void 0}):Jfr($)||u()}let f={};for(let P of["$defs","definitions"])t[P]!==void 0&&(f[P]=t[P]);if(e.length===0)for(let P of Z1)P in t&&(f[P]=t[P]);let p=Object.create(null),m=new Set,h=[],g=[],v=!1,y=!1,w=!1,_=!1,S=P=>{for(let E of Nb)E in P&&(E in f||(f[E]=P[E]))};S(t);for(let P of l)if(P!==void 0)for(let E of P.refChain)S(E);for(let{schema:P,sourcePath:E}of d){for(let O of Object.keys(P))O==="allOf"&&P===t||(O==="$defs"||O==="definitions")&&bo(P[O])||P===t&&e.length===0&&Z1.has(O)||b5t.has(O)||u();if(P.type!==void 0&&(M5t(P.type)||u(),P.type==="object"?w=!0:_=!0),P.properties!==void 0){bo(P.properties)||u(),v=!0;for(let[O,$]of Object.entries(P.properties))g.push({key:O,propertySchema:$,sourcePath:E===void 0?void 0:[...E,"properties",O]})}if(P.required!==void 0){(!Array.isArray(P.required)||P.required.some(O=>typeof O!="string"))&&u(),y=!0;for(let O of P.required)m.add(O)}"additionalProperties"in P&&(P.additionalProperties!==!1&&u(),h.push(new Set(Object.keys(P.properties??{}))))}let I=h.length===0?void 0:h.slice(1).reduce((P,E)=>new Set([...P].filter(O=>E.has(O))),new Set(h[0])),C=I!==void 0&&[...m].some(P=>!I.has(P)),k=C&&!w&&_,T=g.filter(({key:P,sourcePath:E})=>E!==void 0&&(k||I!==void 0&&!I.has(P))).map(({sourcePath:P})=>P);if(Zfr(n,T),t===n&&n.$defs!==void 0&&(f.$defs=n.$defs),C){if(k){f.type="null";for(let P of Object.keys(t))delete t[P];return Object.assign(t,f),!0}u()}for(let{key:P,propertySchema:E}of g)I!==void 0&&!I.has(P)||(Object.prototype.hasOwnProperty.call(p,P)&&!aX(p[P],E)&&u(),p[P]=E);(w||_)&&(f.type=w?"object":["object","null"]),v&&(f.properties=Object.fromEntries(Object.entries(p))),y&&(f.required=[...m]),h.length>0&&(f.additionalProperties=!1);for(let P of Object.keys(t))delete t[P];return Object.assign(t,f),!0}function n9e(t){return t.type!==void 0?M5t(t.type):Object.keys(t).some(e=>i9e.has(e))}function Jfr(t){let e=t;return Object.keys(t).every(n=>Nb.has(n)||(n==="$defs"||n==="definitions")&&bo(e[n]))}function M5t(t){return t==="object"||Array.isArray(t)&&t.length===2&&t.includes("object")&&t.includes("null")}function aX(t,e){if(t===e)return!0;if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((s,a)=>aX(s,e[a]));if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;let n=t,r=e,o=Object.keys(n).sort(),i=Object.keys(r).sort();return o.length!==i.length?!1:o.every((s,a)=>s===i[a]&&aX(n[s],r[s]))}var Nb,Z1,i9e,x5t,S5t,C5t,Ofr,b5t,O5t=b(()=>{Nb=new Set(["$comment","default","description","examples","readOnly","title","writeOnly"]),Z1=new Set(["$id","$schema"]),i9e=new Set(["additionalProperties","dependencies","maxProperties","minProperties","patternProperties","properties","propertyNames","required"]),x5t=["additionalItems","additionalProperties","contains","contentSchema","else","if","not","propertyNames","then","unevaluatedItems","unevaluatedProperties"],S5t=["allOf","anyOf","items","oneOf","prefixItems"],C5t=["$defs","definitions","dependentSchemas","dependencies","patternProperties","properties"],Ofr=new Set(["$anchor","$dynamicAnchor","$dynamicRef","$recursiveAnchor","$recursiveRef","allOf","contains","contentEncoding","contentMediaType","contentSchema","dependentRequired","dependentSchemas","dependencies","else","if","maxContains","maxProperties","minContains","minProperties","not","patternProperties","prefixItems","propertyNames","then","unevaluatedItems","unevaluatedProperties","uniqueItems"]),b5t=new Set([...Nb,"additionalProperties","properties","required","type"])});function Xfr(t){return encodeURIComponent(t.replace(/~/g,"~0").replace(/\//g,"~1"))}function Qfr(t){if(t&&Object.prototype.hasOwnProperty.call(t,"__proto__"))throw new Error('schemaDefinitions cannot include "__proto__" as a definition name')}function N5t(t,e){let n=new Map(Object.keys(e??{}).map(o=>[`#/definitions/${o}`,`#/definitions/${Xfr(o)}`])),r=o=>{if(!o||typeof o!="object")return;if(Array.isArray(o)){for(let a of o)r(a);return}let i=o,s=i.$ref;typeof s=="string"&&(i.$ref=n.get(s)??s);for(let a of Object.values(i))r(a)};return r(t),t}function epr(t,e){let n=t;for(;e&&Object.prototype.hasOwnProperty.call(e,n);)n=`${n}_root`;return n}function tpr(t,e){let n=epr(e.name,e.schemaDefinitions),r=e9e(t,{openaiStrictMode:!0,name:n,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property",...e.schemaDefinitions?{definitions:e.schemaDefinitions}:void 0});return N5t(r,e.schemaDefinitions)}function npr(t,e={}){let n=e.schemaDefinitions?WU():void 0;for(let[i,s]of Object.entries(e.schemaDefinitions??{}))n?.add(s,{id:i});let r=lk(t,{target:"draft-7",...n?{metadata:n}:void 0,override:({zodSchema:i,jsonSchema:s})=>{let a=i._zod.def;if(a.type==="union"&&"discriminator"in a&&Array.isArray(s.oneOf)){if(s.anyOf!==void 0)throw new Error("Zod discriminated union generated both `anyOf` and `oneOf`, which cannot be represented in an OpenAI strict schema");s.anyOf=s.oneOf,delete s.oneOf}}}),o=N5t(r,e.schemaDefinitions);return k5t(o)}function rpr(t){return"_zod"in t}function opr(t,e){let n=JSON.parse(e),r=t.parse;return typeof r=="function"?r.call(t,n):P8(t,n)}function R5t(t,e,n){let r=t,{schemaDefinitions:o,...i}=n??{};return Qfr(o),E3t({type:"json_schema",json_schema:{...i,name:e,strict:!0,schema:rpr(r)?npr(r,{schemaDefinitions:o}):tpr(r,{name:e,schemaDefinitions:o})}},s=>opr(t,s))}var L5t=b(()=>{Eb();E4();w5t();PH();O5t()});function D5t(t,e){if(typeof e<"u"&&!$5t.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${$5t.join(", ")}`);let n=!t.startsWith("gpt-3")&&!t.startsWith("gpt-4-")&&t!=="gpt-4";if(n&&!e)return"jsonSchema";if(!n&&e==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${t}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return e??"functionCalling"}function ipr(t,e){let n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function F5t(t,e,n){if(ev(t))return R5t(t,e,n);if(yd(t))return ipr({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:Ki(t,{cycles:"ref",reused:"ref",override(r){r.jsonSchema.title=e}})}},r=>LN(t,JSON.parse(r)));throw new Error("Unsupported schema response format")}function U5t(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){let n=e.images.filter(r=>typeof r?.image_url?.url=="string").map(r=>({type:"image",url:r.image_url.url}));return[{type:"text",text:t},...n]}return t}var $5t,c9e=b(()=>{tv();tg();tf();L5t();$5t=["jsonSchema","functionCalling","jsonMode"]});var j5t,B5t=b(()=>{j5t={"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex-max":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex-spark":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"gpt-5.1-codex-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:13e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}}});function fpr(t){let e=Nn(spr);if(!(!e||dpr.includes(e.toLowerCase())))return`${upr.includes(e.toLowerCase())?cpr:e.replace(/\/+$/,"")}/${t}`}function _ye({baseURL:t,providerPath:e}){if(t!==void 0)return{baseURL:t};let n=fpr(e);return n===void 0?{}:{baseURL:n,apiKey:Nn(apr)||Nn(lpr)}}var spr,apr,lpr,cpr,upr,dpr,u9e=b(()=>{br();ys();spr="LANGSMITH_GATEWAY",apr="LANGSMITH_GATEWAY_API_KEY",lpr="LANGSMITH_API_KEY",cpr="https://gateway.smith.langchain.com",upr=["true","1","yes"],dpr=["false","0","no"]});function BH(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var xye,J1,lX=b(()=>{aE();FH();lE();cE();c9e();B5t();Pb();rI();tv();tg();ys();u9e();c1();lg();LA();a4();Nx();l1();xye="**REDACTED**";J1=class extends Cb{constructor(e){super(e??{});M(this,"temperature");M(this,"topP");M(this,"frequencyPenalty");M(this,"presencePenalty");M(this,"n");M(this,"logitBias");M(this,"model","gpt-3.5-turbo");M(this,"modelKwargs");M(this,"stop");M(this,"stopSequences");M(this,"user");M(this,"timeout");M(this,"streaming",!1);M(this,"streamUsage",!0);M(this,"maxTokens");M(this,"logprobs");M(this,"topLogprobs");M(this,"apiKey");M(this,"organization");M(this,"__includeRawResponse");M(this,"client");M(this,"clientConfig");M(this,"supportsStrictToolCalling");M(this,"audio");M(this,"modalities");M(this,"reasoning");M(this,"zdrEnabled");M(this,"service_tier");M(this,"promptCacheKey");M(this,"promptCacheRetention");M(this,"verbosity");M(this,"defaultOptions");M(this,"lc_serializable",!0);let n=typeof e?.configuration?.apiKey=="string"||typeof e?.configuration?.apiKey=="function"?e?.configuration?.apiKey:void 0,r=_ye({baseURL:e?.configuration?.baseURL??(Nn("OPENAI_API_BASE")||Nn("OPENAI_BASE_URL")||void 0),providerPath:"openai/v1"});this.apiKey=e?.apiKey??n??r.apiKey??Nn("OPENAI_API_KEY"),this.organization=e?.configuration?.organization??Nn("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.logitBias=e?.logitBias,this.stop=e?.stopSequences??e?.stop,this.stopSequences=this.stop,this.user=e?.user,this.__includeRawResponse=e?.__includeRawResponse,this.audio=e?.audio,this.modalities=e?.modalities,this.reasoning=e?.reasoning,this.maxTokens=e?.maxCompletionTokens??e?.maxTokens,this.promptCacheKey=e?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=e?.promptCacheRetention??this.promptCacheRetention,this.verbosity=e?.verbosity??this.verbosity,this.disableStreaming=e?.disableStreaming===!0,this.streaming=e?.streaming===!0,this.disableStreaming&&(this.streaming=!1),e?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=e?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration,baseURL:r.baseURL},e?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),e?.service_tier!==void 0&&(this.service_tier=e.service_tier),this.zdrEnabled=e?.zdrEnabled??!1,this._addVersion("@langchain/openai","1.5.8")}_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(e){let n=this.invocationParams(e);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:n.temperature??void 0,ls_max_tokens:n.max_tokens??void 0,ls_stop:e.stop}}_getInvocationParamsForTracing(e){let n=this.invocationParams(e);return Array.isArray(n.tools)?{...n,tools:n.tools.map(r=>{if(r?.type!=="mcp")return r;let o={...r};return"headers"in o&&(o.headers=xye),"authorization"in o&&(o.authorization=xye),o})}:n}_getCallOptionsForTracing(e,n){return Array.isArray(e.tools)?{...e,tools:e.tools.map(r=>{if(typeof r!="object"||r===null||!("type"in r)||r.type!=="mcp")return r;let o={...r};return"headers"in o&&(o.headers=xye),"authorization"in o&&(o.authorization=xye),o})}:e}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}_getReasoningParams(e){if(!gI(this.model))return;let n;return this.reasoning!==void 0&&(n={...n,...this.reasoning}),e?.reasoning!==void 0&&(n={...n,...e.reasoning}),e?.reasoningEffort!==void 0&&n?.effort===void 0&&(n={...n,effort:e.reasoningEffort}),n}_getResponseFormat(e){return e&&e.type==="json_schema"&&e.json_schema.schema&&ki(e.json_schema.schema)?F5t(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}_combineCallOptions(e){return{...this.defaultOptions,...e??{}}}_getClientOptions(e){if(!this.client){let n=aS({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:n,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=lS(r.defaultHeaders),this.client=new Rn(r)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,n){return q1(e)?Lqt(e.metadata.customTool):Zx(e)?n?.strict!==void 0?{...e,function:{...e.function,strict:n.strict}}:e:kqt(e,n)}bindTools(e,n){let r;return n?.strict!==void 0?r=n.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:e.map(o=>{if(DH(o)||q1(o))return o;if(Pqt(o))return o.extras.providerToolDefinition;let i=this._convertChatOpenAIToolToCompletionsTool(o,{strict:r});return xf(o)&&o.extras?.defer_loading===!0?{...i,defer_loading:!0}:i}),...n})}async stream(e,n){return super.stream(e,this._combineCallOptions(n))}async invoke(e,n){return super.invoke(e,this._combineCallOptions(n))}_combineLLMOutput(...e){return e.reduce((n,r)=>(r&&r.tokenUsage&&(n.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,n.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,n.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),n),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let n=0,r=0,o=0;this.model==="gpt-3.5-turbo-0301"?(r=4,o=-1):(r=3,o=1);let i=await Promise.all(e.map(async s=>{let[a,l]=await Promise.all([this.getNumTokens(s.content),this.getNumTokens(yI(s))]),c=s.name!==void 0?o+await this.getNumTokens(s.name):0,u=a+r+l+c,d=s;if(d._getType()==="function"&&(u-=2),d.additional_kwargs?.function_call&&(u+=3),d?.additional_kwargs.function_call?.name&&(u+=await this.getNumTokens(d.additional_kwargs.function_call?.name)),d.additional_kwargs.function_call?.arguments)try{u+=await this.getNumTokens(JSON.stringify(JSON.parse(d.additional_kwargs.function_call?.arguments)))}catch(f){console.error("Error parsing function arguments",f,JSON.stringify(d.additional_kwargs.function_call)),u+=await this.getNumTokens(d.additional_kwargs.function_call?.arguments)}return n+=u,u}));return n+=3,{totalCount:n,countPerMessage:i}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async n=>n.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([n.message])).countPerMessage[0]:await this.getNumTokens(n.message.content)))).reduce((n,r)=>n+r,0)}async _getEstimatedTokenCountFromPrompt(e,n,r){let o=(await this.getNumTokensFromMessages(e)).totalCount;if(n&&r!=="auto"){let i=Iqt(n);o+=await this.getNumTokens(i),o+=9}return n&&e.find(i=>i._getType()==="system")&&(o-=4),r==="none"?o+=1:typeof r=="object"&&(o+=await this.getNumTokens(r.name)+4),o}async moderateContent(e,n){let r=this._getClientOptions(n?.options),o={input:e,model:n?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(o,r)}catch(i){throw hg(i)}})}get profile(){return j5t[this.model]??{}}_getStructuredOutputMethod(e){let n={...e};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(n?.method===void 0)return"jsonSchema"}else n.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return n.method}withStructuredOutput(e,n){let r,o,{schema:i,name:s,includeRaw:a}={...n,schema:e};if(n?.strict!==void 0&&n.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let l=D5t(this.model,n?.method);if(l==="jsonMode"){o=pv(i);let c=Ki(i);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...c}}})}else if(l==="jsonSchema"){let c=Ki(i),u={name:s??"extract",description:Fk(c),schema:ki(i)?i:c,strict:n?.strict};if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:u},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:u.name,description:u.description,...c}}}),ki(i)||Ya(i)){let d=pv(i);o=nI.from(async f=>"parsed"in f.additional_kwargs?f.additional_kwargs.parsed:d.invoke(f.content))}else o=new hJ}else{let c=s??"extract",u=Ki(i),d;ki(i)||Ya(i)?d={name:c,description:u.description,parameters:u}:typeof i.name=="string"&&typeof i.parameters=="object"&&i.parameters!=null?(d=i,c=i.name):(c=i.title??c,d={name:c,description:i.description??"",parameters:i}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:d}],tool_choice:{type:"function",function:{name:c}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:c,...u}},...n?.strict!==void 0?{strict:n.strict}:{}}),o=Jx(i,c)}return mv(r,o,a)}}});var Sye=b(()=>{br();cqe()});var cX,Cye,kye,d9e,f9e,X1,zH=b(()=>{lE();c9e();oi();Sye();cX={providerName:"ChatOpenAI",fromStandardTextBlock(t){return{type:"text",text:t.text}},fromStandardImageBlock(t){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};if(t.source_type==="base64")return{type:"image_url",image_url:{url:`data:${t.mime_type??""};base64,${t.data}`,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(t){if(t.source_type==="url"){let e=hf({dataUrl:t.url});if(!e)throw new Error(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);let n=e.mime_type||t.mime_type||"",r;try{r=Fme(n)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(r.type!=="audio"||r.subtype!=="wav"&&r.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:r.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=Fme(t.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(e.type!=="audio"||e.subtype!=="wav"&&e.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:t.data}}}throw new Error(`Audio content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(t){if(t.source_type==="url"){let e=hf({dataUrl:t.url}),n=V1(t);if(!e)throw new Error(`URL file blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:t.url,filename:n}}}if(t.source_type==="base64"){let e=V1(t);return{type:"file",file:{file_data:`data:${t.mime_type??""};base64,${t.data}`,filename:e}}}if(t.source_type==="id")return{type:"file",file:{file_id:t.id}};throw new Error(`File content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)}},Cye=({message:t,rawResponse:e,includeRawResponse:n})=>{let r=t.tool_calls,o=t.reasoning_content;switch(t.role){case"assistant":{let i=[],s=[];for(let c of r??[])try{i.push(jA(c,{returnId:!0}))}catch(u){s.push(iI(c,u.message))}let a={function_call:t.function_call,tool_calls:r};n!==void 0&&(a.__raw_response=e),o!==void 0&&(a.reasoning_content=o);let l={model_provider:"openai",model_name:e.model,usage:{...e.usage},...e.system_fingerprint?{system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(a.audio=t.audio),new cr({content:U5t(t.content||"",e.choices?.[0]?.message),tool_calls:i,invalid_tool_calls:s,additional_kwargs:a,response_metadata:l,id:e.id})}default:return new yf(t.content||"",t.role??"unknown")}},kye=({delta:t,rawResponse:e,includeRawResponse:n,defaultRole:r})=>{let o=t.role??r,i=t.content??"",s;t.function_call?s={function_call:t.function_call}:t.tool_calls?s={tool_calls:t.tool_calls}:s={},n&&(s.__raw_response=e),t.reasoning_content!==void 0&&(s.reasoning_content=t.reasoning_content),t.audio&&(s.audio={...t.audio,index:e.choices[0].index});let a={model_provider:"openai",usage:{...e.usage}};if(o==="user")return new gA({content:i,response_metadata:a});if(o==="assistant"){let l=[];if(Array.isArray(t.tool_calls))for(let c of t.tool_calls)l.push({name:c.function?.name,args:c.function?.arguments,id:c.id,index:c.index,type:"tool_call_chunk"});return new On({content:i,tool_call_chunks:l,additional_kwargs:s,id:e.id,response_metadata:a})}else return o==="system"?new Lx({content:i,response_metadata:a}):o==="developer"?new Lx({content:i,response_metadata:a,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new hA({content:i,additional_kwargs:s,name:t.name,response_metadata:a}):o==="tool"?new xz({content:i,additional_kwargs:s,tool_call_id:t.tool_call_id,response_metadata:a}):new mA({content:i,role:o,response_metadata:a})},d9e=t=>{if(t.type==="image"){if(t.url)return{type:"image_url",image_url:{url:t.url}};if(t.data)return{type:"image_url",image_url:{url:`data:${t.mimeType};base64,${t.data}`}}}if(t.type==="audio"&&t.data){let e=GWe(()=>{let[,n]=t.mimeType.split("/");return n==="wav"||n==="mp3"?n:"wav"});return{type:"input_audio",input_audio:{data:t.data.toString(),format:e}}}if(t.type==="file"){if(t.data){let e=V1(t);return{type:"file",file:{file_data:`data:${t.mimeType};base64,${t.data}`,filename:e}}}if(t.fileId)return{type:"file",file:{file_id:t.fileId}}}},f9e=({message:t,model:e})=>{let n=yI(t);if(n==="system"&&gI(e)&&(n="developer"),n==="developer")return{role:"developer",content:t.contentBlocks.filter(o=>o.type==="text")};if(n==="system")return{role:"system",content:t.contentBlocks.filter(o=>o.type==="text")};if(n==="assistant"){let o={role:"assistant",content:t.contentBlocks.filter(i=>i.type==="text")};return cr.isInstance(t)&&t.tool_calls?.length?o.tool_calls=t.tool_calls.map(l4):t.additional_kwargs.tool_calls!=null&&(o.tool_calls=t.additional_kwargs.tool_calls),o}else{if(n==="tool"&&ig.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(o=>o.type==="text")};if(n==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(o=>o.type==="text").join("")}}function*r(o){for(let i of o){i.type==="text"&&(yield{type:"text",text:i.text});let s=d9e(i);s&&(yield s)}}return{role:"user",content:Array.from(r(t.contentBlocks))}},X1=({messages:t,model:e})=>t.flatMap(n=>{if("output_version"in n.response_metadata&&n.response_metadata?.output_version==="v1")return f9e({message:n});let r=yI(n);r==="system"&&gI(e)&&(r="developer");let o=typeof n.content=="string"?n.content:n.content.flatMap(s=>mf(s)?qk(s,cX):typeof s=="object"&&s!==null&&"type"in s&&(s.type==="tool_use"||s.type==="tool_call"||s.type==="reasoning"||s.type==="reasoning_content"||s.type==="thinking")?[]:s),i={role:r,content:o};return n.name!=null&&(i.name=n.name),n.additional_kwargs.function_call!=null&&(i.function_call=n.additional_kwargs.function_call),cr.isInstance(n)&&n.tool_calls?.length?i.tool_calls=n.tool_calls.map(l4):(n.additional_kwargs.tool_calls!=null&&(i.tool_calls=n.additional_kwargs.tool_calls),ig.isInstance(n)&&n.tool_call_id!=null&&(i.tool_call_id=n.tool_call_id)),n.additional_kwargs.audio&&typeof n.additional_kwargs.audio=="object"&&"id"in n.additional_kwargs.audio?[i,{role:"assistant",audio:{id:n.additional_kwargs.audio.id}}]:i})});async function*HH(t,e={}){let n=e.streamUsage??!0,r=e.provider??"openai",o=e.mapChunk,i=new Map,s=new Map,a=0,l=!1,c,u,d,f=!1,p=(m,h)=>{let g=s.get(m);if(g!==void 0)return{index:g,isNew:!1};let v=a++;return s.set(m,v),i.set(v,{...h}),{index:v,isNew:!0}};for await(let m of t){o&&(m=o(m)),l||(l=!0,yield{event:"message-start",id:m.id}),!f&&(m.model||m.service_tier)&&(f=!0,yield{event:"provider",provider:r,name:"stream_metadata",payload:{model:m.model,service_tier:m.service_tier}}),m.usage&&n&&(c=gpr(m.usage),yield{event:"usage",usage:c});let h=m.x_groq?.usage;h&&n&&(c=mpr(h),yield{event:"usage",usage:c});let g=m.choices?.[0];if(!g)continue;g.finish_reason!=null&&(u=hpr(g.finish_reason),d=ypr(m,g));let{delta:v}=g;if(!v)continue;let y=ppr(v);if(y){let{index:w,isNew:_}=p("reasoning",{type:"reasoning",reasoning:""});_&&(yield{event:"content-block-start",index:w,content:{type:"reasoning",reasoning:""}});let S=i.get(w);S.reasoning=(S.reasoning??"")+y,yield{event:"content-block-delta",index:w,delta:{type:"reasoning-delta",reasoning:y}}}if(v.content){let{index:w,isNew:_}=p("text",{type:"text",text:""});_&&(yield{event:"content-block-start",index:w,content:{type:"text",text:""}});let S=i.get(w);S.text=(S.text??"")+v.content,yield{event:"content-block-delta",index:w,delta:{type:"text-delta",text:v.content}}}if(Array.isArray(v.tool_calls))for(let w of v.tool_calls){let _=w.index??0,{index:S,isNew:I}=p(`tool:${_}`,{type:"tool_call_chunk",id:w.id,name:w.function?.name,args:"",index:_});I&&(yield{event:"content-block-start",index:S,content:{type:"tool_call_chunk",id:w.id,name:w.function?.name,args:"",index:_}});let C=i.get(S);w.id!=null&&(C.id=w.id),w.function?.name!=null&&(C.name=w.function.name);let k=w.function?.arguments??"";C.args=(C.args??"")+k,yield{event:"content-block-delta",index:S,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...C.id!=null?{id:C.id}:{},...C.name!=null?{name:C.name}:{},args:C.args}}}}if(v.audio){let{index:w,isNew:_}=p("audio",{type:"audio",id:v.audio.id,data:"",mimeType:"audio/pcm",transcript:v.audio.transcript??""});_&&(yield{event:"content-block-start",index:w,content:{type:"audio",id:v.audio.id,data:"",mimeType:"audio/pcm",transcript:v.audio.transcript??""}});let S=i.get(w);v.audio.transcript&&(S.transcript=(S.transcript??"")+v.audio.transcript,yield{event:"content-block-delta",index:w,delta:{type:"block-delta",fields:{type:"audio",transcript:S.transcript}}}),v.audio.data&&(S.data=(S.data??"")+v.audio.data,yield{event:"content-block-delta",index:w,delta:{type:"data-delta",data:v.audio.data,encoding:"base64"}})}v.function_call&&(yield{event:"provider",provider:r,name:"function_call",payload:v.function_call}),g.logprobs&&(yield{event:"provider",provider:r,name:"logprobs",payload:g.logprobs})}for(let[m,h]of i)yield{event:"content-block-finish",index:m,content:oI(h)};yield{event:"message-finish",reason:u,...c?{usage:c}:{},...d?{responseMetadata:d}:{}}}function ppr(t){let e=t.reasoning_content??t.reasoning;return typeof e=="string"&&e.length>0?e:void 0}function mpr(t){return{input_tokens:t.prompt_tokens??0,output_tokens:t.completion_tokens??0,total_tokens:t.total_tokens??0}}function hpr(t){switch(t){case"stop":return"stop";case"length":case"max_tokens":return"length";case"tool_calls":case"function_call":return"tool_use";case"content_filter":return"content_filter";default:return"stop"}}function gpr(t){let e={...t.prompt_tokens_details?.audio_tokens!=null&&{audio:t.prompt_tokens_details.audio_tokens},...t.prompt_tokens_details?.cached_tokens!=null&&{cache_read:t.prompt_tokens_details.cached_tokens}},n={...t.completion_tokens_details?.audio_tokens!=null&&{audio:t.completion_tokens_details.audio_tokens},...t.completion_tokens_details?.reasoning_tokens!=null&&{reasoning:t.completion_tokens_details.reasoning_tokens}};return{input_tokens:t.prompt_tokens??0,output_tokens:t.completion_tokens??0,total_tokens:t.total_tokens??0,...Object.keys(e).length>0&&{input_token_details:e},...Object.keys(n).length>0&&{output_token_details:n}}}function ypr(t,e){return{model_provider:"openai",model_name:t.model,system_fingerprint:t.system_fingerprint,service_tier:t.service_tier,finish_reason:e.finish_reason,...t.usage?{usage:t.usage}:{}}}var p9e=b(()=>{br();o4()});var m9e=b(()=>{p9e()});var fE,Iye=b(()=>{aE();FH();lE();lX();zH();m9e();oi();Sd();fE=class extends J1{constructor(t,e){super(BH(t,e))}invocationParams(t,e){let n;t?.strict!==void 0?n=t.strict:this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling),!(this.streaming||e?.streaming)&&t?.response_format?.type==="json_schema"&&n!==!1&&(n=!0);let r={};t?.stream_options!==void 0?r={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(r={stream_options:{include_usage:!0}});let o={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(s=>this._convertChatOpenAIToolToCompletionsTool(s,{strict:n})):void 0,tool_choice:cye(t?.tool_choice),response_format:this._getResponseFormat(t?.response_format),seed:t?.seed,...r,parallel_tool_calls:t?.parallel_tool_calls,...this.audio||t?.audio?{audio:this.audio||t?.audio}:{},...this.modalities||t?.modalities?{modalities:this.modalities||t?.modalities}:{},...this.modelKwargs,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,verbosity:t?.verbosity??this.verbosity};t?.prediction!==void 0&&(o.prediction=t.prediction),this.service_tier!==void 0&&(o.service_tier=this.service_tier),t?.service_tier!==void 0&&(o.service_tier=t.service_tier);let i=this._getReasoningParams(t);return i!==void 0&&i.effort!==void 0&&(o.reasoning_effort=i.effort),gI(o.model)?o.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:o.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,o}async _generate(t,e,n){e.signal?.throwIfAborted();let r={},o=this.invocationParams(e),i=X1({messages:t,model:this.model});if(o.stream){let s=this._streamResponseChunks(t,e,n),a={};for await(let p of s){p.message.response_metadata={...p.generationInfo,...p.message.response_metadata};let m=p.generationInfo?.completion??0;a[m]===void 0?a[m]=p:a[m]=a[m].concat(p)}let l=Object.entries(a).sort(([p],[m])=>parseInt(p,10)-parseInt(m,10)).map(([p,m])=>m),{functions:c,function_call:u}=this.invocationParams(e),d=await this._getEstimatedTokenCountFromPrompt(t,c,u),f=await this._getNumTokensFromGenerations(l);return r.input_tokens=d,r.output_tokens=f,r.total_tokens=d+f,{generations:l,llmOutput:{estimatedTokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}else{let s=await this.completionWithRetry({...o,stream:!1,messages:i},{signal:e?.signal,maxRetries:e?.maxRetries,...e?.options}),{completion_tokens:a,prompt_tokens:l,total_tokens:c,prompt_tokens_details:u,completion_tokens_details:d}=s?.usage??{};a&&(r.output_tokens=(r.output_tokens??0)+a),l&&(r.input_tokens=(r.input_tokens??0)+l),c&&(r.total_tokens=(r.total_tokens??0)+c),(u?.audio_tokens!==null||u?.cached_tokens!==null)&&(r.input_token_details={...u?.audio_tokens!==null&&{audio:u?.audio_tokens},...u?.cached_tokens!==null&&{cache_read:u?.cached_tokens}}),(d?.audio_tokens!==null||d?.reasoning_tokens!==null)&&(r.output_token_details={...d?.audio_tokens!==null&&{audio:d?.audio_tokens},...d?.reasoning_tokens!==null&&{reasoning:d?.reasoning_tokens}});let f=[];for(let p of s?.choices??[]){let m={text:p.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(p.message??{role:"assistant"},s)};m.generationInfo={...p.finish_reason?{finish_reason:p.finish_reason}:{},...p.logprobs?{logprobs:p.logprobs}:{}},cv(m.message)&&(m.message.usage_metadata=r),m.message=new cr(Object.fromEntries(Object.entries(m.message).filter(([h])=>!h.startsWith("lc_")))),f.push(m)}return{generations:f,llmOutput:{tokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}}async*_streamChatModelEvents(t,e,n){let r=X1({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:r,stream:!0},i=await this.completionWithRetry(o,e),s=this.streamUsage??e.streamUsage;yield*HH(async function*(l,c){for await(let u of l){if(c?.aborted)return;yield u}}(i,e.signal),{streamUsage:s??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,n){let r=X1({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:r,stream:!0},i,s=await this.completionWithRetry(o,e),a;for await(let l of s){if(e.signal?.aborted)return;let c=l?.choices?.[0];if(l.usage&&(a=l.usage),!c)continue;let{delta:u}=c;if(!u)continue;let d=this._convertCompletionsDeltaToBaseMessageChunk(u,l,i);i=u.role??i;let f={prompt:e.promptIndex??0,completion:c.index??0};if(typeof d.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let p={...f};c.finish_reason!=null&&(p.finish_reason=c.finish_reason,p.system_fingerprint=l.system_fingerprint,p.model_name=l.model,p.service_tier=l.service_tier),this.logprobs&&(p.logprobs=c.logprobs);let m=new di({message:d,text:d.content,generationInfo:p});yield m,await n?.handleLLMNewToken(m.text??"",f,void 0,void 0,void 0,{chunk:m})}if(a){let l={...a.prompt_tokens_details?.audio_tokens!==null&&{audio:a.prompt_tokens_details?.audio_tokens},...a.prompt_tokens_details?.cached_tokens!==null&&{cache_read:a.prompt_tokens_details?.cached_tokens}},c={...a.completion_tokens_details?.audio_tokens!==null&&{audio:a.completion_tokens_details?.audio_tokens},...a.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:a.completion_tokens_details?.reasoning_tokens}},u=new di({message:new On({content:"",response_metadata:{usage:{...a}},usage_metadata:{input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,total_tokens:a.total_tokens,...Object.keys(l).length>0&&{input_token_details:l},...Object.keys(c).length>0&&{output_token_details:c}}}),text:""});yield u,await n?.handleLLMNewToken(u.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:u})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let{maxRetries:n,...r}=e??{},o=this._getClientOptions(r),i=t.response_format&&t.response_format.type==="json_schema";return this.caller.callWithOptions({maxRetries:n},async()=>{try{return i&&!t.stream?await this.client.chat.completions.parse(t,o):await this.client.chat.completions.create(t,o)}catch(s){throw hg(s)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,n){return kye({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(t,e){return Cye({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}}});var Tye=b(()=>{cE();Pb();ys()});var h9e=b(()=>{Iye();Tye()});function G5t(t){return t.type==="url_citation"?{type:"citation",source:"url_citation",url:t.url,title:t.title,startIndex:t.start_index,endIndex:t.end_index}:t.type==="file_citation"?{type:"citation",source:"file_citation",title:t.filename,startIndex:t.index,file_id:t.file_id}:t.type==="container_file_citation"?{type:"citation",source:"container_file_citation",title:t.filename,startIndex:t.start_index,endIndex:t.end_index,file_id:t.file_id,container_id:t.container_id}:t.type==="file_path"?{type:"citation",source:"file_path",startIndex:t.index,file_id:t.file_id}:{type:"non_standard",value:t}}function wpr(t){if(t.type==="url_citation"||t.type==="file_citation"||t.type==="container_file_citation"||t.type==="file_path")return t;if(t.type==="citation"){let e=t;if(e.source==="url_citation")return{type:"url_citation",url:e.url??"",title:e.title??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_citation")return{type:"file_citation",file_id:e.file_id??"",filename:e.title??"",index:e.startIndex??0};if(e.source==="container_file_citation")return{type:"container_file_citation",file_id:e.file_id??"",filename:e.title??"",container_id:e.container_id??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_path")return{type:"file_path",file_id:e.file_id??"",index:e.startIndex??0}}return t.type==="non_standard"?t.value:t}var WH,VH,qH,uX,g9e,Pye,y9e,KH,dX=b(()=>{FH();lE();zH();oi();Sd();Sye();WH="__openai_function_call_ids__",VH="__openai_custom_tool_call_ids__";qH=t=>{let e={...t?.input_tokens_details?.cached_tokens!=null&&{cache_read:t?.input_tokens_details?.cached_tokens}},n={...t?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:t?.output_tokens_details?.reasoning_tokens}};return{input_tokens:t?.input_tokens??0,output_tokens:t?.output_tokens??0,total_tokens:t?.total_tokens??0,input_token_details:e,output_token_details:n}},uX=t=>{if(t.error){let a=new Error(t.error.message);throw a.name=t.error.code,a}let e=[],n=[],r=[],o=t.output.map(a=>{if(a.type==="function_call"&&"parsed_arguments"in a){let l={...a};return delete l.parsed_arguments,l}return a}),i={model_provider:"openai",model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,output:o,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},s={};for(let a of t.output)if(a.type==="message")e.push(...a.content.flatMap(l=>l.type==="output_text"?("parsed"in l&&l.parsed!=null&&(s.parsed=l.parsed),{type:"text",text:l.text,annotations:l.annotations.map(G5t),...a.phase!==null?{phase:a.phase}:{}}):l.type==="refusal"?(s.refusal=l.refusal,[]):l));else if(a.type==="function_call"){let l={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{n.push(jA(l,{returnId:!0}))}catch(c){let u;typeof c=="object"&&c!=null&&"message"in c&&typeof c.message=="string"&&(u=c.message),r.push(iI(l,u))}s[WH]??(s[WH]={}),a.id&&(s[WH][a.call_id]=a.id)}else if(a.type==="reasoning"){s.reasoning=a;let l=a.summary?.map(c=>c.text).filter(Boolean).join("");l&&e.push({type:"reasoning",reasoning:l})}else if(a.type==="custom_tool_call"){let l=Eqt(a);l?(n.push(l),s[VH]??(s[VH]={}),a.id&&a.call_id&&(s[VH][a.call_id]=a.id)):r.push(iI(a,"Malformed custom tool call"))}else if(a.type==="computer_call"){let l=Mqt(a);l?n.push(l):r.push(iI(a,"Malformed computer call"))}else a.type==="image_generation_call"?(a.result&&e.push({type:"image",mimeType:"image/png",data:a.result,id:a.id,metadata:{status:a.status}}),s.tool_outputs??(s.tool_outputs=[]),s.tool_outputs.push(a)):(s.tool_outputs??(s.tool_outputs=[]),s.tool_outputs.push(a));return new cr({id:t.id,content:e,tool_calls:n,invalid_tool_calls:r,usage_metadata:qH(t.usage),additional_kwargs:s,response_metadata:i})},g9e=t=>{let e=(t.summary.length>1?t.summary.reduce((n,r)=>{let o=n[n.length-1];return o.index===r.index?o.text+=r.text:n.push(r),n},[{...t.summary[0]}]):t.summary).map(n=>Object.fromEntries(Object.entries(n).filter(([r])=>r!=="index")));return{...t,summary:e}},Pye=t=>{let e=[],n={},r,o=[],i={model_provider:"openai"},s={},a;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[G5t(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){let l="phase"in t.item?t.item.phase:void 0;l&&e.push({type:"text",text:"",phase:l,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")o.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),s[WH]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.added"&&t.item.type==="custom_tool_call")o.push({type:"tool_call_chunk",isCustomTool:!0,name:t.item.name,args:t.item.input,id:t.item.call_id,index:t.output_index}),s[VH]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")o.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),s.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),s.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))s.tool_outputs=[t.item];else if(t.type==="response.created")a=t.response.id,i.id=t.response.id,i.model_name=t.response.model,i.model=t.response.model;else if(t.type==="response.completed"||t.type==="response.incomplete"){a=t.response.id;let l=uX(t.response);if(r=qH(t.response.usage),t.response.text?.format?.type==="json_schema"&&l.text)try{s.parsed??(s.parsed=JSON.parse(l.text))}catch{}for(let[c,u]of Object.entries(t.response))c!=="id"&&(c==="output"?i[c]=l.response_metadata.output:i[c]=u)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")o.push({type:"tool_call_chunk",args:t.delta,index:t.output_index,...t.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});else if(t.type==="response.web_search_call.in_progress"||t.type==="response.web_search_call.searching"||t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.in_progress"||t.type==="response.file_search_call.searching"||t.type==="response.file_search_call.completed"||t.type==="response.image_generation_call.in_progress"||t.type==="response.image_generation_call.generating"||t.type==="response.image_generation_call.completed"){let[,l,c]=t.type.match(/^response\.(.*)\.([^.]+)$/)??["","",""];n={tool_outputs:{id:t.item_id,type:l,status:c}}}else if(t.type==="response.refusal.done")s.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){let l=t.item.summary?t.item.summary.map((u,d)=>({...u,index:d})):void 0;s.reasoning={id:t.item.id,type:t.item.type,...l?{summary:l}:{}};let c=t.item.summary?.map(u=>u.text).filter(Boolean).join("");c&&e.push({type:"reasoning",reasoning:c})}else if(t.type==="response.reasoning_summary_part.added")s.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text,index:t.summary_index});else if(t.type==="response.reasoning_summary_text.delta")s.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta,index:t.summary_index});else return t.type==="response.image_generation_call.partial_image",null;return new di({text:e.map(l=>l.text).join(""),message:new On({id:a,content:e,tool_call_chunks:o,usage_metadata:r,additional_kwargs:s,response_metadata:i}),generationInfo:n})},y9e=t=>{let e=cr.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*n(){let r=Ab(()=>{try{let y=yI(t);return y==="system"||y==="developer"||y==="assistant"||y==="user"?y:"assistant"}catch{return"assistant"}}),o=y=>r==="assistant"?{type:"output_text",text:y,annotations:[]}:{type:"input_text",text:y},i,s=new Set,a=new Set,l=new Map,c=new Map;function*u(){if(!i)return;let y=i.content;(typeof y=="string"&&y.length>0||Array.isArray(y)&&y.length>0)&&(yield i),i=void 0}let d=(y,w)=>{i||(i={type:"message",role:r,content:[],...w?{phase:w}:{}}),typeof i.content=="string"?i.content=i.content.length>0?[o(i.content),...y]:[...y]:i.content.push(...y)},f=y=>{if(typeof y=="string")return y;try{return JSON.stringify(y??{})}catch{return"{}"}},p=y=>{let w=Ab(()=>{let _=y.metadata?.detail;return _==="low"||_==="high"||_==="auto"?_:"auto"});if(y.fileId)return{type:"input_image",detail:w,file_id:y.fileId};if(y.url)return{type:"input_image",detail:w,image_url:y.url};if(y.data){let _=typeof y.data=="string"?y.data:Buffer.from(y.data).toString("base64");return{type:"input_image",detail:w,image_url:`data:${y.mimeType??"image/png"};base64,${_}`}}},m=y=>{if(y.fileId){let w=aye(y);return{type:"input_file",file_id:y.fileId,...w?{filename:w}:{}}}if(y.url){let w=aye(y);return{...w?{filename:w}:{},type:"input_file",file_url:y.url}}if(y.data){let w=V1(y),_=typeof y.data=="string"?y.data:Buffer.from(y.data).toString("base64");return{type:"input_file",file_data:`data:${y.mimeType??"application/octet-stream"};base64,${_}`,filename:w}}},h=y=>{let w=Ab(()=>{if(Array.isArray(y.summary)){let S=y.summary?.map(I=>I?.text).filter(I=>typeof I=="string")??[];if(S.length>0)return S}return y.reasoning?[y.reasoning]:[]}),_=w.length>0?w.map(S=>({type:"summary_text",text:S})):[{type:"summary_text",text:""}];return{type:"reasoning",...y.id?{id:y.id}:{},summary:_}},g=y=>({type:"function_call",name:y.name??"",call_id:y.id??"",arguments:f(y.args)}),v=y=>{let w=f(y.output),_=y.status==="success"?"completed":y.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:y.toolCallId??"",output:w,..._?{status:_}:{}}};for(let y of t.contentBlocks)if(y.type==="text"){let w=Ab(()=>{if("extras"in y&&typeof y.extras=="object"&&y.extras!==null&&"phase"in y.extras)return y.extras.phase});d([o(y.text)],w)}else if(y.type!=="invalid_tool_call"){if(y.type==="reasoning")yield*u(),yield h(y);else if(y.type==="tool_call"){yield*u();let w=y.id??"";w&&(s.add(w),l.delete(w)),yield g(y)}else if(y.type==="tool_call_chunk"){if(y.id){let w=l.get(y.id)??{name:y.name,args:[]};y.name&&(w.name=y.name),y.args&&w.args.push(y.args),l.set(y.id,w)}}else if(y.type==="server_tool_call"){yield*u();let w=y.id??"";w&&(a.add(w),c.delete(w)),yield g(y)}else if(y.type==="server_tool_call_chunk"){if(y.id){let w=c.get(y.id)??{name:y.name,args:[]};y.name&&(w.name=y.name),y.args&&w.args.push(y.args),c.set(y.id,w)}}else if(y.type==="server_tool_call_result")yield*u(),yield v(y);else if(y.type!=="audio")if(y.type==="file"){let w=m(y);w&&d([w])}else if(y.type==="image"){let w=p(y);w&&d([w])}else if(y.type==="video"){let w=m(y);w&&d([w])}else y.type==="text-plain"?y.text&&d([o(y.text)]):y.type==="non_standard"&&e&&(yield*u(),yield y.value)}yield*u();for(let[y,w]of l){if(!y||s.has(y))continue;let _=w.args.join("");!w.name&&!_||(yield{type:"function_call",call_id:y,name:w.name??"",arguments:_})}for(let[y,w]of c){if(!y||a.has(y))continue;let _=w.args.join("");!w.name&&!_||(yield{type:"function_call",call_id:y,name:w.name??"",arguments:_})}}return Array.from(n())},KH=({messages:t,zdrEnabled:e,model:n})=>t.flatMap(r=>{let o=r.response_metadata;if(o?.output_version==="v1")return y9e(r);let i=r.additional_kwargs,s=yI(r);if(s==="system"&&gI(n)&&(s="developer"),s==="function")throw new Error("Function messages are not supported in Responses API");if(s==="tool"){let a=r;if(i?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof a.content=="string")return{type:"input_image",image_url:a.content};if(Array.isArray(a.content)){let c=a.content.find(f=>f.type==="input_image");if(c)return c;let u=a.content.find(f=>f.type==="computer_screenshot");if(u)return u;let d=a.content.find(f=>f.type==="image_url");if(d)return{type:"input_image",image_url:typeof d.image_url=="string"?d.image_url:d.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:a.tool_call_id};if(a.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:a.tool_call_id,output:a.content};let l=Array.isArray(a.content)&&a.content.every(c=>typeof c=="object"&&c!==null&&"type"in c&&(c.type==="input_file"||c.type==="input_image"||c.type==="input_text"));return{type:"function_call_output",call_id:a.tool_call_id,id:a.id?.startsWith("fc_")?a.id:void 0,output:l?a.content:typeof a.content!="string"?JSON.stringify(a.content):a.content}}if(s==="assistant"){if(!e&&o?.output!=null&&Array.isArray(o?.output)&&o?.output.length>0&&o?.output.every(h=>"type"in h))return o?.output;let a=[],l=i?.reasoning,c=!!l?.encrypted_content;if(l&&(!e||c)){let h=g9e(l);a.push(h)}let{content:u}=r;if(i?.refusal&&(typeof u=="string"&&(u=[{type:"output_text",text:u,annotations:[]}]),u=[...u,{type:"refusal",refusal:i.refusal}]),typeof u=="string"||u.length>0){let h={type:"message",role:"assistant",...r.id&&!e&&r.id.startsWith("msg_")?{id:r.id}:{},content:Ab(()=>typeof u=="string"?u:u.flatMap(g=>{if(g.type==="text"){let v=g;return{type:"output_text",text:v.text,annotations:(v.annotations??[]).map(wpr)}}return g.type==="output_text"||g.type==="refusal"?g:[]})),phase:Ab(()=>{if(Array.isArray(u))return u.find(g=>"phase"in g&&typeof g.phase=="string")?.phase})};a.push(h)}let d=i?.[WH],f=i?.[VH];cr.isInstance(r)&&r.tool_calls?.length?a.push(...r.tool_calls.map(h=>Nqt(h,f)?{type:"custom_tool_call",id:"call_id"in h&&typeof h.call_id=="string"?h.call_id:f?.[h.id??""]??"",call_id:h.id??"",input:h.args.input,name:h.name}:Oqt(h)?{type:"computer_call",id:h.call_id,call_id:h.id??"",action:h.args.action}:{type:"function_call",name:h.name,arguments:JSON.stringify(h.args),call_id:h.id,...e?{}:{id:d?.[h.id]}})):i?.tool_calls&&a.push(...i.tool_calls.map(h=>({type:"function_call",name:h.function.name,call_id:h.id,arguments:h.function.arguments,...e?{}:{id:d?.[h.id]}})));let p=o?.output?.length?o?.output:i.tool_outputs,m=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(p!=null){let h=p?.filter(g=>m.includes(g.type));h.length>0&&a.push(...h)}return a}if(s==="user"||s==="system"||s==="developer"){if(typeof r.content=="string")return{type:"message",role:s,content:r.content};let a=[],l=r.content.flatMap(c=>{if(c.type==="mcp_approval_response"&&a.push({type:"mcp_approval_response",approval_request_id:c.approval_request_id,approve:c.approve}),mf(c)){if(c.type==="file"){let u=aye(c);if(c.source_type==="url")return{type:"input_file",file_url:c.url,...u?{filename:u}:{}};if(c.source_type==="id")return{type:"input_file",file_id:c.id,...u?{filename:u}:{}};if(c.source_type==="base64")return{type:"input_file",file_data:`data:${c.mime_type??""};base64,${c.data}`,filename:V1(c)}}return qk(c,cX)}return c.type==="text"?{type:"input_text",text:c.text}:c.type==="image_url"?{type:"input_image",image_url:Ab(()=>{if(typeof c.image_url=="string")return c.image_url;if(typeof c.image_url=="object"&&c.image_url!==null&&"url"in c.image_url)return c.image_url.url}),detail:Ab(()=>{if(typeof c.image_url=="string")return"auto";if(typeof c.image_url=="object"&&c.image_url!==null&&"detail"in c.image_url)return c.image_url.detail})}:c.type==="input_text"||c.type==="input_image"||c.type==="input_file"?c:[]});return l.length>0&&a.push({type:"message",role:s,content:l}),a}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${s}`),[]})});async function*Aye(t,e={}){let n=e.streamUsage??!0,r=e.provider??"openai",o=new Map,i=new Map,s=0,a=!1,l,c,u,d,f=new Set,p=(g,v)=>{let y=i.get(g);if(y!==void 0)return{index:y,isNew:!1};let w=s++;return i.set(g,w),o.set(w,{...v}),{index:w,isNew:!0}},m=function*(){a||(a=!0,yield{event:"message-start",id:l})},h=function*(g){if(f.has(g))return;let v=o.get(g);v&&(f.add(g),yield{event:"content-block-finish",index:g,content:oI(v)})};for await(let g of t){if(g.type==="response.created"){l=g.response.id,yield*m(),yield{event:"provider",provider:r,name:"response.created",payload:{model:g.response.model,id:g.response.id}};continue}if(g.type==="response.output_text.delta"){yield*m();let{index:v,isNew:y}=p(`text:${g.output_index}:${g.content_index}`,{type:"text",text:""});y&&(yield{event:"content-block-start",index:v,content:{type:"text",text:""}});let w=o.get(v);w.text=(w.text??"")+g.delta,yield{event:"content-block-delta",index:v,delta:{type:"text-delta",text:g.delta}};continue}if(g.type==="response.reasoning_summary_text.delta"){yield*m();let{index:v,isNew:y}=p(`reasoning:${g.output_index}:${g.summary_index}`,{type:"reasoning",reasoning:""});y&&(yield{event:"content-block-start",index:v,content:{type:"reasoning",reasoning:""}});let w=o.get(v);w.reasoning=(w.reasoning??"")+g.delta,yield{event:"content-block-delta",index:v,delta:{type:"reasoning-delta",reasoning:g.delta}};continue}if(g.type==="response.output_item.added"&&(g.item.type==="function_call"||g.item.type==="custom_tool_call")){yield*m();let v=`tool:${g.output_index}`,y=g.item.type==="custom_tool_call",w=g.item.type==="function_call"?g.item.arguments??"":g.item.input??"",{index:_,isNew:S}=p(v,{type:"tool_call_chunk",id:g.item.call_id,name:g.item.name,args:w,index:g.output_index,...y?{isCustomTool:!0}:{}});if(S&&(yield{event:"content-block-start",index:_,content:{type:"tool_call_chunk",id:g.item.call_id,name:g.item.name,args:w,index:g.output_index}}),w){let I=o.get(_);yield{event:"content-block-delta",index:_,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...I.id!=null?{id:I.id}:{},...I.name!=null?{name:I.name}:{},args:I.args}}}}continue}if(g.type==="response.function_call_arguments.delta"||g.type==="response.custom_tool_call_input.delta"){yield*m();let{index:v,isNew:y}=p(`tool:${g.output_index}`,{type:"tool_call_chunk",args:"",index:g.output_index,...g.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});y&&(yield{event:"content-block-start",index:v,content:{type:"tool_call_chunk",args:"",index:g.output_index}});let w=o.get(v);w.args=(w.args??"")+g.delta,yield{event:"content-block-delta",index:v,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...w.id!=null?{id:w.id}:{},...w.name!=null?{name:w.name}:{},args:w.args}}};continue}if(g.type==="response.output_item.done"&&(g.item.type==="function_call"||g.item.type==="custom_tool_call")){yield*m();let v=`tool:${g.output_index}`,y=g.item.type==="function_call"?g.item.arguments??"":g.item.input??"",{index:w,isNew:_}=p(v,{type:"tool_call_chunk",id:g.item.call_id,name:g.item.name,args:y,index:g.output_index});if(_)yield{event:"content-block-start",index:w,content:{type:"tool_call_chunk",id:g.item.call_id,name:g.item.name,args:y,index:g.output_index}};else{let S=o.get(w);S.args=y,S.id=g.item.call_id,S.name=g.item.name}yield*h(w);continue}if(g.type==="response.completed"||g.type==="response.incomplete"){yield*m(),l=g.response.id,u=bpr(g.response.status,g.type),d={model_provider:r,id:g.response.id,model:g.response.model,status:g.response.status},n&&g.response.usage&&(c=qH(g.response.usage),yield{event:"usage",usage:c});continue}g.type!=="response.image_generation_call.partial_image"&&(yield*m(),yield{event:"provider",provider:r,name:g.type,payload:g})}a||(yield{event:"message-start"});for(let[g]of o)f.has(g)||(yield*h(g));yield{event:"message-finish",reason:u,...c?{usage:c}:{},...d?{responseMetadata:d}:{}}}function bpr(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var v9e=b(()=>{dX();o4()});var Eye,Mye=b(()=>{aE();FH();lX();dX();v9e();lg();Eye=class extends J1{constructor(t,e){super(BH(t,e))}invocationParams(t){let e;t?.strict!==void 0&&(e=t.strict),e===void 0&&this.supportsStrictToolCalling!==void 0&&(e=this.supportsStrictToolCalling);let n={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,stream:this.streaming,previous_response_id:t?.previous_response_id,truncation:t?.truncation,include:t?.include,tools:t?.tools?.length?this._reduceChatOpenAITools(t.tools,{stream:this.streaming,strict:e}):void 0,tool_choice:Aqt(t?.tool_choice)?t?.tool_choice:(()=>{let o=cye(t?.tool_choice);if(typeof o=="object"&&"type"in o){if(o.type==="function")return{type:"function",name:o.function.name};if(o.type==="allowed_tools")return{type:"allowed_tools",mode:o.allowed_tools.mode,tools:o.allowed_tools.tools};if(o.type==="custom")return{type:"custom",name:o.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let o=this._getResponseFormat(t?.response_format);return o?.type==="json_schema"?o.json_schema.schema!=null?{format:{type:"json_schema",schema:o.json_schema.schema,description:o.json_schema.description,name:o.json_schema.name,strict:o.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:o,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},r=this._getReasoningParams(t);return r!==void 0&&(n.reasoning=r),n}async _generate(t,e,n){e.signal?.throwIfAborted();let r=this.invocationParams(e);if(r.stream){let o=this._streamResponseChunks(t,e,n),i;for await(let s of o)s.message.response_metadata={...s.generationInfo,...s.message.response_metadata},i=i?.concat(s)??s;return{generations:i?[i]:[],llmOutput:{estimatedTokenUsage:i?.message?.usage_metadata}}}else{let o=await this.completionWithRetry({input:KH({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...r,stream:!1},{signal:e?.signal,maxRetries:e?.maxRetries,...e?.options});return{generations:[{text:o.output_text,message:uX(o)}],llmOutput:{id:o.id,estimatedTokenUsage:o.usage?{promptTokens:o.usage.input_tokens,completionTokens:o.usage.output_tokens,totalTokens:o.usage.total_tokens}:void 0}}}}async*_streamChatModelEvents(t,e,n){let r=await this.completionWithRetry({...this.invocationParams(e),input:KH({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),o=this.streamUsage??e.streamUsage;yield*Aye(async function*(s,a){for await(let l of s){if(a?.aborted)return;yield l}}(r,e.signal),{streamUsage:o??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,n){let r=await this.completionWithRetry({...this.invocationParams(e),input:KH({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);try{for await(let o of r){if(e.signal?.aborted)return;let i=Pye(o);i!=null&&(yield i,await n?.handleLLMNewToken(i.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:i}))}}catch(o){throw hg(o)}}async completionWithRetry(t,e){let{maxRetries:n,...r}=e??{},o=this._getClientOptions(r);return this.caller.callWithOptions({maxRetries:n},async()=>{try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,o):await this.client.responses.create(t,o)}catch(i){throw hg(i)}})}_reduceChatOpenAITools(t,e){let n=[];for(let r of t)if(DH(r))r.type==="image_generation"&&e?.stream&&(r.partial_images=1),n.push(r);else if(q1(r)){let o=r.metadata.customTool;n.push({type:"custom",name:o.name,description:o.description,format:o.format})}else if(Zx(r)){let o={};for(let[i,s]of Object.entries(r))i!=="type"&&i!=="function"&&(o[i]=s);n.push({type:"function",name:r.function.name,parameters:r.function.parameters,description:r.function.description,strict:e?.strict??null,...o})}else uye(r)&&n.push(Rqt(r));return n}}});var w9e=b(()=>{Tye();Mye()});var gg,b9e=b(()=>{FH();lE();lX();Iye();Mye();gg=class Z5t extends J1{constructor(n,r){let o=BH(n,r);super(o);M(this,"useResponsesApi",!1);M(this,"responses");M(this,"completions");M(this,"fields");this.fields=o,this.useResponsesApi=o?.useResponsesApi??!1,this.responses=o?.responses??new Eye(o),this.completions=o?.completions??new fE(o)}get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}_useResponsesApi(n){let r=n?.tools?.some(DH),o=n?.previous_response_id!=null||n?.text!=null||n?.truncation!=null||n?.include!=null||n?.reasoning?.summary!=null||this.reasoning?.summary!=null,i=n?.tools?.some(uye)||n?.tools?.some(q1);return this.useResponsesApi||r||o||i||xqt(this.model)}getLsParams(n){let r=this._combineCallOptions(n);return this._useResponsesApi(n)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(n){let r=this._combineCallOptions(n);return this._useResponsesApi(n)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(n,r,o){return this._useResponsesApi(r)?this.responses._generate(n,r,o):this.completions._generate(n,r,o)}async*_streamChatModelEvents(n,r,o){if(this._useResponsesApi(r)){yield*this.responses._streamChatModelEvents(n,this._combineCallOptions(r),o);return}yield*this.completions._streamChatModelEvents(n,this._combineCallOptions(r),o)}async*_streamResponseChunks(n,r,o){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(n,this._combineCallOptions(r),o);return}yield*this.completions._streamResponseChunks(n,this._combineCallOptions(r),o)}withConfig(n){let r=new Z5t(this.fields);return r.defaultOptions={...this.defaultOptions,...n},r}}});var Y5t=b(()=>{Tye();h9e();w9e();b9e()});var _9e=b(()=>{aE();cE();Pb();Sd();ys();lg();Pqe();CJ()});var J5t=b(()=>{cE();_9e();Pb();ys()});var vI,x9e=b(()=>{aE();cE();Pb();ys();CJ();SJ();vI=class extends BA{constructor(e){let n={maxConcurrency:2,...e};super(n);M(this,"model","text-embedding-ada-002");M(this,"modelName");M(this,"batchSize",512);M(this,"stripNewLines",!0);M(this,"dimensions");M(this,"timeout");M(this,"organization");M(this,"encodingFormat");M(this,"client");M(this,"clientConfig");M(this,"apiKey");let r=n?.apiKey??n?.openAIApiKey??Nn("OPENAI_API_KEY");this.organization=n?.configuration?.organization??Nn("OPENAI_ORGANIZATION"),this.model=n?.model??n?.modelName??this.model,this.modelName=this.model,this.batchSize=n?.batchSize??this.batchSize,this.stripNewLines=n?.stripNewLines??this.stripNewLines,this.timeout=n?.timeout,this.dimensions=n?.dimensions,this.encodingFormat=n?.encodingFormat,this.clientConfig={apiKey:r,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration}}async embedDocuments(e){let n=u1(this.stripNewLines?e.map(s=>s.replace(/\n/g," ")):e,this.batchSize),r=n.map(s=>{let a={model:this.model,input:s};return this.dimensions&&(a.dimensions=this.dimensions),this.encodingFormat&&(a.encoding_format=this.encodingFormat),this.embeddingWithRetry(a)}),o=await Promise.all(r),i=[];for(let s=0;s<o.length;s+=1){let a=n[s],{data:l}=o[s];for(let c=0;c<a.length;c+=1)i.push(l[c].embedding)}return i}async embedQuery(e){let n={model:this.model,input:this.stripNewLines?e.replace(/\n/g," "):e};this.dimensions&&(n.dimensions=this.dimensions),this.encodingFormat&&(n.encoding_format=this.encodingFormat);let{data:r}=await this.embeddingWithRetry(n);return r[0].embedding}async embeddingWithRetry(e){if(!this.client){let r=aS({baseURL:this.clientConfig.baseURL}),o={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};o.baseURL||delete o.baseURL,o.defaultHeaders=lS(o.defaultHeaders),this.client=new Rn(o)}let n={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(e,n)}catch(r){throw hg(r)}})}}});var S9e,X5t=b(()=>{aE();cE();x9e();Pb();ys();S9e=class extends vI{constructor(e){super(e);M(this,"azureOpenAIApiVersion");M(this,"azureOpenAIApiKey");M(this,"azureADTokenProvider");M(this,"azureOpenAIApiInstanceName");M(this,"azureOpenAIApiDeploymentName");M(this,"azureOpenAIBasePath");this.batchSize=e?.batchSize??1,this.azureOpenAIApiKey=e?.azureOpenAIApiKey??(typeof e?.apiKey=="string"?e?.apiKey:void 0)??Nn("AZURE_OPENAI_API_KEY"),this.azureOpenAIApiVersion=e?.azureOpenAIApiVersion??e?.openAIApiVersion??Nn("AZURE_OPENAI_API_VERSION"),this.azureOpenAIBasePath=e?.azureOpenAIBasePath??Nn("AZURE_OPENAI_BASE_PATH"),this.azureOpenAIApiInstanceName=e?.azureOpenAIApiInstanceName??Nn("AZURE_OPENAI_API_INSTANCE_NAME"),this.azureOpenAIApiDeploymentName=(e?.azureOpenAIApiEmbeddingsDeploymentName||e?.azureOpenAIApiDeploymentName)??(Nn("AZURE_OPENAI_API_EMBEDDINGS_DEPLOYMENT_NAME")||Nn("AZURE_OPENAI_API_DEPLOYMENT_NAME")),this.azureADTokenProvider=e?.azureADTokenProvider}async embeddingWithRetry(e){if(!this.client){let r={azureOpenAIApiDeploymentName:this.azureOpenAIApiDeploymentName,azureOpenAIApiInstanceName:this.azureOpenAIApiInstanceName,azureOpenAIApiKey:this.azureOpenAIApiKey,azureOpenAIBasePath:this.azureOpenAIBasePath,azureADTokenProvider:this.azureADTokenProvider,baseURL:this.clientConfig.baseURL},o=aS(r),{apiKey:i,...s}=this.clientConfig,a={...s,baseURL:o,timeout:this.timeout,maxRetries:0};this.azureADTokenProvider||(a.apiKey=r.azureOpenAIApiKey),a.baseURL||delete a.baseURL,a.defaultHeaders=lS(a.defaultHeaders,!0,"2.0.0"),this.client=new W1({apiVersion:this.azureOpenAIApiVersion,azureADTokenProvider:this.azureADTokenProvider,deployment:this.azureOpenAIApiDeploymentName,...a})}let n={};return this.azureOpenAIApiKey&&(n.headers={"api-key":this.azureOpenAIApiKey,...n.headers},n.query={"api-version":this.azureOpenAIApiVersion,...n.query}),this.caller.call(async()=>{try{return await this.client.embeddings.create(e,n)}catch(r){throw hg(r)}})}}});function cS(t,e){let n=fY(e.schema),r=_Y(e.schema);if(!e.schema||n||r)return new tKt({...e,description:e.description??e.schema?.description??`${e.name} tool`,func:async(s,a,l)=>new Promise((c,u)=>{let d=Ja(l,{callbacks:a?.getChild()});xd.runWithConfig($m(d),async()=>{try{c(t(s,d))}catch(f){u(f)}})})});let o=e.schema,i=e.description??e.schema.description??`${e.name} tool`;return new Cpr({...e,description:i,schema:o,func:async(s,a,l)=>new Promise((c,u)=>{let d,f=()=>{l?.signal&&d&&l.signal.removeEventListener("abort",d)};l?.signal&&(d=()=>{f(),u(MA(l.signal))},l.signal.addEventListener("abort",d,{once:!0}));let p=Ja(l,{callbacks:a?.getChild()});xd.runWithConfig($m(p),async()=>{try{let m=await t(s,p);if(D3e(m)){c(m);return}if(l?.signal?.aborted){f();return}f(),c(m)}catch(m){f(),u(m)}})})})}function kpr(t){return typeof t=="object"&&t!==null&&"type"in t}function Ipr(t){let{content:e,artifact:n,toolCallId:r,metadata:o}=t;return r&&!jWe(e)?typeof e=="string"||Array.isArray(e)&&e.every(kpr)?new ig({status:"success",content:e,artifact:n,tool_call_id:r,name:t.name,metadata:o}):new ig({status:"success",content:Tpr(e),artifact:n,tool_call_id:r,name:t.name,metadata:o}):e}function Tpr(t){try{return JSON.stringify(t)??""}catch{return`${t}`}}var Q5t,eKt,tKt,Cpr,bv=b(()=>{br();Vme();Sz();EA();XL();QL();qx();Qz();Px();tg();U3e();lg();V3e();Ox();$me();Eb();Q5t=class extends yge{constructor(e){super(e??{});M(this,"extras");M(this,"returnDirect",!1);M(this,"verboseParsingErrors",!1);M(this,"responseFormat","content");M(this,"defaultConfig");this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat,this.defaultConfig=e?.defaultConfig??this.defaultConfig,this.metadata=e?.metadata??this.metadata,this.extras=e?.extras??this.extras}get lc_namespace(){return["langchain","tools"]}async invoke(e,n){let r,o=wo(Xz(this.defaultConfig,n));return pA(e)?(r=e.args,o={...o,toolCall:e}):r=e,this.call(r,o)}async call(e,n,r){let o=pA(e)?e.args:e,i;if(ki(this.schema))try{i=await iL(this.schema,o)}catch(m){let h="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(h=`${h}
Details: ${m.message}`),sHe(m)&&(h=`${h}
${x.prettifyError(m)}`),new TY(h,JSON.stringify(e))}else{let m=ta(o,this.schema);if(!m.valid){let h="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(h=`${h}
Details: ${m.errors.map(g=>`${g.keywordLocation}: ${g.error}`).join(`
`)}`),new TY(h,JSON.stringify(e))}i=o}let s=JL(n),a=Ru.configure(s.callbacks,this.callbacks,s.tags||r,this.tags,s.metadata,this.metadata,{verbose:this.verbose}),l;pA(e)&&(l=e.id),!l&&PBt(s)&&(l=s.toolCall.id);let c=await a?.handleToolStart(this.toJSON(),typeof e=="string"?e:JSON.stringify(e),s.runId,void 0,void 0,void 0,s.runName,l);delete s.runId;let u;try{let m=await this._call(i,c,s);u=D3e(m)?await l6t(m,async h=>{try{await c?.handleToolEvent(h)}catch(g){await c?.handleToolError(g)}}):m}catch(m){throw await c?.handleToolError(m),m}let d,f;if(this.responseFormat==="content_and_artifact")if(Array.isArray(u)&&u.length===2)[d,f]=u;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
Result: ${JSON.stringify(u)}`);else d=u;let p=Ipr({content:d,artifact:f,toolCallId:l,name:this.name,metadata:this.metadata});return await c?.handleToolEnd(p),p}},eKt=class extends Q5t{constructor(e){super(e);M(this,"schema",Qh.object({input:Qh.string().optional()}).transform(e=>e.input))}call(e,n){let r=typeof e=="string"||e==null?{input:e}:e;return super.call(r,n)}},tKt=class extends eKt{constructor(e){super(e);M(this,"name");M(this,"description");M(this,"func");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}static lc_name(){return"DynamicTool"}async call(e,n){let r=JL(n);return r.runName===void 0&&(r.runName=this.name),super.call(e,r)}_call(e,n,r){return this.func(e,n,r)}},Cpr=class extends Q5t{constructor(e){super(e);M(this,"description");M(this,"func");M(this,"schema");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}static lc_name(){return"DynamicStructuredTool"}async call(e,n,r){let o=JL(n);return o.runName===void 0&&(o.runName=this.name),super.call(e,o,r)}_call(e,n,r){return this.func(e,n,r)}}});var C9e=b(()=>{Pb();ys();bv()});var nKt=b(()=>{});var rKt=b(()=>{});var oKt=b(()=>{});var iKt=b(()=>{});var sKt=b(()=>{});var Ppr,Apr,Epr,Mpr,Opr,Npr,Rpr,Lpr,$pr,Dpr,mGo,aKt=b(()=>{oi();bv();Eb();Ppr=x.object({type:x.literal("screenshot")}),Apr=x.object({type:x.literal("click"),x:x.number(),y:x.number(),button:x.enum(["left","right","wheel","back","forward"]).default("left")}),Epr=x.object({type:x.literal("double_click"),x:x.number(),y:x.number(),button:x.enum(["left","right","wheel","back","forward"]).default("left")}),Mpr=x.object({type:x.literal("drag"),path:x.array(x.object({x:x.number(),y:x.number()}))}),Opr=x.object({type:x.literal("keypress"),keys:x.array(x.string())}),Npr=x.object({type:x.literal("move"),x:x.number(),y:x.number()}),Rpr=x.object({type:x.literal("scroll"),x:x.number(),y:x.number(),scroll_x:x.number(),scroll_y:x.number()}),Lpr=x.object({type:x.literal("type"),text:x.string()}),$pr=x.object({type:x.literal("wait"),duration:x.number().optional()}),Dpr=x.union([Ppr,Apr,Epr,Mpr,Opr,Npr,Rpr,Lpr,$pr]),mGo=x.object({action:Dpr})});var Fpr,vGo,lKt=b(()=>{bv();Eb();Fpr=x.object({type:x.literal("exec"),command:x.array(x.string()),env:x.record(x.string(),x.string()).optional(),working_directory:x.string().optional(),timeout_ms:x.number().optional(),user:x.string().optional()}),vGo=x.union([Fpr])});var xGo,cKt=b(()=>{bv();Eb();xGo=x.object({commands:x.array(x.string()).describe("Array of shell commands to execute"),timeout_ms:x.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:x.number().optional().describe("Optional maximum number of characters to return from each command")})});var Upr,jpr,Bpr,IGo,uKt=b(()=>{bv();Eb();Upr=x.object({type:x.literal("create_file"),path:x.string(),diff:x.string()}),jpr=x.object({type:x.literal("update_file"),path:x.string(),diff:x.string()}),Bpr=x.object({type:x.literal("delete_file"),path:x.string()}),IGo=x.union([Upr,jpr,Bpr])});var dKt=b(()=>{});var fKt=b(()=>{C9e();nKt();rKt();oKt();iKt();sKt();aKt();lKt();cKt();uKt();dKt()});var pKt=b(()=>{LA();bv();QL()});var mKt=b(()=>{zH()});var hKt=b(()=>{zH();dX()});var wI=b(()=>{aE();lE();cE();lX();zH();m9e();Iye();h9e();dX();v9e();Mye();w9e();b9e();Y5t();_9e();J5t();x9e();X5t();C9e();fKt();pKt();mKt();hKt();Pb()});var Oye,gKt=b(()=>{ut();SJ();CJ();ys();Oye=class extends BA{constructor(n){let r={maxConcurrency:2,...n};super(r);this.model="jina-clip-v2";this.batchSize=24;this.baseUrl="https://api.jina.ai/v1/embeddings";this.stripNewLines=!0;this.dimensions=1024;this.normalized=!0;this.headers={};let o=r?.apiKey||Nn("JINA_API_KEY")||Nn("JINA_AUTH_TOKEN");if(!o)throw new Error("Jina API key not found");this.apiKey=o,this.model=r?.model??r?.modelName??this.model,this.baseUrl=r?.baseUrl??this.baseUrl,this.dimensions=r?.dimensions??this.dimensions,this.batchSize=r?.batchSize??this.batchSize,this.stripNewLines=r?.stripNewLines??this.stripNewLines,this.normalized=r?.normalized??this.normalized,this.headers=r?.headers??this.headers}async embedDocuments(n){let r=u1(this.doStripNewLines(n),this.batchSize),o=r.map(a=>{let l=this.getParams(a);return this.embeddingWithRetry(l)}),i=await Promise.all(o),s=[];for(let a=0;a<i.length;a+=1){let l=r[a],c=i[a]||[];for(let u=0;u<l.length;u+=1)s.push(c[u])}return s}async embedQuery(n){let r=this.getParams(this.doStripNewLines([n]),!0);return(await this.embeddingWithRetry(r)||[[]])[0]}doStripNewLines(n){return this.stripNewLines?n.map(r=>typeof r=="string"?r.replace(/\n/g," "):r.text?{text:r.text.replace(/\n/g," ")}:r):n}getParams(n,r){return{model:this.model,input:n,dimensions:this.dimensions,task:r?"retrieval.query":"retrieval.passage",normalized:this.normalized}}async embeddingWithRetry(n){let o=await(await bh(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.headers},body:JSON.stringify(n)})).json();if("detail"in o&&o.detail)throw new Error(`${o.detail}`);return o.data.map(({embedding:i})=>i)}}});var Q1,yKt=b(()=>{ut();wI();Q1=class extends vI{constructor(e){super(e),this.customConfig=e}async embedQuery(e){return(await this.callEmbeddingAPI([e]))[0]}async embedDocuments(e){return await this.callEmbeddingAPI(e)}async callEmbeddingAPI(e){let n={model:this.customConfig.modelName,input:e,encoding_format:"float"},r=this.customConfig.configuration,i=`${r?.baseURL||"https://api.openai.com/v1"}/embeddings`,s=this.customConfig.apiKey,l=await(r?.fetch||bh)(i,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json",...this.customConfig.headers||{}},body:JSON.stringify(n)});if(!l.ok){let u=await l.text();throw new Error(`Embedding API request failed: ${l.status} ${l.statusText} - ${u}`)}let c=await l.json();if(!c.data||!Array.isArray(c.data))throw new Error("Invalid API response format: missing or invalid data array");return c.data.map(u=>{if(!u.embedding||!Array.isArray(u.embedding))throw new Error("Invalid API response format: missing or invalid embedding array");return u.embedding})}}});var Nye,Hpr,Gc,GH=b(()=>{gt();iy();pe();Se();ut();mqe();Aqe();wI();Nye=require("obsidian");_v();gKt();yKt();Hpr={"copilot-plus":Q1,"copilot-plus-jina":Oye,openai:vI,cohereai:vI,google:pqe,"azure openai":S9e,ollama:Tqe,"lm-studio":Q1,"3rd party (openai-format)":vI,siliconflow:Q1,openrouterai:Q1},Gc=class t{constructor(){this.providerApiKeyMap={"copilot-plus":()=>Y().plusLicenseKey,"copilot-plus-jina":()=>Y().plusLicenseKey,openai:()=>Y().openAIApiKey,cohereai:()=>Y().cohereApiKey,google:()=>Y().googleApiKey,"azure openai":()=>Y().azureOpenAIApiKey,ollama:()=>"default-key","lm-studio":()=>"default-key","3rd party (openai-format)":()=>"default-key",siliconflow:()=>Y().siliconflowApiKey,openrouterai:()=>Y().openRouterAiApiKey};this.initialize(),zr(()=>this.initialize())}initialize(){let e=Y().activeEmbeddingModels;this.activeEmbeddingModels=e,this.buildModelMap(e)}static getInstance(){return t.instance||(t.instance=new t),t.instance}getProviderConstructor(e){let n=Hpr[e.provider];if(!n)throw W(`Unknown provider: ${e.provider} for model: ${e.name}`),new Error(`Unknown provider: ${e.provider} for model: ${e.name}`);return n}buildModelMap(e){t.modelMap={};let n=t.modelMap;e.forEach(r=>{if(r.enabled){if(!Object.values(UO).contains(r.provider)){W(`Unknown provider: ${r.provider} for embedding model: ${r.name}`);return}let o=this.getProviderConstructor(r),i=r.apiKey||this.providerApiKeyMap[r.provider](),s=Jn(r);n[s]={hasApiKey:!!i,EmbeddingConstructor:o,vendor:r.provider}}})}static getModelName(e){let n=e;if(n.model)return n.model;if(n.modelName)return n.modelName;throw new Error(`Embeddings instance missing model or modelName properties: ${JSON.stringify(e)}`)}getCustomModel(e){return this.activeEmbeddingModels.filter(n=>{let r=Jn(n);return e===r})[0]}async getEmbeddingsAPI(){let n=Y().embeddingModelKey;if(!Object.prototype.hasOwnProperty.call(t.modelMap,n))throw new Nr(`No embedding model found for: ${n}`);let r=this.getCustomModel(n);if(r.plusExclusive&&!Y().isPaidUser)throw new Nye.Notice("Plus-only model, please consider upgrading to Plus to access it."),new Nr("Plus-only model selected but user is not on Plus plan");if(r.believerExclusive){let a=await Gi.getInstance().validateLicenseKey(void 0,{trigger:"model_gate"});if(!a.plan||a.plan.toLowerCase()!=="believer")throw new Nye.Notice("Believer-only model, please consider upgrading to Believer to access it."),new Nr("Believer-only model selected but user is not on Believer plan")}let o=t.modelMap[n];if(!o.hasApiKey)throw new Nr(`API key is not provided for the embedding model: ${n}`);let i=await this.getEmbeddingConfig(r);try{return t.embeddingModel=new o.EmbeddingConstructor(i),t.embeddingModel}catch(s){let a=s instanceof Error?s.message:String(s);throw new Nr(`Error creating embedding model: ${n}. ${a}`)}}async getEmbeddingConfig(e){let n=Y(),r=e.name,o={maxRetries:3,maxConcurrency:3},s={"copilot-plus":{modelName:r,apiKey:n.plusLicenseKey,headers:Gi.getInstance().getPluginVersionHeaders(),timeout:1e4,batchSize:Y().embeddingBatchSize,configuration:{baseURL:Jp,fetch:e.enableCors?ks:void 0}},"copilot-plus-jina":{model:r,apiKey:n.plusLicenseKey,headers:Gi.getInstance().getPluginVersionHeaders(),timeout:1e4,batchSize:Y().embeddingBatchSize,dimensions:e.dimensions,baseUrl:Jp+"/embeddings",configuration:{fetch:e.enableCors?ks:void 0}},openai:{modelName:r,apiKey:e.apiKey||n.openAIApiKey,timeout:1e4,batchSize:Y().embeddingBatchSize,configuration:{baseURL:e.baseUrl,fetch:e.enableCors?ks:void 0}},cohereai:{modelName:r,apiKey:e.apiKey||n.cohereApiKey,timeout:1e4,batchSize:Y().embeddingBatchSize,configuration:{baseURL:e.baseUrl||Qp.cohereai.host,fetch:e.enableCors?ks:void 0}},google:{modelName:r,apiKey:n.googleApiKey},"azure openai":{modelName:r,azureOpenAIApiKey:e.apiKey||n.azureOpenAIApiKey,azureOpenAIApiInstanceName:e.azureOpenAIApiInstanceName||n.azureOpenAIApiInstanceName,azureOpenAIApiDeploymentName:e.azureOpenAIApiEmbeddingDeploymentName||n.azureOpenAIApiEmbeddingDeploymentName,azureOpenAIApiVersion:e.azureOpenAIApiVersion||n.azureOpenAIApiVersion},ollama:{baseUrl:e.baseUrl||"http://localhost:11434",model:r,truncate:!0,headers:{Authorization:`Bearer ${e.apiKey||"default-key"}`}},"lm-studio":{modelName:r,openAIApiKey:e.apiKey||"default-key",configuration:{baseURL:e.baseUrl||"http://localhost:1234/v1",fetch:e.enableCors?ks:void 0}},"3rd party (openai-format)":{modelName:r,openAIApiKey:e.apiKey||"",batchSize:Y().embeddingBatchSize,configuration:{baseURL:e.baseUrl,fetch:e.enableCors?ks:void 0,dangerouslyAllowBrowser:!0}},siliconflow:{modelName:r,apiKey:e.apiKey||n.siliconflowApiKey,batchSize:Y().embeddingBatchSize,configuration:{baseURL:e.baseUrl||Qp.siliconflow.host,fetch:e.enableCors?ks:void 0}},openrouterai:{modelName:r,apiKey:e.apiKey||n.openRouterAiApiKey,batchSize:Y().embeddingBatchSize,configuration:{baseURL:e.baseUrl||"https://openrouter.ai/api/v1",fetch:e.enableCors?ks:void 0}}}[e.provider]||{};return{...o,...s}}async ping(e){let n=async r=>{let o={...e,enableCors:r},i=await this.getEmbeddingConfig(o);await new(this.getProviderConstructor(o))(i).embedQuery("test")};try{return await n(!1),!0}catch(r){j("First ping attempt failed, trying with CORS...");try{return await n(!0),new Nye.Notice("Connection successful, but requires CORS to be enabled. Please enable CORS for this model once you add it above."),!0}catch(o){let i=`
without CORS Error: `+kt(r)+`
with CORS Error: `+kt(o);throw new Error(i)}}}}});var bKt={};sr(bKt,{categorizePatterns:()=>bI,createCopilotPatternFilter:()=>pX,createPatternSettingsValue:()=>pE,extractAppIgnoreSettings:()=>e$,getAllQAMarkdownContent:()=>T9e,getDecodedPatterns:()=>yg,getExtensionPattern:()=>Jpr,getFilePattern:()=>YH,getMatchingPatterns:()=>Fi,getPropertyPattern:()=>A9e,getSystemExcludedFolders:()=>vg,getTagPattern:()=>P9e,getVectorLength:()=>I9e,isInternalExcludedFile:()=>mX,isInternalExcludedPath:()=>t$,isSystemExcludedPath:()=>ZH,matchSystemRoots:()=>fX,parsePropertyPattern:()=>Rye,previewPatternValue:()=>qpr,shouldIndexFile:()=>ii});async function I9e(t){if(!t)throw new Nr("Embedding instance not found.");try{let n=await t.embedQuery("Sample text for embedding");if(!n||n.length===0)throw new Nr("Failed to get valid embedding vector length");return j(`Detected vector length: ${n.length} for model: ${Gc.getModelName(t)}`),n.length}catch(e){throw H("Error getting vector length:",e),new Nr("Failed to determine embedding vector length. Please check your Copilot settings to make sure you have a working embedding model.")}}async function T9e(t){let e="",{inclusions:n,exclusions:r}=Fi(),o=t.vault.getMarkdownFiles().filter(i=>ii(t,i,n,r));return await Promise.all(o.map(i=>t.vault.cachedRead(i))).then(i=>i.map(s=>e+=s+" ")),e}function yg(t){let e=[];return e.push(...t.split(",").map(n=>{let r=n.trim();try{return decodeURIComponent(r)}catch{return r}}).filter(n=>n.length>0)),e}function Wpr(){return Y().qaExclusions?yg(Y().qaExclusions):[]}function Vpr(){return Y().qaInclusions?yg(Y().qaInclusions):[]}function Fi(t){let e=t?.inclusions?yg(t.inclusions):t?.isProject?[]:Vpr(),n=t?.exclusions?yg(t.exclusions):t?.isProject?[]:Wpr();return{inclusions:e.length>0?bI(e):null,exclusions:n.length>0?bI(n):null}}function vg(t){let e=Array.isArray(t.copilotRootHistory)?t.copilotRootHistory:[];return _C([R_,t.copilotFolder,...e])}function ZH(t){return fX(t,vg(Y()))}function fX(t,e){return dz()?k9e(t.toLowerCase(),e.map(n=>n.toLowerCase())):k9e(t,e)}function ii(t,e,n,r,o){return!(mX(e)||ZH(e.path)||r&&vKt(t,e,r)||n&&!vKt(t,e,n)||o&&!n)}function pX(t){let e=vg(Y()),{inclusions:n,exclusions:r}=Fi();return o=>{if(fX(o,e)||t$(o))return!1;if(!n&&!r)return!0;let i=t.vault.getAbstractFileByPath(o);return i instanceof wKt.TFile?ii(t,i,n,r):!0}}function bI(t){let e=[],n=[],r=[],o=[],i=[],s=/^#[^\s#]+$/,a=/^\*\.([a-zA-Z0-9.]+)$/,l=/^\[\[(.*?)\]\]$/,c=/^\[([^[\]:]+):(.*)\]$/;return t.forEach(u=>{s.test(u)?e.push(u):a.test(u)?n.push(u):l.test(u)?o.push(u):c.test(u)?i.push(u):r.push(u)}),{tagPatterns:e,extensionPatterns:n,folderPatterns:r,notePatterns:o,propertyPatterns:i}}function Rye(t){let e=t.match(/^\[([^[\]:]+):(.*)\]$/);return e?{key:e[1].trim(),value:e[2].trim()}:null}function qpr(t){return yg(t).join(", ")}function pE({tagPatterns:t,extensionPatterns:e,folderPatterns:n,notePatterns:r,propertyPatterns:o}){return[...t??[],...e??[],...r??[],...o??[],...n??[]].map(s=>encodeURIComponent(s)).join(",")}function Kpr(t,e,n){if(n.length===0)return!1;let r=F_(t,e);return n.some(o=>r.some(i=>i.toLowerCase()===C2(o).toLowerCase()))}function Gpr(t,e,n){return n.length===0?!1:n.some(r=>{let o=Rye(r);if(!o)return!1;if(o.value==="")return jdt(t,e,o.key);let i=Oie(t,e,o.key),s=o.value.toLowerCase();return i.some(a=>a.trim().toLowerCase()===s)})}function Zpr(t,e){if(e.length===0)return!1;let n=t.toLowerCase();return e.some(r=>{let o=r.slice(1).toLowerCase();return n.endsWith(o)})}function k9e(t,e){if(e.length===0)return!1;let n=t.replace(/\\/g,"/");return e.some(r=>{let o=r.replace(/\\/g,"/").replace(/\/$/,"");return n.startsWith(o)&&(n.length===o.length||n[o.length]==="/")})}function Ypr(t,e){return e.length===0?!1:e.some(n=>n.slice(2,-2)===t.basename)}function vKt(t,e,n){if(!n)return!1;let{tagPatterns:r,extensionPatterns:o,folderPatterns:i,notePatterns:s,propertyPatterns:a}=n;return Kpr(t,e,r??[])||Zpr(e.path,o??[])||k9e(e.path,i??[])||Ypr(e,s??[])||Gpr(t,e,a??[])}function e$(t){let e=[];try{let n=t.vault;if(typeof n.getConfig=="function"){let r=n.getConfig("userIgnoreFilters");r&&Array.isArray(r)&&r.forEach(o=>{typeof o=="string"&&e.push(o.endsWith("/")?o.slice(0,-1):o)})}}catch(n){W("Error getting userIgnoreFilters from Obsidian config",n)}return e}function P9e(t){return`#${t}`}function A9e(t,e){return e?`[${t}:${e}]`:`[${t}:]`}function YH(t){return`[[${t.basename}]]`}function Jpr(t){return`*.${t}`}function Xpr(){return[$l.getLogPath(),df,fz]}function Qpr(){let t=Vie().trim();return t?[`${t.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/+$/,"")}/`]:[]}function t$(t){let e=dz()?s=>s.toLowerCase():s=>s,n=e(t);if(new Set(Xpr().map(e)).has(n))return!0;let o=Qpr();if(o.length===0)return!1;let i=[Xh,df,fz].map(e);for(let s of o.map(e)){if(!n.startsWith(s))continue;let a=n.slice(s.length),l=a.split("/");if(l.length===2&&i.includes(l[1])||a.startsWith("unsupported/")||a==="unsupported")return!0}return!1}function mX(t){return t$(t.path)}var wKt,ha=b(()=>{gt();iy();db();sA();GH();pe();Se();Is();nN();ut();Jh();wKt=require("obsidian")});function emr(){let t=window.crypto;if(typeof t?.randomUUID=="function")return t.randomUUID();if(typeof t?.getRandomValues=="function"){let e=new Uint8Array(16);return t.getRandomValues(e),Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}return`${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}function wg(t){if(n$)return n$;try{let e=t.loadLocalStorage(hX);if(typeof e=="string"&&e.length>0)return n$=e,e;let n=window.localStorage.getItem(hX);if(n&&n.length>0)return t.saveLocalStorage(hX,n),n$=n,n;let r=emr();return t.saveLocalStorage(hX,r),t.loadLocalStorage(hX)!==r?(n$=Lye,Lye):(n$=r,r)}catch{return n$=Lye,Lye}}var hX,Lye,n$,gX=b(()=>{hX="obsidian-copilot:device-id:v1",Lye="unknown",n$=null});function r$(t){if(!t.trim())return!0;try{let e=new URL(t).hostname.replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="::1"||/^127(?:\.\d{1,3}){3}$/.test(e)}catch{return!1}}function vX(t,e=nmr){let{extensionPatterns:n,folderPatterns:r}=t.trim()?bI(yg(t)):{extensionPatterns:[],folderPatterns:[]},o=s=>s.replace(/\\/g,"/").replace(/\/+$/,""),i=[...new Set([...r,...e].map(o).filter(s=>s.length>0&&s!=="."&&s!==".."))];return i.length===0&&n.length===0?tmr:{...i.length>0?{exclude_folders:i}:{},...n.length>0?{exclude_patterns:n.map(s=>`**/${s}`)}:{}}}function $ye(t){if(!t.trim())return E9e;let{tagPatterns:e,notePatterns:n,propertyPatterns:r,extensionPatterns:o,folderPatterns:i}=bI(yg(t));if(e.length>0||n.length>0||r.length>0)return E9e;let s=i.map(l=>l.replace(/\\/g,"/").replace(/\/+$/,"")).filter(l=>l.length>0&&l!=="."&&l!==".."),a=o.map(l=>l.replace(/^\*\./,""));return s.length===0&&a.length===0?E9e:{...s.length>0?{include_folders:s}:{},...a.length>0?{include_extensions:a}:{}}}function M9e(t){return t.replace(/\\/g,"/").replace(/\/+$/,"")}function Bu(t=Y()){return lz(t)?"miyo":"keyword"}function CKt(t=Y()){return t.enableSelfHostMode&&t.enableMiyo?"miyo":"plus"}async function O9e(t=Y()){if(t.docProcessorBackend!=="miyo")return"plus";if(!lz(t))return"miyo-unavailable";let e=lY().documentProcessor;return(e==="unknown"||e==="stale")&&await ume(),AUt("documentProcessor")?"miyo":"miyo-unavailable"}function Mp(t){return t.vault.getName()}function Dye(t,e){let n=M9e(e).replace(/^\/+/,""),r=Mp(t);return r?`${r}/${n}`:n}function o$(t,e){let n=M9e(e),r=Mp(t);if(!r)return n;let o=`${r}/`;return n.startsWith(o)?n.slice(o.length):n}function kKt(t,e){let n=Mp(t);return n?M9e(e).startsWith(`${n}/`):!0}function JH(t,e){return JSON.stringify({device:wg(t),url:Ci(e),folder:Mp(t),roots:[...vg(e)].sort()})}function Fye(t){if(typeof t!="string"||t.length===0)return null;try{let e=JSON.parse(t);return typeof e.device!="string"||typeof e.url!="string"||typeof e.folder!="string"||!Array.isArray(e.roots)?null:e}catch{return null}}function N9e(t,e){try{return(typeof e.miyoSyncedExclusions=="string"?e.miyoSyncedExclusions:"")!==JH(t,e)}catch{return!0}}function XH(t,e){let n=typeof e.miyoSyncedExclusions=="string"?e.miyoSyncedExclusions:"";return N9e(t,e)&&(e.enableMiyo===!0||n!=="")}function IKt(t){let e=Fye(t.miyoSyncedExclusions);if(!e)return!1;let n=[...vg(t)].sort();return JSON.stringify(e.roots)!==JSON.stringify(n)}function TKt(t){if((t.qaInclusions||"").trim().length>0)return!0;let e=(t.qaExclusions||"").trim();if(e.length===0)return!1;let n=new Set(vg(t));return yg(e).some(r=>!n.has(r.replace(/\/+$/,"")))}var yX,_Kt,xKt,SKt,tmr,nmr,E9e,zu=b(()=>{dme();ime();ha();Se();gX();ime();yX="miyo://",_Kt=`${yX}add-folder`,xKt=`${yX}connect`,SKt=`${yX}chats`;tmr=Object.freeze({}),nmr=Object.freeze([]);E9e=Object.freeze({})});var PKt,QH,eW,Uye,i$=b(()=>{PKt="https://api.symposium.md",QH="SYMPOSIUM_WORKSPACE_ROOT",eW=".symposium/handoffs",Uye=/^[0123456789abcdefghjkmnpqrstvwxyz]{16}$/});var mE,jye,rmr,omr,imr,smr,amr,lmr,cmr,umr,dmr,fmr,pmr,Bye,mmr,hmr,gmr,ymr,AKt,EKt=b(()=>{mE="a1dc48e68138490d522c04cbf5822214c6eb1202",jye=["claude","codex","opencode"],rmr=String.raw`MIT License
Copyright (c) 2026 Steph Ango (@kepano)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
`,omr=String.raw`---
name: obsidian-markdown
description: Create and edit Obsidian-specific Markdown syntax, including wikilinks, embeds, block references, callouts, properties, tags, and comments. Use for Obsidian notes when these extensions matter; ordinary Markdown is assumed knowledge.
license: MIT
metadata:
copilot-enabled-agents: claude, codex, opencode
copilot-builtin-version: "${1}"
copilot-upstream-revision: "${mE}"
---
# Obsidian Markdown
Use Obsidian-specific syntax accurately. Do not spend tokens explaining ordinary
CommonMark or GFM unless the user asks.
## Workflow
1. Preserve existing frontmatter keys and formatting when editing a note.
2. Use wikilinks for vault notes and Markdown links for external URLs.
3. Use embeds, callouts, properties, tags, comments, and block references only
when they improve the requested note.
4. Check link targets, YAML validity, and block IDs after editing.
5. Read the focused reference file when the task needs more syntax detail.
## Wikilinks and block references
~~~markdown
[[Note Name]]
[[Note Name|Display Text]]
[[Note Name#Heading]]
[[Note Name#^block-id]]
[[#Heading in this note]]
This paragraph is addressable. ^block-id
~~~
Put a block ID on its own line after a list or quote block.
## Embeds
Prefix a wikilink with <code>!</code>:
~~~markdown
![[Note Name]]
![[Note Name#Heading]]
![[image.png|300]]
![[document.pdf#page=3]]
~~~
See [Embeds](references/EMBEDS.md) for media, PDF, and query forms.
## Callouts
~~~markdown
> [!warning] Custom title
> Important content.
> [!faq]- Collapsed by default
> Foldable content.
~~~
See [Callouts](references/CALLOUTS.md) for types, aliases, folding, and nesting.
## Properties, tags, and comments
~~~yaml
---
title: My Note
date: 2026-07-21
tags:
- project
aliases:
- Alternate Name
related: "[[Other Note]]"
---
~~~
Quote wikilinks used as YAML values. See
[Properties](references/PROPERTIES.md) for supported property types and tag rules.
Use <code>#nested/tag</code> for inline tags. Hide content from reading view with
<code>%%inline comments%%</code> or a matching pair of <code>%%</code> markers on
separate lines.
## Attribution
Adapted from <code>kepano/obsidian-skills</code> at revision
<code>${mE}</code>. See <code>LICENSE</code>.
`,imr=String.raw`# Callouts reference
## Folding and nesting
~~~markdown
> [!faq]- Collapsed by default
> Hidden until expanded.
> [!faq]+ Expanded by default
> Visible but collapsible.
> [!question] Outer
> > [!note] Inner
> > Nested content.
~~~
## Built-in types
| Type | Aliases |
| --- | --- |
| note | — |
| abstract | summary, tldr |
| info | — |
| todo | — |
| tip | hint, important |
| success | check, done |
| question | help, faq |
| warning | caution, attention |
| failure | fail, missing |
| danger | error |
| bug | — |
| example | — |
| quote | cite |
`,smr=String.raw`# Embeds reference
~~~markdown
![[Note Name]]
![[Note Name#Heading]]
![[Note Name#^block-id]]
![[image.png]]
![[image.png|640x480]]
![[image.png|300]]
![[audio.mp3]]
![[video.mp4]]
![[document.pdf]]
![[document.pdf#page=3]]
![[document.pdf#height=400]]
~~~
A list embed needs a block ID after the list. An embedded search uses an
Obsidian query block:
~~~~markdown
~~~query
tag:#project status:done
~~~
~~~~
`,amr=String.raw`# Properties reference
Properties are YAML frontmatter at the very start of a note.
| Property type | Example |
| --- | --- |
| Text | <code>title: My title</code> |
| Number | <code>rating: 4.5</code> |
| Checkbox | <code>completed: true</code> |
| Date | <code>date: 2026-07-21</code> |
| Date and time | <code>due: 2026-07-21T14:30:00</code> |
| List | <code>tags: [one, two]</code> or a YAML list |
| Link | <code>related: "[[Other Note]]"</code> |
Obsidian reserves <code>tags</code>, <code>aliases</code>, and
<code>cssclasses</code> for their built-in behaviors. Tags may contain letters,
numbers (not as the first character), underscores, hyphens, and forward slashes.
Prefer YAML lists when a property naturally has multiple values.
`,lmr=String.raw`---
name: obsidian-bases
description: Create and edit Obsidian Bases (.base files) with valid YAML schemas, filters, formulas, properties, summaries, and views. Use for database-like Obsidian views or when the user mentions Bases, .base files, table/card/list views, filters, formulas, or summaries.
license: MIT
metadata:
copilot-enabled-agents: claude, codex, opencode
copilot-builtin-version: "${1}"
copilot-upstream-revision: "${mE}"
---
# Obsidian Bases
## Workflow
1. Read the existing <code>.base</code> file before editing it.
2. Define global scope with <code>filters</code>.
3. Add computed values under <code>formulas</code> only when needed.
4. Configure property display names and one or more views.
5. Validate YAML, formula references, quoting, and date/duration operations.
6. Open or query the Base in Obsidian when the CLI is available.
## Schema
~~~yaml
filters:
and:
- 'file.ext == "md"'
- 'status != "archived"'
formulas:
days_until_due: 'if(due, (date(due) - today()).days, "")'
properties:
status:
displayName: Status
formula.days_until_due:
displayName: "Days Until Due"
summaries:
mean_rounded: 'values.mean().round(2)'
views:
- type: table
name: Active
limit: 50
filters:
and:
- 'status != "done"'
order:
- file.name
- status
- formula.days_until_due
groupBy:
property: status
direction: ASC
summaries:
formula.days_until_due: Average
~~~
Views may be <code>table</code>, <code>cards</code>, or <code>list</code>.
A <code>map</code> view depends on compatible map support.
## Filters and properties
Filters may be a single expression or recursively nested <code>and</code>,
<code>or</code>, and <code>not</code> objects. Property namespaces are:
- note properties: <code>status</code> or <code>note.status</code>
- file metadata: <code>file.name</code>, <code>file.path</code>,
<code>file.folder</code>, <code>file.ctime</code>, <code>file.mtime</code>,
<code>file.tags</code>, <code>file.links</code>, and
<code>file.backlinks</code>
- formulas: <code>formula.days_until_due</code>
Use <code>file.hasTag()</code>, <code>file.hasLink()</code>,
<code>file.hasProperty()</code>, and <code>file.inFolder()</code> for indexed
file relationships. The <code>this</code> value refers to the Base itself, the
embedding note, or the active file depending on where the Base is rendered.
## Formula rules
- Guard optional properties with <code>if()</code>.
- Date subtraction returns a Duration, not a number. Access
<code>.days</code>, <code>.hours</code>, or another numeric field before
calling number methods such as <code>.round()</code>.
- Every <code>formula.X</code> used by a view or property configuration must
have a matching <code>X</code> entry under <code>formulas</code>.
- Wrap formulas containing double quotes in YAML single quotes.
- Quote YAML strings containing special characters, especially colons and
leading punctuation.
Read [Functions reference](references/FUNCTIONS_REFERENCE.md) for function and
type-specific operations, and [Examples](references/EXAMPLES.md) for complete
task-tracker and daily-notes Bases.
## Validation checklist
- The document parses as YAML and has a <code>views</code> list.
- View <code>order</code>, <code>groupBy</code>, and summaries reference defined
note, file, or formula properties.
- Formula quoting is balanced and duration math accesses a numeric field.
- Embedded view names match exactly: <code>![[My Base.base#View Name]]</code>.
## Attribution
Adapted from <code>kepano/obsidian-skills</code> at revision
<code>${mE}</code>. See <code>LICENSE</code>.
`,cmr=String.raw`# Bases functions reference
## Global functions
| Function | Purpose |
| --- | --- |
| <code>date(value)</code> | Parse a date string |
| <code>duration(value)</code> | Parse a duration string |
| <code>now()</code> / <code>today()</code> | Current date-time / date |
| <code>if(condition, yes, no?)</code> | Conditional value |
| <code>number(value)</code> | Convert to number |
| <code>link(path, display?)</code> | Create a link |
| <code>file(path)</code> | Resolve a file object |
| <code>list(value)</code> | Normalize a value to a list |
| <code>image(path)</code> / <code>icon(name)</code> | Create renderable values |
## Common methods
- String: <code>contains</code>, <code>startsWith</code>, <code>endsWith</code>,
<code>lower</code>, <code>trim</code>, <code>replace</code>,
<code>split</code>, <code>isEmpty</code>.
- Number: <code>abs</code>, <code>ceil</code>, <code>floor</code>,
<code>round</code>, <code>toFixed</code>.
- List: <code>contains</code>, <code>containsAll</code>,
<code>containsAny</code>, <code>filter</code>, <code>map</code>,
<code>reduce</code>, <code>flat</code>, <code>join</code>,
<code>sort</code>, <code>unique</code>.
- File: <code>asLink</code>, <code>hasLink</code>, <code>hasTag</code>,
<code>hasProperty</code>, <code>inFolder</code>.
- Link: <code>asFile</code>, <code>linksTo</code>.
- Object: <code>keys</code>, <code>values</code>, <code>isEmpty</code>.
- Regular expression: <code>matches</code>.
Date fields include <code>year</code>, <code>month</code>, <code>day</code>,
<code>hour</code>, <code>minute</code>, and <code>second</code>. Date methods
include <code>date()</code>, <code>format()</code>, <code>time()</code>, and
<code>relative()</code>.
Duration fields are <code>days</code>, <code>hours</code>,
<code>minutes</code>, <code>seconds</code>, and <code>milliseconds</code>.
Duration does not directly support number rounding methods.
`,umr=String.raw`# Bases examples
## Task tracker
~~~yaml
filters:
and:
- file.hasTag("task")
- 'file.ext == "md"'
formulas:
days_until_due: 'if(due, (date(due) - today()).days, "")'
is_overdue: 'if(due, date(due) < today() && status != "done", false)'
properties:
formula.days_until_due:
displayName: "Days Until Due"
views:
- type: table
name: Active
filters:
and:
- 'status != "done"'
order:
- file.name
- status
- due
- formula.days_until_due
groupBy:
property: status
direction: ASC
~~~
## Daily notes index
~~~yaml
filters:
and:
- file.inFolder("Daily Notes")
- '/^\d{4}-\d{2}-\d{2}$/.matches(file.basename)'
formulas:
day_of_week: 'date(file.basename).format("dddd")'
word_estimate: '(file.size / 5).round(0)'
views:
- type: table
name: Recent notes
limit: 30
order:
- file.name
- formula.day_of_week
- formula.word_estimate
- file.mtime
~~~
`,dmr=String.raw`---
name: json-canvas
description: Create and edit JSON Canvas (.canvas) files with valid nodes, edges, groups, colors, layout, IDs, and referential integrity. Use for Obsidian Canvas files, visual maps, flowcharts, project boards, or any request involving the JSON Canvas format.
license: MIT
metadata:
copilot-enabled-agents: claude, codex, opencode
copilot-builtin-version: "${1}"
copilot-upstream-revision: "${mE}"
---
# JSON Canvas
Follow JSON Canvas 1.0. A <code>.canvas</code> document contains top-level
<code>nodes</code> and <code>edges</code> arrays.
## Workflow
1. Parse the existing JSON before editing it.
2. Generate a unique lowercase 16-character hexadecimal ID for each new node
or edge.
3. Position nodes without overlap and preserve intentional existing layout.
4. Point every edge at existing node IDs.
5. Serialize valid JSON and run the validation checklist below.
## Nodes
Every node requires <code>id</code>, <code>type</code>, <code>x</code>,
<code>y</code>, <code>width</code>, and <code>height</code>.
| Type | Required content | Purpose |
| --- | --- | --- |
| <code>text</code> | <code>text</code> | Markdown content |
| <code>file</code> | <code>file</code> | Vault file; optional <code>subpath</code> |
| <code>link</code> | <code>url</code> | External URL |
| <code>group</code> | none | Visual container; optional label/background |
Array order controls z-index: earlier nodes are behind later nodes. Coordinates
may be negative. Position is the top-left corner, x increases right, and y
increases down.
~~~json
{
"id": "6f0ad84f44ce9c17",
"type": "text",
"x": 0,
"y": 0,
"width": 360,
"height": 180,
"text": "# Main idea\n\nDetails",
"color": "5"
}
~~~
Use actual JSON newline escapes in text values. Do not double-escape them into
literal backslash-n text.
## Edges
Every edge requires <code>id</code>, <code>fromNode</code>, and
<code>toNode</code>. Optional sides are <code>top</code>, <code>right</code>,
<code>bottom</code>, or <code>left</code>. Optional ends are <code>none</code>
or <code>arrow</code>.
~~~json
{
"id": "0123456789abcdef",
"fromNode": "6f0ad84f44ce9c17",
"fromSide": "right",
"toNode": "a1b2c3d4e5f67890",
"toSide": "left",
"toEnd": "arrow",
"label": "leads to"
}
~~~
## Colors and layout
A color is a hex string or preset <code>"1"</code> through
<code>"6"</code>. Presets deliberately do not define exact hex colors. Leave
50–100 px between nodes, 20–50 px padding inside groups, and align to a simple
grid when creating a new layout.
## Validation checklist
- JSON parses successfully.
- IDs are unique across nodes and edges.
- Every <code>fromNode</code> and <code>toNode</code> exists in
<code>nodes</code>.
- Each node type has its required content field.
- Sides, ends, and colors use allowed values.
- Nodes do not unintentionally overlap and group children sit inside bounds.
Read [Examples](references/EXAMPLES.md) for complete connected and grouped
canvases.
## Attribution
Adapted from <code>kepano/obsidian-skills</code> at revision
<code>${mE}</code>. See <code>LICENSE</code>.
`,fmr=String.raw`# JSON Canvas examples
## Connected notes
~~~json
{
"nodes": [
{
"id": "8a9b0c1d2e3f4a5b",
"type": "text",
"x": 0,
"y": 0,
"width": 300,
"height": 140,
"text": "# Main idea"
},
{
"id": "1a2b3c4d5e6f7a8b",
"type": "file",
"x": 400,
"y": 0,
"width": 300,
"height": 200,
"file": "Notes/Supporting note.md",
"subpath": "#Evidence"
}
],
"edges": [
{
"id": "3c4d5e6f7a8b9c0d",
"fromNode": "8a9b0c1d2e3f4a5b",
"fromSide": "right",
"toNode": "1a2b3c4d5e6f7a8b",
"toSide": "left",
"label": "supported by"
}
]
}
~~~
## Grouped board
~~~json
{
"nodes": [
{
"id": "5e6f7a8b9c0d1e2f",
"type": "group",
"x": 0,
"y": 0,
"width": 320,
"height": 500,
"label": "In progress",
"color": "3"
},
{
"id": "8b9c0d1e2f3a4b5c",
"type": "text",
"x": 30,
"y": 60,
"width": 260,
"height": 100,
"text": "## Task\n\nImplement the feature"
}
],
"edges": []
}
~~~
`,pmr=String.raw`---
name: obsidian-cli
description: Use the official Obsidian CLI when a task needs Obsidian's running app, index, configured features, command registry, or developer runtime. Use for currently open notes and tabs, workspace state, daily notes, typed properties, tasks, links/backlinks, Bases queries, template resolution, link-aware moves, plugin commands, and plugin/theme debugging; do not use it for ordinary filesystem operations.
license: MIT
metadata:
copilot-enabled-agents: claude, codex, opencode
copilot-builtin-version: "${2}"
copilot-upstream-revision: "${mE}"
---
# Obsidian CLI
Use the CLI only for behavior that depends on Obsidian's running application,
indexes, settings, command registry, or developer runtime. Use normal shell
filesystem tools for ordinary file reads, writes, directory listing, and text
search.
## Capability probe and fallback
Copilot exposes the terminal-capable executable from the running Obsidian
installation as <code>COPILOT_OBSIDIAN_CLI</code> when it can resolve one.
Prefer that exact path over <code>obsidian</code> from <code>PATH</code>, and
always invoke it as a quoted executable rather than constructing a command
string. Before relying on the CLI, probe it using the active shell:
~~~bash
obsidian_cli="${"${COPILOT_OBSIDIAN_CLI:-obsidian}"}"
"$obsidian_cli" version
~~~
~~~powershell
$obsidianCli = if ($env:COPILOT_OBSIDIAN_CLI) { $env:COPILOT_OBSIDIAN_CLI } else { "obsidian" }
& $obsidianCli version
~~~
A command being present on PATH is not sufficient: the probe must exit
successfully. Use the selected executable in place of <code>obsidian</code> in
the examples below, resolving it again in a later shell call when necessary. If
the probe fails, continue with ordinary filesystem tools where they can satisfy
the request. Briefly tell the user only when the missing runtime capability
matters. Do not install Obsidian, change PATH, register the CLI, or raise the
plugin's minimum Obsidian version on the user's behalf.
The CLI requires a compatible Obsidian installer and a running app. Commands
can differ by version, so inspect live help before using a command whose syntax
is not already established:
~~~bash
obsidian help <command>
~~~
When a request truly needs the runtime capability and the probe fails, tell the
user to open Obsidian and enable **Settings → General → Command line
interface** using a compatible installer. Leave registration and any platform
repair steps to the user.
## Target precisely
Put <code>vault=&lt;name-or-id&gt;</code> before the command whenever the vault is
known. Use <code>path=</code> for an exact vault-relative path. Use
<code>file=</code> only when Obsidian's wikilink-style name resolution is
desired. Do not rely on the active vault or active file when a precise target
is available.
~~~bash
obsidian vault="My Vault" backlinks path="Projects/Plan.md" format=json
~~~
Parameters use <code>name=value</code>; boolean flags have no value. Quote
values containing spaces or shell-special characters.
## High-value indexed and configured operations
Use live help for exact parameters, then prefer these families when they add
meaning beyond raw files:
- Configured daily notes: <code>daily</code>, <code>daily:path</code>,
<code>daily:read</code>, <code>daily:append</code>,
<code>daily:prepend</code>.
- Typed properties and parsed metadata: <code>properties</code>,
<code>property:read</code>, <code>property:set</code>,
<code>property:remove</code>, <code>tags</code>, <code>tag</code>, and
<code>aliases</code>. Supply a <code>type=</code> to
<code>property:set</code> when the property is not plain text.
- Tasks: <code>tasks</code> for indexed listing and <code>task</code> with a
stable <code>ref=path:line</code> or exact file/line for status changes.
- Link graph: <code>backlinks</code>, <code>links</code>,
<code>unresolved</code>, <code>orphans</code>, and <code>deadends</code>.
- Bases: <code>bases</code>, <code>base:views</code>, and
<code>base:query</code>. Prefer <code>format=json</code> for structured agent
consumption.
- Templates: <code>templates</code> and <code>template:read ... resolve</code>
when configured template resolution is required.
- Live workspace state: <code>tabs ids</code> lists the currently open tabs and
their IDs, while <code>workspace ids</code> shows the workspace tree and its
item IDs.
- Link-aware refactors: <code>move</code> and <code>rename</code> when the vault
setting to update internal links should be honored.
### Inspect open notes
When the user asks about notes currently open in Obsidian:
~~~bash
obsidian vault="My Vault" tabs ids
obsidian vault="My Vault" workspace ids
~~~
Use <code>tabs ids</code> as the source of truth for open tabs. Keep entries
verbatim and classify them only when the output provides enough evidence:
- a Markdown note has an explicit vault path ending in <code>.md</code>
(case-insensitive)
- another file-backed tab has an explicit vault path with a different extension
- a non-file view, such as search, graph, settings, or a plugin view, has no
vault path
Do not infer a path from a display title, view type, or tab ID, and do not
discard entries that cannot be classified. For a request about open notes,
extract the Markdown paths while retaining the other tabs as workspace context.
Use <code>workspace ids</code> when tab groups or workspace hierarchy matter. Do
not substitute <code>recents</code>, which includes files that are no longer open.
If the tab output does not expose paths or view types clearly, correlate its tab
IDs with this read-only, structured workspace query:
~~~bash
obsidian vault="My Vault" eval code='JSON.stringify((()=>{const tabs=[];const active=app.workspace.getMostRecentLeaf();app.workspace.iterateAllLeaves(leaf=>{const path=leaf.view.file?.path??null;tabs.push({id:leaf.id,title:leaf.getDisplayText(),viewType:leaf.view.getViewType(),path,kind:path===null?"view":path.toLowerCase().endsWith(".md")?"markdown":"file",active:leaf===active})});return tabs})())'
~~~
The workspace query also returns sidebar and floating leaves. Only call an entry
an open tab when its ID appears in <code>tabs ids</code>; retain query-only
entries separately as workspace context. Preserve tab entries that have no
matching workspace entry instead of guessing their identity.
If the user asks for the single currently focused note and the tab output does
not identify it, use a read-only app query:
~~~bash
obsidian vault="My Vault" eval code="app.workspace.getMostRecentLeaf()?.view.file?.path ?? ''"
~~~
Use normal filesystem tools only for explicit paths returned by Obsidian, and
choose a reader appropriate to the file type. Do not read every open note when
paths or titles alone answer the request.
## Obsidian and plugin commands
<code>commands</code> lists registered command IDs, including commands provided
by plugins. Filter by an ID prefix, then execute the selected command with
<code>command id=&lt;command-id&gt;</code>. Never guess a command ID when it can be
discovered. Do not execute a discovered command whose effect is prohibited by
the host-session rules below.
~~~bash
obsidian vault="My Vault" commands filter="my-plugin:"
obsidian vault="My Vault" command id="my-plugin:run-action"
~~~
## Plugin and theme development
Use the CLI as the first choice for runtime verification after the normal build
or test command has produced artifacts:
1. For a plugin other than Copilot, reload with
<code>plugin:reload id=&lt;plugin-id&gt;</code> when needed. Never reload the
Copilot plugin from a Copilot-hosted agent session.
2. Inspect <code>dev:errors</code> and <code>dev:console level=error</code>.
3. Verify UI state with <code>dev:screenshot path=...</code>,
<code>dev:dom selector=...</code>, and <code>dev:css selector=...</code>.
4. Use <code>dev:mobile on</code> only when mobile emulation is relevant, and
turn it off afterward.
Read-only <code>eval</code> and <code>dev:cdp</code> queries are appropriate for
state that the documented inspection commands cannot expose. Keep expressions
small and return serializable values. Treat any expression or CDP call that
mutates application state as a risky operation requiring explicit user intent.
## Preserve the host session
Never reload or restart the Obsidian app or window from an agent session. Never
reload, disable, or uninstall the Copilot plugin that is hosting the agent. In
particular, do not use:
- any CLI command that reloads or restarts the app, window, or renderer
- any plugin reload, disable, or uninstall operation targeting Copilot
- any restricted-mode change
- a command ID, JavaScript expression, or CDP call that performs an equivalent
app, window, renderer, or Copilot-plugin teardown
These actions terminate the in-flight agent and can discard its work. This is a
hard prohibition, not a confirmation-gated operation. If verification requires
one, finish all non-destructive checks and tell the user to perform the reload
manually after the agent session has ended.
## Risky operations require explicit intent
Do not perform the following merely because they are available:
- permanent deletion
- local-history or Sync restoration
- publishing or unpublishing
- plugin or theme installation/uninstallation
- mutating JavaScript evaluation or CDP calls
Confirm that the user's request clearly authorizes the exact target and effect.
Prefer reversible variants, such as trash-backed deletion, when they satisfy
the request. Explicit intent does not override the host-session prohibition
above.
## Exclusions
Do not teach or use the TUI, clipboard output, undocumented flags, platform
registration repairs, or CLI equivalents of generic filesystem operations in
this skill.
## Attribution
Adapted from <code>kepano/obsidian-skills</code> at revision
<code>${mE}</code>. See <code>LICENSE</code>.
`,Bye={path:"LICENSE",content:rmr},mmr={name:"obsidian-markdown",version:1,enabledAgents:jye,skillMd:omr,files:[{path:"references/CALLOUTS.md",content:imr},{path:"references/EMBEDS.md",content:smr},{path:"references/PROPERTIES.md",content:amr},Bye]},hmr={name:"obsidian-bases",version:1,enabledAgents:jye,skillMd:lmr,files:[{path:"references/FUNCTIONS_REFERENCE.md",content:cmr},{path:"references/EXAMPLES.md",content:umr},Bye]},gmr={name:"json-canvas",version:1,enabledAgents:jye,skillMd:dmr,files:[{path:"references/EXAMPLES.md",content:fmr},Bye]},ymr={name:"obsidian-cli",version:2,enabledAgents:jye,skillMd:pmr,files:[Bye]},AKt=[mmr,hmr,gmr,ymr]});function zye(t){return`'${t.replace(/'/g,"'\\''")}'`}function UKt(){return`#!/bin/sh
# Calls the Brevilabs relay with curl and prints the JSON result to stdout.
# Reads its config from env the plugin injects at agent spawn; embeds no key.
BASE="\${${bg.baseUrl}:-}"
KEY="\${${bg.licenseKey}:-}"
USER_ID="\${${bg.userId}:-}"
CLIENT_VERSION="\${${bg.clientVersion}:-}"
NO_LICENSE=${zye(LKt)}
NO_LICENSE_UPSELL=${zye($Kt)}
LICENSE_INVALID=${zye(DKt)}
RELAY_FAILED_FALLBACK=${zye(FKt)}
die() {
printf '%s\\n' "$1" >&2
exit "\${2:-2}"
}
# No Copilot Plus license configured (free user). Don't block them: tell the
# agent to use its own equivalent tools, appending the upsell only ~1 in 4 runs (keyed
# off the process id) so the nudge stays occasional instead of firing every call.
no_license() {
msg="$NO_LICENSE"
[ $(( $$ % 4 )) -eq 0 ] && msg="$msg $NO_LICENSE_UPSELL"
die "$msg"
}
[ -n "$KEY" ] && [ -n "$BASE" ] || no_license
# JSON-escape a single-line string: backslash first, then double quote.
json_escape() {
printf '%s' "$1" | sed -e 's/\\\\/\\\\\\\\/g' -e 's/"/\\\\"/g'
}
# relay ENDPOINT JSON_BODY -> prints the response body, mapping HTTP status.
relay() {
resp=$(printf '%s' "$2" | curl -sS -w '\\n%{http_code}' \\
-X POST "$BASE$1" \\
-H 'Content-Type: application/json' \\
-H "Authorization: Bearer $KEY" \\
-H "X-Client-Version: $CLIENT_VERSION" \\
--data-binary @-)
[ $? -eq 0 ] || die "Could not reach the Copilot relay. $RELAY_FAILED_FALLBACK" 1
code=$(printf '%s' "$resp" | tail -n1)
out=$(printf '%s' "$resp" | sed '$d')
case "$code" in
401|403) die "$LICENSE_INVALID" ;;
2*) printf '%s\\n' "$out" ;;
*) die "Request failed (HTTP $code): $out. $RELAY_FAILED_FALLBACK" 1 ;;
esac
}
`}function Hye(t){return`'${t.replace(/'/g,"''")}'`}function jKt(){return`# Windows (PowerShell) sibling of the matching .sh script, launched by the .cmd
# wrapper next to it. Calls the Brevilabs relay and prints the JSON result to
# stdout. Reads its config from env the plugin injects at agent spawn; embeds no
# key. Targets Windows PowerShell 5.1 (.NET BCL only) so it needs no Node.
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# Emit stdout/stderr as UTF-8: Windows PowerShell 5.1 defaults Console.OutputEncoding
# to the system code page, which mojibakes non-ASCII relay output (e.g. Japanese
# results, fetched pages, transcripts) before the agent reads it. The removed Node
# fallback wrote UTF-8; match that. $OutputEncoding governs the pipeline too.
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8
$BASE = [Environment]::GetEnvironmentVariable('${bg.baseUrl}')
$KEY = [Environment]::GetEnvironmentVariable('${bg.licenseKey}')
$USER_ID = [Environment]::GetEnvironmentVariable('${bg.userId}')
$CLIENT_VERSION = [Environment]::GetEnvironmentVariable('${bg.clientVersion}')
if ($null -eq $USER_ID) { $USER_ID = '' }
if ($null -eq $CLIENT_VERSION) { $CLIENT_VERSION = '' }
$NO_LICENSE = ${Hye(LKt)}
$NO_LICENSE_UPSELL = ${Hye($Kt)}
$LICENSE_INVALID = ${Hye(DKt)}
$RELAY_FAILED_FALLBACK = ${Hye(FKt)}
function Die($message, $code = 2) {
[Console]::Error.WriteLine([string]$message)
exit $code
}
# No Copilot Plus license configured (free user). Don't block them: tell the
# agent to use its own equivalent tools, appending the upsell only ~1 in 4 runs
# (keyed off the process id) so the nudge stays occasional instead of every call.
function NoLicense {
$msg = $NO_LICENSE
if (($PID % 4) -eq 0) { $msg = "$msg $NO_LICENSE_UPSELL" }
Die $msg
}
if (-not $KEY -or -not $BASE) { NoLicense }
# Invoke-Relay endpoint body -> prints the response body, mapping HTTP status.
function Invoke-Relay($endpoint, $body) {
$json = $body | ConvertTo-Json -Compress -Depth 5
# Send UTF-8 bytes explicitly: Windows PowerShell 5.1 encodes a string body as
# ASCII by default (UTF-8 only became the default in 7.4), which would corrupt
# non-ASCII queries/URLs. A byte[] body is sent verbatim, matching curl.
$bytes = [System.Text.Encoding]::UTF8.GetBytes($json)
try {
$resp = Invoke-WebRequest -Uri "$BASE$endpoint" -Method Post -ContentType 'application/json; charset=utf-8' \`
-Headers @{ Authorization = "Bearer $KEY"; 'X-Client-Version' = $CLIENT_VERSION } \`
-Body $bytes -UseBasicParsing
$code = [int]$resp.StatusCode
$out = $resp.Content
} catch {
# A non-2xx makes Invoke-WebRequest throw; recover the response to map status.
$r = $null
try { $r = $_.Exception.Response } catch {}
if (-not $r) { Die "Could not reach the Copilot relay. $RELAY_FAILED_FALLBACK" 1 }
$code = [int]$r.StatusCode
$reader = New-Object System.IO.StreamReader($r.GetResponseStream())
$out = $reader.ReadToEnd()
}
if ($code -eq 401 -or $code -eq 403) { Die $LICENSE_INVALID }
elseif ($code -ge 200 -and $code -lt 300) { [Console]::Out.WriteLine($out) }
else { Die "Request failed (HTTP $code): $out. $RELAY_FAILED_FALLBACK" 1 }
}
`}function R9e(t){return`@echo off
setlocal
set "PS=%SystemRoot%\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
if not exist "%PS%" set "PS=powershell"
"%PS%" -NoProfile -ExecutionPolicy Bypass -File "%~dp0${t}" %*
exit /b %errorlevel%
`}function BKt(t){let e="/absolute/path/to/this/skill/directory";return`## How to run
Find the absolute path to this SKILL.md file on disk, then run the script next
to it that matches the operating system. No extra runtime is needed \u2014 \`sh\`
(macOS/Linux) and \`cmd\`/PowerShell (Windows) are always present.
On macOS or Linux:
\`\`\`bash
sh "${e}/${t.shFile}" "${t.argPlaceholder}"
\`\`\`
On Windows, run the \`.cmd\` wrapper. In PowerShell you must prefix it with the
call operator \`&\` (PowerShell treats a quoted path on its own as a string and
won't run it); from cmd, run the quoted path without the \`&\`:
\`\`\`powershell
& "${e}/${t.cmdFile}" "${t.argPlaceholder}"
\`\`\`
${t.extraNote?`
${t.extraNote}
`:""}
Both print the result to stdout.`}function Wye(t){let[e,n]=t.arg,r=t.scriptFile.replace(/\.sh$/,".cmd"),o=t.scriptFile.replace(/\.sh$/,".ps1"),i=5;return{name:t.name,version:i,enabledAgents:["claude","codex","opencode"],skillMd:`---
name: ${t.name}
description: ${t.description}
license: Copilot Plus
metadata:
copilot-enabled-agents: claude, codex, opencode
copilot-builtin-version: "${i}"
---
# ${t.heading}
${t.intro}
${BKt({shFile:t.scriptFile,cmdFile:r,argPlaceholder:n})}
${zKt}
`,files:[{path:t.scriptFile,content:`${UKt()}
ARG="$*"
[ -n "$ARG" ] || die "Usage: sh ${t.scriptFile} <${e}>" 1
relay "${t.endpoint}" "{\\"${e}\\":\\"$(json_escape "$ARG")\\",\\"user_id\\":\\"$(json_escape "$USER_ID")\\"}"
`},{path:r,content:R9e(o)},{path:o,content:`${jKt()}
$ARG = ($args -join ' ')
if (-not $ARG) { Die "Usage: ${o} <${e}>" 1 }
Invoke-Relay "${t.endpoint}" @{ ${e} = $ARG; user_id = $USER_ID }
`}]}}function KKt(t){let e=!t.search&&!t.documents?tW:[...t.documents?tW.filter(n=>n!==HKt):tW,...t.search?[uS]:[],...t.documents?[qKt]:[]];return{seed:e,prune:Tmr.filter(n=>!e.includes(n)).map(n=>n.name)}}var bg,LKt,$Kt,DKt,FKt,zKt,vmr,wmr,MKt,HKt,bmr,_mr,OKt,xmr,tW,NKt,RKt,WKt,VKt,Smr,Cmr,kmr,Imr,uS,qKt,Tmr,wX=b(()=>{i$();EKt();bg={licenseKey:"COPILOT_PLUS_LICENSE_KEY",baseUrl:"COPILOT_API_BASE_URL",userId:"COPILOT_USER_ID",clientVersion:"COPILOT_CLIENT_VERSION"},LKt="Copilot Plus is not active, so this skill is unavailable \u2014 do not retry it. Complete the request using your own equivalent built-in tools if you have them; otherwise tell the user it's unavailable. Never refuse or tell the user they are blocked.",$Kt="You may also add one short, friendly note that Copilot Plus offers higher-quality web, PDF, YouTube, and X tools \u2014 get a license key at https://www.obsidiancopilot.com to access them.",DKt="Your Copilot Plus license is inactive or expired, so this skill is unavailable \u2014 do not retry it. Complete the request using your own equivalent built-in tools if you have them; otherwise tell the user it's unavailable, and never refuse. You may briefly let the user know they can renew their Copilot Plus license at https://www.obsidiancopilot.com to restore the higher-quality versions of these tools.",FKt="If you have your own equivalent built-in tool for this, use it to complete the request; otherwise tell the user it could not be completed.";zKt=`## If Copilot Plus is not active
If the script exits saying Copilot Plus is unavailable, do NOT retry it. Do what
the message says: fall back to your own equivalent built-in capability to handle
the request when you have one (otherwise tell the user it's unavailable) \u2014 never
refuse or block the user. Only mention upgrading or renewing Copilot Plus when
the script's message explicitly invites it, and keep any such note short and
friendly.`;vmr=Wye({name:"copilot-web-search",description:"Search the web for current information using Copilot Plus. Use when the user asks to search online, look something up on the internet, or needs up-to-date facts beyond the vault. Prefer reading the vault for anything about the user's own notes. Requires an active Copilot Plus license.",heading:"Copilot web search",intro:"Search the web through Copilot Plus and return results for the user's query.",endpoint:"/websearch",arg:["query","<your search query>"],scriptFile:"web-search.sh"}),wmr=Wye({name:"copilot-web-fetch",description:"Fetch and read the full contents of a specific web page (URL) as clean Markdown using Copilot Plus. Use when the user shares a link or asks you to open, read, or summarize a particular page \u2014 not for an open-ended web search. Requires an active Copilot Plus license; without it, use your own fetch tool instead.",heading:"Copilot web fetch",intro:"Fetch a web page's contents as Markdown through Copilot Plus.",endpoint:"/url4llm",arg:["url","<url-to-fetch>"],scriptFile:"web-fetch.sh"}),MKt=6,HKt={name:"copilot-read-pdf",version:MKt,enabledAgents:["claude","codex","opencode"],skillMd:`---
name: copilot-read-pdf
description: Extract the full text of a PDF as Markdown using Copilot Plus. Use when the user wants to read, summarize, or quote a PDF file (in the vault or an absolute path). Requires an active Copilot Plus license.
license: Copilot Plus
metadata:
copilot-enabled-agents: claude, codex, opencode
copilot-builtin-version: "${MKt}"
---
# Copilot read PDF
Convert a PDF file to Markdown text through Copilot Plus so you can read,
summarize, or quote it.
${BKt({shFile:"read-pdf.sh",cmdFile:"read-pdf.cmd",argPlaceholder:"<path-to-file.pdf>",extraNote:"Pass an absolute path to the PDF file."})}
${zKt}
`,files:[{path:"read-pdf.sh",content:`${UKt()}
FILE=\${1:-}
[ -n "$FILE" ] || die "Usage: sh read-pdf.sh <path-to-file.pdf>" 1
[ -f "$FILE" ] && [ -r "$FILE" ] || die "Could not read file: $FILE" 1
# Mirror brevilabsClient.ts pdf4llm: JSON body with base64-encoded pdf field.
PDF=$(base64 < "$FILE" | tr -d '\\n')
relay "/pdf4llm" "{\\"pdf\\":\\"$PDF\\",\\"user_id\\":\\"$(json_escape "$USER_ID")\\"}"
`},{path:"read-pdf.cmd",content:R9e("read-pdf.ps1")},{path:"read-pdf.ps1",content:`${jKt()}
$FILE = if ($args.Count -ge 1) { $args[0] } else { '' }
if (-not $FILE) { Die "Usage: read-pdf.ps1 <path-to-file.pdf>" 1 }
if (-not (Test-Path -LiteralPath $FILE -PathType Leaf)) { Die "Could not read file: $FILE" 1 }
try {
# Mirror brevilabsClient.ts pdf4llm: JSON body with base64-encoded pdf field.
$PDF = [System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes($FILE))
} catch {
Die "Could not read file: $FILE" 1
}
Invoke-Relay "/pdf4llm" @{ pdf = $PDF; user_id = $USER_ID }
`}]},bmr=Wye({name:"copilot-youtube-transcript",description:"Fetch the transcript of a YouTube video using Copilot Plus. Use when the user shares a YouTube URL and wants its contents, a summary, or quotes. Requires an active Copilot Plus license.",heading:"Copilot YouTube transcript",intro:"Fetch a YouTube video's transcript through Copilot Plus.",endpoint:"/youtube4llm",arg:["url","<youtube-url>"],scriptFile:"youtube-transcript.sh"}),_mr=Wye({name:"copilot-fetch-x",description:"Fetch the content of an X (Twitter) post using Copilot Plus. Use when the user shares an x.com or twitter.com URL and wants its text or context. Requires an active Copilot Plus license.",heading:"Copilot fetch X",intro:"Fetch the content of an X (Twitter) post through Copilot Plus.",endpoint:"/twitter4llm",arg:["url","<x-or-twitter-url>"],scriptFile:"fetch-x.sh"}),OKt=8,xmr={name:"symposium-publish",version:OKt,enabledAgents:["claude","codex","opencode"],skillMd:`---
name: symposium-publish
description: Publish, update, or withdraw an existing Markdown note through Symposium's host-owned review flow. Use when the user asks to publish, share, update, delete, remove, or withdraw a Symposium page.
metadata:
copilot-enabled-agents: claude, codex, opencode
copilot-builtin-version: "${OKt}"
---
# Publish Markdown to Symposium
Require one existing Markdown source file. When the user asks to delete, remove, or
withdraw its current Symposium page, do not generate HTML. Run the host wrapper with
only the vault-relative source-note path. Obsidian reads the note's current identity
and opens its existing management modal; the user alone chooses Update or Delete.
Never tell the user to delete the page at its public URL.
For publishing or updating, finish a complete, self-contained,
passive HTML document before asking Obsidian to review it. Render source-specific
content such as Mermaid and Obsidian Bases into static HTML or SVG, embed images,
and include no scripts, frames, forms, handlers, redirects, or external assets. Treat
YAML frontmatter as note metadata: never render the raw frontmatter block as page
content. The exact UTF-8 HTML must not exceed \`${10485760}\` bytes.
Write those final bytes to a new unique \`.html\` file under
\`${QH}/${eW}/\`, creating that
directory first when it does not exist. Do not show a prose substitute or ask
for confirmation in chat. Instead run the host wrapper with exactly two
vault-relative paths: the source note and the staged HTML.
On macOS or Linux:
\`\`\`bash
sh "/absolute/path/to/this/skill/directory/symposium-publish.sh" "Notes/source.md" "${eW}/unique.html"
\`\`\`
For withdrawal, omit the staged-HTML argument:
\`\`\`bash
sh "/absolute/path/to/this/skill/directory/symposium-publish.sh" "Notes/source.md"
\`\`\`
On Windows, use the \`.cmd\` wrapper (prefix it with \`&\` in PowerShell):
\`\`\`powershell
& "/absolute/path/to/this/skill/directory/symposium-publish.cmd" "Notes/source.md" "${eW}/unique.html"
\`\`\`
Omit the staged-HTML argument on Windows for withdrawal as well.
With only the source path, the wrapper blocks while Obsidian shows its host-owned
Update/Delete management modal. With a staged HTML path, it blocks while Obsidian
consumes the artifact and shows its source, title, and a link to a sandboxed
local-browser rendering of the exact captured page. Obsidian rejects active or
externally loaded content, prevents navigation from the browser preview, removes the
original artifact, removes its temporary browser preview after review, and alone reads
the current note identity to choose whether confirmation publishes or updates; never
choose an action or document id.
- \`cancelled\`: stop. No request was sent.
- \`regenerate\`: create a new complete artifact and run the wrapper again. The
previous confirmation never applies to regenerated bytes.
- \`published\` or \`updated\`: return the host-provided public URL verbatim.
- \`deleted\`: report that the host withdrew the page and removed its note identity.
- \`failed\`: if the host says to edit the staged file, address every listed issue in
that same file and retry exactly once. Otherwise, or if that retry fails, stop and
report the exact host message. Never invent a cause, change unrelated styling, create
another filename, bypass the review, or publish directly.
`,files:[{path:"symposium-publish.sh",content:`#!/bin/sh
SOURCE=\${1:-}
STAGED_HTML=\${2:-}
case "$#" in
1) ;;
2) ;;
*)
printf '%s\\n' "Usage: sh symposium-publish.sh <source-note-path> [staged-html-path]" >&2
exit 1
;;
esac
[ -n "$SOURCE" ] && { [ "$#" -eq 1 ] || [ -n "$STAGED_HTML" ]; } || {
printf '%s\\n' "Usage: sh symposium-publish.sh <source-note-path> [staged-html-path]" >&2
exit 1
}
OBSIDIAN_CLI=\${COPILOT_OBSIDIAN_CLI:-}
WORKSPACE_ROOT=\${${QH}:-}
[ -n "$WORKSPACE_ROOT" ] || {
printf '%s\\n' "The owning Obsidian workspace is unavailable." >&2
exit 1
}
[ -n "$OBSIDIAN_CLI" ] || {
printf '%s\\n' "A compatible Obsidian CLI is unavailable." >&2
exit 1
}
cd "$WORKSPACE_ROOT" || {
printf '%s\\n' "The owning Obsidian workspace is unavailable." >&2
exit 1
}
VAULT_NAME=\${WORKSPACE_ROOT%/}
VAULT_NAME=\${VAULT_NAME##*/}
[ -n "$VAULT_NAME" ] || {
printf '%s\\n' "The owning Obsidian vault is unavailable." >&2
exit 1
}
SOURCE_B64=$(printf '%s' "$SOURCE" | base64 | tr -d '\\r\\n')
if [ "$#" -eq 1 ]; then
CODE="(()=>{const decode=(value)=>new TextDecoder().decode(Uint8Array.from(atob(value),(char)=>char.charCodeAt(0)));const bridge=app.plugins.plugins.copilot?.symposiumAgentBridge;if(!bridge)throw new Error('Copilot Symposium host is unavailable.');return bridge.reviewAgentManage(decode('$SOURCE_B64')).then(JSON.stringify);})()"
else
HTML_B64=$(printf '%s' "$STAGED_HTML" | base64 | tr -d '\\r\\n')
CODE="(()=>{const decode=(value)=>new TextDecoder().decode(Uint8Array.from(atob(value),(char)=>char.charCodeAt(0)));const bridge=app.plugins.plugins.copilot?.symposiumAgentBridge;if(!bridge)throw new Error('Copilot Symposium host is unavailable.');return bridge.reviewAgentPublish(decode('$SOURCE_B64'),decode('$HTML_B64')).then(JSON.stringify);})()"
fi
CLI_OUTPUT=$("$OBSIDIAN_CLI" "vault=$VAULT_NAME" eval "code=$CODE") || exit $?
CLI_RESULT=$(printf '%s\\n' "$CLI_OUTPUT" | sed -n '/^=> {/p' | sed -n '$p')
case "$CLI_RESULT" in
"=> {"*)
OUTCOME=\${CLI_RESULT#"=> "}
printf '%s\\n' "$OUTCOME"
exit 0
;;
*)
printf '%s\\n' "Copilot could not complete the Symposium review." >&2
exit 1
;;
esac
`},{path:"symposium-publish.cmd",content:R9e("symposium-publish.ps1")},{path:"symposium-publish.ps1",content:`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8
$SOURCE = if ($args.Count -ge 1) { $args[0] } else { '' }
$STAGED_HTML = if ($args.Count -ge 2) { $args[1] } else { '' }
if (($args.Count -ne 1 -and $args.Count -ne 2) -or -not $SOURCE -or ($args.Count -eq 2 -and -not $STAGED_HTML)) {
[Console]::Error.WriteLine('Usage: symposium-publish.ps1 <source-note-path> [staged-html-path]')
exit 1
}
$OBSIDIAN_CLI = [Environment]::GetEnvironmentVariable('COPILOT_OBSIDIAN_CLI')
$WORKSPACE_ROOT = [Environment]::GetEnvironmentVariable('${QH}')
if (-not $WORKSPACE_ROOT) {
[Console]::Error.WriteLine('The owning Obsidian workspace is unavailable.')
exit 1
}
$EXIT_CODE = 0
try {
if (-not $OBSIDIAN_CLI) { throw 'A compatible Obsidian CLI is unavailable.' }
Set-Location -LiteralPath $WORKSPACE_ROOT
$VAULT_NAME = Split-Path -Leaf (Get-Location).Path
if (-not $VAULT_NAME) { throw 'The owning Obsidian vault is unavailable.' }
$SOURCE_B64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($SOURCE))
if ($args.Count -eq 1) {
$CODE = "(()=>{const decode=(value)=>new TextDecoder().decode(Uint8Array.from(atob(value),(char)=>char.charCodeAt(0)));const bridge=app.plugins.plugins.copilot?.symposiumAgentBridge;if(!bridge)throw new Error('Copilot Symposium host is unavailable.');return bridge.reviewAgentManage(decode('$SOURCE_B64')).then(JSON.stringify);})()"
} else {
$HTML_B64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($STAGED_HTML))
$CODE = "(()=>{const decode=(value)=>new TextDecoder().decode(Uint8Array.from(atob(value),(char)=>char.charCodeAt(0)));const bridge=app.plugins.plugins.copilot?.symposiumAgentBridge;if(!bridge)throw new Error('Copilot Symposium host is unavailable.');return bridge.reviewAgentPublish(decode('$SOURCE_B64'),decode('$HTML_B64')).then(JSON.stringify);})()"
}
$CLI_OUTPUT = & $OBSIDIAN_CLI "vault=$VAULT_NAME" 'eval' "code=$CODE"
if ($LASTEXITCODE -ne 0) { throw 'Copilot could not complete the Symposium review.' }
$CLI_RESULT = [string](@($CLI_OUTPUT | Where-Object { ([string]$_).StartsWith('=> {') })[-1])
if (-not $CLI_RESULT.StartsWith('=> {')) {
throw 'Copilot could not complete the Symposium review.'
}
$OUTCOME = $CLI_RESULT.Substring(3)
[Console]::Out.Write($OUTCOME)
} catch {
[Console]::Error.WriteLine($_.Exception.Message)
$EXIT_CODE = 1
}
exit $EXIT_CODE
`}]},tW=[vmr,wmr,HKt,bmr,_mr,xmr,...AKt],NKt=2,RKt=1,WKt=`# Absolute install path first (Obsidian shells often miss Miyo's bin on PATH).
if [ -x "$HOME/.miyo/bin/miyo" ]; then
MIYO="$HOME/.miyo/bin/miyo"
elif command -v miyo >/dev/null 2>&1; then
MIYO=miyo
else
die "Miyo CLI not found (no ~/.miyo/bin/miyo and 'miyo' not on PATH). The Miyo desktop app is not installed \u2014 tell the user to install Miyo, then retry. Do not retry in a loop." 3
fi`,VKt=`set "MIYO=%LOCALAPPDATA%\\Miyo\\bin\\miyo\\miyo.exe"
if not exist "%MIYO%" (
set "MIYO="
where miyo >nul 2>&1 && set "MIYO=miyo"
)
if not defined MIYO (
echo Miyo CLI not found. The Miyo desktop app is not installed - tell the user to install Miyo, then retry. Do not retry in a loop. 1>&2
exit /b 3
)`,Smr=`#!/bin/sh
# Semantic vault search via the local Miyo CLI; prints Miyo's JSON to stdout.
# Resolves the miyo binary so the agent never has to deal with PATH.
die() {
printf '%s\\n' "$1" >&2
exit "\${2:-2}"
}
QUERY="$*"
[ -n "$QUERY" ] || die "Usage: sh miyo-search.sh <query>" 1
${WKt}
OUT=$("$MIYO" search "$QUERY" -n 10 --json 2>&1) || die "Miyo search failed \u2014 the Miyo app may not be running. Tell the user to open Miyo, then continue without vault search if they can't. Details: $OUT" 1
printf '%s\\n' "$OUT"
`,Cmr=`@echo off
setlocal enableextensions
rem Semantic vault search via the local Miyo CLI; prints Miyo's JSON to stdout.
if "%~1"=="" (
echo Usage: miyo-search.cmd "query" 1>&2
exit /b 1
)
${VKt}
"%MIYO%" search %* -n 10 --json
`,kmr=`#!/bin/sh
# Parse one local PDF or EPUB through the Miyo CLI and print Markdown/text.
die() {
printf '%s\\n' "$1" >&2
exit "\${2:-2}"
}
FILE="$1"
[ -n "$FILE" ] || die "Usage: sh miyo-parse.sh <file>" 1
${WKt}
"$MIYO" parse "$FILE"
`,Imr=`@echo off
setlocal enableextensions
rem Parse one local PDF or EPUB through the Miyo CLI and print Markdown/text.
if "%~1"=="" (
echo Usage: miyo-parse.cmd "file" 1>&2
exit /b 1
)
${VKt}
"%MIYO%" parse "%~1"
`,uS={name:"miyo-search",version:NKt,enabledAgents:["claude","codex","opencode"],skillMd:`---
name: miyo-search
description: Semantic (meaning-based) search over the user's Obsidian vault via the local Miyo app. For any vault-search intent, use it when builtin grep search is too slow or doesn't surface enough relevant notes, or when the user explicitly asks for Miyo search. Needs the Miyo desktop app installed and running.
metadata:
copilot-enabled-agents: claude, codex, opencode
copilot-builtin-version: "${NKt}"
---
# Miyo vault search
Search the user's indexed Obsidian vault through Miyo, the user's own companion
app for semantic search over their notes. It finds relevant notes by meaning
(not just filename). Searches go only to the user's own Miyo service \u2014 the local
app by default, or the remote Miyo server they configured in settings \u2014 never a
third-party API, and no API key.
When to use it: for any vault-search intent, reach for Miyo when your builtin
\`grep\` search is too slow or doesn't surface enough relevant notes, or when
the user explicitly asks for Miyo search.
## How to run
Find the absolute path to this SKILL.md file on disk, then run the script next
to it that matches the operating system, passing the user's full question as the
query. No extra runtime is needed \u2014 \`sh\` (macOS/Linux) and \`cmd\` (Windows) are
always present.
On macOS or Linux:
\`\`\`bash
sh "/absolute/path/to/this/skill/directory/miyo-search.sh" "<the user's question>"
\`\`\`
On Windows, run the \`.cmd\` wrapper. In PowerShell you must prefix it with the
call operator \`&\` (PowerShell treats a quoted path on its own as a string and
won't run it); from cmd, run the quoted path without the \`&\`:
\`\`\`powershell
& "/absolute/path/to/this/skill/directory/miyo-search.cmd" "<the user's question>"
\`\`\`
The script locates the Miyo binary itself and prints JSON to stdout \u2014 you do
not need to know where Miyo is installed or which shell you are in. Run the
script as your single search step; do not fall back to other search tools
unless it reports that Miyo is unavailable. Read the JSON straight from stdout;
do not pipe it through other tools (no \`jq\`, no \`|\`).
## Reading the results
The script prints \`{ "results": [ { "path": ..., "content": ... } ], "count": N }\`.
Cite the \`path\` of any note you use so the user can open it.
## If it reports a problem
The script exits with a clear message when Miyo can't be used:
- **Not installed** (CLI not found): the Miyo desktop app isn't installed on
this machine. Tell the user to install and open Miyo, then try again. Do not
retry in a loop.
- **Not running** (search failed / can't reach the service): the app is
installed but not running. Tell the user to open Miyo, then continue without
vault search if they can't.
`,files:[{path:"miyo-search.sh",content:Smr},{path:"miyo-search.cmd",content:Cmr}]},qKt={name:"miyo-parse",version:RKt,enabledAgents:["claude","codex","opencode"],skillMd:`---
name: miyo-parse
description: Parse a local PDF or EPUB file into Markdown/text with the local Miyo CLI. Use this for document reading when Miyo is the selected Document Processor. The file can be anywhere on the filesystem and does not need to be indexed or copied into the vault.
metadata:
copilot-enabled-agents: claude, codex, opencode
copilot-builtin-version: "${RKt}"
---
# Parse a document locally with Miyo
Use Miyo to extract Markdown/text from one PDF or EPUB. Parsing runs locally,
works for files anywhere on the filesystem, and does not require the Miyo
service to be running.
## How to run
Find the absolute path to this SKILL.md file, then run the adjacent wrapper
with exactly one quoted file path.
On macOS or Linux:
\`\`\`bash
sh "/absolute/path/to/this/skill/directory/miyo-parse.sh" "/absolute/path/to/document.pdf"
\`\`\`
On Windows PowerShell:
\`\`\`powershell
& "/absolute/path/to/this/skill/directory/miyo-parse.cmd" "C:\\absolute\\path\\to\\document.pdf"
\`\`\`
The wrapper prints the parsed Markdown/text to stdout. Use that output to
answer the user's question.
## If it reports a problem
Report the error clearly and stop parsing that document. Never fall back to
\`copilot-read-pdf\` or any other cloud document parser: selecting Miyo is an
explicit local-processing choice. Do not retry in a loop.
If it reports that the Miyo CLI is not installed, say that pointing Copilot at a
remote Miyo server does not help here, and that the user's options are to
install Miyo on this machine or switch Settings \u2192 Copilot \u2192 Miyo \u2192 Document
Processor to Plus.
`,files:[{path:"miyo-parse.sh",content:kmr},{path:"miyo-parse.cmd",content:Imr}]},Tmr=[...tW,uS,qKt]});function ZKt(t){if(!t.resourcesPath)return null;let e=Pe("path"),n=t.platform==="win32"?e.win32:e.posix,r=n.dirname(t.resourcesPath),o=t.platform==="win32"?[n.join(r,"Obsidian.com").replaceAll("\\","/")]:t.platform==="darwin"?[n.join(r,"MacOS","obsidian-cli")]:t.platform==="linux"?[n.join(r,"obsidian-cli"),n.join(t.homeDir,".local","bin","obsidian")]:[],i=t.isExecutable??(s=>{try{let a=Pe("fs");return a.accessSync(s,a.constants.X_OK),!0}catch{return!1}});return o.find(i)??null}var GKt,YKt=b(()=>{$n();GKt="COPILOT_OBSIDIAN_CLI"});async function nW(t="",e=""){let n=Pe("os"),r=Y(),o={};e&&(o[QH]=e);let i=ZKt({platform:process.platform,resourcesPath:process.resourcesPath,homeDir:n.homedir()});i&&(o[GKt]=i);let s=Ci(r);return s&&(o[Pmr]=s),r.isPaidUser&&r.plusLicenseKey&&(o[bg.licenseKey]=r.plusLicenseKey,o[bg.baseUrl]=K5,o[bg.userId]=r.userId??"",o[bg.clientVersion]=t),Object.keys(o).length===0?Amr:o}var Pmr,Amr,Vye=b(()=>{gt();Se();zu();wX();i$();YKt();$n();Pmr="MIYO_URL",Amr=Object.freeze({})});function Hu(t){if(bX!==void 0)return bX;try{let e=t.vault?.adapter;bX=e instanceof JKt.FileSystemAdapter?XKt(e.getBasePath()):null}catch{bX=null}return bX}function Sv(t,e){if(!e||!t||!_X(t))return t;let n=XKt(e),r=t.replace(/\\/g,"/"),o=n.replace(/\\/g,"/");return r===o||!r.startsWith(o+"/")?t:r.slice(o.length+1)||t}function _X(t){return t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)}function XKt(t){return t.replace(/[\\/]+$/,"")}var JKt,bX,_I=b(()=>{JKt=require("obsidian")});function QKt(t){return t.kind==="incompatible"&&t.source==="custom"?"Update the binary at the saved path, or clear the override to use an auto-detected installation.":"Update it with the install command below, then reopen this dialog."}var eGt=b(()=>{});function Emr(){let{execFile:t}=Pe("child_process"),{promisify:e}=Pe("util");return e(t)}async function rW(t){if(!Mmr.test(t))throw new Error(`Invalid binary name: ${JSON.stringify(t)}`);let e=process.platform==="win32",n=e?"where":"which",r={...process.env,PATH:Uvt(process.env.PATH)},o=Emr();try{let{stdout:i}=await o(n,[t],{timeout:5e3,env:r}),s=i.split(/\r?\n/).map(a=>a.trim()).filter(Boolean);return e?Omr(s):s[0]??null}catch{return null}}function Omr(t){let e=Pe("path"),n=t.filter(o=>!/\.(cmd|bat|ps1)$/i.test(o)&&e.win32.extname(o)!=="");return n.find(o=>/\.exe$/i.test(o))??n[0]??null}async function qye(t){let e=Pe("fs"),n=await e.promises.stat(t).catch(()=>null);if(!n||!n.isFile())return`No file at ${t}.`;if(process.platform!=="win32")try{await e.promises.access(t,e.constants.X_OK)}catch{return`${t} is not executable. chmod +x and try again.`}return null}var Mmr,oW=b(()=>{aP();$n();Mmr=/^[A-Za-z0-9._+-]+$/});var tGt,xl,iW,Kye=b(()=>{yt();hl();pe();aP();oW();tGt=require("obsidian"),xl=L(B());Hl();iW=({binaryName:t,placeholder:e,initialPath:n,hasPersistedPath:r=n.trim()!=="",notFoundHint:o,onSave:i,onClear:s,persistOnAutoDetect:a=!1,detect:l,searchedDirs:c})=>{let[u,d]=xl.default.useState(n),[f,p]=xl.default.useState(null),[m,h]=xl.default.useState([]),[g,v]=xl.default.useState(!1);xl.default.useEffect(()=>{d(n)},[n]);let y=xl.default.useCallback(async()=>{let k=u.trim();if(!k){p("Path is required.");return}let T=await i(k);if(T){p(T);return}p(null),h([])},[u,i]),w=xl.default.useCallback(async()=>{if(!(g||!s)){v(!0),p(null);try{await s()}finally{v(!1)}}},[g,s]),_=xl.default.useCallback(async()=>{if(!g){v(!0),p(null),h([]);try{let k=l?await l():await rW(t);if(!k){p(o??`${t} not found on PATH. Install it or paste a custom path manually.`),h((c??(l?void 0:L9))?.()??[]);return}if(d(k),a){let T=await i(k);if(T){p(T);return}}new tGt.Notice(`Found ${t} at ${k}`)}catch(k){H(`[AgentMode] auto-detect ${t} failed`,k),p(k instanceof Error?k.message:String(k))}finally{v(!1)}}},[t,g,o,i,a,l,c]),S=u.trim()===n.trim(),I=!!s&&r&&S,C=!S||n.trim()==="";return xl.default.createElement("div",{className:"tw-flex tw-w-full tw-flex-col tw-gap-2"},xl.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},xl.default.createElement(Ir,{type:"text",placeholder:e,value:u,onChange:k=>d(k.target.value),className:"tw-flex-1"}),xl.default.createElement(oe,{variant:"secondary",size:"default",onClick:xn(_),disabled:g},"Auto-detect"),I?xl.default.createElement(oe,{variant:"destructive",size:"default",onClick:xn(w),disabled:g},"Clear"):C?xl.default.createElement(oe,{variant:"default",size:"default",onClick:xn(y),disabled:g},"Apply"):null),f&&xl.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1 tw-text-sm tw-text-error"},xl.default.createElement("span",null,f),m.length>0&&xl.default.createElement("div",{className:"tw-text-muted"},xl.default.createElement("span",null,"Searched:"),xl.default.createElement("ul",{className:"tw-my-0 tw-pl-4"},m.map(k=>xl.default.createElement("li",{key:k},k))))))}});function L9e(t){return t.kind==="ready"?{label:"Ready",variant:"success",showCheck:!0}:t.kind==="checking"?{label:"Checking\u2026",variant:"outline"}:t.kind==="incompatible"?{label:"Incompatible version",variant:"destructive",title:t.message}:t.kind==="error"?{label:"Error",variant:"destructive",title:t.message}:null}var sW,Nmr,nGt,Gye,rGt,$9e=b(()=>{pm();Re();sW=L(B());Nmr={ready:{label:"Ready",variant:"success",showCheck:!0},absent:{label:"Not set up",variant:"outline"},incompatible:{label:"Update required",variant:"destructive",showAlert:!0},checking:{label:"Checking\u2026",variant:"outline"},error:{label:"Error",variant:"destructive"}},nGt=({spec:t})=>sW.default.createElement(ei,{variant:t.variant,className:"tw-gap-1",title:t.title},t.showCheck&&sW.default.createElement(Hr,{"aria-hidden":!0,className:"tw-size-icon-xs"}),t.showAlert&&sW.default.createElement(Wr,{"aria-hidden":!0,className:"tw-size-icon-xs"}),t.label),Gye=({state:t})=>{let e=L9e(t);return e?sW.default.createElement(nGt,{spec:e}):null},rGt=({state:t})=>sW.default.createElement(nGt,{spec:Nmr[t.kind]})});var Bm,aW,lW,Zye,hE,s$=b(()=>{$9e();yt();Re();Bm=L(B()),aW="copilot-config-modal",lW=({title:t,state:e,warning:n,children:r,footer:o,onClose:i})=>Bm.default.createElement("div",{className:"tw-flex tw-flex-col"},Bm.default.createElement("div",{className:"tw-flex tw-flex-wrap tw-items-center tw-gap-2 tw-px-4 tw-pb-3 tw-pt-4"},Bm.default.createElement("h3",{className:"tw-m-0 tw-text-ui-medium tw-font-semibold tw-leading-tight tw-text-normal"},t),Bm.default.createElement(rGt,{state:e})),(e.kind==="incompatible"||e.kind==="error")&&n&&Bm.default.createElement("div",{className:"tw-px-4 tw-pb-3"},n),r,Bm.default.createElement("div",{className:"copilot-divider-t tw-flex tw-justify-end tw-gap-2 tw-bg-secondary tw-px-4 tw-py-3"},o??Bm.default.createElement(oe,{variant:"default",size:"default",onClick:i},"Done"))),Zye=({state:t,detail:e,action:n})=>t.kind!=="incompatible"&&t.kind!=="error"?null:Bm.default.createElement("div",{role:"alert",className:"tw-flex tw-items-start tw-gap-2 tw-rounded-md tw-border tw-border-solid tw-bg-callout-warning/20 tw-p-3 tw-text-sm tw-border-warning/40"},Bm.default.createElement(Wr,{"aria-hidden":!0,className:"tw-mt-0.5 tw-size-4 tw-shrink-0 tw-text-warning"}),Bm.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-flex-col tw-gap-2"},Bm.default.createElement("p",{className:"tw-my-0 tw-break-words tw-text-normal"},e?`${t.message} ${e}`:t.message),n)),hE=({title:t,children:e})=>Bm.default.createElement("div",{className:"copilot-divider-t tw-flex tw-flex-col tw-gap-2 tw-p-4"},t&&Bm.default.createElement("div",{className:"tw-text-sm tw-font-medium"},t),e)});var zm,Rmr,cW,uW,D9e=b(()=>{yt();pe();zm=L(B()),Rmr=1400,cW=({command:t,shell:e,action:n})=>{let[r,o]=zm.default.useState(!1),i=zm.default.useRef(null),s=(e??(process.platform==="win32"?"powershell":"posix"))==="powershell"?"PS> ":"$ ";zm.default.useEffect(()=>()=>{i.current!==null&&window.clearTimeout(i.current)},[]);let a=zm.default.useCallback(()=>{navigator.clipboard.writeText(t).catch(l=>{H("[AgentMode] copy setup command failed",l)}),o(!0),i.current!==null&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>o(!1),Rmr)},[t]);return zm.default.createElement("div",{className:"tw-flex tw-items-start tw-gap-2 tw-rounded-md tw-bg-secondary tw-p-2"},zm.default.createElement("code",{className:"tw-min-w-0 tw-flex-1 tw-break-all tw-bg-transparent tw-px-0 tw-py-0.5 tw-text-xs tw-leading-5"},zm.default.createElement("span",{className:"tw-select-none tw-text-faint"},s),t),zm.default.createElement("div",{className:"tw-flex tw-shrink-0 tw-items-center tw-gap-1"},zm.default.createElement(oe,{variant:"ghost",size:"sm",onClick:a},r?"Copied":"Copy"),n))},uW=({index:t,title:e,children:n})=>zm.default.createElement("div",{className:"tw-flex tw-items-start tw-gap-3"},zm.default.createElement("span",{className:"tw-flex tw-size-5 tw-shrink-0 tw-items-center tw-justify-center tw-rounded-full tw-bg-modifier-hover tw-text-xs tw-font-medium tw-leading-5 tw-text-normal"},t),zm.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-flex-col tw-gap-2"},zm.default.createElement("div",{className:"tw-text-sm tw-font-medium tw-leading-5"},e),n))});var Td,Lmr,oGt,iGt=b(()=>{wNe();eGt();Kye();s$();D9e();yt();Td=L(B()),Lmr=process.platform==="win32"?"/absolute/path/to/claude.exe":"/absolute/path/to/claude",oGt=({state:t,binaryPath:e,hasBinaryPathOverride:n,onSavePath:r,onClearPath:o,detect:i,searchedDirs:s,auth:a,onClose:l})=>Td.default.createElement(lW,{title:"Configure Claude",state:t,warning:Td.default.createElement(Zye,{state:t,detail:QKt(t)}),onClose:l},Td.default.createElement(hE,{title:"Claude Code binary"},Td.default.createElement("p",{className:"tw-my-0 tw-text-sm tw-text-muted"},"Copilot runs the ",Td.default.createElement("code",null,"claude")," CLI on this machine. Auto-detect checks the usual install locations."),Td.default.createElement(iW,{binaryName:"claude",placeholder:Lmr,initialPath:e,hasPersistedPath:n,notFoundHint:"claude not found in known install locations. Run the install command below, then click Auto-detect again.",onSave:r,onClear:o,persistOnAutoDetect:!0,detect:i,searchedDirs:s})),Td.default.createElement(hE,{title:"Don't have it yet?"},Td.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Td.default.createElement(uW,{index:1,title:"Install it"},Td.default.createElement(cW,{command:Lae})),Td.default.createElement(uW,{index:2,title:"Sign in"},Td.default.createElement(cW,{command:Wvt,action:t.kind==="ready"&&a.status?.signedIn===!1?a.signingIn&&a.url?Td.default.createElement(oe,{asChild:!0,variant:"secondary",size:"sm"},Td.default.createElement("a",{href:a.url,target:"_blank",rel:"noopener noreferrer"},"Open sign-in page")):Td.default.createElement(oe,{variant:"secondary",size:"sm",onClick:a.onSignIn,disabled:a.signingIn},a.signingIn?"Signing in\u2026":"Sign in"):void 0}),Td.default.createElement("p",{className:"tw-my-0 tw-text-sm tw-text-muted"},"Copilot inherits whatever credentials the Claude Code CLI holds \u2014 there is no key to paste here.")))))});function Xye(t,e){let n=xt(),r=a$.default.useRef(n);r.current=n;let o=t.auth,i=a$.default.useCallback(c=>o?$mr(o,c):()=>{},[o]),s=a$.default.useCallback(()=>o?dW(o):lGt,[o]),a=a$.default.useSyncExternalStore(i,s,s);a$.default.useEffect(()=>{if(!o||dW(o).signingIn)return;let c=sGt(o);o.getStatus(r.current).then(u=>aGt(o,u,c),u=>{H("[AgentMode] auth status probe failed",u),aGt(o,{signedIn:!1},c)})},[o,e]);let l=a$.default.useCallback(()=>{!o||dW(o).signingIn||(sGt(o),xX(o,{signingIn:!0,url:null}),new Yye.Notice(`Opening your browser to sign in to ${t.displayName}\u2026`),o.signIn(r.current,{onUrl:c=>{dW(o).signingIn&&xX(o,{url:c})}}).then(c=>{xX(o,{status:c}),new Yye.Notice(c.signedIn?`Signed in to ${t.displayName}${c.label?` as ${c.label}`:""}.`:"Sign-in didn't complete. Please try again.")}).catch(c=>{H("[AgentMode] sign-in failed",c),new Yye.Notice(`Sign-in to ${t.displayName} failed. Please try again.`)}).finally(()=>{xX(o,{signingIn:!1,url:null})}))},[o,t.displayName]);return{...a,signIn:l}}var Yye,a$,lGt,cGt,Jye,F9e,dW,$mr,xX,sGt,aGt,U9e=b(()=>{pe();Se();Yye=require("obsidian"),a$=L(B()),lGt=Object.freeze({status:null,signingIn:!1,url:null}),cGt=new WeakMap,Jye=new WeakMap,F9e=new WeakMap,dW=t=>cGt.get(t)??lGt,$mr=(t,e)=>{let n=Jye.get(t)??new Set;return n.add(e),Jye.set(t,n),()=>{n.delete(e),n.size===0&&Jye.delete(t)}},xX=(t,e)=>{let n=dW(t),r=Object.freeze({...n,...e});n.status===r.status&&n.signingIn===r.signingIn&&n.url===r.url||(cGt.set(t,r),Jye.get(t)?.forEach(o=>o()))},sGt=t=>{let e=(F9e.get(t)??0)+1;return F9e.set(t,e),e},aGt=(t,e,n)=>{F9e.get(t)!==n||dW(t).signingIn||xX(t,{status:e})}});var j9e,gE,Dmr,Qye,uGt=b(()=>{iGt();s$();U9e();Kj();Se();oW();j9e=require("obsidian"),gE=L(B());eve();Dmr=({descriptor:t,onClose:e})=>{let n=xt(),r=gE.default.useCallback(()=>B9e(n),[n]),o=gE.default.useSyncExternalStore(z9e,r),i=n.agentMode?.claudeCli?.path,s=t.getResolvedBinaryPath(n)??i??"",a=Xye(t,s);gE.default.useEffect(()=>{SX(Y(),!0)},[]);let l=gE.default.useCallback(async u=>{let d=await qye(u);return d||(En(f=>({agentMode:{...f.agentMode,claudeCli:{path:u}}})),await SX(Y(),!0),new j9e.Notice("Claude CLI path saved."),null)},[]),c=gE.default.useCallback(()=>{En(u=>({agentMode:{...u.agentMode,claudeCli:void 0}})),new j9e.Notice("Claude CLI override cleared. Auto-detection will be used.")},[]);return gE.default.createElement(oGt,{state:o,binaryPath:s,hasBinaryPathOverride:!!i,onSavePath:l,onClearPath:c,detect:()=>Promise.resolve(dGt()),searchedDirs:fGt,auth:{status:a.status,onSignIn:a.signIn,signingIn:a.signingIn,url:a.url},onClose:e})},Qye=class extends Uy{constructor(n,r){super(n,void 0,aW);this.descriptor=r}renderContent(n){return gE.default.createElement(Dmr,{descriptor:this.descriptor,onClose:n})}}});var H9e,Fmr,pGt,mGt=b(()=>{H9e=L(B()),Fmr=t=>H9e.createElement("svg",{fill:"currentColor",role:"img",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",...t},H9e.createElement("path",{d:"m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z"})),pGt=Fmr});function gGt(){return hGt+=1,`row-${hGt}`}function Umr(t){return t?Object.entries(t).map(([e,n])=>({id:gGt(),name:e,value:n})):[]}function jmr(t){let e={};for(let n of t){let r=n.name.trim();r&&rK.test(r)&&(e[r]=n.value)}return Object.keys(e).length>0?e:void 0}var el,hGt,Bmr,fW,tve=b(()=>{yt();hl();Se();AC();Re();el=L(B()),hGt=0;Bmr=400,fW=({value:t,onChange:e,backendDisplayName:n,hintExamples:r})=>{let[o,i]=el.default.useState(()=>Umr(t)),s=el.default.useRef(e);el.default.useEffect(()=>{s.current=e},[e]);let a=el.default.useMemo(()=>Ba(m=>{s.current(jmr(m))},Bmr),[]);el.default.useEffect(()=>()=>a.flush(),[a]);let l=m=>{i(m),a(m)},c=(m,h)=>{l(o.map(g=>g.id===m?{...g,...h}:g))},u=m=>{l(o.filter(h=>h.id!==m))},d=()=>{i(m=>[...m,{id:gGt(),name:"",value:""}])},[f,p]=r;return el.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2 tw-py-4"},el.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1"},el.default.createElement("div",{className:"tw-text-sm tw-font-medium tw-leading-none"},"Environment variables"),el.default.createElement("div",{className:"tw-text-xs tw-text-muted"},"Set values for ",n,", like ",el.default.createElement("code",null,f)," or ",el.default.createElement("code",null,p),".")),el.default.createElement("div",{className:"tw-flex tw-w-full tw-flex-col tw-gap-2"},o.map(m=>{let h=m.name.trim(),g=h.length>0&&!rK.test(h);return el.default.createElement("div",{key:m.id,className:"tw-flex tw-flex-col tw-gap-1"},el.default.createElement("div",{className:"tw-flex tw-items-start tw-gap-2"},el.default.createElement(Ir,{type:"text",placeholder:f,value:m.name,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",className:"tw-flex-1 tw-font-mono","aria-invalid":g||void 0,onChange:v=>c(m.id,{name:v.target.value})}),el.default.createElement(Ir,{type:"text",placeholder:"value",value:m.value,spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",className:"tw-flex-[2] tw-font-mono",onChange:v=>c(m.id,{value:v.target.value})}),el.default.createElement(oe,{variant:"ghost",size:"icon","aria-label":"Remove variable",onClick:()=>u(m.id)},el.default.createElement(Ts,{className:"tw-size-icon-s"}))),g&&el.default.createElement("div",{className:"tw-text-xs tw-text-error"},"Name must start with a letter or underscore and contain only letters, digits, and underscores."))}),el.default.createElement(oe,{variant:"ghost2",size:"sm",className:"tw-self-start",onClick:d},el.default.createElement(zs,{className:"tw-size-icon-xs"}),"Add variable")))}});var Cv,If,xI=b(()=>{Cv=L(B());De();If=Cv.forwardRef(({className:t,value:e,...n},r)=>{let o=Cv.useRef(null),i=Cv.useCallback(()=>{let a=o.current;if(a){a.setCssProps({"--copilot-autosize-height":"auto"});let l=Math.min(a.scrollHeight,300);a.setCssProps({"--copilot-autosize-height":`${l}px`})}},[]);Cv.useLayoutEffect(()=>{i()},[e,i]),Cv.useEffect(()=>(i(),window.addEventListener("resize",i),()=>window.removeEventListener("resize",i)),[i]);let s=a=>{o.current=a,typeof r=="function"?r(a):r&&(r.current=a)};return Cv.createElement("textarea",{className:J("tw-min-w-fit tw-resize-y tw-overflow-auto tw-border-solid","tw-flex tw-max-h-[300px] tw-min-h-[60px] tw-w-full tw-rounded-md tw-border tw-bg-transparent tw-px-3 tw-py-2 tw-text-base tw-shadow-sm placeholder:tw-text-muted focus-visible:tw-outline-none focus-visible:tw-ring-1 focus-visible:tw-ring-ring disabled:tw-cursor-not-allowed disabled:tw-opacity-50 md:tw-text-sm","tw-h-[var(--copilot-autosize-height,_auto)]",t),value:e,ref:s,onChange:a=>{i(),n.onChange?.(a)},onInput:i,onCompositionEnd:i,onPaste:()=>{window.setTimeout(i,0)},...n})});If.displayName="Textarea"});function CX(t,[e,n]){return Math.min(n,Math.max(e,t))}var W9e=b(()=>{});function l$(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var yGt=b(()=>{});function vGt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function V9e(...t){return e=>{let n=!1,r=t.map(o=>{let i=vGt(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():vGt(t[o],null)}}}}function c$(...t){return wGt.useCallback(V9e(...t),t)}var wGt,q9e=b(()=>{wGt=L(B(),1)});function _Gt(t,e=[]){let n=[];function r(i,s){let a=SI.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=SI.useMemo(()=>m,Object.values(m));return(0,bGt.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=SI.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>SI.createContext(s));return function(a){let l=a?.[t]||i;return SI.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,zmr(o,...e)]}function zmr(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return SI.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var SI,bGt,xGt=b(()=>{SI=L(B(),1),bGt=L(Mt(),1)});var SGt,nve,K9e=b(()=>{SGt=L(B(),1),nve=globalThis?.document?SGt.useLayoutEffect:()=>{}});function CGt({prop:t,defaultProp:e,onChange:n=()=>{},caller:r}){let[o,i,s]=Wmr({defaultProp:e,onChange:n}),a=t!==void 0,l=a?t:o;{let u=kv.useRef(t!==void 0);kv.useEffect(()=>{let d=u.current;d!==a&&console.warn(`${r} is changing from ${d?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=a},[a,r])}let c=kv.useCallback(u=>{if(a){let d=Vmr(u)?u(t):u;d!==t&&s.current?.(d)}else i(u)},[a,t,i,s]);return[l,c]}function Wmr({defaultProp:t,onChange:e}){let[n,r]=kv.useState(t),o=kv.useRef(n),i=kv.useRef(e);return Hmr(()=>{i.current=e},[e]),kv.useEffect(()=>{o.current!==n&&(i.current?.(n),o.current=n)},[n,o]),[n,r,i]}function Vmr(t){return typeof t=="function"}var kv,rve,Hmr,BZo,kGt=b(()=>{kv=L(B(),1);K9e();rve=L(B(),1),Hmr=kv[" useInsertionEffect ".trim().toString()]||nve;BZo=Symbol("RADIX:SYNC_STATE")});function IGt(t){let e=ove.useContext(Kmr);return t||e||"ltr"}var ove,qmr,Kmr,TGt=b(()=>{ove=L(B(),1),qmr=L(Mt(),1),Kmr=ove.createContext(void 0)});function PGt(t){let e=ive.useRef({value:t,previous:t});return ive.useMemo(()=>(e.current.value!==t&&(e.current.previous=e.current.value,e.current.value=t),e.current.previous),[t])}var ive,AGt=b(()=>{ive=L(B(),1)});function MGt(t){let[e,n]=EGt.useState(void 0);return nve(()=>{if(t){n({width:t.offsetWidth,height:t.offsetHeight});let r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;let i=o[0],s,a;if("borderBoxSize"in i){let l=i.borderBoxSize,c=Array.isArray(l)?l[0]:l;s=c.inlineSize,a=c.blockSize}else s=t.offsetWidth,a=t.offsetHeight;n({width:s,height:a})});return r.observe(t,{box:"border-box"}),()=>r.unobserve(t)}else n(void 0)},[t]),e}var EGt,OGt=b(()=>{EGt=L(B(),1);K9e()});function NGt(t){let e=Gmr(t),n=Zc.forwardRef((r,o)=>{let{children:i,...s}=r,a=Zc.Children.toArray(i),l=a.find(Ymr);if(l){let c=l.props.children,u=a.map(d=>d===l?Zc.Children.count(c)>1?Zc.Children.only(null):Zc.isValidElement(c)?c.props.children:null:d);return(0,sve.jsx)(e,{...s,ref:o,children:Zc.isValidElement(c)?Zc.cloneElement(c,void 0,u):null})}return(0,sve.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function Gmr(t){let e=Zc.forwardRef((n,r)=>{let{children:o,...i}=n;if(Zc.isValidElement(o)){let s=Xmr(o),a=Jmr(i,o.props);return o.type!==Zc.Fragment&&(a.ref=r?V9e(r,s):s),Zc.cloneElement(o,a)}return Zc.Children.count(o)>1?Zc.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}function Ymr(t){return Zc.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===Zmr}function Jmr(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function Xmr(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Zc,sve,Zmr,RGt=b(()=>{Zc=L(B(),1);q9e();sve=L(Mt(),1);Zmr=Symbol("radix.slottable")});var LGt,Qmr,$Gt,ehr,pW,DGt=b(()=>{LGt=L(B(),1),Qmr=L(Es(),1);RGt();$Gt=L(Mt(),1),ehr=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],pW=ehr.reduce((t,e)=>{let n=NGt(`Primitive.${e}`),r=LGt.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,$Gt.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{})});function lhr(t=[],e,n){let r=[...t];return r[n]=e,r.sort((o,i)=>o-i)}function JGt(t,e,n){let i=100/(n-e)*(t-e);return CX(i,[0,100])}function chr(t,e){return e>2?`Value ${t+1} of ${e}`:e===2?["Minimum","Maximum"][t]:void 0}function uhr(t,e){if(t.length===1)return 0;let n=t.map(o=>Math.abs(o-e)),r=Math.min(...n);return n.indexOf(r)}function dhr(t,e,n){let r=t/2,i=J9e([0,50],[0,r]);return(r-i(e)*n)*n}function fhr(t){return t.slice(0,-1).map((e,n)=>t[n+1]-e)}function phr(t,e){if(e>0){let n=fhr(t);return Math.min(...n)>=e}return!0}function J9e(t,e){return n=>{if(t[0]===t[1]||e[0]===e[1])return e[0];let r=(e[1]-e[0])/(t[1]-t[0]);return e[0]+r*(n-t[0])}}function mhr(t){return(String(t).split(".")[1]||"").length}function hhr(t,e){let n=Math.pow(10,e);return Math.round(t*n)/n}var is,Yc,FGt,UGt,jGt,mW,G9e,thr,nhr,BGt,a7o,rhr,ave,zGt,HGt,WGt,ohr,ihr,VGt,qGt,KGt,Z9e,GGt,Y9e,ZGt,shr,ahr,YGt,kX,lve,cve,uve,X9e=b(()=>{"use client";is=L(B(),1);W9e();yGt();q9e();xGt();kGt();TGt();AGt();OGt();DGt();nue();Yc=L(Mt(),1),FGt=["PageUp","PageDown"],UGt=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],jGt={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},mW="Slider",[G9e,thr,nhr]=Cj(mW),[BGt,a7o]=_Gt(mW,[nhr]),[rhr,ave]=BGt(mW),zGt=is.forwardRef((t,e)=>{let{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:a=!1,minStepsBetweenThumbs:l=0,defaultValue:c=[r],value:u,onValueChange:d=()=>{},onValueCommit:f=()=>{},inverted:p=!1,form:m,...h}=t,g=is.useRef(new Set),v=is.useRef(0),w=s==="horizontal"?ohr:ihr,[_=[],S]=CGt({prop:u,defaultProp:c,onChange:E=>{[...g.current][v.current]?.focus(),d(E)}}),I=is.useRef(_);function C(E){let O=uhr(_,E);P(E,O)}function k(E){P(E,v.current)}function T(){let E=I.current[v.current];_[v.current]!==E&&f(_)}function P(E,O,{commit:$}={commit:!1}){let U=mhr(i),V=hhr(Math.round((E-r)/i)*i+r,U),K=CX(V,[r,o]);S((se=[])=>{let le=lhr(se,K,O);if(phr(le,l*i)){v.current=le.indexOf(K);let Q=String(le)!==String(se);return Q&&$&&f(le),Q?le:se}else return se})}return(0,Yc.jsx)(rhr,{scope:t.__scopeSlider,name:n,disabled:a,min:r,max:o,valueIndexToChangeRef:v,thumbs:g.current,values:_,orientation:s,form:m,children:(0,Yc.jsx)(G9e.Provider,{scope:t.__scopeSlider,children:(0,Yc.jsx)(G9e.Slot,{scope:t.__scopeSlider,children:(0,Yc.jsx)(w,{"aria-disabled":a,"data-disabled":a?"":void 0,...h,ref:e,onPointerDown:l$(h.onPointerDown,()=>{a||(I.current=_)}),min:r,max:o,inverted:p,onSlideStart:a?void 0:C,onSlideMove:a?void 0:k,onSlideEnd:a?void 0:T,onHomeKeyDown:()=>!a&&P(r,0,{commit:!0}),onEndKeyDown:()=>!a&&P(o,_.length-1,{commit:!0}),onStepKeyDown:({event:E,direction:O})=>{if(!a){let V=FGt.includes(E.key)||E.shiftKey&&UGt.includes(E.key)?10:1,K=v.current,se=_[K],le=i*V*O;P(se+le,K,{commit:!0})}}})})})})});zGt.displayName=mW;[HGt,WGt]=BGt(mW,{startEdge:"left",endEdge:"right",size:"width",direction:1}),ohr=is.forwardRef((t,e)=>{let{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:a,onSlideEnd:l,onStepKeyDown:c,...u}=t,[d,f]=is.useState(null),p=c$(e,w=>f(w)),m=is.useRef(void 0),h=IGt(o),g=h==="ltr",v=g&&!i||!g&&i;function y(w){let _=m.current||d.getBoundingClientRect(),S=[0,_.width],C=J9e(S,v?[n,r]:[r,n]);return m.current=_,C(w-_.left)}return(0,Yc.jsx)(HGt,{scope:t.__scopeSlider,startEdge:v?"left":"right",endEdge:v?"right":"left",direction:v?1:-1,size:"width",children:(0,Yc.jsx)(VGt,{dir:h,"data-orientation":"horizontal",...u,ref:p,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:w=>{let _=y(w.clientX);s?.(_)},onSlideMove:w=>{let _=y(w.clientX);a?.(_)},onSlideEnd:()=>{m.current=void 0,l?.()},onStepKeyDown:w=>{let S=jGt[v?"from-left":"from-right"].includes(w.key);c?.({event:w,direction:S?-1:1})}})})}),ihr=is.forwardRef((t,e)=>{let{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:a,onStepKeyDown:l,...c}=t,u=is.useRef(null),d=c$(e,u),f=is.useRef(void 0),p=!o;function m(h){let g=f.current||u.current.getBoundingClientRect(),v=[0,g.height],w=J9e(v,p?[r,n]:[n,r]);return f.current=g,w(h-g.top)}return(0,Yc.jsx)(HGt,{scope:t.__scopeSlider,startEdge:p?"bottom":"top",endEdge:p?"top":"bottom",size:"height",direction:p?1:-1,children:(0,Yc.jsx)(VGt,{"data-orientation":"vertical",...c,ref:d,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:h=>{let g=m(h.clientY);i?.(g)},onSlideMove:h=>{let g=m(h.clientY);s?.(g)},onSlideEnd:()=>{f.current=void 0,a?.()},onStepKeyDown:h=>{let v=jGt[p?"from-bottom":"from-top"].includes(h.key);l?.({event:h,direction:v?-1:1})}})})}),VGt=is.forwardRef((t,e)=>{let{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:a,onStepKeyDown:l,...c}=t,u=ave(mW,n);return(0,Yc.jsx)(pW.span,{...c,ref:e,onKeyDown:l$(t.onKeyDown,d=>{d.key==="Home"?(s(d),d.preventDefault()):d.key==="End"?(a(d),d.preventDefault()):FGt.concat(UGt).includes(d.key)&&(l(d),d.preventDefault())}),onPointerDown:l$(t.onPointerDown,d=>{let f=d.target;f.setPointerCapture(d.pointerId),d.preventDefault(),u.thumbs.has(f)?f.focus():r(d)}),onPointerMove:l$(t.onPointerMove,d=>{d.target.hasPointerCapture(d.pointerId)&&o(d)}),onPointerUp:l$(t.onPointerUp,d=>{let f=d.target;f.hasPointerCapture(d.pointerId)&&(f.releasePointerCapture(d.pointerId),i(d))})})}),qGt="SliderTrack",KGt=is.forwardRef((t,e)=>{let{__scopeSlider:n,...r}=t,o=ave(qGt,n);return(0,Yc.jsx)(pW.span,{"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation,...r,ref:e})});KGt.displayName=qGt;Z9e="SliderRange",GGt=is.forwardRef((t,e)=>{let{__scopeSlider:n,...r}=t,o=ave(Z9e,n),i=WGt(Z9e,n),s=is.useRef(null),a=c$(e,s),l=o.values.length,c=o.values.map(f=>JGt(f,o.min,o.max)),u=l>1?Math.min(...c):0,d=100-Math.max(...c);return(0,Yc.jsx)(pW.span,{"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0,...r,ref:a,style:{...t.style,[i.startEdge]:u+"%",[i.endEdge]:d+"%"}})});GGt.displayName=Z9e;Y9e="SliderThumb",ZGt=is.forwardRef((t,e)=>{let n=thr(t.__scopeSlider),[r,o]=is.useState(null),i=c$(e,a=>o(a)),s=is.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return(0,Yc.jsx)(shr,{...t,ref:i,index:s})}),shr=is.forwardRef((t,e)=>{let{__scopeSlider:n,index:r,name:o,...i}=t,s=ave(Y9e,n),a=WGt(Y9e,n),[l,c]=is.useState(null),u=c$(e,y=>c(y)),d=l?s.form||!!l.closest("form"):!0,f=MGt(l),p=s.values[r],m=p===void 0?0:JGt(p,s.min,s.max),h=chr(r,s.values.length),g=f?.[a.size],v=g?dhr(g,m,a.direction):0;return is.useEffect(()=>{if(l)return s.thumbs.add(l),()=>{s.thumbs.delete(l)}},[l,s.thumbs]),(0,Yc.jsxs)("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${m}% + ${v}px)`},children:[(0,Yc.jsx)(G9e.ItemSlot,{scope:t.__scopeSlider,children:(0,Yc.jsx)(pW.span,{role:"slider","aria-label":t["aria-label"]||h,"aria-valuemin":s.min,"aria-valuenow":p,"aria-valuemax":s.max,"aria-orientation":s.orientation,"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,tabIndex:s.disabled?void 0:0,...i,ref:u,style:p===void 0?{display:"none"}:t.style,onFocus:l$(t.onFocus,()=>{s.valueIndexToChangeRef.current=r})})}),d&&(0,Yc.jsx)(YGt,{name:o??(s.name?s.name+(s.values.length>1?"[]":""):void 0),form:s.form,value:p},r)]})});ZGt.displayName=Y9e;ahr="RadioBubbleInput",YGt=is.forwardRef(({__scopeSlider:t,value:e,...n},r)=>{let o=is.useRef(null),i=c$(o,r),s=PGt(e);return is.useEffect(()=>{let a=o.current;if(!a)return;let l=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(l,"value").set;if(s!==e&&u){let d=new Event("input",{bubbles:!0});u.call(a,e),a.dispatchEvent(d)}},[s,e]),(0,Yc.jsx)(pW.input,{style:{display:"none"},...n,ref:i,defaultValue:e})});YGt.displayName=ahr;kX=zGt,lve=KGt,cve=GGt,uve=ZGt});var u$,Q9e,QGt=b(()=>{u$=L(B());X9e();De();Q9e=u$.forwardRef(({className:t,...e},n)=>u$.createElement(kX,{ref:n,className:J("tw-relative tw-flex tw-w-full tw-touch-none tw-select-none tw-items-center",t),...e},u$.createElement(lve,{className:"tw-relative tw-h-1.5 tw-w-full tw-grow tw-overflow-hidden tw-rounded-full tw-border tw-border-solid tw-bg-interactive-accent/20 tw-border-interactive-accent/30"},u$.createElement(cve,{className:"tw-absolute tw-h-full tw-bg-interactive-accent"})),u$.createElement(uve,{className:"tw-block tw-size-4 tw-rounded-full tw-border tw-bg-toggle-thumb tw-shadow tw-transition-colors focus-visible:tw-outline-none focus-visible:tw-ring-1 focus-visible:tw-ring-ring disabled:tw-pointer-events-none disabled:tw-opacity-50"})));Q9e.displayName=kX.displayName});function e9t({value:t,onChange:e,min:n,max:r,step:o,disabled:i,className:s,suffix:a}){let[l,c]=(0,hW.useState)(null),u=l??t;return hW.default.createElement("div",{className:J("tw-flex tw-items-center tw-gap-4",s)},hW.default.createElement(Q9e,{value:[u],onValueChange:([d])=>c(d),onValueCommit:([d])=>{c(null),e?.(d)},min:n,max:r,step:o,disabled:i,className:"tw-flex-1"}),hW.default.createElement("div",{className:"tw-min-w-[60px] tw-text-right tw-text-sm tw-tabular-nums"},u>=1e3?`${u%1e3===0?u/1e3:(u/1e3).toFixed(1)}k`:u,a))}var hW,t9t=b(()=>{hW=L(B());De();QGt()});function _o(t){let{title:e,description:n,className:r,disabled:o}=t,i="onChange"in t?t.onChange:void 0,s=(0,Jc.useMemo)(()=>{if(i)return Ba(l=>{i(l)},1e3)},[i]),a=()=>{switch(t.type){case"text":case"number":return Jc.default.createElement(Ir,{type:t.type,defaultValue:t.value,onChange:l=>{s?.(l.target.value)},placeholder:t.placeholder,disabled:o,className:"tw-w-full sm:tw-w-[200px]"});case"password":return Jc.default.createElement(Yj,{value:t.value!==void 0?String(t.value):void 0,onChange:l=>{s?.(l)},placeholder:t.placeholder,disabled:o,className:"tw-w-full sm:tw-w-[200px]"});case"textarea":return Jc.default.createElement(If,{defaultValue:t.value,onChange:l=>{s?.(l.target.value)},placeholder:t.placeholder,rows:t.rows||3,disabled:o,className:"tw-min-h-[80px] tw-w-full sm:tw-w-[300px]"});case"switch":return Jc.default.createElement(fp,{checked:t.checked,onCheckedChange:t.onCheckedChange,disabled:o});case"select":return Jc.default.createElement("div",{className:"tw-group tw-relative tw-w-full sm:tw-w-[200px]"},Jc.default.createElement("select",{value:t.value?.toString(),onChange:l=>t.onChange?.(l.target.value),disabled:o,className:J("tw-w-full tw-appearance-none","tw-flex tw-h-9 tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-dropdown tw-px-3 tw-py-1 tw-pr-8","tw-text-left tw-text-sm !tw-shadow tw-transition-colors","focus:tw-outline-none focus:tw-ring-1 focus:tw-ring-ring","disabled:tw-cursor-not-allowed disabled:tw-opacity-50","hover:tw-bg-interactive-hover hover:tw-text-normal")},t.placeholder&&Jc.default.createElement("option",{value:"",disabled:!0},t.placeholder),t.options.map(l=>Jc.default.createElement("option",{key:l.value,value:l.value.toString()},l.label))),Jc.default.createElement("div",{className:J("tw-pointer-events-none tw-absolute tw-inset-y-0 tw-right-0 tw-flex tw-items-center tw-pr-2","tw-transition-colors group-hover:[&>svg]:tw-text-normal",o&&"tw-opacity-50")},Jc.default.createElement(Bs,{className:"tw-size-4"})));case"slider":return Jc.default.createElement(e9t,{value:t.value||0,onChange:t.onChange,min:t.min,max:t.max,step:t.step,suffix:t.suffix,disabled:o,className:"tw-w-full sm:tw-w-[300px]"});case"custom":return t.children}};return Jc.default.createElement("div",{className:J("tw-flex tw-flex-col tw-items-start tw-justify-between tw-gap-4 tw-py-4 sm:tw-flex-row sm:tw-items-center","tw-w-full",r)},Jc.default.createElement("div",{className:"tw-w-full tw-space-y-1.5 sm:tw-w-[300px]"},Jc.default.createElement("div",{className:"tw-text-sm tw-font-medium tw-leading-none"},e),n&&Jc.default.createElement("div",{className:"tw-text-xs tw-text-muted"},n)),Jc.default.createElement("div",{className:"tw-w-full tw-flex-1 sm:tw-flex sm:tw-justify-end"},a()))}var Jc,Iv=b(()=>{Jc=L(B());De();hl();cde();xI();OP();Re();t9t();EEe()});var n9t,ghr,r9t,o9t=b(()=>{Iv();n9t=L(B()),ghr=[{label:"Auto",value:"auto"},{label:"Accept edits",value:"acceptEdits"},{label:"Bypass permissions",value:"bypassPermissions"}],r9t=({value:t,onChange:e})=>n9t.default.createElement(_o,{type:"select",title:"Auto mode permissions",description:"Auto lets Claude judge each request and still ask about risky ones, Accept edits auto-approves file edits only, and Bypass permissions skips every check.",value:t,options:ghr,onChange:n=>e(n)})});var gW,i9t,s9t=b(()=>{tve();o9t();Iv();Se();gW=L(B());eve();i9t=()=>{let t=xt();return gW.default.createElement(gW.default.Fragment,null,gW.default.createElement(r9t,{value:e8e(t),onChange:e=>dve({autoModePermission:e})}),gW.default.createElement(_o,{type:"switch",title:"Show extended thinking",description:"Stream the model's reasoning blocks during a turn. Increases token usage.",checked:!!t.agentMode?.backends?.claude?.enableThinking,onCheckedChange:e=>dve({enableThinking:e})}),gW.default.createElement(fW,{backendDisplayName:"Claude",value:t.agentMode?.backends?.claude?.envOverrides,onChange:e=>dve({envOverrides:e}),hintExamples:["CLAUDE_CONFIG_DIR","HTTPS_PROXY"]}))}});var a9t,t8e,fve,l9t=b(()=>{xNe();a9t=Object.freeze({managed:Object.freeze({kind:"checking",source:"managed"}),custom:Object.freeze({kind:"checking",source:"custom"})}),t8e=class{constructor(){this.states=new Map;this.inflight=new Map;this.listeners=new Set}get(e){return this.states.get(e.cacheKey)??a9t[e.source]}refresh(e,n={}){let r=this.inflight.get(e.cacheKey);if(r)return r;let o=this.states.get(e.cacheKey);if(!n.force&&o&&o.kind!=="checking")return Promise.resolve(o);this.set(e.cacheKey,a9t[e.source]);let i=_Ne(e.path,e.env,n.run).then(s=>s.kind==="supported"?{kind:"ready",source:e.source}:{...s,source:e.source}).catch(s=>({kind:"error",message:s instanceof Error?s.message:String(s)})).then(s=>(this.set(e.cacheKey,s),s)).finally(()=>this.inflight.delete(e.cacheKey));return this.inflight.set(e.cacheKey,i),i}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}set(e,n){this.states.set(e,n);for(let r of this.listeners)r()}},fve=new t8e});function e8e(t){return t.agentMode?.backends?.claude?.autoModePermission??"auto"}function dve(t){xC("claude",t)}function n8e(){let t=Pe("fs");return{homeDir:Pe("os").homedir(),platform:process.platform,env:process.env,fs:{existsSync:n=>t.existsSync(n),readFileSync:(n,r)=>t.readFileSync(n,r),readdirSync:n=>t.readdirSync(n)}}}function IX(t){let e=t.agentMode?.backends?.claude?.envOverrides;return e&&Object.keys(e).length>0?{...process.env,...e}:process.env}function d9t(t,e){let n=t.agentMode?.backends?.claude?.envOverrides,r=JSON.stringify(Object.entries(n??{}).sort(([i],[s])=>i.localeCompare(s))),o=t.agentMode?.claudeCli?.path?"custom":"managed";return{cacheKey:`${o}\0${e}\0${r}`,path:e,source:o,env:IX(t)}}function yW(t){return vNe({override:t.agentMode?.claudeCli?.path,...n8e()})}function dGt(){return vNe({override:void 0,...n8e()})}function fGt(){return jvt({override:void 0,...n8e()})}function B9e(t){let e=yW(t);return e?fve.get(d9t(t,e)):u9t}async function SX(t,e=!1){let n=yW(t);return n?fve.refresh(d9t(t,n),{force:e}):u9t}function z9e(t){return fve.subscribe(t)}function c9t(t){let e=Pe("path");return!e.isAbsolute(t)||!t.endsWith(".md")?!1:e.dirname(t).endsWith(e.join(".claude","plans"))}async function yhr(t,e){if(!e)return;let n=async()=>{let r=t.getState(),o=r?.model?.current;if(!o)return!1;if(o.effort===e||!r?.model?.availableModels.find(a=>a.baseModelId===o.baseModelId)?.effortOptions.some(a=>a.value===e))return!0;let s=vW.wire.effortConfigFor?.(o.baseModelId);if(!s)return!0;try{await t.setConfigOption(s.id,e)}catch(a){if(a instanceof da)return!0;W(`[AgentMode] could not apply default effort ${e}`,a)}return!0};await n()||await new Promise(r=>{let o=!1,i=()=>{o||(o=!0,s(),window.clearTimeout(a),r())},s=t.subscribe({onMessagesChanged:()=>{},onStatusChanged:()=>{},onModelChanged:()=>{n().then(l=>{l&&i()})}}),a=window.setTimeout(i,1e4)})}var u9t,pve,vW,eve=b(()=>{pe();$n();Se();ok();Hvt();wNe();Gvt();xNe();MUe();kUt();eHe();O9();Vye();_I();uGt();mGt();s9t();l9t();u9t=Object.freeze({kind:"absent"});pve={encode:t=>t.baseModelId,decode:t=>({selection:{baseModelId:t,effort:null},provider:"anthropic"}),effortConfigFor:t=>{let e=eme(Y().agentMode?.backends?.claude?.envOverrides);if(!e)return null;let n=e.find(r=>r.value===t);return n?Qpe(n,void 0):null}};vW={id:"claude",displayName:"Claude",Icon:pGt,selfHostable:!1,routesCopilotModels:!1,setupDescription:"Anthropic models, billed to your Claude Code subscription. Runs the claude CLI already on your machine.",skillsProjectDir:".claude/skills",crossDiscoveredAgents:[],restartOnManagedSkillsChange:!1,restartOnProviderConfigChange:!1,restartOnSystemPromptChange:!1,summarizesSessionTitle:!1,wire:pve,showModelDescriptions:!0,getEnabledModelEntries(t){return[..._de(t,"claude",e=>pve.decode(e))]},getInstallState(t){return B9e(t)},getResolvedBinaryPath(t){return yW(t)},subscribeInstallState(t,e){let n=zr((o,i)=>{(o.agentMode?.claudeCli?.path!==i.agentMode?.claudeCli?.path||o.agentMode?.backends?.claude?.envOverrides!==i.agentMode?.backends?.claude?.envOverrides)&&(e(),SX(i,!0))}),r=z9e(e);return()=>{n(),r()}},async onPluginLoad(){await SX(Y(),!0)},openInstallUI(t){new Qye(t.app,vW).open()},auth:{async getStatus(t){let e=yW(t);if(!e)return{signedIn:!1};let n=await $ae(e,IX(t));return{signedIn:n.loggedIn,label:n.label}},async signIn(t,e){let n=yW(t);if(!n)return{signedIn:!1};let r=await Kvt(n,IX(t),e).done;return{signedIn:r.loggedIn,label:r.label}}},isPlanModePlanFilePath(t){return c9t(t)},async applySelection(t,e,n){if((n?n.backendReportedCurrent?.baseModelId:t.getState()?.model?.current.baseModelId)!==e.baseModelId&&await t.applyModelWireId(pve.encode(e)),e.effort===null)return;let o=pve.effortConfigFor?.(e.baseModelId);if(o)try{await t.setConfigOption(o.id,e.effort)}catch(i){if(!(i instanceof da))throw i}},createBackendProcess(t){let e=yW(Y());if(!e)throw new Error(`Claude CLI not found. Install with: ${Lae}, or set agentMode.claudeCli.path in settings.`);return new tme({pathToClaudeCodeExecutable:e,app:t.app,clientVersion:t.clientVersion,descriptor:t.descriptor,getEnableThinking:()=>!!Y().agentMode?.backends?.claude?.enableThinking,getEnvOverrides:()=>Y().agentMode?.backends?.claude?.envOverrides,getManagedEnv:()=>nW(t.clientVersion,Hu(t.app)??""),checkAuth:async()=>(await $ae(e,IX(Y()))).loggedIn,checkCompatibility:()=>Yvt(e,IX(Y())),isPlanModePlanFilePath:c9t,getDefaultModelId:()=>Y().agentMode?.backends?.claude?.defaultModel?.baseModelId,getSystemPromptAppend:()=>sP()})},SettingsPanel:i9t,getModeMapping(){return{kind:"setMode",canonical:{default:"default",plan:"plan",auto:e8e(Y())}}},async applyInitialSessionConfig(t,e,n){let r=e.agentMode?.backends?.claude?.defaultModel?.effort??null,o=n?n.effort:r;await yhr(t,o??void 0)}}});var f9t=b(()=>{eve()});var ia,Tv,p9t,r8e=b(()=>{ia={authenticate:"authenticate",document_did_change:"document/didChange",document_did_close:"document/didClose",document_did_focus:"document/didFocus",document_did_open:"document/didOpen",document_did_save:"document/didSave",initialize:"initialize",logout:"logout",nes_accept:"nes/accept",nes_close:"nes/close",nes_reject:"nes/reject",nes_start:"nes/start",nes_suggest:"nes/suggest",providers_disable:"providers/disable",providers_list:"providers/list",providers_set:"providers/set",session_cancel:"session/cancel",session_close:"session/close",session_fork:"session/fork",session_list:"session/list",session_load:"session/load",session_new:"session/new",session_prompt:"session/prompt",session_resume:"session/resume",session_set_config_option:"session/set_config_option",session_set_mode:"session/set_mode",session_set_model:"session/set_model"},Tv={elicitation_complete:"elicitation/complete",elicitation_create:"elicitation/create",fs_read_text_file:"fs/read_text_file",fs_write_text_file:"fs/write_text_file",session_request_permission:"session/request_permission",session_update:"session/update",terminal_create:"terminal/create",terminal_kill:"terminal/kill",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit"},p9t=1});var whr,bhr,_hr,xhr,Shr,Chr,m9t,khr,Ihr,Thr,Phr,Ahr,Ehr,Mhr,Ohr,Nhr,Rhr,Lhr,$hr,Dhr,Fhr,h9t,i8e,Uhr,jhr,Bhr,zhr,g9t,y9t,Hhr,v9t,w9t,b9t,_9t,Whr,x9t,S9t,Vhr,qhr,Khr,C9t,s8e,Ghr,Zhr,k9t,Yhr,Jhr,Xhr,Qhr,egr,mve,a8e,tgr,ngr,rgr,ogr,igr,sgr,agr,lgr,cgr,ugr,dgr,fgr,pgr,mgr,hgr,ggr,ygr,vgr,wgr,bgr,_gr,xgr,Sgr,Cgr,kgr,I9t,Igr,T9t,Tgr,Pgr,Agr,Egr,Mgr,Ogr,yE,Ngr,Rgr,Lgr,P9t,$gr,Dgr,A9t,E9t,Fgr,Ugr,jgr,Bgr,wW,zgr,Hgr,Wgr,Vgr,qgr,Kgr,Ggr,Zgr,vE,eYo,M9t,Ygr,TX,Jgr,Xgr,Qgr,eyr,tyr,nyr,ryr,oyr,iyr,syr,O9t,ayr,l8e,N9t,lyr,cyr,uyr,bW,dyr,fyr,fi,R9t,L9t,$9t,D9t,c8e,F9t,U9t,j9t,B9t,z9t,u8e,H9t,d8e,W9t,f8e,V9t,pyr,myr,hyr,gyr,hve,yyr,vyr,gve,yve,wyr,byr,_yr,xyr,Syr,Cyr,kyr,Iyr,q9t,Tyr,K9t,Pyr,G9t,Ayr,Eyr,Myr,Oyr,Nyr,Z9t,Ryr,Lyr,$yr,p8e,Dyr,Fyr,Uyr,Y9t,tYo,jyr,Byr,zyr,Hyr,Wyr,Vyr,qyr,Kyr,Gyr,Zyr,m8e,Yyr,o8e,J9t,Jyr,X9t,h8e,Q9t,Xyr,e8t,t8t,n8t,Qyr,r8t,g8e,evr,tvr,nvr,rvr,ovr,ivr,svr,avr,lvr,cvr,y8e,uvr,dvr,nYo,fvr,pvr,v8e,rYo,w8e,mvr,hvr,o8t,oYo,b8e,iYo,gvr,sYo,i8t=b(()=>{Eb();whr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),terminal:x.boolean().optional().default(!1)}),bhr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),label:x.string().nullish(),name:x.string(),optional:x.boolean().optional().default(!1),secret:x.boolean().optional().default(!0)}),_hr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),description:x.string().nullish(),id:x.string(),name:x.string()}),xhr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),description:x.string().nullish(),id:x.string(),link:x.string().nullish(),name:x.string(),vars:x.array(bhr)}),Shr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),args:x.array(x.string()).optional(),description:x.string().nullish(),env:x.record(x.string(),x.string()).optional(),id:x.string(),name:x.string()}),Chr=x.union([xhr.and(x.object({type:x.literal("env_var")})),Shr.and(x.object({type:x.literal("terminal")})),_hr]),m9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),methodId:x.string()}),khr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),Ihr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),blob:x.string(),mimeType:x.string().nullish(),uri:x.string()}),Thr=x.object({default:x.boolean().nullish(),description:x.string().nullish(),title:x.string().nullish()}),Phr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),Ahr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),Ehr=x.object({amount:x.number(),currency:x.string()}),Mhr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),terminalId:x.string()}),Ohr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),newText:x.string(),oldText:x.string().nullish(),path:x.string()}),Nhr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),id:x.string()}),Rhr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),Lhr=x.union([x.string(),x.number(),x.number(),x.boolean(),x.array(x.string())]),$hr=x.object({content:x.record(x.string(),Lhr).nullish()}),Dhr=x.intersection(x.union([$hr.and(x.object({action:x.literal("accept")})),x.object({action:x.literal("decline")}),x.object({action:x.literal("cancel")})]),x.object({_meta:x.record(x.string(),x.unknown()).nullish()})),Fhr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),h9t=x.string(),i8e=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),elicitationId:h9t}),Uhr=x.literal("object"),jhr=x.literal("string"),Bhr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),zhr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),form:Fhr.nullish(),url:Bhr.nullish()}),g9t=x.object({const:x.string(),title:x.string()}),y9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),name:x.string(),value:x.string()}),Hhr=x.union([x.literal(-32700),x.literal(-32600),x.literal(-32601),x.literal(-32602),x.literal(-32603),x.literal(-32800),x.literal(-32e3),x.literal(-32002),x.literal(-32042),x.number().int().min(-2147483648,{message:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{message:"Invalid value: Expected int32 to be <= 2147483647"})]),v9t=x.object({code:Hhr,data:x.unknown().optional(),message:x.string()}),w9t=x.unknown(),b9t=x.unknown(),_9t=x.unknown(),Whr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),readTextFile:x.boolean().optional().default(!1),writeTextFile:x.boolean().optional().default(!1)}),x9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),name:x.string(),value:x.string()}),S9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),name:x.string(),title:x.string().nullish(),version:x.string()}),Vhr=x.object({default:x.number().nullish(),description:x.string().nullish(),maximum:x.number().nullish(),minimum:x.number().nullish(),title:x.string().nullish()}),qhr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),Khr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),C9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),additionalDirectories:x.array(x.string()).optional(),cursor:x.string().nullish(),cwd:x.string().nullish()}),s8e=x.union([x.literal("anthropic"),x.literal("openai"),x.literal("azure"),x.literal("vertex"),x.literal("bedrock"),x.string()]),Ghr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),Zhr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),logout:Ghr.nullish()}),k9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),Yhr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),Jhr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),http:x.boolean().optional().default(!1),sse:x.boolean().optional().default(!1)}),Xhr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),headers:x.array(x9t),name:x.string(),url:x.string()}),Qhr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),headers:x.array(x9t),name:x.string(),url:x.string()}),egr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),args:x.array(x.string()),command:x.string(),env:x.array(y9t),name:x.string()}),mve=x.union([Xhr.and(x.object({type:x.literal("http")})),Qhr.and(x.object({type:x.literal("sse")})),egr]),a8e=x.string(),tgr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),description:x.string().nullish(),modelId:a8e,name:x.string()}),ngr=x.union([x.literal("error"),x.literal("warning"),x.literal("information"),x.literal("hint")]),rgr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),ogr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),igr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),sgr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),agr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),lgr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),maxCount:x.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish()}),cgr=x.object({diff:x.string(),uri:x.string()}),ugr=x.object({endLine:x.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}),startLine:x.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}),text:x.string()}),dgr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),fgr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),pgr=x.object({languageId:x.string(),text:x.string(),uri:x.string()}),mgr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),maxCount:x.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish()}),hgr=x.union([x.literal("rejected"),x.literal("ignored"),x.literal("replaced"),x.literal("cancelled")]),ggr=x.object({excerpts:x.array(ugr),uri:x.string()}),ygr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),vgr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),wgr=x.object({name:x.string(),owner:x.string(),remoteUrl:x.string()}),bgr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),_gr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),jump:dgr.nullish(),rename:vgr.nullish(),searchAndReplace:bgr.nullish()}),xgr=x.object({id:x.string(),isRegex:x.boolean().nullish(),replace:x.string(),search:x.string(),uri:x.string()}),Sgr=x.union([x.literal("automatic"),x.literal("diagnostic"),x.literal("manual")]),Cgr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),maxCount:x.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish()}),kgr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),diagnostics:rgr.nullish(),editHistory:lgr.nullish(),openFiles:fgr.nullish(),recentFiles:mgr.nullish(),relatedSnippets:ygr.nullish(),userActions:Cgr.nullish()}),I9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),additionalDirectories:x.array(x.string()).optional(),cwd:x.string(),mcpServers:x.array(mve)}),Igr=x.object({default:x.number().nullish(),description:x.string().nullish(),maximum:x.number().nullish(),minimum:x.number().nullish(),title:x.string().nullish()}),T9t=x.string(),Tgr=x.union([x.literal("allow_once"),x.literal("allow_always"),x.literal("reject_once"),x.literal("reject_always")]),Pgr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),kind:Tgr,name:x.string(),optionId:T9t}),Agr=x.union([x.literal("high"),x.literal("medium"),x.literal("low")]),Egr=x.union([x.literal("pending"),x.literal("in_progress"),x.literal("completed")]),Mgr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),content:x.string(),priority:Agr,status:Egr}),Ogr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),entries:x.array(Mgr)}),yE=x.object({character:x.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}),line:x.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"})}),Ngr=x.object({id:x.string(),position:yE,uri:x.string()}),Rgr=x.object({id:x.string(),newName:x.string(),position:yE,uri:x.string()}),Lgr=x.object({action:x.string(),position:yE,timestampMs:x.number(),uri:x.string()}),P9t=x.union([x.literal("utf-16"),x.literal("utf-32"),x.literal("utf-8")]),$gr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),auth:whr.optional().default({terminal:!1}),elicitation:zhr.nullish(),fs:Whr.optional().default({readTextFile:!1,writeTextFile:!1}),nes:_gr.nullish(),positionEncodings:x.array(P9t).optional(),terminal:x.boolean().optional().default(!1)}),Dgr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),audio:x.boolean().optional().default(!1),embeddedContext:x.boolean().optional().default(!1),image:x.boolean().optional().default(!1)}),A9t=x.number().int().gte(0).lte(65535),E9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),clientCapabilities:$gr.optional().default({auth:{terminal:!1},fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:S9t.nullish(),protocolVersion:A9t}),Fgr=x.object({apiType:s8e,baseUrl:x.string()}),Ugr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),current:Fgr.nullish(),id:x.string(),required:x.boolean(),supported:x.array(s8e)}),jgr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),providers:x.array(Ugr)}),Bgr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),wW=x.object({end:yE,start:yE}),zgr=x.object({message:x.string(),range:wW,severity:ngr,uri:x.string()}),Hgr=x.object({languageId:x.string(),lastFocusedMs:x.number().nullish(),uri:x.string(),visibleRange:wW.nullish()}),Wgr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),diagnostics:x.array(zgr).nullish(),editHistory:x.array(cgr).nullish(),openFiles:x.array(Hgr).nullish(),recentFiles:x.array(pgr).nullish(),relatedSnippets:x.array(ggr).nullish(),userActions:x.array(Lgr).nullish()}),Vgr=x.object({newText:x.string(),range:wW}),qgr=x.object({cursorPosition:yE.nullish(),edits:x.array(Vgr),id:x.string(),uri:x.string()}),Kgr=x.union([qgr.and(x.object({kind:x.literal("edit")})),Ngr.and(x.object({kind:x.literal("jump")})),Rgr.and(x.object({kind:x.literal("rename")})),xgr.and(x.object({kind:x.literal("searchAndReplace")}))]),Ggr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),content:x.string()}),Zgr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),vE=x.union([x.number(),x.string()]).nullable(),eYo=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),requestId:vE}),M9t=x.object({requestId:vE}),Ygr=x.enum(["assistant","user"]),TX=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),audience:x.array(Ygr).nullish(),lastModified:x.string().nullish(),priority:x.number().nullish()}),Jgr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),annotations:TX.nullish(),data:x.string(),mimeType:x.string()}),Xgr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),annotations:TX.nullish(),data:x.string(),mimeType:x.string(),uri:x.string().nullish()}),Qgr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),annotations:TX.nullish(),description:x.string().nullish(),mimeType:x.string().nullish(),name:x.string(),size:x.number().nullish(),title:x.string().nullish(),uri:x.string()}),eyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),optionId:T9t}),tyr=x.union([x.object({outcome:x.literal("cancelled")}),eyr.and(x.object({outcome:x.literal("selected")}))]),nyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),outcome:tyr}),ryr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),oyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),iyr=x.object({currentValue:x.boolean()}),syr=x.string(),O9t=x.string(),ayr=x.union([x.literal("mode"),x.literal("model"),x.literal("thought_level"),x.string()]),l8e=x.string(),N9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),description:x.string().nullish(),name:x.string(),value:l8e}),lyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),group:syr,name:x.string(),options:x.array(N9t)}),cyr=x.union([x.array(N9t),x.array(lyr)]),uyr=x.object({currentValue:l8e,options:cyr}),bW=x.intersection(x.union([uyr.and(x.object({type:x.literal("select")})),iyr.and(x.object({type:x.literal("boolean")}))]),x.object({_meta:x.record(x.string(),x.unknown()).nullish(),category:ayr.nullish(),description:x.string().nullish(),id:O9t,name:x.string()})),dyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),configOptions:x.array(bW)}),fyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),fi=x.string(),R9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),id:x.string(),sessionId:fi}),L9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),sessionId:fi}),$9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),sessionId:fi}),D9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),sessionId:fi}),c8e=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),args:x.array(x.string()).optional(),command:x.string(),cwd:x.string().nullish(),env:x.array(y9t).optional(),outputByteLimit:x.number().nullish(),sessionId:fi}),F9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),sessionId:fi,uri:x.string()}),U9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),position:yE,sessionId:fi,uri:x.string(),version:x.number(),visibleRange:wW}),j9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),languageId:x.string(),sessionId:fi,text:x.string(),uri:x.string(),version:x.number()}),B9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),sessionId:fi,uri:x.string()}),z9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),additionalDirectories:x.array(x.string()).optional(),cwd:x.string(),mcpServers:x.array(mve).optional(),sessionId:fi}),u8e=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),sessionId:fi,terminalId:x.string()}),H9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),additionalDirectories:x.array(x.string()).optional(),cwd:x.string(),mcpServers:x.array(mve),sessionId:fi}),d8e=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),limit:x.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),line:x.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),path:x.string(),sessionId:fi}),W9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),id:x.string(),reason:hgr.nullish(),sessionId:fi}),f8e=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),sessionId:fi,terminalId:x.string()}),V9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),additionalDirectories:x.array(x.string()).optional(),cwd:x.string(),mcpServers:x.array(mve).optional(),sessionId:fi}),pyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),additionalDirectories:x.array(x.string()).optional(),cwd:x.string(),sessionId:fi,title:x.string().nullish(),updatedAt:x.string().nullish()}),myr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),nextCursor:x.string().nullish(),sessions:x.array(pyr)}),hyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),title:x.string().nullish(),updatedAt:x.string().nullish()}),gyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),hve=x.string(),yyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),currentModeId:hve}),vyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),description:x.string().nullish(),id:hve,name:x.string()}),gve=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),availableModes:x.array(vyr),currentModeId:hve}),yve=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),availableModels:x.array(tgr),currentModelId:a8e}),wyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),configOptions:x.array(bW).nullish(),models:yve.nullish(),modes:gve.nullish(),sessionId:fi}),byr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),configOptions:x.array(bW).nullish(),models:yve.nullish(),modes:gve.nullish()}),_yr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),configOptions:x.array(bW).nullish(),models:yve.nullish(),modes:gve.nullish(),sessionId:fi}),xyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),configOptions:x.array(bW).nullish(),models:yve.nullish(),modes:gve.nullish()}),Syr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),Cyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),additionalDirectories:ryr.nullish(),close:oyr.nullish(),fork:fyr.nullish(),list:gyr.nullish(),resume:Syr.nullish()}),kyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),apiType:s8e,baseUrl:x.string(),headers:x.record(x.string(),x.string()).optional(),id:x.string()}),Iyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),q9t=x.intersection(x.union([x.object({type:x.literal("boolean"),value:x.boolean()}),x.object({value:l8e})]),x.object({_meta:x.record(x.string(),x.unknown()).nullish(),configId:O9t,sessionId:fi})),Tyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),configOptions:x.array(bW)}),K9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),modeId:hve,sessionId:fi}),Pyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),G9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),modelId:a8e,sessionId:fi}),Ayr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),Eyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),sessionId:fi}),Myr=x.union([x.literal("end_turn"),x.literal("max_tokens"),x.literal("max_turn_requests"),x.literal("refusal"),x.literal("cancelled")]),Oyr=x.union([x.literal("email"),x.literal("uri"),x.literal("date"),x.literal("date-time")]),Nyr=x.object({default:x.string().nullish(),description:x.string().nullish(),enum:x.array(x.string()).nullish(),format:Oyr.nullish(),maxLength:x.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),minLength:x.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),oneOf:x.array(g9t).nullish(),pattern:x.string().nullish(),title:x.string().nullish()}),Z9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),context:Wgr.nullish(),position:yE,selection:wW.nullish(),sessionId:fi,triggerKind:Sgr,uri:x.string(),version:x.number()}),Ryr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),suggestions:x.array(Kgr)}),Lyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),terminalId:x.string()}),$yr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),exitCode:x.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),signal:x.string().nullish()}),p8e=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),sessionId:fi,terminalId:x.string()}),Dyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),exitStatus:$yr.nullish(),output:x.string(),truncated:x.boolean()}),Fyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),annotations:TX.nullish(),text:x.string()}),Uyr=x.object({range:wW.nullish(),text:x.string()}),Y9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),contentChanges:x.array(Uyr),sessionId:fi,uri:x.string(),version:x.number()}),tYo=x.object({method:x.string(),params:x.union([L9t,j9t,Y9t,F9t,B9t,U9t,R9t,W9t,w9t]).nullish()}),jyr=x.union([x.literal("full"),x.literal("incremental")]),Byr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),syncKind:jyr}),zyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),didChange:Byr.nullish(),didClose:ogr.nullish(),didFocus:igr.nullish(),didOpen:sgr.nullish(),didSave:agr.nullish()}),Hyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),document:zyr.nullish()}),Wyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),context:kgr.nullish(),events:Hyr.nullish()}),Vyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),auth:Zhr.optional().default({}),loadSession:x.boolean().optional().default(!1),mcpCapabilities:Jhr.optional().default({http:!1,sse:!1}),nes:Wyr.nullish(),positionEncoding:P9t.nullish(),promptCapabilities:Dgr.optional().default({audio:!1,embeddedContext:!1,image:!1}),providers:Bgr.nullish(),sessionCapabilities:Cyr.optional().default({})}),qyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),agentCapabilities:Vyr.optional().default({auth:{},loadSession:!1,mcpCapabilities:{http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:S9t.nullish(),authMethods:x.array(Chr).optional().default([]),protocolVersion:A9t}),Kyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),mimeType:x.string().nullish(),text:x.string(),uri:x.string()}),Gyr=x.union([Kyr,Ihr]),Zyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),annotations:TX.nullish(),resource:Gyr}),m8e=x.union([Fyr.and(x.object({type:x.literal("text")})),Xgr.and(x.object({type:x.literal("image")})),Jgr.and(x.object({type:x.literal("audio")})),Qgr.and(x.object({type:x.literal("resource_link")})),Zyr.and(x.object({type:x.literal("resource")}))]),Yyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),content:m8e}),o8e=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),content:m8e,messageId:x.string().nullish()}),J9t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),messageId:x.string().nullish(),prompt:x.array(m8e),sessionId:fi}),Jyr=x.object({anyOf:x.array(g9t)}),X9t=x.union([Yyr.and(x.object({type:x.literal("content")})),Ohr.and(x.object({type:x.literal("diff")})),Lyr.and(x.object({type:x.literal("terminal")}))]),h8e=x.string(),Q9t=x.object({sessionId:fi,toolCallId:h8e.nullish()}),Xyr=x.intersection(x.union([Q9t,M9t]),x.object({elicitationId:h9t,url:x.string().url()})),e8t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),line:x.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),path:x.string()}),t8t=x.union([x.literal("pending"),x.literal("in_progress"),x.literal("completed"),x.literal("failed")]),n8t=x.union([x.literal("read"),x.literal("edit"),x.literal("delete"),x.literal("move"),x.literal("search"),x.literal("execute"),x.literal("think"),x.literal("fetch"),x.literal("switch_mode"),x.literal("other")]),Qyr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),content:x.array(X9t).optional(),kind:n8t.optional(),locations:x.array(e8t).optional(),rawInput:x.unknown().optional(),rawOutput:x.unknown().optional(),status:t8t.optional(),title:x.string(),toolCallId:h8e}),r8t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),content:x.array(X9t).nullish(),kind:n8t.nullish(),locations:x.array(e8t).nullish(),rawInput:x.unknown().optional(),rawOutput:x.unknown().optional(),status:t8t.nullish(),title:x.string().nullish(),toolCallId:h8e}),g8e=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),options:x.array(Pgr),sessionId:fi,toolCall:r8t}),evr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),hint:x.string()}),tvr=evr,nvr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),description:x.string(),input:tvr.nullish(),name:x.string()}),rvr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),availableCommands:x.array(nvr)}),ovr=x.object({enum:x.array(x.string()),type:jhr}),ivr=x.union([ovr,Jyr]),svr=x.object({default:x.array(x.string()).nullish(),description:x.string().nullish(),items:ivr,maxItems:x.number().nullish(),minItems:x.number().nullish(),title:x.string().nullish()}),avr=x.union([Nyr.and(x.object({type:x.literal("string")})),Igr.and(x.object({type:x.literal("number")})),Vhr.and(x.object({type:x.literal("integer")})),Thr.and(x.object({type:x.literal("boolean")})),svr.and(x.object({type:x.literal("array")}))]),lvr=x.object({description:x.string().nullish(),properties:x.record(x.string(),avr).optional().default({}),required:x.array(x.string()).nullish(),title:x.string().nullish(),type:Uhr.optional().default("object")}),cvr=x.intersection(x.union([Q9t,M9t]),x.object({requestedSchema:lvr})),y8e=x.intersection(x.union([cvr.and(x.object({mode:x.literal("form")})),Xyr.and(x.object({mode:x.literal("url")}))]),x.object({_meta:x.record(x.string(),x.unknown()).nullish(),message:x.string()})),uvr=x.object({cachedReadTokens:x.number().nullish(),cachedWriteTokens:x.number().nullish(),inputTokens:x.number(),outputTokens:x.number(),thoughtTokens:x.number().nullish(),totalTokens:x.number()}),dvr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),stopReason:Myr,usage:uvr.nullish(),userMessageId:x.string().nullish()}),nYo=x.union([x.object({id:vE,result:x.union([qyr,khr,jgr,Iyr,Rhr,Yhr,_yr,byr,myr,wyr,xyr,Ahr,Pyr,Tyr,dvr,Ayr,Eyr,Ryr,Phr,_9t])}),x.object({error:v9t,id:vE})]),fvr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),cost:Ehr.nullish(),size:x.number(),used:x.number()}),pvr=x.union([o8e.and(x.object({sessionUpdate:x.literal("user_message_chunk")})),o8e.and(x.object({sessionUpdate:x.literal("agent_message_chunk")})),o8e.and(x.object({sessionUpdate:x.literal("agent_thought_chunk")})),Qyr.and(x.object({sessionUpdate:x.literal("tool_call")})),r8t.and(x.object({sessionUpdate:x.literal("tool_call_update")})),Ogr.and(x.object({sessionUpdate:x.literal("plan")})),rvr.and(x.object({sessionUpdate:x.literal("available_commands_update")})),yyr.and(x.object({sessionUpdate:x.literal("current_mode_update")})),dyr.and(x.object({sessionUpdate:x.literal("config_option_update")})),hyr.and(x.object({sessionUpdate:x.literal("session_info_update")})),fvr.and(x.object({sessionUpdate:x.literal("usage_update")}))]),v8e=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),sessionId:fi,update:pvr}),rYo=x.object({method:x.string(),params:x.union([v8e,i8e,w9t]).nullish()}),w8e=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),sessionId:fi,terminalId:x.string()}),mvr=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),exitCode:x.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),signal:x.string().nullish()}),hvr=x.object({name:x.string(),uri:x.string()}),o8t=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),repository:wgr.nullish(),workspaceFolders:x.array(hvr).nullish(),workspaceUri:x.string().nullish()}),oYo=x.object({id:vE,method:x.string(),params:x.union([E9t,m9t,Khr,kyr,Nhr,k9t,I9t,H9t,C9t,z9t,V9t,D9t,K9t,q9t,J9t,G9t,o8t,Z9t,$9t,b9t]).nullish()}),b8e=x.object({_meta:x.record(x.string(),x.unknown()).nullish(),content:x.string(),path:x.string(),sessionId:fi}),iYo=x.object({id:vE,method:x.string(),params:x.union([b8e,d8e,g8e,c8e,p8e,f8e,w8e,u8e,y8e,b9t]).nullish()}),gvr=x.object({_meta:x.record(x.string(),x.unknown()).nullish()}),sYo=x.union([x.object({id:vE,result:x.union([gvr,Ggr,nyr,Mhr,Dyr,Zgr,mvr,qhr,Dhr,_9t])}),x.object({error:v9t,id:vE})])});function s8t(t,e){let n=new TextEncoder,r=new TextDecoder,o=new ReadableStream({async start(s){let a="",l=e.getReader();try{for(;;){let{value:u,done:d}=await l.read();if(d){a+=r.decode();break}if(!u)continue;a+=r.decode(u,{stream:!0});let f=a.split(`
`);a=f.pop()||"";for(let p of f){let m=p.trim();if(m)try{let h=JSON.parse(m);s.enqueue(h)}catch(h){console.error("Failed to parse JSON message:",m,h)}}}let c=a.trim();if(c)try{let u=JSON.parse(c);s.enqueue(u)}catch(u){console.error("Failed to parse JSON message:",c,u)}}catch(c){s.error(c);return}finally{l.releaseLock()}s.close()}}),i=new WritableStream({async write(s){let a=JSON.stringify(s)+`
`,l=t.getWriter();try{await l.write(n.encode(a))}finally{l.releaseLock()}}});return{readable:o,writable:i}}var a8t=b(()=>{});var vve,_8e,Xl,x8e=b(()=>{Eb();r8e();i8t();r8e();a8t();vve=class{constructor(e,n){M(this,"connection");let r=e(this),o=async(s,a)=>{switch(s){case Tv.fs_write_text_file:{let l=b8e.parse(a);return r.writeTextFile?.(l)}case Tv.fs_read_text_file:{let l=d8e.parse(a);return r.readTextFile?.(l)}case Tv.session_request_permission:{let l=g8e.parse(a);return r.requestPermission(l)}case Tv.terminal_create:{let l=c8e.parse(a);return r.createTerminal?.(l)}case Tv.terminal_output:{let l=p8e.parse(a);return r.terminalOutput?.(l)}case Tv.terminal_release:{let l=f8e.parse(a);return await r.releaseTerminal?.(l)??{}}case Tv.terminal_wait_for_exit:{let l=w8e.parse(a);return r.waitForTerminalExit?.(l)}case Tv.terminal_kill:{let l=u8e.parse(a);return await r.killTerminal?.(l)??{}}case Tv.elicitation_create:{if(!r.unstable_createElicitation)throw Xl.methodNotFound(s);let l=y8e.parse(a);return r.unstable_createElicitation(l)}default:if(r.extMethod)return r.extMethod(s,a);throw Xl.methodNotFound(s)}},i=async(s,a)=>{switch(s){case Tv.session_update:{let l=v8e.parse(a);return r.sessionUpdate(l)}case Tv.elicitation_complete:{if(!r.unstable_completeElicitation)return;let l=i8e.parse(a);return r.unstable_completeElicitation(l)}default:if(r.extNotification)return r.extNotification(s,a);throw Xl.methodNotFound(s)}};this.connection=new _8e(o,i,n)}async initialize(e){return await this.connection.sendRequest(ia.initialize,e)}async newSession(e){return await this.connection.sendRequest(ia.session_new,e)}async loadSession(e){return await this.connection.sendRequest(ia.session_load,e)??{}}async unstable_forkSession(e){return await this.connection.sendRequest(ia.session_fork,e)}async listSessions(e){return await this.connection.sendRequest(ia.session_list,e)}async resumeSession(e){return await this.connection.sendRequest(ia.session_resume,e)}async closeSession(e){return await this.connection.sendRequest(ia.session_close,e)}async setSessionMode(e){return await this.connection.sendRequest(ia.session_set_mode,e)??{}}async unstable_setSessionModel(e){return await this.connection.sendRequest(ia.session_set_model,e)??{}}async setSessionConfigOption(e){return await this.connection.sendRequest(ia.session_set_config_option,e)}async authenticate(e){return await this.connection.sendRequest(ia.authenticate,e)??{}}async unstable_logout(e){return await this.connection.sendRequest(ia.logout,e)??{}}async prompt(e){return await this.connection.sendRequest(ia.session_prompt,e)}async cancel(e){return await this.connection.sendNotification(ia.session_cancel,e)}async unstable_startNes(e){return await this.connection.sendRequest(ia.nes_start,e)}async unstable_suggestNes(e){return await this.connection.sendRequest(ia.nes_suggest,e)}async unstable_closeNes(e){return await this.connection.sendRequest(ia.nes_close,e)??{}}async unstable_didOpenDocument(e){return await this.connection.sendNotification(ia.document_did_open,e)}async unstable_didChangeDocument(e){return await this.connection.sendNotification(ia.document_did_change,e)}async unstable_didCloseDocument(e){return await this.connection.sendNotification(ia.document_did_close,e)}async unstable_didSaveDocument(e){return await this.connection.sendNotification(ia.document_did_save,e)}async unstable_didFocusDocument(e){return await this.connection.sendNotification(ia.document_did_focus,e)}async unstable_acceptNes(e){return await this.connection.sendNotification(ia.nes_accept,e)}async unstable_rejectNes(e){return await this.connection.sendNotification(ia.nes_reject,e)}async extMethod(e,n){return await this.connection.sendRequest(e,n)}async extNotification(e,n){return await this.connection.sendNotification(e,n)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},_8e=class{constructor(e,n,r){M(this,"pendingResponses",new Map);M(this,"nextRequestId",0);M(this,"requestHandler");M(this,"notificationHandler");M(this,"stream");M(this,"writeQueue",Promise.resolve());M(this,"abortController",new AbortController);M(this,"closedPromise");this.requestHandler=e,this.notificationHandler=n,this.stream=r,this.closedPromise=new Promise(o=>{this.abortController.signal.addEventListener("abort",()=>o())}),this.receive()}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}async receive(){let e;try{let n=this.stream.readable.getReader();try{for(;!this.abortController.signal.aborted;){let{value:r,done:o}=await n.read();if(o)break;if(r)try{this.processMessage(r)}catch(i){console.error("Unexpected error during message processing:",r,i),"id"in r&&r.id!==void 0&&this.sendMessage({jsonrpc:"2.0",id:r.id,error:{code:-32700,message:"Parse error"}})}}}finally{n.releaseLock()}}catch(n){e=n}finally{this.close(e)}}close(e){if(this.abortController.signal.aborted)return;let n=e??new Error("ACP connection closed");for(let r of this.pendingResponses.values())r.reject(n);this.pendingResponses.clear(),this.abortController.abort(n)}async processMessage(e){if("method"in e&&"id"in e){let n=await this.tryCallRequestHandler(e.method,e.params);"error"in n&&console.error("Error handling request",e,n.error),await this.sendMessage({jsonrpc:"2.0",id:e.id,...n})}else if("method"in e){let n=await this.tryCallNotificationHandler(e.method,e.params);"error"in n&&console.error("Error handling notification",e,n.error)}else"id"in e?this.handleResponse(e):console.error("Invalid message",{message:e})}async tryCallRequestHandler(e,n){try{return{result:await this.requestHandler(e,n)??null}}catch(r){if(r instanceof Xl)return r.toResult();if(r instanceof x.ZodError)return Xl.invalidParams(r.format()).toResult();let o;(r instanceof Error||typeof r=="object"&&r!=null&&"message"in r&&typeof r.message=="string")&&(o=r.message);try{return Xl.internalError(o?JSON.parse(o):{}).toResult()}catch{return Xl.internalError({details:o}).toResult()}}}async tryCallNotificationHandler(e,n){try{return await this.notificationHandler(e,n),{result:null}}catch(r){if(r instanceof Xl)return r.toResult();if(r instanceof x.ZodError)return Xl.invalidParams(r.format()).toResult();let o;(r instanceof Error||typeof r=="object"&&r!=null&&"message"in r&&typeof r.message=="string")&&(o=r.message);try{return Xl.internalError(o?JSON.parse(o):{}).toResult()}catch{return Xl.internalError({details:o}).toResult()}}}handleResponse(e){let n=this.pendingResponses.get(e.id);if(n){if("result"in e)n.resolve(e.result);else if("error"in e){let{code:r,message:o,data:i}=e.error;n.reject(new Xl(r,o,i))}this.pendingResponses.delete(e.id)}else console.error("Got response to unknown request",e.id)}sendRequest(e,n){this.throwIfClosed();let r=this.nextRequestId++,o=new Promise((i,s)=>{this.pendingResponses.set(r,{resolve:i,reject:s})});return o.catch(()=>{}),this.sendMessage({jsonrpc:"2.0",id:r,method:e,params:n}),o}async sendNotification(e,n){this.throwIfClosed(),await this.sendMessage({jsonrpc:"2.0",method:e,params:n})}throwIfClosed(){if(this.abortController.signal.aborted)throw this.abortController.signal.reason??new Error("ACP connection closed")}async sendMessage(e){return this.writeQueue=this.writeQueue.then(async()=>{let n=this.stream.writable.getWriter();try{await n.write(e)}finally{n.releaseLock()}}).catch(n=>{this.close(n)}),this.writeQueue}},Xl=class t extends Error{constructor(n,r,o){super(r);M(this,"code");M(this,"data");this.code=n,this.name="RequestError",this.data=o}static parseError(n,r){return new t(-32700,`Parse error${r?`: ${r}`:""}`,n)}static invalidRequest(n,r){return new t(-32600,`Invalid request${r?`: ${r}`:""}`,n)}static methodNotFound(n){return new t(-32601,`"Method not found": ${n}`,{method:n})}static invalidParams(n,r){return new t(-32602,`Invalid params${r?`: ${r}`:""}`,n)}static internalError(n,r){return new t(-32603,`Internal error${r?`: ${r}`:""}`,n)}static authRequired(n,r){return new t(-32e3,`Authentication required${r?`: ${r}`:""}`,n)}static resourceNotFound(n){return new t(-32002,`Resource not found${n?`: ${n}`:""}`,n&&{uri:n})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}}});function c8t(t,e,n){let r=new Map,o=new Map;return{stdin:vvr(t,i=>l8t("\u2192",i,n,r,o)),stdout:wvr(e,i=>l8t("\u2190",i,n,o,r))}}function vvr(t,e){let n=t.getWriter(),r=new _W(e);return new WritableStream({async write(o){r.push(o),await n.write(o)},async close(){r.flush(),await n.close()},async abort(o){r.flush(),await n.abort(o)}})}function wvr(t,e){let[n,r]=t.tee(),o=new _W(e);return(async()=>{let i=r.getReader();try{for(;;){let{value:s,done:a}=await i.read();if(a)break;s&&o.push(s)}o.flush()}catch{}})(),n}function l8t(t,e,n,r,o){let s=!!Y().agentMode?.debugFullFrames?(d,f,p,m)=>$k.append({ts:new Date().toISOString(),dir:t,tag:n,kind:d,method:f,id:p,payload:m}):null,a;try{a=JSON.parse(e)}catch{j(`[ACP ${t}][${n}] (unparsed) ${VR(e)}`),s?.("raw","(unparsed)",null,{raw:e});return}let l=a.id!==void 0?String(a.id):null;if(a.method){let d=a.method,f=l!==null?`#${l}`:"(notif)";l!==null&&r.set(l,d),j(`[ACP ${t}][${n}] ${d} ${f} ${VR(a.params)}`),s?.(l!==null?"request":"notif",d,l,a.params);return}let c=l!==null?o.get(l)??"(unknown)":"(unknown)";l!==null&&o.delete(l);let u=l!==null?`#${l}`:"(no-id)";a.error?(j(`[ACP ${t}][${n}] (error) ${c} ${u} ${VR(a.error)}`),s?.("error",c,l,a.error)):(j(`[ACP ${t}][${n}] ${c} ${u} ${VR(a.result)}`),s?.("result",c,l,a.result))}var _W,S8e=b(()=>{pe();Se();iY();_W=class{constructor(e){this.onLine=e;this.buffer="";this.decoder=new TextDecoder}push(e){this.buffer+=this.decoder.decode(e,{stream:!0});let n;for(;(n=this.buffer.indexOf(`
`))!==-1;){let r=this.buffer.slice(0,n).trim();this.buffer=this.buffer.slice(n+1),r&&this.emit(r)}}flush(){let e=this.buffer.trim();this.buffer="",e&&this.emit(e)}emit(e){try{this.onLine(e)}catch{}}}});function _vr(t){let e=t.getReader(),n=new TextEncoder,r=0,o;return new ReadableStream({start(i){o=new _W(s=>{let a=s.replace(bvr,"").trim();a&&(i.enqueue(n.encode(`${a}
`)),r+=1)})},async pull(i){for(r=0;r===0;){let{value:s,done:a}=await e.read();if(a){o.flush(),i.close();return}s&&o.push(s)}},cancel(i){return e.cancel(i)}})}function xvr(t,e){let n="";t.setEncoding("utf-8"),t.on("data",r=>{n+=r;let o;for(;(o=n.indexOf(`
`))!==-1;){let i=n.slice(0,o).trimEnd();n=n.slice(o+1),i&&d8t(i,e)}}),t.on("end",()=>{n.trim()&&d8t(n.trim(),e)})}function d8t(t,e){let n=t.toLowerCase();n.startsWith("error")||n.startsWith("fatal")?H(`[AgentMode][${e}] ${t}`):n.startsWith("warn")?W(`[AgentMode][${e}] ${t}`):j(`[AgentMode][${e}] ${t}`)}var u8t,wve,bvr,f8t=b(()=>{pe();$n();S8e();u8t=3e3,wve=class{constructor(e){this.opts=e;this.child=null;this.exitListeners=new Set;this.hasExited=!1;this.exitCode=null;this.exitSignal=null}start(){if(this.child)throw new Error("AcpProcessManager already started");let e=this.opts.logTag??"acp",{spawn:n}=Pe("child_process"),{Readable:r,Writable:o}=Pe("stream");j(`[AgentMode] spawning ${this.opts.command} ${this.opts.args.join(" ")} (tag=${e})`);let i=n(this.opts.command,this.opts.args,{env:this.opts.env,stdio:["pipe","pipe","pipe"],windowsHide:!0});this.child=i,i.on("error",l=>{H(`[AgentMode] subprocess error (${e})`,l)}),i.on("exit",(l,c)=>{this.hasExited=!0,this.exitCode=l,this.exitSignal=c,j(`[AgentMode] subprocess exit (${e}) code=${l} signal=${c}`);for(let u of this.exitListeners)try{u(l,c)}catch(d){W("[AgentMode] exit listener threw",d)}}),xvr(i.stderr,e);let s=o.toWeb,a=r.toWeb;return{stdin:s(i.stdin),stdout:_vr(a(i.stdout))}}onExit(e){if(this.hasExited){try{e(this.exitCode,this.exitSignal)}catch(n){W("[AgentMode] exit listener threw",n)}return()=>{}}return this.exitListeners.add(e),()=>this.exitListeners.delete(e)}isRunning(){return this.child!==null&&!this.hasExited}async shutdown(){if(!this.child||this.hasExited)return;let e=this.child,n=this.opts.logTag??"acp",r=new Promise(s=>{this.onExit(()=>s())});try{e.kill("SIGTERM")}catch(s){W(`[AgentMode] SIGTERM failed (${n})`,s)}let o=new Promise(s=>window.setTimeout(()=>s("timeout"),u8t));if(await Promise.race([r.then(()=>"exited"),o])==="timeout"&&!this.hasExited){W(`[AgentMode] subprocess (${n}) did not exit within ${u8t}ms; SIGKILL`);try{e.kill("SIGKILL")}catch(s){W(`[AgentMode] SIGKILL failed (${n})`,s)}await r}}},bvr=/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g});function Svr(t,e,n){if(e==null&&n==null)return t;let r=t.split(`
`),o=e!=null?Math.max(0,e-1):0,i=n!=null?Math.min(r.length,o+n):r.length;return o>=r.length?"":r.slice(o,i).join(`
`)}var _ve,bve,p8t=b(()=>{x8e();pe();_ve=require("obsidian");$n();bve=class{constructor(e,n){this.app=e;this.handlers=n}async sessionUpdate(e){try{this.handlers.onSessionUpdate(e.sessionId,e)}catch(n){W("[AgentMode] sessionUpdate handler threw",n)}}async requestPermission(e){return this.handlers.requestPermission(e)}async readTextFile(e){let n=this.resolveVaultRelative(e.path),r=await this.app.vault.adapter.read(n),o=Svr(r,e.line??null,e.limit??null);return j(`[AgentMode] readTextFile ${n} (${o.length} chars)`),{content:o}}async writeTextFile(e){let n=Pe("path"),r=this.resolveVaultRelative(e.path),o=this.app.vault.adapter,i=n.posix.dirname(r);return i&&i!=="."&&i!=="/"&&!await o.exists(i)&&await o.mkdir(i),await o.write(r,e.content),j(`[AgentMode] writeTextFile ${r} (${e.content.length} chars)`),{}}resolveVaultRelative(e){let n=Pe("path"),r=this.app.vault.adapter;if(!(r instanceof _ve.FileSystemAdapter))throw Xl.invalidParams(void 0,"Agent Mode requires a FileSystemAdapter (desktop).");let o=n.resolve(r.getBasePath()),i=n.isAbsolute(e)?n.resolve(e):n.resolve(o,e),s=n.relative(o,i);if(s.startsWith("..")||n.isAbsolute(s))throw Xl.invalidParams({path:e},`Path "${e}" is outside the vault and cannot be accessed by Agent Mode.`);let a=(0,_ve.normalizePath)(s.split(n.sep).join("/")),l=a.split("/")[0]??"";if(l.startsWith("."))throw Xl.invalidParams({path:e},`Path "${e}" is in a hidden directory (${l}) and is not accessible to Agent Mode.`);return a}}});function m8t(){return{messages:[],current:null}}function h8t(t,e){let n,r;switch(e.sessionUpdate){case"user_message_chunk":n=ar,r=e.messageId??void 0;break;case"agent_message_chunk":case"agent_thought_chunk":case"tool_call":case"plan":n=pl;break;case"tool_call_update":return!0;default:return!1}Cvr(t.current,n,r)&&y8t(t);let o=t.current??(t.current={sender:n,wireId:r,text:""});if(e.sessionUpdate==="user_message_chunk"||e.sessionUpdate==="agent_message_chunk"){let{content:i}=e;i?.type==="text"&&(o.text+=i.text)}return!0}function g8t(t){return y8t(t),t.messages.length>0?t.messages:void 0}function Cvr(t,e,n){return!t||t.sender!==e?!0:e!==ar?!1:n===void 0||n!==t.wireId}function y8t(t){let e=t.current;if(t.current=null,!e)return;let n=e.sender===ar?Y7(e.text):e.text;n.trim()&&t.messages.push({id:`acp-loaded-${t.messages.length}`,sender:e.sender,message:n,isVisible:!0,timestamp:null})}var v8t=b(()=>{gt();D4e()});function kvr(t){return t?{currentModelId:t.currentModelId,availableModels:t.availableModels.map(e=>({modelId:e.modelId,name:e.name,description:e.description??void 0}))}:null}function Ivr(t){return t?{currentModeId:t.currentModeId,availableModes:t.availableModes.map(e=>({id:e.id,name:e.name,description:e.description??void 0}))}:null}function _8t(t){return t?t.map(Tvr):null}function Tvr(t){return t.type==="select"?{id:t.id,type:"select",name:t.name,description:t.description??void 0,category:t.category??null,currentValue:String(t.currentValue),options:t.options.map(e=>"options"in e?{name:e.name,options:e.options.map(n=>({value:n.value,name:n.name,description:n.description??void 0}))}:{value:e.value,name:e.name,description:e.description??void 0})}:{id:t.id,type:"boolean",name:t.name,description:t.description??void 0,category:t.category??null,currentValue:!!t.currentValue}}function x8t(t,e,n,r){return Upe({models:kvr(t),modes:Ivr(e),configOptions:_8t(n)},r)}function S8t(t){switch(t){case"end_turn":case"cancelled":case"refusal":case"max_tokens":case"max_turn_requests":return t;default:return"end_turn"}}function C8e(t){if(t!=null)return t}function k8e(t){if(t)return t}function C8t(t){return t.map(e=>e.type==="text"?{type:"text",text:e.text}:e.type==="image"?{type:"image",mimeType:e.mimeType,data:e.data}:{type:"resource_link",uri:e.uri,name:e.name??e.uri})}function w8t(t){return t.type==="text"?{type:"text",text:t.text}:t.type==="image"?{type:"image",mimeType:t.mimeType,data:t.data}:t.type==="resource_link"?{type:"resource_link",uri:t.uri,name:t.name??void 0}:null}function I8e(t){if(!t)return;let e=[];for(let n of t)n.type==="content"&&n.content.type==="text"?e.push({type:"content",content:{type:"text",text:n.content.text}}):n.type==="diff"&&e.push({type:"diff",path:n.path,oldText:n.oldText??null,newText:n.newText});return e.length>0?e:void 0}function Pvr(t){let{tool:e,mcpServer:n}=cb(t.title);return{toolCallId:t.toolCallId,title:e,kind:C8e(t.kind),status:k8e(t.status),rawInput:t.rawInput,content:I8e(t.content),locations:t.locations?.map(r=>({path:r.path,line:r.line??void 0})),mcpServer:n}}function b8t(t,e){if(t===null)return null;if(t!==void 0)return e(t)}function Avr(t){let e=t.title!=null?cb(t.title):null;return{toolCallId:t.toolCallId,title:e?.tool,kind:C8e(t.kind??void 0),status:k8e(t.status),rawInput:t.rawInput,content:b8t(t.content,I8e),locations:b8t(t.locations,n=>n.map(r=>({path:r.path,line:r.line??void 0}))),mcpServer:e?.mcpServer}}function T8e(t,e){if(t.update.sessionUpdate==="user_message_chunk")return[];let n=t.sessionId,r=[{sessionId:n,update:Mvr(t.update)}],o=Evr(t.update,e);return o&&r.push({sessionId:n,update:o}),r}function Evr(t,e){if(t.sessionUpdate!=="tool_call"&&t.sessionUpdate!=="tool_call_update")return null;let n=t.toolCallId,r=t.title,o=r!=null&&(()=>{let{tool:l,mcpServer:c}=cb(r);return!c&&l.toLowerCase()==="todowrite"})();if(o&&n&&e?.add(n),!(o||n!=null&&e?.has(n)===!0))return null;let s=t.rawInput?.todos;if(!Array.isArray(s))return null;let a=[];for(let l of s){if(typeof l!="object"||l===null)continue;let c=l;typeof c.content!="string"||c.content.length===0||c.status!=="pending"&&c.status!=="in_progress"&&c.status!=="completed"||a.push({content:c.content,status:c.status,priority:c.priority==="high"||c.priority==="medium"||c.priority==="low"?c.priority:"medium"})}return a.length===0&&s.length>0?null:{sessionUpdate:"plan",entries:a}}function Mvr(t){switch(t.sessionUpdate){case"agent_message_chunk":return{sessionUpdate:"agent_message_chunk",content:w8t(t.content)??{type:"text",text:""},messageId:t.messageId??void 0};case"agent_thought_chunk":return{sessionUpdate:"agent_thought_chunk",content:w8t(t.content)??{type:"text",text:""},messageId:t.messageId??void 0};case"tool_call":return{sessionUpdate:"tool_call",...Pvr(t)};case"tool_call_update":return{sessionUpdate:"tool_call_update",...Avr(t)};case"plan":return{sessionUpdate:"plan",entries:t.entries.map(e=>({content:e.content,priority:e.priority,status:e.status}))};case"session_info_update":return{sessionUpdate:"session_info_update",title:t.title??null};case"current_mode_update":return{sessionUpdate:"current_mode_update",currentModeId:t.currentModeId};case"config_option_update":return{sessionUpdate:"config_option_update",configOptions:_8t(t.configOptions)??[]};case"usage_update":{let e=t;return{sessionUpdate:"usage_update",usage:{usedTokens:e.used,contextWindow:e.size,updatedAt:Date.now()}}}default:return{sessionUpdate:"session_info_update",title:null}}}function k8t(t,e){let n=t.toolCall;return{sessionId:t.sessionId,toolCall:{toolCallId:n.toolCallId,title:n.title??"Tool call",kind:C8e(n.kind??void 0),status:k8e(n.status)??"pending",rawInput:n.rawInput,content:I8e(n.content),locations:n.locations?.map(r=>({path:r.path,line:r.line??void 0}))},options:t.options.map(r=>Ovr(r,e))}}function Ovr(t,e){let n={optionId:t.optionId,name:t.name,kind:eA.includes(t.kind)?t.kind:"reject_once"};return e?.(n,t._meta)??n}function I8t(t){return{sessionId:t.sessionId}}function T8t(t){return{sessionId:t.sessionId,cwd:t.cwd,title:t.title??null,updatedAt:t.updatedAt??null}}var P8t=b(()=>{rz();Bpe();XB()});function Nvr(t){return t instanceof Xl?t.code===gNe:typeof t=="object"&&t!==null&&"code"in t?t.code===gNe:!1}function Lvr(t,e){return t&&t.map(n=>n.type==="select"&&n.category==="model"?{...n,currentValue:e}:n)}var A8t,Rvr,Sve,xve,E8t=b(()=>{pe();x8e();A8t=require("obsidian");f8t();p8t();ok();S8e();HR();v8t();P8t();Rvr="obsidian-copilot";Sve=class Sve{constructor(e,n,r,o){this.app=e;this.backend=n;this.clientVersion=r;this.descriptor=o;this.process=null;this.connection=null;this.domainHandlers=new Map;this.pendingUpdates=new Map;this.permissionPrompter=null;this.exitListeners=new Set;this.capabilities=new Map;this.sessionWireState=new Map;this.todoToolCallIdsBySession=new Map;this.sawLiveUsage=new Set;this.loadSessionCollectors=new Map;this.lastPlanUsage=null;this.planUsageRead=null;this.planUsageReadQueued=!1;this.backendContextWindows=new Map}async start(){if(this.connection)return;let e=this.app.vault.adapter;if(!(e instanceof A8t.FileSystemAdapter))throw new Error("Agent Mode requires desktop Obsidian (FileSystemAdapter).");let n=await this.backend.buildSpawnDescriptor({vaultBasePath:e.getBasePath()}),r={command:n.command,args:n.args,env:n.env,logTag:this.backend.id},o=new wve(r);this.process=o;let i=o.start(),{stdin:s,stdout:a}=c8t(i.stdin,i.stdout,this.backend.id);o.onExit(()=>{W(`[AgentMode] backend ${this.backend.id} exited`),this.connection=null,this.domainHandlers.clear(),this.pendingUpdates.clear(),this.sessionWireState.clear(),this.todoToolCallIdsBySession.clear(),this.sawLiveUsage.clear(),this.loadSessionCollectors.clear(),this.permissionPrompter=null,this.capabilities.clear(),this.lastPlanUsage=null,this.planUsageReadQueued=!1,this.backendContextWindows.clear();for(let u of this.exitListeners)try{u()}catch(d){W("[AgentMode] exit listener threw",d)}});let l=s8t(s,a),c=new bve(this.app,{onSessionUpdate:(u,d)=>this.routeSessionUpdate(u,d),requestPermission:u=>this.handlePermission(u)});this.connection=new vve(()=>c,l);try{let u=await this.connection.initialize({protocolVersion:p9t,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}},clientInfo:{name:Rvr,version:this.clientVersion}});u.agentCapabilities?.sessionCapabilities?.list!=null&&this.capabilities.set("session/list",!0),u.agentCapabilities?.sessionCapabilities?.resume!=null&&this.capabilities.set("session/resume",!0),u.agentCapabilities?.loadSession===!0&&this.capabilities.set("session/load",!0),u.agentCapabilities?.sessionCapabilities?.additionalDirectories!=null&&this.capabilities.set("session/additional_directories",!0),j(`[AgentMode] initialized backend ${this.backend.id} (negotiated protocol v${u.protocolVersion}, listSessions=${this.hasCapability("session/list")}, resumeSession=${this.hasCapability("session/resume")}, loadSession=${this.hasCapability("session/load")}, additionalDirectories=${this.hasCapability("session/additional_directories")})`)}catch(u){H(`[AgentMode] initialize failed for ${this.backend.id}; tearing down subprocess`,u),this.connection=null;try{await o.shutdown()}catch(d){H("[AgentMode] shutdown after failed initialize threw",d)}throw this.process=null,u}}isRunning(){return this.process?.isRunning()??!1}onExit(e){return this.exitListeners.add(e),()=>this.exitListeners.delete(e)}setPermissionPrompter(e){this.permissionPrompter=e}registerSessionHandler(e,n){this.domainHandlers.set(e,n);let r=this.pendingUpdates.get(e);if(r){this.pendingUpdates.delete(e);for(let o of r)try{for(let i of T8e(o,this.todoToolCallIdsFor(e)))n(i)}catch(i){W(`[AgentMode] replay of buffered session/update threw for ${e}`,i)}}if(this.lastPlanUsage=this.lastPlanUsage&&QP(this.lastPlanUsage),this.lastPlanUsage)try{n({sessionId:e,update:{sessionUpdate:"plan_usage_update",planUsage:this.planUsageFor(e)}})}catch(o){W(`[AgentMode] replay of plan usage threw for ${e}`,o)}else this.refreshPlanUsage();return()=>{this.domainHandlers.get(e)===n&&(this.domainHandlers.delete(e),this.todoToolCallIdsBySession.delete(e),this.sawLiveUsage.delete(e))}}async newSession(e){let n={cwd:e.cwd,mcpServers:[],...this.additionalDirectoriesField(e.additionalDirectories)},r=await this.requireConnection().newSession(n);return this.recordWireState(r.sessionId,{models:r.models??null,modes:r.modes??null,configOptions:r.configOptions??null}),{sessionId:r.sessionId,state:this.computeState(r.sessionId)}}async prompt(e){let n=await this.requireConnection().prompt({sessionId:e.sessionId,prompt:C8t(e.prompt)}),r=n.usage;if(r&&!this.sawLiveUsage.has(e.sessionId)){let o=this.domainHandlers.get(e.sessionId);o&&o(this.withBackendContextWindow({sessionId:e.sessionId,update:{sessionUpdate:"usage_update",usage:{usedTokens:r.totalTokens,inputTokens:r.inputTokens,outputTokens:r.outputTokens,cacheReadTokens:r.cachedReadTokens??void 0,cacheWriteTokens:r.cachedWriteTokens??void 0,updatedAt:Date.now()}}}))}return this.refreshPlanUsage(),{stopReason:S8t(n.stopReason)}}refreshPlanUsage(){return!this.backend.readPlanUsage||!this.connection?Promise.resolve():this.planUsageRead?(this.planUsageReadQueued=!0,this.planUsageRead):(this.planUsageRead=this.readAndPublishPlanUsage().finally(()=>{this.planUsageRead=null,this.planUsageReadQueued&&(this.planUsageReadQueued=!1,this.refreshPlanUsage())}),this.planUsageRead)}async readAndPublishPlanUsage(){if(!this.backend.readPlanUsage)return;let e;try{e=await this.backend.readPlanUsage()}catch(n){W(`[AgentMode] ${this.backend.id} plan usage read threw`,n);return}if(this.connection&&e.kind!=="unavailable"){this.lastPlanUsage=e.kind==="usage"?e.planUsage:null;for(let[n,r]of this.domainHandlers)try{r({sessionId:n,update:{sessionUpdate:"plan_usage_update",planUsage:this.planUsageFor(n)}})}catch(o){W(`[AgentMode] plan usage dispatch threw for ${n}`,o)}}}planUsageFor(e){return this.lastPlanUsage&&(this.backend.planUsageAppliesTo?.(this.currentWireModelId(e))??!0)?this.lastPlanUsage:null}republishPlanUsage(e){!this.lastPlanUsage||!this.backend.planUsageAppliesTo||this.domainHandlers.get(e)?.({sessionId:e,update:{sessionUpdate:"plan_usage_update",planUsage:this.planUsageFor(e)}})}async cancel(e){return this.requireConnection().cancel(I8t(e))}hasCapability(e){return this.capabilities.get(e)===!0}supportsAdditionalDirectories(){return this.hasCapability("session/additional_directories")}additionalDirectoriesField(e){return this.supportsAdditionalDirectories()&&e?.length?{additionalDirectories:e}:{}}async setSessionModel(e){await this.dispatchCapability("session/set_model",r=>r.unstable_setSessionModel({sessionId:e.sessionId,modelId:e.modelId}));let n=this.sessionWireState.get(e.sessionId);return n&&(n.models?n.models={...n.models,currentModelId:e.modelId}:n.configOptions=Lvr(n.configOptions,e.modelId)),this.republishPlanUsage(e.sessionId),this.computeState(e.sessionId)}isSetSessionModelSupported(){return this.capabilitySupported("session/set_model")}async setSessionMode(e){await this.dispatchCapability("session/set_mode",r=>r.setSessionMode({sessionId:e.sessionId,modeId:e.modeId}));let n=this.sessionWireState.get(e.sessionId);if(n){let r=n.modes??{availableModes:[],currentModeId:""};n.modes={...r,currentModeId:e.modeId}}return this.computeState(e.sessionId)}isSetSessionModeSupported(){return this.capabilitySupported("session/set_mode")}async setSessionConfigOption(e){let n=await this.dispatchCapability("session/set_config_option",o=>o.setSessionConfigOption({sessionId:e.sessionId,configId:e.configId,value:e.value})),r=this.sessionWireState.get(e.sessionId);return r&&(r.configOptions=n.configOptions),this.republishPlanUsage(e.sessionId),this.computeState(e.sessionId)}isSetSessionConfigOptionSupported(){return this.capabilitySupported("session/set_config_option")}async dispatchCapability(e,n,r={}){let o=this.capabilities.get(e);if(o===!1||r.mustBeAdvertised&&o!==!0)throw new da(e);try{let i=await n(this.requireConnection());return this.capabilities.set(e,!0),i}catch(i){throw Nvr(i)?(this.capabilities.set(e,!1),new da(e)):i}}capabilitySupported(e){return this.capabilities.has(e)?this.capabilities.get(e):null}async listSessions(e){return{sessions:(await this.dispatchCapability("session/list",r=>r.listSessions(e.cwd?{cwd:e.cwd}:{}),{mustBeAdvertised:!0})).sessions.map(r=>T8t({sessionId:r.sessionId,cwd:r.cwd,title:r.title??null,updatedAt:r.updatedAt??null}))}}async resumeSession(e){let n=await this.dispatchCapability("session/resume",r=>r.resumeSession({sessionId:e.sessionId,cwd:e.cwd,mcpServers:[],...this.additionalDirectoriesField(e.additionalDirectories)}),{mustBeAdvertised:!0});return this.recordWireState(e.sessionId,{models:n.models??null,modes:n.modes??null,configOptions:n.configOptions??null}),{sessionId:e.sessionId,state:this.computeState(e.sessionId)}}async loadSession(e){let n=e.sessionId,r=m8t();this.loadSessionCollectors.set(n,r);try{let o=await this.dispatchCapability("session/load",i=>i.loadSession({sessionId:n,cwd:e.cwd,mcpServers:[],...this.additionalDirectoriesField(e.additionalDirectories)}),{mustBeAdvertised:!0});return this.recordWireState(n,{models:o.models??null,modes:o.modes??null,configOptions:o.configOptions??null}),{sessionId:n,state:this.computeState(n),transcript:g8t(r)}}finally{this.loadSessionCollectors.get(n)===r&&this.loadSessionCollectors.delete(n)}}async shutdown(){if(this.connection=null,this.domainHandlers.clear(),this.pendingUpdates.clear(),this.sessionWireState.clear(),this.todoToolCallIdsBySession.clear(),this.loadSessionCollectors.clear(),this.sawLiveUsage.clear(),this.permissionPrompter=null,this.capabilities.clear(),this.lastPlanUsage=null,this.backendContextWindows.clear(),this.process){try{await this.process.shutdown()}catch(e){H("[AgentMode] backend shutdown failed",e)}this.process=null}}requireConnection(){if(!this.connection)throw new Error(this.process?"AcpBackendProcess subprocess has exited":"AcpBackendProcess.start() not called");return this.connection}recordWireState(e,n){this.sessionWireState.set(e,n)}todoToolCallIdsFor(e){let n=this.todoToolCallIdsBySession.get(e);return n||(n=new Set,this.todoToolCallIdsBySession.set(e,n)),n}computeState(e){let n=this.sessionWireState.get(e)??{models:null,modes:null,configOptions:null};return x8t(n.models,n.modes,n.configOptions,this.descriptor)}routeSessionUpdate(e,n){let r=e;if(n.update.sessionUpdate==="agent_message_chunk"&&n.update.content.type==="text"&&this.backend.shouldRouteAgentMessageText?.(n.update.content.text)===!1)return;let o=this.loadSessionCollectors.get(r);if(o&&h8t(o,n.update))return;let i=this.sessionWireState.get(r);if(i){let l=n.update;if(l.sessionUpdate==="current_mode_update"){let c=i.modes??{availableModes:[],currentModeId:""};i.modes={...c,currentModeId:l.currentModeId}}else l.sessionUpdate==="config_option_update"&&(i.configOptions=l.configOptions)}n.update.sessionUpdate==="usage_update"&&this.sawLiveUsage.add(r);let s=this.domainHandlers.get(r);if(!s){let l=this.pendingUpdates.get(r);if(l||(l=[],this.pendingUpdates.set(r,l)),l.length>=Sve.PENDING_UPDATE_LIMIT){let c=n.update.sessionUpdate??"unknown";W(`[AgentMode] dropping session/update for ${r}: pending buffer full (${l.length}, kind=${c})`);return}l.push(n);return}let a=n.update.sessionUpdate;if(a==="current_mode_update"||a==="config_option_update"){s({sessionId:r,update:{sessionUpdate:"state_changed",state:this.computeState(r)}}),a==="config_option_update"&&this.republishPlanUsage(r);return}for(let l of T8e(n,this.todoToolCallIdsFor(r)))s(this.withBackendContextWindow(l))}withBackendContextWindow(e){if(!this.backend.readContextWindow||e.update.sessionUpdate!=="usage_update")return e;let n=e.update.usage;if(n.contextWindow)return e;let r=this.currentWireModelId(e.sessionId);if(!r)return e;let o=this.backendContextWindows.get(r);return o===void 0?(this.resolveBackendContextWindow(e.sessionId,r,n),e):{sessionId:e.sessionId,update:{sessionUpdate:"usage_update",usage:{...n,contextWindow:o}}}}async readContextWindow(e){if(!e||!this.backend.readContextWindow)return null;let n=this.backendContextWindows.get(e);if(n!==void 0)return n;let r;try{r=await this.backend.readContextWindow(e)??null}catch(o){return W(`[AgentMode] ${this.backend.id} context window read threw for ${e}`,o),null}return r&&this.backendContextWindows.set(e,r),r}async resolveBackendContextWindow(e,n,r){let o=await this.readContextWindow(n);o&&this.currentWireModelId(e)===n&&this.domainHandlers.get(e)?.({sessionId:e,update:{sessionUpdate:"usage_update",usage:{...r,contextWindow:o}}})}currentWireModelId(e){let n=this.sessionWireState.get(e);if(!n)return null;if(n.models?.currentModelId)return n.models.currentModelId;for(let r of n.configOptions??[])if(r.type==="select"&&r.category==="model"&&r.currentValue)return r.currentValue;return null}async handlePermission(e){if(!this.permissionPrompter)return W("[AgentMode] permission requested but no prompter is registered; auto-cancelling"),{outcome:{outcome:"cancelled"}};let n=await this.permissionPrompter(k8t(e,(r,o)=>this.descriptor.presentPermissionOption?.(r,o)??r));return n}};Sve.PENDING_UPDATE_LIMIT=32;xve=Sve});function M8t(t,e){let n=Pe("path");return yNe([n.dirname(t),...L9()],e)}var O8t=b(()=>{aP();$n()});function N8t(t,e,n,r){if(!t)throw new Error(e);return{command:t,args:[],env:{...process.env,PATH:M8t(t,process.env.PATH),...r??{},...n??{}}}}function Cve(t,e=n=>Pe("fs").existsSync(n)){return!t||!e(t)?{kind:"absent"}:{kind:"ready",source:"custom"}}function kve(t,e){return new xve(t.app,e,t.clientVersion,t.descriptor)}var PX=b(()=>{E8t();O8t();$n()});function $vr(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t===10080?"Weekly":t%1440===0?`${t/1440}d`:t%60===0?`${t/60}h`:`${Math.round(t)}m`}function Dvr(t){if(!(typeof t!="number"||!Number.isFinite(t)||t<=0))return Math.round(t*1e3)}function Uvr(t,e=Date.now()){let n=[];for(let r of Fvr){let o=t?.[r],i=QB(o?.used_percent),s=$vr(o?.window_minutes);i===null||s===null||n.push({id:r,label:s,percent:i,resetsAt:Dvr(o?.resets_at)})}return ez(n,e)}function Ive(){return Pe("fs")}function xW(){return Pe("path")}function R8t(){let t=Pe("os");return xW().join(t.homedir(),".codex")}async function L8t(t){try{let e=await Hvr(xW().join(t,"sessions"),jvr),n=await Wvr(e);for(let r of n.slice(0,Bvr)){let o=qvr(await Vvr(r));if(!o)continue;let i=Uvr(o);if(i.kind!=="usage")return i;let s=QP(i.planUsage);return s?{kind:"usage",planUsage:s}:{kind:"unavailable"}}return j("[AgentMode] no Codex rollout carries rate limits; plan caps unavailable"),{kind:"unavailable"}}catch(e){return j("[AgentMode] Codex plan cap read failed; plan caps unavailable",e),{kind:"unavailable"}}}async function Hvr(t,e){let n=[];for(let r of await P8e(t))for(let o of await P8e(xW().join(t,r)))for(let i of await P8e(xW().join(t,r,o)))if(n.push(xW().join(t,r,o,i)),n.length>=e)return n;return n}async function P8e(t){try{return(await Ive().promises.readdir(t,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name).sort().reverse()}catch{return[]}}async function Wvr(t){let e=[];for(let n of t){let r;try{r=await Ive().promises.readdir(n)}catch{continue}for(let o of r){if(!o.startsWith("rollout-")||!o.endsWith(".jsonl"))continue;let i=xW().join(n,o);try{let s=await Ive().promises.stat(i);e.push({file:i,mtimeMs:s.mtimeMs})}catch{}}}return e.sort((n,r)=>r.mtimeMs-n.mtimeMs).map(n=>n.file)}async function Vvr(t){let e=await Ive().promises.open(t,"r");try{let{size:n}=await e.stat(),r=Math.max(0,n-zvr),o=Buffer.alloc(n-r);await e.read(o,0,o.length,r);let i=o.toString("utf-8");if(r===0)return i;let s=i.indexOf(`
`);return s===-1?"":i.slice(s+1)}finally{await e.close()}}function qvr(t){let e=t.split(`
`);for(let n=e.length-1;n>=0;n--){let r=e[n];if(r?.includes('"rate_limits"'))try{let i=JSON.parse(r).payload?.rate_limits;if(i)return i}catch{}}return null}var Fvr,jvr,Bvr,zvr,$8t=b(()=>{$n();HR();pe();Fvr=["primary","secondary"];jvr=7,Bvr=8,zvr=256*1024});function Kvr(t){if(!t?.trim())return{};let e;try{e=JSON.parse(t)}catch{throw new Error("Codex CODEX_CONFIG must be a valid JSON object.")}if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("Codex CODEX_CONFIG must be a valid JSON object.");return e}function D8t(t,e){let n={developer_instructions:e,approval_policy:"on-request",approvals_reviewer:"user",sandbox_mode:"workspace-write"};return JSON.stringify({...Kvr(t),...n})}var F8t=b(()=>{});function U8t(t){return!Gvr.some(e=>e.test(t.trim()))}var Gvr,j8t=b(()=>{Gvr=[/^Warning: Skill descriptions were shortened to fit the \d+% skills context budget\. Codex can still see every skill, but some descriptions are shorter\. Disable unused skills or plugins to leave more room for the rest\.$/,/^Warning: Skill descriptions were shortened to fit the skills context budget\. Codex can still see every skill, but some descriptions are shorter\.$/]});function Zvr(t){let e='"';for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);r===92?e+="\\\\":r===34?e+='\\"':r===8?e+="\\b":r===9?e+="\\t":r===10?e+="\\n":r===12?e+="\\f":r===13?e+="\\r":r<32||r===127?e+="\\u"+r.toString(16).padStart(4,"0"):e+=t[n]}return e+='"',e}var Tve,B8t=b(()=>{Se();PX();O9();Vye();$8t();F8t();j8t();Tve=class{constructor(e=""){this.clientVersion=e;this.id="codex";this.displayName="Codex";this.shouldRouteAgentMessageText=U8t;this.codexHome=null}async buildSpawnDescriptor(e){let n=N8t(Y().agentMode?.backends?.codex?.binaryPath,"Codex binary path not configured. Open Agent Mode settings and set the path to codex-acp.",Y().agentMode?.backends?.codex?.envOverrides,{...await nW(this.clientVersion,e.vaultBasePath),INITIAL_AGENT_MODE:"agent"}),r=sP();return n.env.CODEX_CONFIG=D8t(n.env.CODEX_CONFIG,r),n.args=[...n.args,"-c",`developer_instructions=${Zvr(r)}`,"-c",'approval_policy="on-request"',"-c",'sandbox_mode="workspace-write"'],this.codexHome=n.env.CODEX_HOME??R8t(),n}async readPlanUsage(){return this.codexHome===null?{kind:"unavailable"}:L8t(this.codexHome)}}});function z8t(t){return t==="win32"?"/absolute/path/to/codex-acp.exe":"/absolute/path/to/codex-acp"}var SW,H8t,W8t,A8e=b(()=>{SW="codex-acp";H8t=process.platform==="win32"?"irm https://gist.githubusercontent.com/logancyang/380ef4dbf9f98900771da76eca3d21e6/raw/install-codex-agent-mode-windows.ps1 | iex":"npm install -g @agentclientprotocol/codex-acp",W8t="codex login"});var _g,V8t,q8t=b(()=>{A8e();Kye();s$();D9e();_g=L(B()),V8t=({state:t,binaryPath:e,onSavePath:n,onClearPath:r,detect:o,searchedDirs:i,onClose:s})=>_g.default.createElement(lW,{title:"Configure Codex",state:t,onClose:s},_g.default.createElement(hE,{title:"codex-acp binary"},_g.default.createElement("p",{className:"tw-my-0 tw-text-sm tw-text-muted"},"Copilot spawns the ",_g.default.createElement("code",null,SW)," adapter on this machine. Auto-detect checks the usual install locations and your PATH."),_g.default.createElement(iW,{binaryName:SW,placeholder:z8t(process.platform),initialPath:e,notFoundHint:`${SW} not found in known install locations or PATH. Run the install command below, then click Auto-detect again.`,onSave:n,onClear:r,persistOnAutoDetect:!0,detect:o,searchedDirs:i})),_g.default.createElement(hE,{title:"Don't have it yet?"},_g.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},_g.default.createElement(uW,{index:1,title:"Install it"},_g.default.createElement(cW,{command:H8t})),_g.default.createElement(uW,{index:2,title:"Sign in"},_g.default.createElement(cW,{command:W8t}),_g.default.createElement("p",{className:"tw-my-0 tw-text-sm tw-text-muted"},"Copilot inherits whatever credentials the Codex CLI holds \u2014 there is no key to paste here.")))))});var E8e,AX,Yvr,Pve,K8t=b(()=>{q8t();PX();s$();Kj();Se();oW();E8e=require("obsidian"),AX=L(B());Ave();Yvr=({onClose:t})=>{let n=xt().agentMode?.backends?.codex?.binaryPath??"",r=Cve(n),o=AX.default.useCallback(async s=>{let a=await qye(s);return a||(EX({binaryPath:s}),new E8e.Notice("Codex binary path saved."),null)},[]),i=AX.default.useCallback(()=>{EX({binaryPath:void 0}),new E8e.Notice("Codex binary path cleared.")},[]);return AX.default.createElement(V8t,{state:r,binaryPath:n,onSavePath:o,onClearPath:i,detect:G8t,searchedDirs:Z8t,onClose:t})},Pve=class extends Uy{constructor(e){super(e,void 0,aW)}renderContent(e){return AX.default.createElement(Yvr,{onClose:e})}}});var M8e,Jvr,Y8t,J8t=b(()=>{M8e=L(B()),Jvr=t=>M8e.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"currentColor",preserveAspectRatio:"xMidYMid",viewBox:"0 0 256 260",...t},M8e.createElement("path",{d:"M239.184 106.203a64.716 64.716 0 0 0-5.576-53.103C219.452 28.459 191 15.784 163.213 21.74A65.586 65.586 0 0 0 52.096 45.22a64.716 64.716 0 0 0-43.23 31.36c-14.31 24.602-11.061 55.634 8.033 76.74a64.665 64.665 0 0 0 5.525 53.102c14.174 24.65 42.644 37.324 70.446 31.36a64.72 64.72 0 0 0 48.754 21.744c28.481.025 53.714-18.361 62.414-45.481a64.767 64.767 0 0 0 43.229-31.36c14.137-24.558 10.875-55.423-8.083-76.483Zm-97.56 136.338a48.397 48.397 0 0 1-31.105-11.255l1.535-.87 51.67-29.825a8.595 8.595 0 0 0 4.247-7.367v-72.85l21.845 12.636c.218.111.37.32.409.563v60.367c-.056 26.818-21.783 48.545-48.601 48.601Zm-104.466-44.61a48.345 48.345 0 0 1-5.781-32.589l1.534.921 51.722 29.826a8.339 8.339 0 0 0 8.441 0l63.181-36.425v25.221a.87.87 0 0 1-.358.665l-52.335 30.184c-23.257 13.398-52.97 5.431-66.404-17.803ZM23.549 85.38a48.499 48.499 0 0 1 25.58-21.333v61.39a8.288 8.288 0 0 0 4.195 7.316l62.874 36.272-21.845 12.636a.819.819 0 0 1-.767 0L41.353 151.53c-23.211-13.454-31.171-43.144-17.804-66.405v.256Zm179.466 41.695-63.08-36.63L161.73 77.86a.819.819 0 0 1 .768 0l52.233 30.184a48.6 48.6 0 0 1-7.316 87.635v-61.391a8.544 8.544 0 0 0-4.4-7.213Zm21.742-32.69-1.535-.922-51.619-30.081a8.39 8.39 0 0 0-8.492 0L99.98 99.808V74.587a.716.716 0 0 1 .307-.665l52.233-30.133a48.652 48.652 0 0 1 72.236 50.391v.205ZM88.061 139.097l-21.845-12.585a.87.87 0 0 1-.41-.614V65.685a48.652 48.652 0 0 1 79.757-37.346l-1.535.87-51.67 29.825a8.595 8.595 0 0 0-4.246 7.367l-.051 72.697Zm11.868-25.58 28.138-16.217 28.188 16.218v32.434l-28.086 16.218-28.188-16.218-.052-32.434Z"})),Y8t=Jvr});var X8t,Q8t,eZt=b(()=>{tve();Se();X8t=L(B());Ave();Q8t=()=>{let t=xt();return X8t.default.createElement(fW,{backendDisplayName:"Codex",value:t.agentMode?.backends?.codex?.envOverrides,onChange:e=>EX({envOverrides:e}),hintExamples:["CODEX_HOME","OPENAI_BASE_URL"]})}});function tZt(t){let e=t.platform==="win32"?oZt(t):rZt(t);for(let n of e)if(n&&t.fs.existsSync(n))return n;return null}function nZt(t){let e=t.platform==="win32"?oZt(t):rZt(t),n=Pe("path"),r=t.platform==="win32"?n.win32:n.posix;return Array.from(new Set(e.map(o=>r.dirname(o))))}function rZt(t){let e=Pe("path").posix,{homeDir:n}=t;return[e.join(n,".local","bin"),e.join(n,".codex-acp","bin"),...tx(t),"/usr/local/bin","/opt/homebrew/bin"].map(o=>e.join(o,"codex-acp"))}function oZt(t){let e=Pe("path").win32,{homeDir:n,env:r}=t,o=r.LOCALAPPDATA??e.join(n,"AppData","Local"),i=r.APPDATA??e.join(n,"AppData","Roaming"),s=e.join(i,"npm"),a=[e.join(o,"Programs","codex-acp","codex-acp.exe"),e.join(o,"codex-acp","package","bin","codex-acp.exe"),e.join(o,"codex-acp","codex-acp.exe"),e.join(n,".local","bin","codex-acp.exe")];for(let l of[...tx(t),s])a.push(e.join(l,"codex-acp.exe")),a.push(e.join(l,"node_modules","@zed-industries","codex-acp-win32-x64","bin","codex-acp.exe")),a.push(e.join(l,"node_modules","@zed-industries","codex-acp-win32-arm64","bin","codex-acp.exe")),a.push(e.join(l,"node_modules","@zed-industries","codex-acp","node_modules","@zed-industries","codex-acp-win32-x64","bin","codex-acp.exe")),a.push(e.join(l,"node_modules","@zed-industries","codex-acp","node_modules","@zed-industries","codex-acp-win32-arm64","bin","codex-acp.exe"));return a}var iZt=b(()=>{$n();N9()});function N8e(t,e){return e.find(n=>t.has(n))}function sZt(t){if(!t)return{kind:"setMode",canonical:Xvr,readOnlyModeId:"read-only"};let e=new Set(t.availableModes.map(n=>n.id));return{kind:"setMode",canonical:{default:N8e(e,O8e.default),plan:N8e(e,O8e.plan),auto:N8e(e,O8e.auto)},readOnlyModeId:e.has("read-only")?"read-only":null}}var O8e,Xvr,aZt=b(()=>{O8e={default:["agent","auto","default"],plan:["plan","read-only"],auto:["agent-full-access","full-access","bypassPermissions"]},Xvr={default:"auto",plan:"read-only",auto:"full-access"}});function EX(t){xC("codex",t)}function lZt(){let t=Pe("fs");return{homeDir:Pe("os").homedir(),platform:process.platform,env:process.env,fs:{existsSync:n=>t.existsSync(n),readFileSync:(n,r)=>t.readFileSync(n,r),readdirSync:n=>t.readdirSync(n)}}}async function G8t(){let t=tZt(lZt());return t||rW(SW)}function Z8t(){return nZt(lZt())}function ewr(t){if(t===null||typeof t!="object")return;let e=t.codex;if(!(e===null||typeof e!="object"))return e.decision}var Qvr,R8e,L8e,Ave=b(()=>{$n();Se();B8t();K8t();J8t();eZt();MUe();PX();oW();iZt();A8e();aZt();Qvr=new Set(["minimal","low","medium","high","xhigh"]);R8e={encode:t=>t.effort?`${t.baseModelId}/${t.effort}`:t.baseModelId,decode:t=>{if(!t)return{selection:{baseModelId:t,effort:null},provider:null};let e=t.split("/");return e.length===1?{selection:{baseModelId:t,effort:null},provider:null}:e.length===2&&Qvr.has(e[1])?{selection:{baseModelId:e[0],effort:e[1]},provider:null}:{selection:{baseModelId:t,effort:null},provider:null}}},L8e={id:"codex",displayName:"Codex",Icon:Y8t,selfHostable:!1,routesCopilotModels:!1,setupDescription:"OpenAI models, billed to your ChatGPT subscription. Runs the codex-acp adapter on your machine.",skillsProjectDir:".agents/skills",crossDiscoveredAgents:[],restartOnManagedSkillsChange:!1,restartOnProviderConfigChange:!1,restartOnSystemPromptChange:!0,summarizesSessionTitle:!1,wire:R8e,showModelDescriptions:!0,getEnabledModelEntries(t){return[..._de(t,"codex",e=>R8e.decode(e))]},normalizeModelName(t){return t.replace(/^gpt/i,"GPT")},presentPermissionOption(t,e){let n=ewr(e),r=n==="acceptWithExecpolicyAmendment"&&t.kind==="allow_always",o=n==="applyNetworkPolicyAmendment"&&(t.kind==="allow_always"||t.kind==="reject_always");return!r&&!o?t:{...t,name:t.kind==="reject_always"?"Block Always":"Allow Always",description:t.name}},getInstallState(t){return Cve(t.agentMode?.backends?.codex?.binaryPath)},getResolvedBinaryPath(t){return t.agentMode?.backends?.codex?.binaryPath??null},subscribeInstallState(t,e){return zr((n,r)=>{n.agentMode?.backends?.codex?.binaryPath!==r.agentMode?.backends?.codex?.binaryPath&&e()})},openInstallUI(t){new Pve(t.app).open()},async applySelection(t,e){await t.applyModelWireId(R8e.encode(e))},createBackendProcess(t){return kve(t,new Tve(t.clientVersion))},SettingsPanel:Q8t,getModeMapping(t){return sZt(t)}}});function uZt(t,e=[]){let n=[];function r(i,s){let a=CI.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=CI.useMemo(()=>m,Object.values(m));return(0,cZt.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=CI.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>CI.createContext(s));return function(a){let l=a?.[t]||i;return CI.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,twr(o,...e)]}function twr(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return CI.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var CI,cZt,dZt=b(()=>{CI=L(B(),1),cZt=L(Mt(),1)});function fZt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function pZt(...t){return e=>{let n=!1,r=t.map(o=>{let i=fZt(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():fZt(t[o],null)}}}}var nwr,mZt=b(()=>{nwr=L(B(),1)});function hZt(t){let e=rwr(t),n=Xc.forwardRef((r,o)=>{let{children:i,...s}=r,a=Xc.Children.toArray(i),l=a.find(iwr);if(l){let c=l.props.children,u=a.map(d=>d===l?Xc.Children.count(c)>1?Xc.Children.only(null):Xc.isValidElement(c)?c.props.children:null:d);return(0,Eve.jsx)(e,{...s,ref:o,children:Xc.isValidElement(c)?Xc.cloneElement(c,void 0,u):null})}return(0,Eve.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function rwr(t){let e=Xc.forwardRef((n,r)=>{let{children:o,...i}=n;if(Xc.isValidElement(o)){let s=awr(o),a=swr(i,o.props);return o.type!==Xc.Fragment&&(a.ref=r?pZt(r,s):s),Xc.cloneElement(o,a)}return Xc.Children.count(o)>1?Xc.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}function iwr(t){return Xc.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===owr}function swr(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function awr(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Xc,Eve,owr,gZt=b(()=>{Xc=L(B(),1);mZt();Eve=L(Mt(),1);owr=Symbol("radix.slottable")});var yZt,lwr,vZt,cwr,$8e,wZt=b(()=>{yZt=L(B(),1),lwr=L(Es(),1);gZt();vZt=L(Mt(),1),cwr=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],$8e=cwr.reduce((t,e)=>{let n=hZt(`Primitive.${e}`),r=yZt.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,vZt.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{})});function pwr(t,e){return`${Math.round(t/e*100)}%`}function kZt(t,e){return t==null?"indeterminate":t===e?"complete":"loading"}function Ove(t){return typeof t=="number"}function bZt(t){return Ove(t)&&!isNaN(t)&&t>0}function _Zt(t,e){return Ove(t)&&!isNaN(t)&&t<=e&&t>=0}function mwr(t,e){return`Invalid prop \`max\` of value \`${t}\` supplied to \`${e}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${U8e}\`.`}function hwr(t,e){return`Invalid prop \`value\` of value \`${t}\` supplied to \`${e}\`. The \`value\` prop must be:
- a positive number
- less than the value passed to \`max\` (or ${U8e} if no \`max\` prop is set)
- \`null\` or \`undefined\` if the progress is indeterminate.
Defaulting to \`null\`.`}var D8e,Mve,F8e,U8e,uwr,sXo,dwr,fwr,xZt,SZt,CZt,j8e,IZt,TZt=b(()=>{"use client";D8e=L(B(),1);dZt();wZt();Mve=L(Mt(),1),F8e="Progress",U8e=100,[uwr,sXo]=uZt(F8e),[dwr,fwr]=uwr(F8e),xZt=D8e.forwardRef((t,e)=>{let{__scopeProgress:n,value:r=null,max:o,getValueLabel:i=pwr,...s}=t;(o||o===0)&&!bZt(o)&&console.error(mwr(`${o}`,"Progress"));let a=bZt(o)?o:U8e;r!==null&&!_Zt(r,a)&&console.error(hwr(`${r}`,"Progress"));let l=_Zt(r,a)?r:null,c=Ove(l)?i(l,a):void 0;return(0,Mve.jsx)(dwr,{scope:n,value:l,max:a,children:(0,Mve.jsx)($8e.div,{"aria-valuemax":a,"aria-valuemin":0,"aria-valuenow":Ove(l)?l:void 0,"aria-valuetext":c,role:"progressbar","data-state":kZt(l,a),"data-value":l??void 0,"data-max":a,...s,ref:e})})});xZt.displayName=F8e;SZt="ProgressIndicator",CZt=D8e.forwardRef((t,e)=>{let{__scopeProgress:n,...r}=t,o=fwr(SZt,n);return(0,Mve.jsx)($8e.div,{"data-state":kZt(o.value,o.max),"data-value":o.value??void 0,"data-max":o.max,...r,ref:e})});CZt.displayName=SZt;j8e=xZt,IZt=CZt});var MX,Op,d$=b(()=>{MX=L(B());TZt();De();Op=MX.forwardRef(({className:t,value:e,...n},r)=>MX.createElement(j8e,{ref:r,className:J("tw-relative tw-h-2 tw-w-full tw-overflow-hidden tw-rounded-full tw-bg-interactive-accent/20 tw-border-interactive-accent/30",t),...n},MX.createElement(IZt,{className:"tw-size-full tw-flex-1 tw-bg-interactive-accent tw-transition-all",style:{transform:`translateX(-${100-Math.min(Math.max(e||0,0),100)}%)`}})));Op.displayName=j8e.displayName});function NX({options:t,value:e,onChange:n,disabled:r=!1,"aria-label":o,className:i}){let s=OX.useRef([]),a=t.map((f,p)=>f.disabled||r?-1:p).filter(f=>f!==-1),l=t.findIndex(f=>f.value===e),c=l!==-1&&a.includes(l)?l:a[0]??-1,u=(f,p)=>{if(a.length===0)return;let h=(a.indexOf(f)+p+a.length)%a.length,g=a[h];s.current[g]?.focus(),n(t[g].value)},d=(f,p)=>{switch(f.key){case"ArrowRight":case"ArrowDown":f.preventDefault(),u(p,1);break;case"ArrowLeft":case"ArrowUp":f.preventDefault(),u(p,-1);break;default:break}};return OX.createElement("div",{role:"radiogroup","aria-label":o,"aria-disabled":r||void 0,className:J("tw-inline-flex tw-overflow-hidden tw-rounded-md tw-border tw-border-solid tw-border-border tw-text-ui-smaller tw-font-medium",i)},t.map((f,p)=>{let m=f.value===e,h=r||f.disabled;return OX.createElement("button",{key:f.value,ref:g=>{s.current[p]=g},type:"button",role:"radio","aria-checked":m,disabled:h,tabIndex:p===c?0:-1,onClick:()=>!h&&n(f.value),onKeyDown:g=>d(g,p),className:J("tw-cursor-pointer !tw-rounded-none tw-border-none !tw-px-3 !tw-py-1.5 !tw-shadow-none tw-transition-colors focus-visible:tw-outline-none focus-visible:tw-ring-1 focus-visible:tw-ring-ring",p>0&&"tw-border-l tw-border-solid tw-border-border",m?"!tw-bg-interactive-accent !tw-text-on-accent":"!tw-bg-secondary tw-text-muted hover:!tw-bg-modifier-hover hover:tw-text-normal",h&&"tw-cursor-not-allowed tw-opacity-50")},f.label)}))}var OX,B8e=b(()=>{De();OX=L(B())});var Zr,ywr,vwr,PZt,AZt=b(()=>{Kye();s$();yt();d$();B8e();De();Zr=L(B()),ywr=[{label:"Managed by Copilot",value:"managed"},{label:"My own binary",value:"custom"}],vwr=({managed:t,installed:e,actions:n})=>{let{run:r}=t;return r.kind==="running"?Zr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Zr.default.createElement("p",{className:"tw-my-0 tw-text-sm"},r.label),Zr.default.createElement(Op,{value:r.percent}),Zr.default.createElement("div",{className:"tw-flex tw-justify-end"},Zr.default.createElement(oe,{variant:"ghost",size:"default",onClick:n.cancelInstall},"Cancel"))):Zr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Zr.default.createElement("dl",{className:"tw-my-0 tw-grid tw-grid-cols-[max-content_1fr] tw-gap-x-4 tw-gap-y-1 tw-text-sm [&>dd]:tw-ml-0"},Zr.default.createElement("dt",{className:"tw-text-muted"},"Platform"),Zr.default.createElement("dd",{className:"tw-font-mono"},t.platform),Zr.default.createElement("dt",{className:"tw-text-muted"},"Version"),Zr.default.createElement("dd",{className:"tw-font-mono"},"v",t.version," (pinned)"),Zr.default.createElement("dt",{className:"tw-text-muted"},"Destination"),Zr.default.createElement("dd",{className:"tw-break-all tw-font-mono tw-text-xs"},t.destination)),r.kind==="error"&&Zr.default.createElement("pre",{className:"tw-my-0 tw-max-h-32 tw-overflow-auto tw-whitespace-pre-wrap tw-rounded tw-bg-secondary tw-p-2 tw-text-xs tw-text-error"},r.message),Zr.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},e?Zr.default.createElement(Zr.default.Fragment,null,Zr.default.createElement(oe,{variant:"secondary",size:"default",onClick:n.install},"Reinstall"),Zr.default.createElement(oe,{variant:"destructive",size:"default",onClick:n.uninstall},"Uninstall")):Zr.default.createElement(oe,{variant:"default",size:"default",onClick:n.install},"Download & install")))},PZt=({state:t,source:e,onSourceChange:n,activeSource:r,managed:o,customPath:i,upgradeRun:s,actions:a,onClose:l})=>Zr.default.createElement(lW,{title:"Configure opencode",state:t,warning:Zr.default.createElement(Zye,{state:t,action:s.kind==="running"?Zr.default.createElement(Zr.default.Fragment,null,Zr.default.createElement("p",{className:"tw-my-0 tw-text-xs"},s.label),Zr.default.createElement(Op,{value:s.percent})):Zr.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-end tw-gap-2"},s.kind==="error"&&Zr.default.createElement("span",{className:"tw-text-xs tw-text-error"},s.message),Zr.default.createElement(oe,{variant:"default",size:"sm",onClick:a.upgrade},r==="custom"?"Run opencode upgrade":"Upgrade to latest"))}),onClose:l},Zr.default.createElement(hE,null,Zr.default.createElement(NX,{"aria-label":"opencode binary source",className:J("tw-self-start"),options:ywr,value:e,onChange:n,disabled:o.run.kind==="running"}),e==="managed"?Zr.default.createElement(Zr.default.Fragment,null,Zr.default.createElement("p",{className:"tw-my-0 tw-text-sm tw-text-muted"},"Let Copilot download and manage the official opencode binary from its GitHub repo."),r==="custom"&&Zr.default.createElement("p",{className:"tw-my-0 tw-text-sm tw-text-muted"},"Your own binary is in use right now \u2014 download the managed copy to switch to it."),Zr.default.createElement(vwr,{managed:o,installed:r==="managed",actions:a})):Zr.default.createElement(Zr.default.Fragment,null,Zr.default.createElement("p",{className:"tw-my-0 tw-text-sm tw-text-muted"},"Point Agent Mode at a binary you already have on disk. Useful for self-builders or air-gapped machines."),r==="managed"&&Zr.default.createElement("p",{className:"tw-my-0 tw-text-sm tw-text-muted"},"The managed binary is in use right now \u2014 apply a path here to switch to it."),Zr.default.createElement(iW,{binaryName:"opencode",placeholder:"/absolute/path/to/opencode",initialPath:i,notFoundHint:"opencode not found. Install it natively (`~/.opencode/bin/opencode[.exe]`), via bun/npm, or paste a custom path manually.",onSave:a.saveCustomPath,onClear:a.clearCustomPath,persistOnAutoDetect:!0,detect:a.detectCustomPath}))))});var CW,RX,z8e=b(()=>{CW="1.18.16",RX="1.16.0"});async function Np(t,e,n=3){let r=Pe("fs"),o;for(let i=0;i<n;i++)try{await r.promises.rename(t,e);return}catch(s){o=s,await new Promise(a=>window.setTimeout(a,200))}throw o}var kW=b(()=>{$n()});function EZt(t){let{override:e,fs:n}=t;if(e&&n.existsSync(e))return e;let r=t.platform==="win32"?bwr(t):wwr(t);for(let o of r)if(o&&n.existsSync(o))return o;return null}function wwr(t){let e=Pe("path").posix,{homeDir:n}=t,r=[...tx(t),...R9];return[e.join(n,".opencode","bin","opencode"),e.join(n,".bun","bin","opencode"),e.join(n,".local","bin","opencode"),...r.map(o=>e.join(o,"opencode"))]}function bwr(t){let e=Pe("path").win32,{homeDir:n,env:r}=t,o=r.LOCALAPPDATA??e.join(n,"AppData","Local"),i=r.ProgramFiles??"C:\\Program Files",s=r["ProgramFiles(x86)"]??"C:\\Program Files (x86)",a=[e.join(n,".opencode","bin","opencode.exe"),e.join(n,".bun","bin","opencode.exe"),e.join(n,".local","bin","opencode.exe"),e.join(o,"opencode","bin","opencode.exe"),e.join(i,"opencode","bin","opencode.exe"),e.join(s,"opencode","bin","opencode.exe")];for(let l of tx(t))a.push(e.join(l,"opencode.exe"));return a}var MZt=b(()=>{aP();$n();N9()});async function LX(){let t=Pe("fs"),e=Pe("os"),n=EZt({override:void 0,homeDir:e.homedir(),platform:process.platform,env:process.env,fs:{existsSync:r=>t.existsSync(r),readFileSync:(r,o)=>t.readFileSync(r,o),readdirSync:r=>t.readdirSync(r)}});return n||rW("opencode")}var H8e=b(()=>{oW();$n();MZt()});function _wr(t){let e=`opencode-${t.platform}-${t.arch}`,n=[];return t.platform==="linux"&&t.libc==="musl"&&n.push(`${e}-musl`),t.arch==="x64"&&t.hasAvx2===!1&&n.push(`${e}-baseline`),n.push(e),[...new Set(n)]}function W8e(t){if(t==="darwin")return"darwin";if(t==="linux")return"linux";if(t==="win32")return"windows"}function V8e(t){if(t==="x64")return"x64";if(t==="arm64")return"arm64";if(t==="arm")return"arm"}async function xwr(){if(process.platform!=="linux")return!1;let t=Pe("fs"),{execFile:e}=Pe("child_process"),{promisify:n}=Pe("util"),r=n(e);try{return await t.promises.access("/etc/alpine-release"),!0}catch{}try{let{stdout:o,stderr:i}=await r("ldd",["--version"]);return/musl/i.test(`${o}
${i}`)}catch{return!1}}async function Swr(){if(process.arch!=="x64")return!1;let t=Pe("fs"),{execFile:e}=Pe("child_process"),{promisify:n}=Pe("util"),r=n(e);try{if(process.platform==="darwin"){let{stdout:o}=await r("sysctl",["-n","hw.optional.avx2_0"]);return o.trim()==="1"}if(process.platform==="linux"){let o=await t.promises.readFile("/proc/cpuinfo","utf-8");return/\bavx2\b/.test(o)}if(process.platform==="win32"){let{stdout:o}=await r("powershell.exe",["-NoProfile","-Command","[System.Runtime.Intrinsics.X86.Avx2]::IsSupported"]);return/true/i.test(o)}}catch{}return!0}async function OZt(){let t=W8e(process.platform),e=V8e(process.arch);if(!t||!e)throw new Error(`Unsupported platform/arch: ${process.platform}/${process.arch}. Agent Mode requires darwin/linux/windows on x64/arm64.`);let[n,r]=await Promise.all([t==="linux"?xwr():Promise.resolve(!1),e==="x64"?Swr():Promise.resolve(void 0)]),s={platform:t,arch:e,libc:t==="linux"?n?"musl":"glibc":void 0,hasAvx2:e==="x64"?r:void 0};return{target:s,candidates:_wr(s)}}function NZt(t){return t==="windows"?"opencode.exe":"opencode"}var q8e=b(()=>{$n()});function Vu(){return Pe("fs")}function Wu(){return Pe("path")}async function DZt(t,e,n){let{execFile:r}=Pe("child_process"),{promisify:o}=Pe("util"),{stdout:i}=await o(r)(t,e,n);return{stdout:i}}function Iwr(t,e){let n=[".zip",".tar.gz",".tar.xz",".tgz"],r=i=>{for(let s of n)if(i.endsWith(s))return i.slice(0,-s.length);return i},o=new Map;for(let i of t.assets)o.set(r(i.name),i);for(let i of e){let s=o.get(i);if(s)return s}throw new Error(`No matching opencode release asset found. Tried: ${e.join(", ")}. Available: ${t.assets.map(i=>i.name).join(", ")}`)}function TW(t,e=n=>Vu().existsSync(n)){let n=t??{};return n.binaryPath&&n.binaryVersion&&e(n.binaryPath)?{kind:"installed",version:n.binaryVersion,path:n.binaryPath,source:n.binarySource??"managed"}:{kind:"absent"}}function IW(){return Y().agentMode?.backends?.opencode??{}}function FZt(t){return t?Dae(t,RX)<0:!1}function Lve(t){return t.kind==="absent"?t:FZt(t.version)?{kind:"incompatible",source:t.source,currentVersion:t.version,minVersion:RX,message:`opencode v${t.version} is not supported. Copilot requires opencode v${RX} or newer.`}:{kind:"ready",source:t.source}}function $X(t){En(e=>({agentMode:{...e.agentMode,backends:{...e.agentMode.backends,opencode:{...e.agentMode.backends?.opencode??{},...t}}}}))}function K8e(){$X({binaryVersion:void 0,binaryPath:void 0,binarySource:void 0})}function Twr(t){return Wu().join(TU(t),"opencode")}function Pwr(t,e,n){return Wu().join(t,e,"plugins",n,"data","opencode")}function $Zt(t){return t.match(/\d+\.\d+\.\d+(?:[-+][\w.]+)?/)?.[0]}async function G8e(t){try{return await Vu().promises.access(t),!0}catch{return!1}}async function Awr(t){try{let e=await Vu().promises.readFile(t,"utf-8");return JSON.parse(e)}catch{return null}}async function Nve(t){await Vu().promises.rm(t,{recursive:!0,force:!0})}async function UZt(t){let e;try{e=await Vu().promises.readdir(t,{withFileTypes:!0})}catch{return 0}let n=0;for(let r of e){let o=Wu().join(t,r.name);r.isDirectory()?n+=await UZt(o):r.isFile()&&(n+=await Vu().promises.stat(o).then(i=>i.size).catch(()=>0))}return n}function Ewr(t,e,n=5){let r=Pe("https");return new Promise((o,i)=>{let s=(a,l)=>{let c=null,u=()=>{c&&e?.removeEventListener("abort",c),c=null},d=r.get(a,f=>{let p=f.statusCode??0;if(p>=300&&p<400&&f.headers.location){if(u(),l<=0){f.resume(),i(new Error(`Too many redirects fetching ${t}`));return}f.resume();let m=new URL(f.headers.location,a).toString();s(m,l-1);return}if(p!==200){u(),f.resume(),i(new Error(`HTTP ${p} fetching ${a}`));return}f.on("close",u),o(f)});d.on("error",f=>{u(),i(f)}),e&&(e.aborted?d.destroy(new Rb):(c=()=>{d.destroy(new Rb)},e.addEventListener("abort",c,{once:!0})))};s(t,n)})}async function Mwr(t,e,n,r){let o=Wu().basename(e),i=await Ewr(t,r.signal),s=n??(i.headers["content-length"]?Number(i.headers["content-length"]):void 0),a=0,l=!1,c=null,u=Vu().createWriteStream(e);await new Promise((d,f)=>{let p=()=>{c&&(window.clearTimeout(c),c=null)},m=()=>{p(),c=window.setTimeout(()=>{l=!0,i.destroy(new Error(`Download stalled \u2014 no bytes received for ${Math.round(RZt/1e3)}s. Check your network and retry.`))},RZt)};m(),i.on("data",g=>{a+=g.length,m(),r.onProgress?.({phase:"download",received:a,total:s,assetName:o})});let h=g=>{p(),f(g)};i.on("error",h),u.on("error",h),u.on("finish",()=>{p(),!l&&d()}),i.pipe(u)})}async function Owr(t,e){let{spawn:n}=Pe("child_process");await new Promise((r,o)=>{let i=n("tar",["-xf",t,"-C",e],{stdio:["ignore","pipe","pipe"]}),s="";i.stderr.on("data",a=>{s+=Buffer.from(a).toString()}),i.on("error",a=>{a.code==="ENOENT"?o(new Error("`tar` was not found on PATH. macOS/Linux ship it by default; on Windows you need 10 1803+ (which ships `tar.exe`/bsdtar) or to install bsdtar manually.")):o(new Error(`Failed to launch tar: ${a instanceof Error?a.message:String(a)}`))}),i.on("close",a=>{a===0?r():o(new Error(`tar exited with code ${a}: ${s.slice(0,500)}`))})})}async function Nwr(t,e){let n=[t];for(;n.length>0;){let r=n.shift(),o=await Vu().promises.readdir(r,{withFileTypes:!0});for(let i of o){let s=Wu().join(r,i.name);if(i.isDirectory())n.push(s);else if(i.isFile()&&i.name===e)return s}}throw new Error(`File "${e}" not found anywhere under ${t}`)}async function Z8e(t){try{let{stdout:e}=await DZt(t,["--version"],{timeout:LZt,windowsHide:!0});return{stdout:e.toString().trim()}}catch(e){let n=e;throw n.code==="ENOENT"?new Error(`No file at ${t}`):n.signal==="SIGTERM"?new Error(`${t} did not respond to --version within ${LZt}ms. Is this an opencode binary?`):new Error(`${t} --version failed: ${n.message??String(n)}. Is this an opencode binary?`)}}var DX,RZt,LZt,Cwr,wE,FX,kwr,Rb,Rve,$ve=b(()=>{z8e();gt();bNe();pe();Se();DX=require("obsidian");kW();Mae();$n();H8e();q8e();RZt=3e4,LZt=8e3,Cwr=18e4,wE=class extends Error{constructor(){super("An opencode setup operation is already running."),this.name="OperationInFlightError"}},FX=class extends Error{constructor(){super("Couldn't find opencode in the usual install locations or on PATH."),this.name="OpencodeNotFoundError"}},kwr=t=>t instanceof Error?t.message:String(t),Rb=class extends Error{constructor(){super("Aborted"),this.name="AbortError"}};Rve=class{constructor(e){this.plugin=e;this.operation=null;this.runtimeState={kind:"idle"};this.runtimeSubscribers=new Set;this.subscribeRuntimeState=e=>(this.runtimeSubscribers.add(e),()=>{this.runtimeSubscribers.delete(e)});this.getRuntimeState=()=>this.runtimeState}adoptPlugin(e){this.plugin=e}setRuntimeState(e){this.runtimeState=e,this.runtimeSubscribers.forEach(n=>n())}forgetSettledError(){this.operation||this.runtimeState.kind!=="error"||this.setRuntimeState({kind:"idle"})}isBusy(){return this.operation!==null}cancelCurrentOperation(){this.operation?.controller.abort()}async runExclusive(e,n){if(this.operation)throw new wE;let r=new AbortController;this.operation={controller:r},this.setRuntimeState(e);try{let o=await n(r.signal);return this.operation=null,this.setRuntimeState({kind:"idle"}),o}catch(o){throw this.operation=null,o instanceof Rb||o?.name==="AbortError"?this.setRuntimeState({kind:"idle"}):this.setRuntimeState({kind:"error",message:kwr(o)}),o}}getInstallState(){return TW(IW())}async refreshInstallState(){let e=IW();!e.binaryPath||(e.binarySource??"managed")!=="managed"||await G8e(e.binaryPath)||(W(`[AgentMode] persisted opencode binary missing at ${e.binaryPath}; clearing settings.`),K8e())}getDataDir(){if(!(this.plugin.app.vault.adapter instanceof DX.FileSystemAdapter))throw new Error("Agent Mode requires desktop Obsidian (FileSystemAdapter).");let n=Pe("os").homedir();if(!n||!Wu().isAbsolute(n)||Wu().parse(n).root===n)throw new Error("Could not resolve your home directory to install the opencode runtime. Agent Mode installs it under ~/.obsidian-copilot; check that your account has a valid home directory.");return Twr(n)}getPinnedVersion(){return CW}async install(e={}){return this.runExclusive({kind:"installing",progress:null},n=>this.installPipeline({...e,signal:n,onProgress:r=>{this.setRuntimeState({kind:"installing",progress:r}),e.onProgress?.(r)}}))}async installPipeline(e={}){let n=e.version??CW,r=this.getDataDir(),o=Wu().join(r,n);e.onProgress?.({phase:"resolve",message:"Resolving platform asset\u2026"});let{target:i,candidates:s}=await OZt();this.throwIfAborted(e.signal);let a=await this.fetchReleaseMetadata(n);this.throwIfAborted(e.signal);let l=Iwr(a,s),c=NZt(i.platform),u=Wu().join(o,"bin",c),d=await Awr(Wu().join(o,"install-manifest.json"));if(d&&d.assetName===l.name&&await G8e(u)){j(`[AgentMode] opencode ${n} already installed at ${u}`);let m=IW();return(m.binaryVersion!==n||m.binaryPath!==u||m.binarySource!=="managed")&&$X({binaryVersion:n,binaryPath:u,binarySource:"managed"}),e.onProgress?.({phase:"done",version:n,path:u}),{version:n,path:u}}try{await Vu().promises.mkdir(r,{recursive:!0})}catch(m){throw new Error(`Could not create the opencode install directory at ${r}: ${m instanceof Error?m.message:String(m)}. Check that it is writable.`)}let f=Pe("crypto").randomBytes,p=Wu().join(r,`.tmp-${n}-${f(4).toString("hex")}`);await Vu().promises.mkdir(p,{recursive:!0});try{let m=Wu().join(p,l.name);await Mwr(l.browser_download_url,m,l.size,e),this.throwIfAborted(e.signal),e.onProgress?.({phase:"extract",message:"Extracting archive\u2026"});let h=Wu().join(p,"extract");await Vu().promises.mkdir(h,{recursive:!0}),await Owr(m,h),this.throwIfAborted(e.signal);let g=await Nwr(h,c);i.platform!=="windows"&&await Vu().promises.chmod(g,493);let v=Wu().join(p,"stage"),y=Wu().join(v,"bin");await Vu().promises.mkdir(y,{recursive:!0}),await Vu().promises.rename(g,Wu().join(y,c));let w={version:n,assetName:l.name,installedAt:new Date().toISOString()};await Vu().promises.writeFile(Wu().join(v,"install-manifest.json"),JSON.stringify(w,null,2));let _=null;await G8e(o)&&(_=`${o}.old-${f(4).toString("hex")}`,await Np(o,_));try{await Np(v,o)}catch(S){throw _&&await Np(_,o).catch(I=>H("[AgentMode] failed to restore previous opencode install",I)),S}return _&&await Nve(_).catch(S=>W(`[AgentMode] failed to remove ${_}: ${S}`)),await Z8e(u),this.throwIfAborted(e.signal),$X({binaryVersion:n,binaryPath:u,binarySource:"managed"}),e.onProgress?.({phase:"done",version:n,path:u}),j(`[AgentMode] opencode ${n} installed at ${u}`),{version:n,path:u}}catch(m){throw H("[AgentMode] opencode install failed",m),m}finally{await Nve(p).catch(()=>{})}}async upgradeManaged(e={}){return this.runExclusive({kind:"installing",progress:null},async n=>{let r=IW(),o=await this.installPipeline({...e,signal:n,version:CW,onProgress:i=>{this.setRuntimeState({kind:"installing",progress:i}),e.onProgress?.(i)}});if(r.binarySource==="managed"&&r.binaryVersion&&r.binaryVersion!==o.version){let i=Wu().join(this.getDataDir(),r.binaryVersion);await Nve(i).catch(s=>W(`[AgentMode] failed to remove old opencode ${i}: ${s}`))}return o})}async upgradeCustomBinary(){return this.runExclusive({kind:"busy"},async()=>{let e=IW();if(e.binarySource!=="custom"||!e.binaryPath)throw new Error("No custom opencode binary is configured to upgrade.");let n=e.binaryPath;try{await DZt(n,["upgrade"],{timeout:Cwr,windowsHide:!0})}catch(i){let s=i;throw new Error(`\`${n} upgrade\` failed: ${s.message??String(s)}`)}let{stdout:r}=await Z8e(n),o=$Zt(r);if(!o)throw new Error(`${n} --version didn't report a version after upgrade.`);if(FZt(o))throw new Error(`opencode upgrade did not reach the required version ${RX}+ (still v${o}).`);return $X({binaryVersion:o,binaryPath:n,binarySource:"custom"}),j(`[AgentMode] upgraded custom opencode to ${o}`),{version:o,path:n}})}reclaimableDirs(){let e=[];try{e.push(this.getDataDir())}catch{}let n=this.plugin.app.vault.adapter;return n instanceof DX.FileSystemAdapter&&e.push(Pwr(n.getBasePath(),this.plugin.app.vault.configDir,this.plugin.manifest.id)),e}async downloadsSize(){return(await Promise.all(this.reclaimableDirs().map(UZt))).reduce((n,r)=>n+r,0)}async uninstall(){return this.runExclusive({kind:"busy"},async()=>{await Promise.all(this.reclaimableDirs().map(e=>Nve(e))),IW().binarySource!=="custom"&&K8e()})}async setCustomBinaryPath(e){return this.runExclusive({kind:"busy"},()=>this.writeCustomBinaryPath(e))}async adoptExistingBinary(){return this.runExclusive({kind:"detecting"},async()=>{let e=await LX();if(!e)throw new FX;return await this.writeCustomBinaryPath(e),e})}async writeCustomBinaryPath(e){if(e===null){K8e();return}let n=await Vu().promises.stat(e).catch(()=>null);if(!n||!n.isFile())throw new Error(`No file at ${e}`);if(process.platform!=="win32")try{await Vu().promises.access(e,Vu().constants.X_OK)}catch{throw new Error(`${e} is not executable. chmod +x and try again.`)}let{stdout:r}=await Z8e(e),o=$Zt(r);if(!o)throw new Error(`${e} --version output didn't include a version number. Is this an opencode binary?`);$X({binaryVersion:o,binaryPath:e,binarySource:"custom"})}async fetchReleaseMetadata(e){let n=Cct.replace("{version}",e),r=await(0,DX.requestUrl)({url:n,method:"GET",headers:{Accept:"application/vnd.github+json"},throw:!1});if(r.status===403)throw new Error("GitHub API rate-limited (60/hour for unauthenticated requests). Set GITHUB_TOKEN or retry later.");if(r.status===404)throw new Error(`opencode release v${e} not found on GitHub.`);if(r.status<200||r.status>=300)throw new Error(`GitHub release fetch failed with status ${r.status}`);return r.json}throwIfAborted(e){if(e?.aborted)throw new Rb}}});function dS(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}var Y8e=b(()=>{});var fS,xg,J8e,Rwr,Lwr,Dve,jZt=b(()=>{AZt();$ve();UX();s$();Kj();fm();aP();Y8e();z8e();pe();Se();fS=require("obsidian"),xg=L(B()),J8e=t=>{if(!t)return{kind:"running",label:"Starting\u2026",percent:0};switch(t.phase){case"resolve":return{kind:"running",label:t.message,percent:0};case"download":{if(!t.total)return{kind:"running",label:`Downloading ${t.assetName} \u2014 ${dS(t.received)}`,percent:0};let e=Math.min(100,Math.floor(t.received/t.total*100));return{kind:"running",label:`Downloading ${t.assetName} \u2014 ${dS(t.received)} / ${dS(t.total)} (${e}%)`,percent:e}}case"extract":return{kind:"running",label:t.message,percent:98};case"done":return{kind:"running",label:"Done",percent:100}}},Rwr=t=>({kind:"error",message:t instanceof Error?t.message:String(t)}),Lwr=({manager:t,hostPlatform:e,hostArch:n,app:r,onClose:o})=>{let s=xt().agentMode?.backends?.opencode,a=TW(s),l=a.kind==="installed"?a.source:null,c=a.kind==="installed"&&a.source==="custom"?a.path:"",[u,d]=xg.default.useState(s?.binarySource??"managed"),f=xg.default.useSyncExternalStore(t.subscribeRuntimeState,t.getRuntimeState,t.getRuntimeState),[p,m]=xg.default.useState({kind:"idle"}),h=xg.default.useCallback(()=>m({kind:"idle"}),[]),g=f.kind==="installing"?J8e(f.progress):f.kind==="error"?{kind:"error",message:f.message}:{kind:"idle"},v=xg.default.useCallback(()=>{t.install().then(({version:C})=>{h(),new fS.Notice(`opencode v${C} installed.`)}).catch(C=>{if(!(C instanceof Rb||C?.name==="AbortError")){if(C instanceof wE){new fS.Notice(C.message);return}H("[AgentMode] opencode install failed",C)}})},[t,h]),y=xg.default.useCallback(()=>t.cancelCurrentOperation(),[t]),w=xg.default.useCallback(async()=>{let C=await t.downloadsSize().catch(()=>0);new _i(r,async()=>{try{await t.uninstall(),h(),new fS.Notice(`opencode uninstalled${C>0?` (freed ${dS(C)})`:""}.`)}catch(k){H("[AgentMode] uninstall failed",k),new fS.Notice(`Uninstall failed: ${k instanceof Error?k.message:String(k)}`)}},`Remove all downloaded opencode binaries${C>0?` (${dS(C)})`:""}, including any old copy inside your vault? Your custom binary path and BYOK keys are kept.`,"Uninstall opencode","Uninstall").open()},[r,t,h]),_=xg.default.useCallback(()=>{m(J8e(null)),(l==="custom"?t.upgradeCustomBinary():t.upgradeManaged({onProgress:k=>m(J8e(k))})).then(({version:k})=>{m({kind:"idle"}),new fS.Notice(`opencode upgraded to v${k}.`)}).catch(k=>{if(k instanceof Rb||k?.name==="AbortError"){m({kind:"idle"});return}if(k instanceof wE){m({kind:"idle"}),new fS.Notice(k.message);return}H("[AgentMode] opencode upgrade failed",k),m(Rwr(k))})},[t,l]),S=xg.default.useCallback(async C=>{try{await t.setCustomBinaryPath(C)}catch(k){return k instanceof Error?k.message:String(k)}return h(),new fS.Notice("Custom opencode binary path saved."),null},[t,h]),I=xg.default.useCallback(async()=>{try{await t.setCustomBinaryPath(null)}catch(C){new fS.Notice(`Couldn't clear the custom path: ${C instanceof Error?C.message:String(C)}`);return}h(),new fS.Notice("Custom opencode path cleared.")},[t,h]);return xg.default.createElement(PZt,{state:Lve(a),source:u,onSourceChange:d,activeSource:l,managed:{platform:`${e}-${n}`,version:CW,destination:Rae(t.getDataDir()),run:g},customPath:c,upgradeRun:p,actions:{install:v,cancelInstall:y,uninstall:()=>void w(),upgrade:_,saveCustomPath:S,clearCustomPath:I,detectCustomPath:LX},onClose:o})},Dve=class extends Uy{constructor(n,r,o){super(n,void 0,aW);this.manager=r;this.hostInfo=o}renderContent(n){return xg.default.createElement(Lwr,{manager:this.manager,hostPlatform:this.hostInfo.platform,hostArch:this.hostInfo.arch,app:this.app,onClose:n})}}});function BZt(t){if(!t)return"Starting\u2026";switch(t.phase){case"resolve":return t.message;case"download":if(t.total){let e=Math.min(100,Math.floor(t.received/t.total*100));return`Downloading ${t.assetName} \u2014 ${dS(t.received)} / ${dS(t.total)} (${e}%)`}return`Downloading ${t.assetName} \u2014 ${dS(t.received)}`;case"extract":return t.message;case"done":return"Done"}}function zZt(t){if(t){if(t.phase==="download"&&t.total)return Math.min(100,Math.floor(t.received/t.total*100));if(t.phase==="extract")return 98;if(t.phase==="done")return 100}}var HZt=b(()=>{Y8e()});var Sg,WZt,VZt=b(()=>{yt();d$();Re();Sg=L(B()),WZt=({state:t,onInstall:e,onCancel:n,onAdoptExisting:r,onConfigure:o})=>t.kind==="installing"?Sg.default.createElement("div",{className:"tw-flex tw-w-56 tw-shrink-0 tw-items-center tw-gap-2"},Sg.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-flex-col tw-gap-1"},Sg.default.createElement("span",{className:"tw-truncate tw-text-xs tw-text-muted",title:t.label},t.label),Sg.default.createElement(Op,{value:t.percent})),Sg.default.createElement(oe,{variant:"ghost",size:"sm",onClick:n},"Cancel")):Sg.default.createElement("div",{className:"tw-flex tw-shrink-0 tw-flex-col tw-items-end tw-gap-1"},Sg.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Sg.default.createElement(oe,{variant:"default",size:"default",onClick:e,disabled:t.kind==="detecting"},Sg.default.createElement(LC,{className:"tw-size-4"}),t.kind==="error"?"Try again":"Download opencode"),t.kind==="error"?Sg.default.createElement(oe,{variant:"ghost",size:"default",onClick:o},"Configure"):Sg.default.createElement(oe,{variant:"ghost",size:"default",onClick:r,disabled:t.kind==="detecting"},t.kind==="detecting"?"Looking\u2026":"I already have it")),t.kind==="error"&&Sg.default.createElement("span",{className:"tw-max-w-xs tw-text-right tw-text-xs tw-text-error"},t.message))});var X8e,PW,qZt,KZt=b(()=>{UX();HZt();$ve();VZt();pe();X8e=require("obsidian"),PW=L(B()),qZt=({plugin:t})=>{let e=PW.default.useMemo(()=>jX(t),[t]),n=PW.default.useSyncExternalStore(e.subscribeRuntimeState,e.getRuntimeState,e.getRuntimeState),r=a=>l=>{l instanceof wE||l instanceof FX||l instanceof Rb||l?.name==="AbortError"||H(`[AgentMode] ${a}`,l)},o=PW.default.useCallback(()=>{e.install().then(({version:a})=>new X8e.Notice(`opencode v${a} installed.`)).catch(r("inline opencode install failed"))},[e]),i=PW.default.useCallback(()=>{e.adoptExistingBinary().then(a=>new X8e.Notice(`Using the opencode at ${a}.`)).catch(r("adopting an existing opencode failed"))},[e]),s=n.kind==="installing"?{kind:"installing",label:BZt(n.progress),percent:zZt(n.progress)??0}:n.kind==="busy"?{kind:"detecting"}:n;return PW.default.createElement(WZt,{state:s,onInstall:o,onCancel:()=>e.cancelCurrentOperation(),onAdoptExisting:i,onConfigure:()=>kI.openInstallUI(t)})}});var Q8e,$wr,GZt,ZZt=b(()=>{Q8e=L(B()),$wr=t=>Q8e.createElement("svg",{viewBox:"0 0 512 512",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...t},Q8e.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M384 416H128V96H384V416ZM320 160H192V352H320V160Z"})),GZt=$wr});function YZt(t){return(t??"").trim().replace(/\/+$/,"")||void 0}function JZt(t){let e=YZt(t);if(e)return e.replace(/\/v1(beta)?$/i,"")||void 0}function XZt(t){let e=YZt(t);if(e)return e.replace(/(\/openai\/v1|\/openai|\/v1)$/i,"")||void 0}function QZt(t,e){if(!t)return!1;let n=Dwr[t];if(!n)return!1;try{let r=new URL(e.trim()),o=r.pathname.replace(/\/+$/,"").toLowerCase();return r.origin===n&&Fwr.has(o)}catch{return!1}}var Dwr,Fwr,eZe=b(()=>{Dwr={anthropic:"https://api.anthropic.com",google:"https://generativelanguage.googleapis.com",groq:"https://api.groq.com",openai:"https://api.openai.com"},Fwr=new Set(["","/v1","/v1beta","/openai","/openai/v1"])});function Ti(t){if(t&&typeof t=="object")switch(t[Rp]){case Lb:case II:return!0}return!1}function zo(t){if(t&&typeof t=="object")switch(t[Rp]){case Fve:case Lb:case Cg:case II:return!0}return!1}var Fve,Uve,Lb,tZe,Cg,II,Rp,$b,pS,Lp,Lo,Ur,Db,jve,qo=b(()=>{Fve=Symbol.for("yaml.alias"),Uve=Symbol.for("yaml.document"),Lb=Symbol.for("yaml.map"),tZe=Symbol.for("yaml.pair"),Cg=Symbol.for("yaml.scalar"),II=Symbol.for("yaml.seq"),Rp=Symbol.for("yaml.node.type"),$b=t=>!!t&&typeof t=="object"&&t[Rp]===Fve,pS=t=>!!t&&typeof t=="object"&&t[Rp]===Uve,Lp=t=>!!t&&typeof t=="object"&&t[Rp]===Lb,Lo=t=>!!t&&typeof t=="object"&&t[Rp]===tZe,Ur=t=>!!t&&typeof t=="object"&&t[Rp]===Cg,Db=t=>!!t&&typeof t=="object"&&t[Rp]===II;jve=t=>(Ur(t)||Ti(t))&&!!t.anchor});function hS(t,e){let n=t7t(e);pS(t)?AW(null,t.contents,n,Object.freeze([t]))===mS&&(t.contents=null):AW(null,t,n,Object.freeze([]))}function AW(t,e,n,r){let o=n7t(t,e,n,r);if(zo(o)||Lo(o))return r7t(t,r,o),AW(t,o,n,r);if(typeof o!="symbol"){if(Ti(e)){r=Object.freeze(r.concat(e));for(let i=0;i<e.items.length;++i){let s=AW(i,e.items[i],n,r);if(typeof s=="number")i=s-1;else{if(s===Hm)return Hm;s===mS&&(e.items.splice(i,1),i-=1)}}}else if(Lo(e)){r=Object.freeze(r.concat(e));let i=AW("key",e.key,n,r);if(i===Hm)return Hm;i===mS&&(e.key=null);let s=AW("value",e.value,n,r);if(s===Hm)return Hm;s===mS&&(e.value=null)}}return o}async function Bve(t,e){let n=t7t(e);pS(t)?await EW(null,t.contents,n,Object.freeze([t]))===mS&&(t.contents=null):await EW(null,t,n,Object.freeze([]))}async function EW(t,e,n,r){let o=await n7t(t,e,n,r);if(zo(o)||Lo(o))return r7t(t,r,o),EW(t,o,n,r);if(typeof o!="symbol"){if(Ti(e)){r=Object.freeze(r.concat(e));for(let i=0;i<e.items.length;++i){let s=await EW(i,e.items[i],n,r);if(typeof s=="number")i=s-1;else{if(s===Hm)return Hm;s===mS&&(e.items.splice(i,1),i-=1)}}}else if(Lo(e)){r=Object.freeze(r.concat(e));let i=await EW("key",e.key,n,r);if(i===Hm)return Hm;i===mS&&(e.key=null);let s=await EW("value",e.value,n,r);if(s===Hm)return Hm;s===mS&&(e.value=null)}}return o}function t7t(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function n7t(t,e,n,r){if(typeof n=="function")return n(t,e,r);if(Lp(e))return n.Map?.(t,e,r);if(Db(e))return n.Seq?.(t,e,r);if(Lo(e))return n.Pair?.(t,e,r);if(Ur(e))return n.Scalar?.(t,e,r);if($b(e))return n.Alias?.(t,e,r)}function r7t(t,e,n){let r=e[e.length-1];if(Ti(r))r.items[t]=n;else if(Lo(r))t==="key"?r.key=n:r.value=n;else if(pS(r))r.contents=n;else{let o=$b(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}var Hm,e7t,mS,BX=b(()=>{qo();Hm=Symbol("break visit"),e7t=Symbol("skip children"),mS=Symbol("remove node");hS.BREAK=Hm;hS.SKIP=e7t;hS.REMOVE=mS;Bve.BREAK=Hm;Bve.SKIP=e7t;Bve.REMOVE=mS});var Uwr,jwr,gS,nZe=b(()=>{qo();BX();Uwr={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},jwr=t=>t.replace(/[!,[\]{}]/g,e=>Uwr[e]),gS=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let r=e.trim().split(/[ \t]+/),o=r.shift();switch(o){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[i,s]=r;return this.tags[i]=s,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[i]=r;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{let s=/^\d+\.\d+$/.test(i);return n(6,`Unsupported YAML version ${i}`,s),!1}}default:return n(0,`Unknown directive ${o}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let s=e.slice(2,-1);return s==="!"||s==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),s)}let[,r,o]=e.match(/^(.*!)([^!]*)$/s);o||n(`The ${e} tag has no suffix`);let i=this.tags[r];if(i)try{return i+decodeURIComponent(o)}catch(s){return n(String(s)),null}return r==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,r]of Object.entries(this.tags))if(e.startsWith(r))return n+jwr(e.substring(r.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),o;if(e&&r.length>0&&zo(e.contents)){let i={};hS(e.contents,(s,a)=>{zo(a)&&a.tag&&(i[a.tag]=!0)}),o=Object.keys(i)}else o=[];for(let[i,s]of r)i==="!!"&&s==="tag:yaml.org,2002:"||(!e||o.some(a=>a.startsWith(s)))&&n.push(`%TAG ${i} ${s}`);return n.join(`
`)}};gS.defaultYaml={explicit:!1,version:"1.2"};gS.defaultTags={"!!":"tag:yaml.org,2002:"}});function zve(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function rZe(t){let e=new Set;return hS(t,{Value(n,r){r.anchor&&e.add(r.anchor)}}),e}function oZe(t,e){for(let n=1;;++n){let r=`${t}${n}`;if(!e.has(r))return r}}function o7t(t,e){let n=[],r=new Map,o=null;return{onAnchor:i=>{n.push(i),o??(o=rZe(t));let s=oZe(e,o);return o.add(s),s},setAnchors:()=>{for(let i of n){let s=r.get(i);if(typeof s=="object"&&s.anchor&&(Ur(s.node)||Ti(s.node)))s.node.anchor=s.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},sourceObjects:r}}var Hve=b(()=>{qo();BX()});function bE(t,e,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let o=0,i=r.length;o<i;++o){let s=r[o],a=bE(t,r,String(o),s);a===void 0?delete r[o]:a!==s&&(r[o]=a)}else if(r instanceof Map)for(let o of Array.from(r.keys())){let i=r.get(o),s=bE(t,r,o,i);s===void 0?r.delete(o):s!==i&&r.set(o,s)}else if(r instanceof Set)for(let o of Array.from(r)){let i=bE(t,r,o,o);i===void 0?r.delete(o):i!==o&&(r.delete(o),r.add(i))}else for(let[o,i]of Object.entries(r)){let s=bE(t,r,o,i);s===void 0?delete r[o]:s!==i&&(r[o]=s)}return t.call(e,n,r)}var iZe=b(()=>{});function Qc(t,e,n){if(Array.isArray(t))return t.map((r,o)=>Qc(r,String(o),n));if(t&&typeof t.toJSON=="function"){if(!n||!jve(t))return t.toJSON(e,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(t,r),n.onCreate=i=>{r.res=i,delete n.onCreate};let o=t.toJSON(e,n);return n.onCreate&&n.onCreate(o),o}return typeof t=="bigint"&&!n?.keep?Number(t):t}var _E=b(()=>{qo()});var xE,Wve=b(()=>{iZe();qo();_E();xE=class{constructor(e){Object.defineProperty(this,Rp,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:r,onAnchor:o,reviver:i}={}){if(!pS(e))throw new TypeError("A document argument is required");let s={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=Qc(this,"",s);if(typeof o=="function")for(let{count:l,res:c}of s.anchors.values())o(c,l);return typeof i=="function"?bE(i,{"":a},"",a):a}}});function Vve(t,e,n){if($b(e)){let r=e.resolve(t),o=n&&r&&n.get(r);return o?o.count*o.aliasCount:0}else if(Ti(e)){let r=0;for(let o of e.items){let i=Vve(t,o,n);i>r&&(r=i)}return r}else if(Lo(e)){let r=Vve(t,e.key,n),o=Vve(t,e.value,n);return Math.max(r,o)}return 1}var TI,zX=b(()=>{Hve();BX();qo();Wve();_E();TI=class extends xE{constructor(e){super(Fve),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],hS(e,{Node:(i,s)=>{($b(s)||jve(s))&&r.push(s)}}),n&&(n.aliasResolveCache=r));let o;for(let i of r){if(i===this)break;i.anchor===this.source&&(o=i)}return o}toJSON(e,n){if(!n)return{source:this.source};let{anchors:r,doc:o,maxAliasCount:i}=n,s=this.resolve(o,n);if(!s){let l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let a=r.get(s);if(a||(Qc(s,null,n),a=r.get(s)),a?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Vve(o,s,r)),a.count*a.aliasCount>i)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return a.res}toString(e,n,r){let o=`*${this.source}`;if(e){if(zve(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${o} `}return o}}});var qve,un,Ql=b(()=>{qo();Wve();_E();qve=t=>!t||typeof t!="function"&&typeof t!="object",un=class extends xE{constructor(e){super(Cg),this.value=e}toJSON(e,n){return n?.keep?this.value:Qc(this.value,e,n)}toString(){return String(this.value)}};un.BLOCK_FOLDED="BLOCK_FOLDED";un.BLOCK_LITERAL="BLOCK_LITERAL";un.PLAIN="PLAIN";un.QUOTE_DOUBLE="QUOTE_DOUBLE";un.QUOTE_SINGLE="QUOTE_SINGLE"});function zwr(t,e,n){if(e){let r=n.filter(i=>i.tag===e),o=r.find(i=>!i.format)??r[0];if(!o)throw new Error(`Tag ${e} not found`);return o}return n.find(r=>r.identify?.(t)&&!r.format)}function PI(t,e,n){if(pS(t)&&(t=t.contents),zo(t))return t;if(Lo(t)){let d=n.schema[Lb].createNode?.(n.schema,null,n);return d.items.push(t),d}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:r,onAnchor:o,onTagObj:i,schema:s,sourceObjects:a}=n,l;if(r&&t&&typeof t=="object"){if(l=a.get(t),l)return l.anchor??(l.anchor=o(t)),new TI(l.anchor);l={anchor:null,node:null},a.set(t,l)}e?.startsWith("!!")&&(e=Bwr+e.slice(2));let c=zwr(t,e,s.tags);if(!c){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let d=new un(t);return l&&(l.node=d),d}c=t instanceof Map?s[Lb]:Symbol.iterator in Object(t)?s[II]:s[Lb]}i&&(i(c),delete n.onTagObj);let u=c?.createNode?c.createNode(n.schema,t,n):typeof c?.nodeClass?.from=="function"?c.nodeClass.from(n.schema,t,n):new un(t);return e?u.tag=e:c.default||(u.tag=c.tag),l&&(l.node=u),u}var Bwr,HX=b(()=>{zX();qo();Ql();Bwr="tag:yaml.org,2002:"});function WX(t,e,n){let r=n;for(let o=e.length-1;o>=0;--o){let i=e[o];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){let s=[];s[i]=r,r=s}else r=new Map([[i,r]])}return PI(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var OW,MW,Kve=b(()=>{HX();qo();Wve();OW=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,MW=class extends xE{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(r=>zo(r)||Lo(r)?r.clone(e):r),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(OW(e))this.add(n);else{let[r,...o]=e,i=this.get(r,!0);if(Ti(i))i.addIn(o,n);else if(i===void 0&&this.schema)this.set(r,WX(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}deleteIn(e){let[n,...r]=e;if(r.length===0)return this.delete(n);let o=this.get(n,!0);if(Ti(o))return o.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(e,n){let[r,...o]=e,i=this.get(r,!0);return o.length===0?!n&&Ur(i)?i.value:i:Ti(i)?i.getIn(o,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!Lo(n))return!1;let r=n.value;return r==null||e&&Ur(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[n,...r]=e;if(r.length===0)return this.has(n);let o=this.get(n,!0);return Ti(o)?o.hasIn(r):!1}setIn(e,n){let[r,...o]=e;if(o.length===0)this.set(r,n);else{let i=this.get(r,!0);if(Ti(i))i.setIn(o,n);else if(i===void 0&&this.schema)this.set(r,WX(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}}});function Pv(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var i7t,yS,VX=b(()=>{i7t=t=>t.replace(/^(?!$)(?: $)?/gm,"#");yS=(t,e,n)=>t.endsWith(`
`)?Pv(n,e):n.includes(`
`)?`
`+Pv(n,e):(t.endsWith(" ")?"":" ")+n});function KX(t,e,n="flow",{indentAtStart:r,lineWidth:o=80,minContentWidth:i=20,onFold:s,onOverflow:a}={}){if(!o||o<0)return t;o<i&&(i=0);let l=Math.max(1+i,1+o-e.length);if(t.length<=l)return t;let c=[],u={},d=o-e.length;typeof r=="number"&&(r>o-Math.max(2,i)?c.push(0):d=o-r);let f,p,m=!1,h=-1,g=-1,v=-1;n===Gve&&(h=s7t(t,h,e.length),h!==-1&&(d=h+l));for(let w;w=t[h+=1];){if(n===qX&&w==="\\"){switch(g=h,t[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}v=h}if(w===`
`)n===Gve&&(h=s7t(t,h,e.length)),d=h+e.length+l,f=void 0;else{if(w===" "&&p&&p!==" "&&p!==`
`&&p!==" "){let _=t[h+1];_&&_!==" "&&_!==`
`&&_!==" "&&(f=h)}if(h>=d)if(f)c.push(f),d=f+l,f=void 0;else if(n===qX){for(;p===" "||p===" ";)p=w,w=t[h+=1],m=!0;let _=h>v+1?h-2:g-1;if(u[_])return t;c.push(_),u[_]=!0,d=_+l,f=void 0}else m=!0}p=w}if(m&&a&&a(),c.length===0)return t;s&&s();let y=t.slice(0,c[0]);for(let w=0;w<c.length;++w){let _=c[w],S=c[w+1]||t.length;_===0?y=`
${e}${t.slice(0,S)}`:(n===qX&&u[_]&&(y+=`${t[_]}\\`),y+=`
${e}${t.slice(_+1,S)}`)}return y}function s7t(t,e,n){let r=e,o=e+1,i=t[o];for(;i===" "||i===" ";)if(e<o+n)i=t[++e];else{do i=t[++e];while(i&&i!==`
`);r=e,o=e+1,i=t[o]}return r}var sZe,Gve,qX,a7t=b(()=>{sZe="flow",Gve="block",qX="quoted"});function Hwr(t,e,n){if(!e||e<0)return!1;let r=e-n,o=t.length;if(o<=r)return!1;for(let i=0,s=0;i<o;++i)if(t[i]===`
`){if(i-s>r)return!0;if(s=i+1,o-s<=r)return!1}return!0}function GX(t,e){let n=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=e,o=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(Jve(t)?" ":""),s="",a=0;for(let l=0,c=n[l];c;c=n[++l])if(c===" "&&n[l+1]==="\\"&&n[l+2]==="n"&&(s+=n.slice(a,l)+"\\ ",l+=1,a=l,c="\\"),c==="\\")switch(n[l+1]){case"u":{s+=n.slice(a,l);let u=n.substr(l+2,4);switch(u){case"0000":s+="\\0";break;case"0007":s+="\\a";break;case"000b":s+="\\v";break;case"001b":s+="\\e";break;case"0085":s+="\\N";break;case"00a0":s+="\\_";break;case"2028":s+="\\L";break;case"2029":s+="\\P";break;default:u.substr(0,2)==="00"?s+="\\x"+u.substr(2):s+=n.substr(l,6)}l+=5,a=l+1}break;case"n":if(r||n[l+2]==='"'||n.length<o)l+=1;else{for(s+=n.slice(a,l)+`
`;n[l+2]==="\\"&&n[l+3]==="n"&&n[l+4]!=='"';)s+=`
`,l+=2;s+=i,n[l+2]===" "&&(s+="\\"),l+=1,a=l+1}break;default:l+=1}return s=a?s+n.slice(a):n,r?s:KX(s,i,qX,Yve(e,!1))}function aZe(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
`)||/[ \t]\n|\n[ \t]/.test(t))return GX(t,e);let n=e.indent||(Jve(t)?" ":""),r="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
${n}`)+"'";return e.implicitKey?r:KX(r,n,sZe,Yve(e,!1))}function NW(t,e){let{singleQuote:n}=e.options,r;if(n===!1)r=GX;else{let o=t.includes('"'),i=t.includes("'");o&&!i?r=aZe:i&&!o?r=GX:r=n?aZe:GX}return r(t,e)}function Zve({comment:t,type:e,value:n},r,o,i){let{blockQuote:s,commentString:a,lineWidth:l}=r.options;if(!s||/\n[\t ]+$/.test(n))return NW(n,r);let c=r.indent||(r.forceBlockIndent||Jve(n)?" ":""),u=s==="literal"?!0:s==="folded"||e===un.BLOCK_FOLDED?!1:e===un.BLOCK_LITERAL?!0:!Hwr(n,l,c.length);if(!n)return u?`|
`:`>
`;let d,f;for(f=n.length;f>0;--f){let S=n[f-1];if(S!==`
`&&S!==" "&&S!==" ")break}let p=n.substring(f),m=p.indexOf(`
`);m===-1?d="-":n===p||m!==p.length-1?(d="+",i&&i()):d="",p&&(n=n.slice(0,-p.length),p[p.length-1]===`
`&&(p=p.slice(0,-1)),p=p.replace(lZe,`$&${c}`));let h=!1,g,v=-1;for(g=0;g<n.length;++g){let S=n[g];if(S===" ")h=!0;else if(S===`
`)v=g;else break}let y=n.substring(0,v<g?v+1:g);y&&(n=n.substring(y.length),y=y.replace(/\n+/g,`$&${c}`));let _=(h?c?"2":"1":"")+d;if(t&&(_+=" "+a(t.replace(/ ?[\r\n]+/g," ")),o&&o()),!u){let S=n.replace(/\n+/g,`
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${c}`),I=!1,C=Yve(r,!0);s!=="folded"&&e!==un.BLOCK_FOLDED&&(C.onOverflow=()=>{I=!0});let k=KX(`${y}${S}${p}`,c,Gve,C);if(!I)return`>${_}
${c}${k}`}return n=n.replace(/\n+/g,`$&${c}`),`|${_}
${c}${y}${n}${p}`}function Wwr(t,e,n,r){let{type:o,value:i}=t,{actualString:s,implicitKey:a,indent:l,indentStep:c,inFlow:u}=e;if(a&&i.includes(`
`)||u&&/[[\]{},]/.test(i))return NW(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||u||!i.includes(`
`)?NW(i,e):Zve(t,e,n,r);if(!a&&!u&&o!==un.PLAIN&&i.includes(`
`))return Zve(t,e,n,r);if(Jve(i)){if(l==="")return e.forceBlockIndent=!0,Zve(t,e,n,r);if(a&&l===c)return NW(i,e)}let d=i.replace(/\n+/g,`$&
${l}`);if(s){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:m}=e.doc.schema;if(m.some(f)||p?.some(f))return NW(i,e)}return a?d:KX(d,l,sZe,Yve(e,!1))}function f$(t,e,n,r){let{implicitKey:o,inFlow:i}=e,s=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==un.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(s.value)&&(a=un.QUOTE_DOUBLE);let l=u=>{switch(u){case un.BLOCK_FOLDED:case un.BLOCK_LITERAL:return o||i?NW(s.value,e):Zve(s,e,n,r);case un.QUOTE_DOUBLE:return GX(s.value,e);case un.QUOTE_SINGLE:return aZe(s.value,e);case un.PLAIN:return Wwr(s,e,n,r);default:return null}},c=l(a);if(c===null){let{defaultKeyType:u,defaultStringType:d}=e.options,f=o&&u||d;if(c=l(f),c===null)throw new Error(`Unsupported default string type ${f}`)}return c}var Yve,Jve,lZe,ZX=b(()=>{Ql();a7t();Yve=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),Jve=t=>/^(%|---|\.\.\.)/m.test(t);try{lZe=new RegExp(`(^|(?<!
))
+(?!
|$)`,"g")}catch{lZe=/\n+(?!\n|$)/g}});function Xve(t,e){let n=Object.assign({blockQuote:!0,commentString:i7t,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),r;switch(n.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:t,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:r,options:n}}function Vwr(t,e){if(e.tag){let o=t.filter(i=>i.tag===e.tag);if(o.length>0)return o.find(i=>i.format===e.format)??o[0]}let n,r;if(Ur(e)){r=e.value;let o=t.filter(i=>i.identify?.(r));if(o.length>1){let i=o.filter(s=>s.test);i.length>0&&(o=i)}n=o.find(i=>i.format===e.format)??o.find(i=>!i.format)}else r=e,n=t.find(o=>o.nodeClass&&r instanceof o.nodeClass);if(!n){let o=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${o} value`)}return n}function qwr(t,e,{anchors:n,doc:r}){if(!r.directives)return"";let o=[],i=(Ur(t)||Ti(t))&&t.anchor;i&&zve(i)&&(n.add(i),o.push(`&${i}`));let s=t.tag??(e.default?null:e.tag);return s&&o.push(r.directives.tagString(s)),o.join(" ")}function AI(t,e,n,r){if(Lo(t))return t.toString(e,n,r);if($b(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let o,i=zo(t)?t:e.doc.createNode(t,{onTagObj:l=>o=l});o??(o=Vwr(e.doc.schema.tags,i));let s=qwr(i,o,e);s.length>0&&(e.indentAtStart=(e.indentAtStart??0)+s.length+1);let a=typeof o.stringify=="function"?o.stringify(i,e,n,r):Ur(i)?f$(i,e,n,r):i.toString(e,n,r);return s?Ur(i)||a[0]==="{"||a[0]==="["?`${s} ${a}`:`${s}
${e.indent}${a}`:a}var YX=b(()=>{Hve();qo();VX();ZX()});function l7t({key:t,value:e},n,r,o){let{allNullValues:i,doc:s,indent:a,indentStep:l,options:{commentString:c,indentSeq:u,simpleKeys:d}}=n,f=zo(t)&&t.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Ti(t)||!zo(t)&&typeof t=="object"){let C="With simple keys, collection cannot be used as a key value";throw new Error(C)}}let p=!d&&(!t||f&&e==null&&!n.inFlow||Ti(t)||(Ur(t)?t.type===un.BLOCK_FOLDED||t.type===un.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!i),indent:a+l});let m=!1,h=!1,g=AI(t,n,()=>m=!0,()=>h=!0);if(!p&&!n.inFlow&&g.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(n.inFlow){if(i||e==null)return m&&r&&r(),g===""?"?":p?`? ${g}`:g}else if(i&&!d||e==null&&p)return g=`? ${g}`,f&&!m?g+=yS(g,n.indent,c(f)):h&&o&&o(),g;m&&(f=null),p?(f&&(g+=yS(g,n.indent,c(f))),g=`? ${g}
${a}:`):(g=`${g}:`,f&&(g+=yS(g,n.indent,c(f))));let v,y,w;zo(e)?(v=!!e.spaceBefore,y=e.commentBefore,w=e.comment):(v=!1,y=null,w=null,e&&typeof e=="object"&&(e=s.createNode(e))),n.implicitKey=!1,!p&&!f&&Ur(e)&&(n.indentAtStart=g.length+1),h=!1,!u&&l.length>=2&&!n.inFlow&&!p&&Db(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let _=!1,S=AI(e,n,()=>_=!0,()=>h=!0),I=" ";if(f||v||y){if(I=v?`
`:"",y){let C=c(y);I+=`
${Pv(C,n.indent)}`}S===""&&!n.inFlow?I===`
`&&w&&(I=`
`):I+=`
${n.indent}`}else if(!p&&Ti(e)){let C=S[0],k=S.indexOf(`
`),T=k!==-1,P=n.inFlow??e.flow??e.items.length===0;if(T||!P){let E=!1;if(T&&(C==="&"||C==="!")){let O=S.indexOf(" ");C==="&"&&O!==-1&&O<k&&S[O+1]==="!"&&(O=S.indexOf(" ",O+1)),(O===-1||k<O)&&(E=!0)}E||(I=`
${n.indent}`)}}else(S===""||S[0]===`
`)&&(I="");return g+=I+S,n.inFlow?_&&r&&r():w&&!_?g+=yS(g,n.indent,c(w)):h&&o&&o(),g}var c7t=b(()=>{qo();Ql();YX();VX()});function cZe(t,e){(t==="debug"||t==="warn")&&console.warn(e)}var uZe=b(()=>{});function fZe(t,e,n){let r=d7t(t,n);if(Db(r))for(let o of r.items)dZe(t,e,o);else if(Array.isArray(r))for(let o of r)dZe(t,e,o);else dZe(t,e,r)}function dZe(t,e,n){let r=d7t(t,n);if(!Lp(r))throw new Error("Merge sources must be maps or map aliases");let o=r.toJSON(null,t,Map);for(let[i,s]of o)e instanceof Map?e.has(i)||e.set(i,s):e instanceof Set?e.add(i):Object.prototype.hasOwnProperty.call(e,i)||Object.defineProperty(e,i,{value:s,writable:!0,enumerable:!0,configurable:!0});return e}function d7t(t,e){return t&&$b(e)?e.resolve(t.doc,t):e}var Qve,Fb,u7t,ewe=b(()=>{qo();Ql();Qve="<<",Fb={identify:t=>t===Qve||typeof t=="symbol"&&t.description===Qve,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new un(Symbol(Qve)),{addToJSMap:fZe}),stringify:()=>Qve},u7t=(t,e)=>(Fb.identify(e)||Ur(e)&&(!e.type||e.type===un.PLAIN)&&Fb.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===Fb.tag&&n.default)});function twe(t,e,{key:n,value:r}){if(zo(n)&&n.addToJSMap)n.addToJSMap(t,e,r);else if(u7t(t,n))fZe(t,e,r);else{let o=Qc(n,"",t);if(e instanceof Map)e.set(o,Qc(r,o,t));else if(e instanceof Set)e.add(o);else{let i=Kwr(n,o,t),s=Qc(r,i,t);i in e?Object.defineProperty(e,i,{value:s,writable:!0,enumerable:!0,configurable:!0}):e[i]=s}}return e}function Kwr(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(zo(t)&&n?.doc){let r=Xve(n.doc,{});r.anchors=new Set;for(let i of n.anchors.keys())r.anchors.add(i.anchor);r.inFlow=!0,r.inStringifyKey=!0;let o=t.toString(r);if(!n.mapKeyWarned){let i=JSON.stringify(o);i.length>40&&(i=i.substring(0,36)+'..."'),cZe(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return o}return JSON.stringify(e)}var pZe=b(()=>{uZe();ewe();YX();qo();_E()});function RW(t,e,n){let r=PI(t,void 0,n),o=PI(e,void 0,n);return new tl(r,o)}var tl,SE=b(()=>{HX();c7t();pZe();qo();tl=class t{constructor(e,n=null){Object.defineProperty(this,Rp,{value:tZe}),this.key=e,this.value=n}clone(e){let{key:n,value:r}=this;return zo(n)&&(n=n.clone(e)),zo(r)&&(r=r.clone(e)),new t(n,r)}toJSON(e,n){let r=n?.mapAsMap?new Map:{};return twe(n,r,this)}toString(e,n,r){return e?.doc?l7t(this,e,n,r):JSON.stringify(this)}}});function rwe(t,e,n){return(e.inFlow??t.flow?Zwr:Gwr)(t,e,n)}function Gwr({comment:t,items:e},n,{blockItemPrefix:r,flowChars:o,itemIndent:i,onChompKeep:s,onComment:a}){let{indent:l,options:{commentString:c}}=n,u=Object.assign({},n,{indent:i,type:null}),d=!1,f=[];for(let m=0;m<e.length;++m){let h=e[m],g=null;if(zo(h))!d&&h.spaceBefore&&f.push(""),nwe(n,f,h.commentBefore,d),h.comment&&(g=h.comment);else if(Lo(h)){let y=zo(h.key)?h.key:null;y&&(!d&&y.spaceBefore&&f.push(""),nwe(n,f,y.commentBefore,d))}d=!1;let v=AI(h,u,()=>g=null,()=>d=!0);g&&(v+=yS(v,i,c(g))),d&&g&&(d=!1),f.push(r+v)}let p;if(f.length===0)p=o.start+o.end;else{p=f[0];for(let m=1;m<f.length;++m){let h=f[m];p+=h?`
${l}${h}`:`
`}}return t?(p+=`
`+Pv(c(t),l),a&&a()):d&&s&&s(),p}function Zwr({items:t},e,{flowChars:n,itemIndent:r}){let{indent:o,indentStep:i,flowCollectionPadding:s,options:{commentString:a}}=e;r+=i;let l=Object.assign({},e,{indent:r,inFlow:!0,type:null}),c=!1,u=0,d=[];for(let m=0;m<t.length;++m){let h=t[m],g=null;if(zo(h))h.spaceBefore&&d.push(""),nwe(e,d,h.commentBefore,!1),h.comment&&(g=h.comment);else if(Lo(h)){let y=zo(h.key)?h.key:null;y&&(y.spaceBefore&&d.push(""),nwe(e,d,y.commentBefore,!1),y.comment&&(c=!0));let w=zo(h.value)?h.value:null;w?(w.comment&&(g=w.comment),w.commentBefore&&(c=!0)):h.value==null&&y?.comment&&(g=y.comment)}g&&(c=!0);let v=AI(h,l,()=>g=null);c||(c=d.length>u||v.includes(`
`)),m<t.length-1?v+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(c||(c=d.reduce((y,w)=>y+w.length+2,2)+(v.length+2)>e.options.lineWidth)),c&&(v+=",")),g&&(v+=yS(v,r,a(g))),d.push(v),u=d.length}let{start:f,end:p}=n;if(d.length===0)return f+p;if(!c){let m=d.reduce((h,g)=>h+g.length+2,2);c=e.options.lineWidth>0&&m>e.options.lineWidth}if(c){let m=f;for(let h of d)m+=h?`
${i}${o}${h}`:`
`;return`${m}
${o}${p}`}else return`${f}${s}${d.join(" ")}${s}${p}`}function nwe({indent:t,options:{commentString:e}},n,r,o){if(r&&o&&(r=r.replace(/^\n+/,"")),r){let i=Pv(e(r),t);n.push(i.trimStart())}}var mZe=b(()=>{qo();YX();VX()});function CE(t,e){let n=Ur(e)?e.value:e;for(let r of t)if(Lo(r)&&(r.key===e||r.key===n||Ur(r.key)&&r.key.value===n))return r}var La,kE=b(()=>{mZe();pZe();Kve();qo();SE();Ql();La=class extends MW{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Lb,e),this.items=[]}static from(e,n,r){let{keepUndefined:o,replacer:i}=r,s=new this(e),a=(l,c)=>{if(typeof i=="function")c=i.call(n,l,c);else if(Array.isArray(i)&&!i.includes(l))return;(c!==void 0||o)&&s.items.push(RW(l,c,r))};if(n instanceof Map)for(let[l,c]of n)a(l,c);else if(n&&typeof n=="object")for(let l of Object.keys(n))a(l,n[l]);return typeof e.sortMapEntries=="function"&&s.items.sort(e.sortMapEntries),s}add(e,n){let r;Lo(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new tl(e,e?.value):r=new tl(e.key,e.value);let o=CE(this.items,r.key),i=this.schema?.sortMapEntries;if(o){if(!n)throw new Error(`Key ${r.key} already set`);Ur(o.value)&&qve(r.value)?o.value.value=r.value:o.value=r.value}else if(i){let s=this.items.findIndex(a=>i(r,a)<0);s===-1?this.items.push(r):this.items.splice(s,0,r)}else this.items.push(r)}delete(e){let n=CE(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let o=CE(this.items,e)?.value;return(!n&&Ur(o)?o.value:o)??void 0}has(e){return!!CE(this.items,e)}set(e,n){this.add(new tl(e,n),!0)}toJSON(e,n,r){let o=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(o);for(let i of this.items)twe(n,o,i);return o}toString(e,n,r){if(!e)return JSON.stringify(this);for(let o of this.items)if(!Lo(o))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),rwe(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:n})}}});var Ub,LW=b(()=>{qo();kE();Ub={collection:"map",default:!0,nodeClass:La,tag:"tag:yaml.org,2002:map",resolve(t,e){return Lp(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>La.from(t,e,n)}});function owe(t){let e=Ur(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}var Tf,IE=b(()=>{HX();mZe();Kve();qo();Ql();_E();Tf=class extends MW{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(II,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=owe(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let r=owe(e);if(typeof r!="number")return;let o=this.items[r];return!n&&Ur(o)?o.value:o}has(e){let n=owe(e);return typeof n=="number"&&n<this.items.length}set(e,n){let r=owe(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);let o=this.items[r];Ur(o)&&qve(n)?o.value=n:this.items[r]=n}toJSON(e,n){let r=[];n?.onCreate&&n.onCreate(r);let o=0;for(let i of this.items)r.push(Qc(i,String(o++),n));return r}toString(e,n,r){return e?rwe(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:r,onComment:n}):JSON.stringify(this)}static from(e,n,r){let{replacer:o}=r,i=new this(e);if(n&&Symbol.iterator in Object(n)){let s=0;for(let a of n){if(typeof o=="function"){let l=n instanceof Set?a:String(s++);a=o.call(n,l,a)}i.items.push(PI(a,void 0,r))}}return i}}});var jb,$W=b(()=>{qo();IE();jb={collection:"seq",default:!0,nodeClass:Tf,tag:"tag:yaml.org,2002:seq",resolve(t,e){return Db(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>Tf.from(t,e,n)}});var TE,JX=b(()=>{ZX();TE={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,r){return e=Object.assign({actualString:!0},e),f$(t,e,n,r)}}});var p$,iwe=b(()=>{Ql();p$={identify:t=>t==null,createNode:()=>new un(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new un(null),stringify:({source:t},e)=>typeof t=="string"&&p$.test.test(t)?t:e.options.nullStr}});var XX,hZe=b(()=>{Ql();XX={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new un(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&XX.test.test(t)){let r=t[0]==="t"||t[0]==="T";if(e===r)return t}return e?n.options.trueStr:n.options.falseStr}}});function Ef({format:t,minFractionDigits:e,tag:n,value:r}){if(typeof r=="bigint")return String(r);let o=typeof r=="number"?r:Number(r);if(!isFinite(o))return isNaN(o)?".nan":o<0?"-.inf":".inf";let i=Object.is(r,-0)?"-0":JSON.stringify(r);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(i)&&!i.includes("e")){let s=i.indexOf(".");s<0&&(s=i.length,i+=".");let a=e-(i.length-s-1);for(;a-- >0;)i+="0"}return i}var DW=b(()=>{});var swe,awe,lwe,gZe=b(()=>{Ql();DW();swe={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ef},awe={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Ef(t)}},lwe={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new un(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:Ef}});function f7t(t,e,n){let{value:r}=t;return cwe(r)&&r>=0?n+r.toString(e):Ef(t)}var cwe,yZe,uwe,dwe,fwe,vZe=b(()=>{DW();cwe=t=>typeof t=="bigint"||Number.isInteger(t),yZe=(t,e,n,{intAsBigInt:r})=>r?BigInt(t):parseInt(t.substring(e),n);uwe={identify:t=>cwe(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>yZe(t,2,8,n),stringify:t=>f7t(t,8,"0o")},dwe={identify:cwe,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>yZe(t,0,10,n),stringify:Ef},fwe={identify:t=>cwe(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>yZe(t,2,16,n),stringify:t=>f7t(t,16,"0x")}});var p7t,m7t=b(()=>{LW();iwe();$W();JX();hZe();gZe();vZe();p7t=[Ub,jb,TE,p$,XX,uwe,dwe,fwe,swe,awe,lwe]});function h7t(t){return typeof t=="bigint"||Number.isInteger(t)}var pwe,Ywr,Jwr,g7t,y7t=b(()=>{Ql();LW();$W();pwe=({value:t})=>JSON.stringify(t),Ywr=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:pwe},{identify:t=>t==null,createNode:()=>new un(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:pwe},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:pwe},{identify:h7t,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:n})=>n?BigInt(t):parseInt(t,10),stringify:({value:t})=>h7t(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:pwe}],Jwr={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},g7t=[Ub,jb].concat(Ywr,Jwr)});var QX,wZe=b(()=>{Ql();ZX();QX={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof atob=="function"){let n=atob(t.replace(/[\n\r]/g,"")),r=new Uint8Array(n.length);for(let o=0;o<n.length;++o)r[o]=n.charCodeAt(o);return r}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:n},r,o,i){if(!n)return"";let s=n,a;if(typeof btoa=="function"){let l="";for(let c=0;c<s.length;++c)l+=String.fromCharCode(s[c]);a=btoa(l)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=un.BLOCK_LITERAL),e!==un.QUOTE_DOUBLE){let l=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),c=Math.ceil(a.length/l),u=new Array(c);for(let d=0,f=0;d<c;++d,f+=l)u[d]=a.substr(f,l);a=u.join(e===un.BLOCK_LITERAL?`
`:" ")}return f$({comment:t,type:e,value:a},r,o,i)}}});function bZe(t,e){if(Db(t))for(let n=0;n<t.items.length;++n){let r=t.items[n];if(!Lo(r)){if(Lp(r)){r.items.length>1&&e("Each pair must have its own sequence indicator");let o=r.items[0]||new tl(new un(null));if(r.commentBefore&&(o.key.commentBefore=o.key.commentBefore?`${r.commentBefore}
${o.key.commentBefore}`:r.commentBefore),r.comment){let i=o.value??o.key;i.comment=i.comment?`${r.comment}
${i.comment}`:r.comment}r=o}t.items[n]=Lo(r)?r:new tl(r)}}else e("Expected a sequence for this tag");return t}function _Ze(t,e,n){let{replacer:r}=n,o=new Tf(t);o.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let s of e){typeof r=="function"&&(s=r.call(e,String(i++),s));let a,l;if(Array.isArray(s))if(s.length===2)a=s[0],l=s[1];else throw new TypeError(`Expected [key, value] tuple: ${s}`);else if(s&&s instanceof Object){let c=Object.keys(s);if(c.length===1)a=c[0],l=s[a];else throw new TypeError(`Expected tuple with one key, not ${c.length} keys`)}else a=s;o.items.push(RW(a,l,n))}return o}var eQ,mwe=b(()=>{qo();SE();Ql();IE();eQ={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:bZe,createNode:_Ze}});var FW,tQ,xZe=b(()=>{qo();_E();kE();IE();mwe();FW=class t extends Tf{constructor(){super(),this.add=La.prototype.add.bind(this),this.delete=La.prototype.delete.bind(this),this.get=La.prototype.get.bind(this),this.has=La.prototype.has.bind(this),this.set=La.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let r=new Map;n?.onCreate&&n.onCreate(r);for(let o of this.items){let i,s;if(Lo(o)?(i=Qc(o.key,"",n),s=Qc(o.value,i,n)):i=Qc(o,"",n),r.has(i))throw new Error("Ordered maps must not include duplicate keys");r.set(i,s)}return r}static from(e,n,r){let o=_Ze(e,n,r),i=new this;return i.items=o.items,i}};FW.tag="tag:yaml.org,2002:omap";tQ={collection:"seq",identify:t=>t instanceof Map,nodeClass:FW,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=bZe(t,e),r=[];for(let{key:o}of n.items)Ur(o)&&(r.includes(o.value)?e(`Ordered maps must not include duplicate keys: ${o.value}`):r.push(o.value));return Object.assign(new FW,n)},createNode:(t,e,n)=>FW.from(t,e,n)}});function v7t({value:t,source:e},n){return e&&(t?SZe:CZe).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var SZe,CZe,w7t=b(()=>{Ql();SZe={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new un(!0),stringify:v7t},CZe={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new un(!1),stringify:v7t}});var b7t,_7t,x7t,S7t=b(()=>{Ql();DW();b7t={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ef},_7t={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Ef(t)}},x7t={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new un(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let r=t.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(e.minFractionDigits=r.length)}return e},stringify:Ef}});function hwe(t,e,n,{intAsBigInt:r}){let o=t[0];if((o==="-"||o==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),r){switch(n){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let s=BigInt(t);return o==="-"?BigInt(-1)*s:s}let i=parseInt(t,n);return o==="-"?-1*i:i}function kZe(t,e,n){let{value:r}=t;if(nQ(r)){let o=r.toString(e);return r<0?"-"+n+o.substr(1):n+o}return Ef(t)}var nQ,C7t,k7t,I7t,T7t,P7t=b(()=>{DW();nQ=t=>typeof t=="bigint"||Number.isInteger(t);C7t={identify:nQ,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>hwe(t,2,2,n),stringify:t=>kZe(t,2,"0b")},k7t={identify:nQ,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>hwe(t,1,8,n),stringify:t=>kZe(t,8,"0")},I7t={identify:nQ,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>hwe(t,0,10,n),stringify:Ef},T7t={identify:nQ,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>hwe(t,2,16,n),stringify:t=>kZe(t,16,"0x")}});var UW,rQ,IZe=b(()=>{qo();SE();kE();UW=class t extends La{constructor(e){super(e),this.tag=t.tag}add(e){let n;Lo(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new tl(e.key,null):n=new tl(e,null),CE(this.items,n.key)||this.items.push(n)}get(e,n){let r=CE(this.items,e);return!n&&Lo(r)?Ur(r.key)?r.key.value:r.key:r}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=CE(this.items,e);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new tl(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(e,n,r){let{replacer:o}=r,i=new this(e);if(n&&Symbol.iterator in Object(n))for(let s of n)typeof o=="function"&&(s=o.call(n,s,s)),i.items.push(RW(s,null,r));return i}};UW.tag="tag:yaml.org,2002:set";rQ={collection:"map",identify:t=>t instanceof Set,nodeClass:UW,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>UW.from(t,e,n),resolve(t,e){if(Lp(t)){if(t.hasAllNullValues(!0))return Object.assign(new UW,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}}});function TZe(t,e){let n=t[0],r=n==="-"||n==="+"?t.substring(1):t,o=s=>e?BigInt(s):Number(s),i=r.replace(/_/g,"").split(":").reduce((s,a)=>s*o(60)+o(a),o(0));return n==="-"?o(-1)*i:i}function A7t(t){let{value:e}=t,n=s=>s;if(typeof e=="bigint")n=s=>BigInt(s);else if(isNaN(e)||!isFinite(e))return Ef(t);let r="";e<0&&(r="-",e*=n(-1));let o=n(60),i=[e%o];return e<60?i.unshift(0):(e=(e-i[0])/o,i.unshift(e%o),e>=60&&(e=(e-i[0])/o,i.unshift(e))),r+i.map(s=>String(s).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var gwe,ywe,jW,PZe=b(()=>{DW();gwe={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>TZe(t,n),stringify:A7t},ywe={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>TZe(t,!1),stringify:A7t},jW={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(jW.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,o,i,s,a]=e.map(Number),l=e[7]?Number((e[7]+"00").substr(1,3)):0,c=Date.UTC(n,r-1,o,i||0,s||0,a||0,l),u=e[8];if(u&&u!=="Z"){let d=TZe(u,!1);Math.abs(d)<30&&(d*=60),c-=6e4*d}return new Date(c)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""}});var AZe,E7t=b(()=>{LW();iwe();$W();JX();wZe();w7t();S7t();P7t();ewe();xZe();mwe();IZe();PZe();AZe=[Ub,jb,TE,p$,SZe,CZe,C7t,k7t,I7t,T7t,b7t,_7t,x7t,QX,Fb,tQ,eQ,rQ,gwe,ywe,jW]});function vwe(t,e,n){let r=M7t.get(e);if(r&&!t)return n&&!r.includes(Fb)?r.concat(Fb):r.slice();let o=r;if(!o)if(Array.isArray(t))o=[];else{let i=Array.from(M7t.keys()).filter(s=>s!=="yaml11").map(s=>JSON.stringify(s)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${i} or define customTags array`)}if(Array.isArray(t))for(let i of t)o=o.concat(i);else typeof t=="function"&&(o=t(o.slice()));return n&&(o=o.concat(Fb)),o.reduce((i,s)=>{let a=typeof s=="string"?O7t[s]:s;if(!a){let l=JSON.stringify(s),c=Object.keys(O7t).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${c}`)}return i.includes(a)||i.push(a),i},[])}var M7t,O7t,N7t,R7t=b(()=>{LW();iwe();$W();JX();hZe();gZe();vZe();m7t();y7t();wZe();ewe();xZe();mwe();E7t();IZe();PZe();M7t=new Map([["core",p7t],["failsafe",[Ub,jb,TE]],["json",g7t],["yaml11",AZe],["yaml-1.1",AZe]]),O7t={binary:QX,bool:XX,float:lwe,floatExp:awe,floatNaN:swe,floatTime:ywe,int:dwe,intHex:fwe,intOct:uwe,intTime:gwe,map:Ub,merge:Fb,null:p$,omap:tQ,pairs:eQ,seq:jb,set:rQ,timestamp:jW},N7t={"tag:yaml.org,2002:binary":QX,"tag:yaml.org,2002:merge":Fb,"tag:yaml.org,2002:omap":tQ,"tag:yaml.org,2002:pairs":eQ,"tag:yaml.org,2002:set":rQ,"tag:yaml.org,2002:timestamp":jW}});var Xwr,oQ,EZe=b(()=>{qo();LW();$W();JX();R7t();Xwr=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,oQ=class t{constructor({compat:e,customTags:n,merge:r,resolveKnownTags:o,schema:i,sortMapEntries:s,toStringDefaults:a}){this.compat=Array.isArray(e)?vwe(e,"compat"):e?vwe(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=o?N7t:{},this.tags=vwe(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,Lb,{value:Ub}),Object.defineProperty(this,Cg,{value:TE}),Object.defineProperty(this,II,{value:jb}),this.sortMapEntries=typeof s=="function"?s:s===!0?Xwr:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}});function L7t(t,e){let n=[],r=e.directives===!0;if(e.directives!==!1&&t.directives){let l=t.directives.toString(t);l?(n.push(l),r=!0):t.directives.docStart&&(r=!0)}r&&n.push("---");let o=Xve(t,e),{commentString:i}=o.options;if(t.commentBefore){n.length!==1&&n.unshift("");let l=i(t.commentBefore);n.unshift(Pv(l,""))}let s=!1,a=null;if(t.contents){if(zo(t.contents)){if(t.contents.spaceBefore&&r&&n.push(""),t.contents.commentBefore){let u=i(t.contents.commentBefore);n.push(Pv(u,""))}o.forceBlockIndent=!!t.comment,a=t.contents.comment}let l=a?void 0:()=>s=!0,c=AI(t.contents,o,()=>a=null,l);a&&(c+=yS(c,"",i(a))),(c[0]==="|"||c[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${c}`:n.push(c)}else n.push(AI(t.contents,o));if(t.directives?.docEnd)if(t.comment){let l=i(t.comment);l.includes(`
`)?(n.push("..."),n.push(Pv(l,""))):n.push(`... ${l}`)}else n.push("...");else{let l=t.comment;l&&s&&(l=l.replace(/^\n+/,"")),l&&((!s||a)&&n[n.length-1]!==""&&n.push(""),n.push(Pv(i(l),"")))}return n.join(`
`)+`
`}var $7t=b(()=>{qo();YX();VX()});function BW(t){if(Ti(t))return!0;throw new Error("Expected a YAML collection as document contents")}var PE,iQ=b(()=>{zX();Kve();qo();SE();_E();EZe();$7t();Hve();iZe();HX();nZe();PE=class t{constructor(e,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Rp,{value:Uve});let o=null;typeof n=="function"||Array.isArray(n)?o=n:r===void 0&&n&&(r=n,n=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=i;let{version:s}=i;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(s=this.directives.yaml.version)):this.directives=new gS({version:s}),this.setSchema(s,r),this.contents=e===void 0?null:this.createNode(e,o,r)}clone(){let e=Object.create(t.prototype,{[Rp]:{value:Uve}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=zo(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){BW(this.contents)&&this.contents.add(e)}addIn(e,n){BW(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let r=rZe(this);e.anchor=!n||r.has(n)?oZe(n||"a",r):n}return new TI(e.anchor)}createNode(e,n,r){let o;if(typeof n=="function")e=n.call({"":e},"",e),o=n;else if(Array.isArray(n)){let g=y=>typeof y=="number"||y instanceof String||y instanceof Number,v=n.filter(g).map(String);v.length>0&&(n=n.concat(v)),o=n}else r===void 0&&n&&(r=n,n=void 0);let{aliasDuplicateObjects:i,anchorPrefix:s,flow:a,keepUndefined:l,onTagObj:c,tag:u}=r??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=o7t(this,s||"a"),m={aliasDuplicateObjects:i??!0,keepUndefined:l??!1,onAnchor:d,onTagObj:c,replacer:o,schema:this.schema,sourceObjects:p},h=PI(e,u,m);return a&&Ti(h)&&(h.flow=!0),f(),h}createPair(e,n,r={}){let o=this.createNode(e,null,r),i=this.createNode(n,null,r);return new tl(o,i)}delete(e){return BW(this.contents)?this.contents.delete(e):!1}deleteIn(e){return OW(e)?this.contents==null?!1:(this.contents=null,!0):BW(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return Ti(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return OW(e)?!n&&Ur(this.contents)?this.contents.value:this.contents:Ti(this.contents)?this.contents.getIn(e,n):void 0}has(e){return Ti(this.contents)?this.contents.has(e):!1}hasIn(e){return OW(e)?this.contents!==void 0:Ti(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=WX(this.schema,[e],n):BW(this.contents)&&this.contents.set(e,n)}setIn(e,n){OW(e)?this.contents=n:this.contents==null?this.contents=WX(this.schema,Array.from(e),n):BW(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let r;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new gS({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new gS({version:e}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let o=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${o}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(r)this.schema=new oQ(Object.assign(r,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:r,maxAliasCount:o,onAnchor:i,reviver:s}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof o=="number"?o:100},l=Qc(this.contents,n??"",a);if(typeof i=="function")for(let{count:c,res:u}of a.anchors.values())i(u,c);return typeof s=="function"?bE(s,{"":l},"",l):l}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return L7t(this,e)}}});var sQ,Bb,aQ,MZe,lQ=b(()=>{sQ=class extends Error{constructor(e,n,r,o){super(),this.name=e,this.code=r,this.message=o,this.pos=n}},Bb=class extends sQ{constructor(e,n,r){super("YAMLParseError",e,n,r)}},aQ=class extends sQ{constructor(e,n,r){super("YAMLWarning",e,n,r)}},MZe=(t,e)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>e.linePos(a));let{line:r,col:o}=n.linePos[0];n.message+=` at line ${r}, column ${o}`;let i=o-1,s=t.substring(e.lineStarts[r-1],e.lineStarts[r]).replace(/[\n\r]+$/,"");if(i>=60&&s.length>80){let a=Math.min(i-39,s.length-79);s="\u2026"+s.substring(a),i-=a-1}if(s.length>80&&(s=s.substring(0,79)+"\u2026"),r>1&&/^ *$/.test(s.substring(0,i))){let a=t.substring(e.lineStarts[r-2],e.lineStarts[r-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
`),s=a+s}if(/[^ ]/.test(s)){let a=1,l=n.linePos[1];l?.line===r&&l.col>o&&(a=Math.max(1,Math.min(l.col-o,80-i)));let c=" ".repeat(i)+"^".repeat(a);n.message+=`:
${s}
${c}
`}}});function vS(t,{flow:e,indicator:n,next:r,offset:o,onError:i,parentIndent:s,startOnNewline:a}){let l=!1,c=a,u=a,d="",f="",p=!1,m=!1,h=null,g=null,v=null,y=null,w=null,_=null,S=null;for(let k of t)switch(m&&(k.type!=="space"&&k.type!=="newline"&&k.type!=="comma"&&i(k.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(c&&k.type!=="comment"&&k.type!=="newline"&&i(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),k.type){case"space":!e&&(n!=="doc-start"||r?.type!=="flow-collection")&&k.source.includes(" ")&&(h=k),u=!0;break;case"comment":{u||i(k,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let T=k.source.substring(1)||" ";d?d+=f+T:d=T,f="",c=!1;break}case"newline":c?d?d+=k.source:(!_||n!=="seq-item-ind")&&(l=!0):f+=k.source,c=!0,p=!0,(g||v)&&(y=k),u=!0;break;case"anchor":g&&i(k,"MULTIPLE_ANCHORS","A node can have at most one anchor"),k.source.endsWith(":")&&i(k.offset+k.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=k,S??(S=k.offset),c=!1,u=!1,m=!0;break;case"tag":{v&&i(k,"MULTIPLE_TAGS","A node can have at most one tag"),v=k,S??(S=k.offset),c=!1,u=!1,m=!0;break}case n:(g||v)&&i(k,"BAD_PROP_ORDER",`Anchors and tags must be after the ${k.source} indicator`),_&&i(k,"UNEXPECTED_TOKEN",`Unexpected ${k.source} in ${e??"collection"}`),_=k,c=n==="seq-item-ind"||n==="explicit-key-ind",u=!1;break;case"comma":if(e){w&&i(k,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),w=k,c=!1,u=!1;break}default:i(k,"UNEXPECTED_TOKEN",`Unexpected ${k.type} token`),c=!1,u=!1}let I=t[t.length-1],C=I?I.offset+I.source.length:o;return m&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&i(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(c&&h.indent<=s||r?.type==="block-map"||r?.type==="block-seq")&&i(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:w,found:_,spaceBefore:l,comment:d,hasNewline:p,anchor:g,tag:v,newlineAfterProp:y,end:C,start:S??C}}var cQ=b(()=>{});function AE(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(`
`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(AE(e.key)||AE(e.value))return!0}return!1;default:return!0}}var wwe=b(()=>{});function uQ(t,e,n){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&&AE(e)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}var OZe=b(()=>{wwe()});function bwe(t,e,n){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let o=typeof r=="function"?r:(i,s)=>i===s||Ur(i)&&Ur(s)&&i.value===s.value;return e.some(i=>o(i.key,n))}var NZe=b(()=>{qo()});function F7t({composeNode:t,composeEmptyNode:e},n,r,o,i){let s=i?.nodeClass??La,a=new s(n.schema);n.atRoot&&(n.atRoot=!1);let l=r.offset,c=null;for(let u of r.items){let{start:d,key:f,sep:p,value:m}=u,h=vS(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:l,onError:o,parentIndent:r.indent,startOnNewline:!0}),g=!h.found;if(g){if(f&&(f.type==="block-seq"?o(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&o(l,"BAD_INDENT",D7t)),!h.anchor&&!h.tag&&!p){c=h.end,h.comment&&(a.comment?a.comment+=`
`+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||AE(f))&&o(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&o(l,"BAD_INDENT",D7t);n.atKey=!0;let v=h.end,y=f?t(n,f,h,o):e(n,v,d,null,h,o);n.schema.compat&&uQ(r.indent,f,o),n.atKey=!1,bwe(n,a.items,y)&&o(v,"DUPLICATE_KEY","Map keys must be unique");let w=vS(p??[],{indicator:"map-value-ind",next:m,offset:y.range[2],onError:o,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(l=w.end,w.found){g&&(m?.type==="block-map"&&!w.hasNewline&&o(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&h.start<w.found.offset-1024&&o(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let _=m?t(n,m,w,o):e(n,l,p,null,w,o);n.schema.compat&&uQ(r.indent,m,o),l=_.range[2];let S=new tl(y,_);n.options.keepSourceTokens&&(S.srcToken=u),a.items.push(S)}else{g&&o(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),w.comment&&(y.comment?y.comment+=`
`+w.comment:y.comment=w.comment);let _=new tl(y);n.options.keepSourceTokens&&(_.srcToken=u),a.items.push(_)}}return c&&c<l&&o(c,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,l,c??l],a}var D7t,U7t=b(()=>{SE();kE();cQ();wwe();OZe();NZe();D7t="All mapping items must start at the same column"});function j7t({composeNode:t,composeEmptyNode:e},n,r,o,i){let s=i?.nodeClass??Tf,a=new s(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let l=r.offset,c=null;for(let{start:u,value:d}of r.items){let f=vS(u,{indicator:"seq-item-ind",next:d,offset:l,onError:o,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?o(f.end,"BAD_INDENT","All sequence items must start at the same column"):o(l,"MISSING_CHAR","Sequence item without - indicator");else{c=f.end,f.comment&&(a.comment=f.comment);continue}let p=d?t(n,d,f,o):e(n,f.end,u,null,f,o);n.schema.compat&&uQ(r.indent,d,o),l=p.range[2],a.items.push(p)}return a.range=[r.offset,l,c??l],a}var B7t=b(()=>{IE();cQ();OZe()});function wS(t,e,n,r){let o="";if(t){let i=!1,s="";for(let a of t){let{source:l,type:c}=a;switch(c){case"space":i=!0;break;case"comment":{n&&!i&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=l.substring(1)||" ";o?o+=s+u:o=u,s="";break}case"newline":o&&(s+=l),i=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}e+=l.length}}return{comment:o,offset:e}}var zW=b(()=>{});function z7t({composeNode:t,composeEmptyNode:e},n,r,o,i){let s=r.start.source==="{",a=s?"flow map":"flow sequence",l=i?.nodeClass??(s?La:Tf),c=new l(n.schema);c.flow=!0;let u=n.atRoot;u&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let d=r.offset+r.start.source.length;for(let g=0;g<r.items.length;++g){let v=r.items[g],{start:y,key:w,sep:_,value:S}=v,I=vS(y,{flow:a,indicator:"explicit-key-ind",next:w??_?.[0],offset:d,onError:o,parentIndent:r.indent,startOnNewline:!1});if(!I.found){if(!I.anchor&&!I.tag&&!_&&!S){g===0&&I.comma?o(I.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):g<r.items.length-1&&o(I.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),I.comment&&(c.comment?c.comment+=`
`+I.comment:c.comment=I.comment),d=I.end;continue}!s&&n.options.strict&&AE(w)&&o(w,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(g===0)I.comma&&o(I.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(I.comma||o(I.start,"MISSING_CHAR",`Missing , between ${a} items`),I.comment){let C="";e:for(let k of y)switch(k.type){case"comma":case"space":break;case"comment":C=k.source.substring(1);break e;default:break e}if(C){let k=c.items[c.items.length-1];Lo(k)&&(k=k.value??k.key),k.comment?k.comment+=`
`+C:k.comment=C,I.comment=I.comment.substring(C.length+1)}}if(!s&&!_&&!I.found){let C=S?t(n,S,I,o):e(n,I.end,_,null,I,o);c.items.push(C),d=C.range[2],LZe(S)&&o(C.range,"BLOCK_IN_FLOW",RZe)}else{n.atKey=!0;let C=I.end,k=w?t(n,w,I,o):e(n,C,y,null,I,o);LZe(w)&&o(k.range,"BLOCK_IN_FLOW",RZe),n.atKey=!1;let T=vS(_??[],{flow:a,indicator:"map-value-ind",next:S,offset:k.range[2],onError:o,parentIndent:r.indent,startOnNewline:!1});if(T.found){if(!s&&!I.found&&n.options.strict){if(_)for(let O of _){if(O===T.found)break;if(O.type==="newline"){o(O,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}I.start<T.found.offset-1024&&o(T.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else S&&("source"in S&&S.source?.[0]===":"?o(S,"MISSING_CHAR",`Missing space after : in ${a}`):o(T.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let P=S?t(n,S,T,o):T.found?e(n,T.end,_,null,T,o):null;P?LZe(S)&&o(P.range,"BLOCK_IN_FLOW",RZe):T.comment&&(k.comment?k.comment+=`
`+T.comment:k.comment=T.comment);let E=new tl(k,P);if(n.options.keepSourceTokens&&(E.srcToken=v),s){let O=c;bwe(n,O.items,k)&&o(C,"DUPLICATE_KEY","Map keys must be unique"),O.items.push(E)}else{let O=new La(n.schema);O.flow=!0,O.items.push(E);let $=(P??k).range;O.range=[k.range[0],$[1],$[2]],c.items.push(O)}d=P?P.range[2]:T.end}}let f=s?"}":"]",[p,...m]=r.end,h=d;if(p?.source===f)h=p.offset+p.source.length;else{let g=a[0].toUpperCase()+a.substring(1),v=u?`${g} must end with a ${f}`:`${g} in block collection must be sufficiently indented and end with a ${f}`;o(d,u?"MISSING_CHAR":"BAD_INDENT",v),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let g=wS(m,h,n.options.strict,o);g.comment&&(c.comment?c.comment+=`
`+g.comment:c.comment=g.comment),c.range=[r.offset,h,g.offset]}else c.range=[r.offset,h,h];return c}var RZe,LZe,H7t=b(()=>{qo();SE();kE();IE();zW();cQ();wwe();NZe();RZe="Block collections are not allowed within flow collections",LZe=t=>t&&(t.type==="block-map"||t.type==="block-seq")});function $Ze(t,e,n,r,o,i){let s=n.type==="block-map"?F7t(t,e,n,r,i):n.type==="block-seq"?j7t(t,e,n,r,i):z7t(t,e,n,r,i),a=s.constructor;return o==="!"||o===a.tagName?(s.tag=a.tagName,s):(o&&(s.tag=o),s)}function W7t(t,e,n,r,o){let i=r.tag,s=i?e.directives.tagName(i.source,f=>o(i,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=r,m=f&&i?f.offset>i.offset?f:i:f??i;m&&(!p||p.offset<m.offset)&&o(m,"MISSING_CHAR","Missing newline after block sequence props")}let a=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!i||!s||s==="!"||s===La.tagName&&a==="map"||s===Tf.tagName&&a==="seq")return $Ze(t,e,n,o,s);let l=e.schema.tags.find(f=>f.tag===s&&f.collection===a);if(!l){let f=e.schema.knownTags[s];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),l=f;else return f?o(i,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):o(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${s}`,!0),$Ze(t,e,n,o,s)}let c=$Ze(t,e,n,o,s,l),u=l.resolve?.(c,f=>o(i,"TAG_RESOLVE_FAILED",f),e.options)??c,d=zo(u)?u:new un(u);return d.range=c.range,d.tag=s,l?.format&&(d.format=l.format),d}var V7t=b(()=>{qo();Ql();kE();IE();U7t();B7t();H7t()});function DZe(t,e,n){let r=e.offset,o=Qwr(e,t.options.strict,n);if(!o)return{value:"",type:null,comment:"",range:[r,r,r]};let i=o.mode===">"?un.BLOCK_FOLDED:un.BLOCK_LITERAL,s=e.source?ebr(e.source):[],a=s.length;for(let h=s.length-1;h>=0;--h){let g=s[h][1];if(g===""||g==="\r")a=h;else break}if(a===0){let h=o.chomp==="+"&&s.length>0?`
`.repeat(Math.max(1,s.length-1)):"",g=r+o.length;return e.source&&(g+=e.source.length),{value:h,type:i,comment:o.comment,range:[r,g,g]}}let l=e.indent+o.indent,c=e.offset+o.length,u=0;for(let h=0;h<a;++h){let[g,v]=s[h];if(v===""||v==="\r")o.indent===0&&g.length>l&&(l=g.length);else{g.length<l&&n(c+g.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),o.indent===0&&(l=g.length),u=h,l===0&&!t.atRoot&&n(c,"BAD_INDENT","Block scalar values in collections must be indented");break}c+=g.length+v.length+1}for(let h=s.length-1;h>=a;--h)s[h][0].length>l&&(a=h+1);let d="",f="",p=!1;for(let h=0;h<u;++h)d+=s[h][0].slice(l)+`
`;for(let h=u;h<a;++h){let[g,v]=s[h];c+=g.length+v.length+1;let y=v[v.length-1]==="\r";if(y&&(v=v.slice(0,-1)),v&&g.length<l){let _=`Block scalar lines must not be less indented than their ${o.indent?"explicit indentation indicator":"first line"}`;n(c-v.length-(y?2:1),"BAD_INDENT",_),g=""}i===un.BLOCK_LITERAL?(d+=f+g.slice(l)+v,f=`
`):g.length>l||v[0]===" "?(f===" "?f=`
`:!p&&f===`
`&&(f=`
`),d+=f+g.slice(l)+v,f=`
`,p=!0):v===""?f===`
`?d+=`
`:f=`
`:(d+=f+v,f=" ",p=!1)}switch(o.chomp){case"-":break;case"+":for(let h=a;h<s.length;++h)d+=`
`+s[h][0].slice(l);d[d.length-1]!==`
`&&(d+=`
`);break;default:d+=`
`}let m=r+o.length+e.source.length;return{value:d,type:i,comment:o.comment,range:[r,m,m]}}function Qwr({offset:t,props:e},n,r){if(e[0].type!=="block-scalar-header")return r(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:o}=e[0],i=o[0],s=0,a="",l=-1;for(let f=1;f<o.length;++f){let p=o[f];if(!a&&(p==="-"||p==="+"))a=p;else{let m=Number(p);!s&&m?s=m:l===-1&&(l=t+f)}}l!==-1&&r(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${o}`);let c=!1,u="",d=o.length;for(let f=1;f<e.length;++f){let p=e[f];switch(p.type){case"space":c=!0;case"newline":d+=p.source.length;break;case"comment":n&&!c&&r(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=p.source.length,u=p.source.substring(1);break;case"error":r(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let m=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",m);let h=p.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:i,indent:s,chomp:a,comment:u,length:d}}function ebr(t){let e=t.split(/\n( *)/),n=e[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let s=1;s<e.length;s+=2)i.push([e[s],e[s+1]]);return i}var FZe=b(()=>{Ql()});function UZe(t,e,n){let{offset:r,type:o,source:i,end:s}=t,a,l,c=(f,p,m)=>n(r+f,p,m);switch(o){case"scalar":a=un.PLAIN,l=tbr(i,c);break;case"single-quoted-scalar":a=un.QUOTE_SINGLE,l=nbr(i,c);break;case"double-quoted-scalar":a=un.QUOTE_DOUBLE,l=rbr(i,c);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${o}`),{value:"",type:null,comment:"",range:[r,r+i.length,r+i.length]}}let u=r+i.length,d=wS(s,u,e,n);return{value:l,type:a,comment:d.comment,range:[r,u,d.offset]}}function tbr(t,e){let n="";switch(t[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),q7t(t)}function nbr(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),q7t(t.slice(1,-1)).replace(/''/g,"'")}function q7t(t){let e,n;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
`,"sy"),n=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
`,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=e.exec(t);if(!r)return t;let o=r[1],i=" ",s=e.lastIndex;for(n.lastIndex=s;r=n.exec(t);)r[1]===""?i===`
`?o+=i:i=`
`:(o+=i+r[1],i=" "),s=n.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=s,r=a.exec(t),o+i+(r?.[1]??"")}function rbr(t,e){let n="";for(let r=1;r<t.length-1;++r){let o=t[r];if(!(o==="\r"&&t[r+1]===`
`))if(o===`
`){let{fold:i,offset:s}=obr(t,r);n+=i,r=s}else if(o==="\\"){let i=t[++r],s=ibr[i];if(s)n+=s;else if(i===`
`)for(i=t[r+1];i===" "||i===" ";)i=t[++r+1];else if(i==="\r"&&t[r+1]===`
`)for(i=t[++r+1];i===" "||i===" ";)i=t[++r+1];else if(i==="x"||i==="u"||i==="U"){let a=i==="x"?2:i==="u"?4:8;n+=sbr(t,r+1,a,e),r+=a}else{let a=t.substr(r-1,2);e(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),n+=a}}else if(o===" "||o===" "){let i=r,s=t[r+1];for(;s===" "||s===" ";)s=t[++r+1];s!==`
`&&!(s==="\r"&&t[r+2]===`
`)&&(n+=r>i?t.slice(i,r+1):o)}else n+=o}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),n}function obr(t,e){let n="",r=t[e+1];for(;(r===" "||r===" "||r===`
`||r==="\r")&&!(r==="\r"&&t[e+2]!==`
`);)r===`
`&&(n+=`
`),e+=1,r=t[e+1];return n||(n=" "),{fold:n,offset:e}}function sbr(t,e,n,r){let o=t.substr(e,n),s=o.length===n&&/^[0-9a-fA-F]+$/.test(o)?parseInt(o,16):NaN;try{return String.fromCodePoint(s)}catch{let a=t.substr(e-2,n+2);return r(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}var ibr,jZe=b(()=>{Ql();zW();ibr={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "}});function BZe(t,e,n,r){let{value:o,type:i,comment:s,range:a}=e.type==="block-scalar"?DZe(t,e,r):UZe(e,t.options.strict,r),l=n?t.directives.tagName(n.source,d=>r(n,"TAG_RESOLVE_FAILED",d)):null,c;t.options.stringKeys&&t.atKey?c=t.schema[Cg]:l?c=abr(t.schema,o,l,n,r):e.type==="scalar"?c=lbr(t,o,e,r):c=t.schema[Cg];let u;try{let d=c.resolve(o,f=>r(n??e,"TAG_RESOLVE_FAILED",f),t.options);u=Ur(d)?d:new un(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(n??e,"TAG_RESOLVE_FAILED",f),u=new un(o)}return u.range=a,u.source=o,i&&(u.type=i),l&&(u.tag=l),c.format&&(u.format=c.format),s&&(u.comment=s),u}function abr(t,e,n,r,o){if(n==="!")return t[Cg];let i=[];for(let a of t.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)i.push(a);else return a;for(let a of i)if(a.test?.test(e))return a;let s=t.knownTags[n];return s&&!s.collection?(t.tags.push(Object.assign({},s,{default:!1,test:void 0})),s):(o(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),t[Cg])}function lbr({atKey:t,directives:e,schema:n},r,o,i){let s=n.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(r))||n[Cg];if(n.compat){let a=n.compat.find(l=>l.default&&l.test?.test(r))??n[Cg];if(s.tag!==a.tag){let l=e.tagString(s.tag),c=e.tagString(a.tag),u=`Value may be parsed as either ${l} or ${c}`;i(o,"TAG_RESOLVE_FAILED",u,!0)}}return s}var K7t=b(()=>{qo();Ql();FZe();jZe()});function G7t(t,e,n){if(e){n??(n=e.length);for(let r=n-1;r>=0;--r){let o=e[r];switch(o.type){case"space":case"comment":case"newline":t-=o.source.length;continue}for(o=e[++r];o?.type==="space";)t+=o.source.length,o=e[++r];break}}return t}var Z7t=b(()=>{});function zZe(t,e,n,r){let o=t.atKey,{spaceBefore:i,comment:s,anchor:a,tag:l}=n,c,u=!0;switch(e.type){case"alias":c=ubr(t,e,r),(a||l)&&r(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":c=BZe(t,e,l,r),a&&(c.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{c=W7t(cbr,t,e,n,r),a&&(c.anchor=a.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(e,"RESOURCE_EXHAUSTION",f)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",d),u=!1}}return c??(c=_we(t,e.offset,void 0,null,n,r)),a&&c.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),o&&t.options.stringKeys&&(!Ur(c)||typeof c.value!="string"||c.tag&&c.tag!=="tag:yaml.org,2002:str")&&r(l??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),i&&(c.spaceBefore=!0),s&&(e.type==="scalar"&&e.source===""?c.comment=s:c.commentBefore=s),t.options.keepSourceTokens&&u&&(c.srcToken=e),c}function _we(t,e,n,r,{spaceBefore:o,comment:i,anchor:s,tag:a,end:l},c){let u={type:"scalar",offset:G7t(e,n,r),indent:-1,source:""},d=BZe(t,u,a,c);return s&&(d.anchor=s.source.substring(1),d.anchor===""&&c(s,"BAD_ALIAS","Anchor cannot be an empty string")),o&&(d.spaceBefore=!0),i&&(d.comment=i,d.range[2]=l),d}function ubr({options:t},{offset:e,source:n,end:r},o){let i=new TI(n.substring(1));i.source===""&&o(e,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&o(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let s=e+n.length,a=wS(r,s,t.strict,o);return i.range=[e,s,a.offset],a.comment&&(i.comment=a.comment),i}var cbr,Y7t=b(()=>{zX();qo();V7t();K7t();zW();Z7t();cbr={composeNode:zZe,composeEmptyNode:_we}});function J7t(t,e,{offset:n,start:r,value:o,end:i},s){let a=Object.assign({_directives:e},t),l=new PE(void 0,a),c={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},u=vS(r,{indicator:"doc-start",next:o??i?.[0],offset:n,onError:s,parentIndent:0,startOnNewline:!0});u.found&&(l.directives.docStart=!0,o&&(o.type==="block-map"||o.type==="block-seq")&&!u.hasNewline&&s(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=o?zZe(c,o,u,s):_we(c,u.end,r,null,u,s);let d=l.contents.range[2],f=wS(i,d,!1,s);return f.comment&&(l.comment=f.comment),l.range=[n,d,f.offset],l}var X7t=b(()=>{iQ();Y7t();zW();cQ()});function dQ(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:n}=t;return[e,e+(typeof n=="string"?n.length:1)]}function Q7t(t){let e="",n=!1,r=!1;for(let o=0;o<t.length;++o){let i=t[o];switch(i[0]){case"#":e+=(e===""?"":r?`
`:`
`)+(i.substring(1)||" "),n=!0,r=!1;break;case"%":t[o+1]?.[0]!=="#"&&(o+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:e,afterEmptyLine:r}}var fQ,HZe=b(()=>{nZe();iQ();lQ();qo();X7t();zW();fQ=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,o,i)=>{let s=dQ(n);i?this.warnings.push(new aQ(s,r,o)):this.errors.push(new Bb(s,r,o))},this.directives=new gS({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:r,afterEmptyLine:o}=Q7t(this.prelude);if(r){let i=e.contents;if(n)e.comment=e.comment?`${e.comment}
${r}`:r;else if(o||e.directives.docStart||!i)e.commentBefore=r;else if(Ti(i)&&!i.flow&&i.items.length>0){let s=i.items[0];Lo(s)&&(s=s.key);let a=s.commentBefore;s.commentBefore=a?`${r}
${a}`:r}else{let s=i.commentBefore;i.commentBefore=s?`${r}
${s}`:r}}if(n){for(let i=0;i<this.errors.length;++i)e.errors.push(this.errors[i]);for(let i=0;i<this.warnings.length;++i)e.warnings.push(this.warnings[i])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Q7t(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,n=!1,r=-1){for(let o of e)yield*this.next(o);yield*this.end(n,r)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,(n,r,o)=>{let i=dQ(e);i[0]+=n,this.onError(i,"BAD_DIRECTIVE",r,o)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let n=J7t(this.options,this.directives,e,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let n=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,r=new Bb(dQ(e),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new Bb(dQ(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=wS(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new Bb(dQ(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let r=Object.assign({_directives:this.directives},this.options),o=new PE(void 0,r);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),o.range=[0,n,n],this.decorate(o,!1),yield o}}}});var eYt=b(()=>{FZe();jZe();lQ();ZX()});var tYt=b(()=>{});function m$(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),rYt(Object.freeze([]),t,e)}function rYt(t,e,n){let r=n(e,t);if(typeof r=="symbol")return r;for(let o of["key","value"]){let i=e[o];if(i&&"items"in i){for(let s=0;s<i.items.length;++s){let a=rYt(Object.freeze(t.concat([[o,s]])),i.items[s],n);if(typeof a=="number")s=a-1;else{if(a===WZe)return WZe;a===nYt&&(i.items.splice(s,1),s-=1)}}typeof r=="function"&&o==="key"&&(r=r(e,t))}}return typeof r=="function"?r(e,t):r}var WZe,dbr,nYt,oYt=b(()=>{WZe=Symbol("break visit"),dbr=Symbol("skip children"),nYt=Symbol("remove item");m$.BREAK=WZe;m$.SKIP=dbr;m$.REMOVE=nYt;m$.itemAtPath=(t,e)=>{let n=t;for(let[r,o]of e){let i=n?.[r];if(i&&"items"in i)n=i.items[o];else return}return n};m$.parentCollection=(t,e)=>{let n=m$.itemAtPath(t,e.slice(0,-1)),r=e[e.length-1][0],o=n?.[r];if(o&&"items"in o)return o;throw new Error("Parent collection not found")}});function iYt(t){switch(t){case VZe:return"byte-order-mark";case qZe:return"doc-mode";case KZe:return"flow-error-end";case xwe:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
`:case`\r
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}var VZe,qZe,KZe,xwe,Swe=b(()=>{eYt();tYt();oYt();VZe="\uFEFF",qZe="",KZe="",xwe=""});function zb(t){switch(t){case void 0:case" ":case`
`:case"\r":case" ":return!0;default:return!1}}var sYt,pbr,Cwe,mbr,GZe,pQ,ZZe=b(()=>{Swe();sYt=new Set("0123456789ABCDEFabcdef"),pbr=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Cwe=new Set(",[]{}"),mbr=new Set(` ,[]{}
\r `),GZe=t=>!t||mbr.has(t),pQ=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===`
`?!0:n==="\r"?this.buffer[e+1]===`
`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let n=this.buffer[e];if(this.indentNext>0){let r=0;for(;n===" ";)n=this.buffer[++r+e];if(n==="\r"){let o=this.buffer[r+e+1];if(o===`
`||!o&&!this.atEnd)return e+r+1}return n===`
`||r>=this.indentNext||!n&&!this.atEnd?e+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(e,3);if((r==="---"||r==="...")&&zb(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===VZe&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let n=e.length,r=e.indexOf("#");for(;r!==-1;){let i=e[r-1];if(i===" "||i===" "){n=r-1;break}else r=e.indexOf("#",r+1)}for(;;){let i=e[n-1];if(i===" "||i===" ")n-=1;else break}let o=(yield*this.pushCount(n))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-o),this.pushNewline(),"stream"}if(this.atLineEnd()){let n=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-n),yield*this.pushNewline(),"stream"}return yield qZe,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let n=this.peek(3);if((n==="---"||n==="...")&&zb(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,n==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!zb(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&zb(n)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(e[n]){case"#":yield*this.pushCount(e.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(GZe),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,n,r=-1;do e=yield*this.pushNewline(),e>0?(n=yield*this.pushSpaces(!1),this.indentValue=r=n):n=0,n+=yield*this.pushSpaces(!0);while(e+n>0);let o=this.getLine();if(o===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&o[0]!=="#"||r===0&&(o.startsWith("---")||o.startsWith("..."))&&zb(o[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(o[0]==="]"||o[0]==="}")))return this.flowLevel=0,yield KZe,yield*this.parseLineStart();let i=0;for(;o[i]===",";)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),o[i]){case void 0:return"flow";case"#":return yield*this.pushCount(o.length-i),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(GZe),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let s=this.charAt(1);if(this.flowKey||zb(s)||s===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),n=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;n!==-1&&this.buffer[n+1]==="'";)n=this.buffer.indexOf("'",n+2);else for(;n!==-1;){let i=0;for(;this.buffer[n-1-i]==="\\";)i+=1;if(i%2===0)break;n=this.buffer.indexOf('"',n+1)}let r=this.buffer.substring(0,n),o=r.indexOf(`
`,this.pos);if(o!==-1){for(;o!==-1;){let i=this.continueScalar(o+1);if(i===-1)break;o=r.indexOf(`
`,i)}o!==-1&&(n=o-(r[o-1]==="\r"?2:1))}if(n===-1){if(!this.atEnd)return this.setNext("quoted-scalar");n=this.buffer.length}return yield*this.pushToIndex(n+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let n=this.buffer[++e];if(n==="+")this.blockScalarKeep=!0;else if(n>"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>zb(n)||n==="#")}*parseBlockScalar(){let e=this.pos-1,n=0,r;e:for(let i=this.pos;r=this.buffer[i];++i)switch(r){case" ":n+=1;break;case`
`:e=i,n=0;break;case"\r":{let s=this.buffer[i+1];if(!s&&!this.atEnd)return this.setNext("block-scalar");if(s===`
`)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=n:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let i=this.continueScalar(e+1);if(i===-1)break;e=this.buffer.indexOf(`
`,i)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let o=e+1;for(r=this.buffer[o];r===" ";)r=this.buffer[++o];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
`;)r=this.buffer[++o];e=o-1}else if(!this.blockScalarKeep)do{let i=e-1,s=this.buffer[i];s==="\r"&&(s=this.buffer[--i]);let a=i;for(;s===" ";)s=this.buffer[--i];if(s===`
`&&i>=this.pos&&i+1+n>a)e=i;else break}while(!0);return yield xwe,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,n=this.pos-1,r=this.pos-1,o;for(;o=this.buffer[++r];)if(o===":"){let i=this.buffer[r+1];if(zb(i)||e&&Cwe.has(i))break;n=r}else if(zb(o)){let i=this.buffer[r+1];if(o==="\r"&&(i===`
`?(r+=1,o=`
`,i=this.buffer[r+1]):n=r),i==="#"||e&&Cwe.has(i))break;if(o===`
`){let s=this.continueScalar(r+1);if(s===-1)break;r=Math.max(r,s-2)}}else{if(e&&Cwe.has(o))break;n=r}return!o&&!this.atEnd?this.setNext("plain-scalar"):(yield xwe,yield*this.pushToIndex(n+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,n){let r=this.buffer.slice(this.pos,e);return r?(yield r,this.pos+=r.length,r.length):(n&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(GZe),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(zb(r)||n&&Cwe.has(r)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!zb(n)&&n!==">";)n=this.buffer[++e];return yield*this.pushToIndex(n===">"?e+1:e,!1)}else{let e=this.pos+1,n=this.buffer[e];for(;n;)if(pbr.has(n))n=this.buffer[++e];else if(n==="%"&&sYt.has(this.buffer[e+1])&&sYt.has(this.buffer[e+2]))n=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
`?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
`?yield*this.pushCount(2):0}*pushSpaces(e){let n=this.pos-1,r;do r=this.buffer[++n];while(r===" "||e&&r===" ");let o=n-this.pos;return o>0&&(yield this.buffer.substr(this.pos,o),this.pos=n),o}*pushUntil(e){let n=this.pos,r=this.buffer[n];for(;!e(r);)r=this.buffer[++n];return yield*this.pushToIndex(n,!1)}}});var mQ,YZe=b(()=>{mQ=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,r=this.lineStarts.length;for(;n<r;){let i=n+r>>1;this.lineStarts[i]<e?n=i+1:r=i}if(this.lineStarts[n]===e)return{line:n+1,col:1};if(n===0)return{line:0,col:e};let o=this.lineStarts[n-1];return{line:n,col:e-o+1}}}}});function EE(t,e){for(let n=0;n<t.length;++n)if(t[n].type===e)return!0;return!1}function aYt(t){for(let e=0;e<t.length;++e)switch(t[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function cYt(t){switch(t?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function kwe(t){switch(t.type){case"document":return t.start;case"block-map":{let e=t.items[t.items.length-1];return e.sep??e.start}case"block-seq":return t.items[t.items.length-1].start;default:return[]}}function HW(t){if(t.length===0)return[];let e=t.length;e:for(;--e>=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function Iwe(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let n=0;n<e.length;++n)t.push(e[n])}function lYt(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!EE(e.start,"explicit-key-ind")&&!EE(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,cYt(e.value)?e.value.end?Iwe(e.value.end,e.sep):e.value.end=e.sep:Iwe(e.start,e.sep),delete e.sep)}var hQ,JZe=b(()=>{Swe();ZZe();hQ=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new pQ,this.onNewLine=e}*parse(e,n=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(e,n))yield*this.next(r);n||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let n=iYt(e);if(n)if(n==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=n,yield*this.step(),n){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let r=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let n=e??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let r=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in r?r.indent:0:n.type==="flow-collection"&&r.type==="document"&&(n.indent=0),n.type==="flow-collection"&&lYt(n),r.type){case"document":r.value=n;break;case"block-scalar":r.props.push(n);break;case"block-map":{let o=r.items[r.items.length-1];if(o.value){r.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(o.sep)o.value=n;else{Object.assign(o,{key:n,sep:[]}),this.onKeyLine=!o.explicitKey;return}break}case"block-seq":{let o=r.items[r.items.length-1];o.value?r.items.push({start:[],value:n}):o.value=n;break}case"flow-collection":{let o=r.items[r.items.length-1];!o||o.value?r.items.push({start:[],key:n,sep:[]}):o.sep?o.value=n:Object.assign(o,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let o=n.items[n.items.length-1];o&&!o.sep&&!o.value&&o.start.length>0&&aYt(o.start)===-1&&(n.indent===0||o.start.every(i=>i.type!=="comment"||i.indent<n.indent))&&(r.type==="document"?r.end=o.start:r.items.push({start:o.start}),n.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 e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{aYt(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let n=kwe(this.peek(2)),r=HW(n),o;e.end?(o=e.end,o.push(this.sourceToken),delete e.end):o=[this.sourceToken];let i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let n=this.source.indexOf(`
`)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
`,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){Iwe(o,n.start),o.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,o=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",i=[];if(o&&n.sep&&!n.value){let s=[];for(let a=0;a<n.sep.length;++a){let l=n.sep[a];switch(l.type){case"newline":s.push(a);break;case"space":break;case"comment":l.indent>e.indent&&(s.length=0);break;default:s.length=0}}s.length>=2&&(i=n.sep.splice(s[1]))}switch(this.type){case"anchor":case"tag":o||n.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):o||n.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):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(n.explicitKey)if(n.sep)if(n.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(EE(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(cYt(n.key)&&!EE(n.sep,"newline")){let s=HW(n.start),a=n.key,l=n.sep;l.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:a,sep:l}]})}else i.length>0?n.sep=n.sep.concat(i,this.sourceToken):n.sep.push(this.sourceToken);else if(EE(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let s=HW(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||o?e.items.push({start:i,key:null,sep:[this.sourceToken]}):EE(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);o||n.value?(e.items.push({start:i,key:s,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(s):(Object.assign(n,{key:s,sep:[]}),this.onKeyLine=!0);return}default:{let s=this.startBlockValue(e);if(s){if(s.type==="block-seq"){if(!n.explicitKey&&n.sep&&!EE(n.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 r&&e.items.push({start:i});this.stack.push(s);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){Iwe(o,n.start),o.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=e.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;n.value||EE(n.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let n=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?e.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);!n||n.value?e.items.push({start:[],key:o,sep:[]}):n.sep?this.stack.push(o):Object.assign(n,{key:o,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let o=kwe(r),i=HW(o);lYt(e);let s=e.end.splice(1,e.end.length);s.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let n=this.source.indexOf(`
`)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=kwe(e),r=HW(n);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=kwe(e),r=HW(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}}});function hbr(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new mQ||null,prettyErrors:e}}function XZe(t,e={}){let{lineCounter:n,prettyErrors:r}=hbr(e),o=new hQ(n?.addNewLine),i=new fQ(e),s=null;for(let a of i.compose(o.parse(t),!0,t.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new Bb(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(s.errors.forEach(MZe(t,n)),s.warnings.forEach(MZe(t,n))),s}var uYt=b(()=>{HZe();iQ();lQ();uZe();qo();YZe();JZe()});var QZe=b(()=>{HZe();iQ();EZe();lQ();zX();qo();SE();Ql();kE();IE();Swe();ZZe();YZe();JZe();uYt();BX()});var dYt=b(()=>{QZe();QZe()});function vbr(t){let e=ybr.exec(t);if(!e)throw new ec("SKILL.md must begin with a YAML frontmatter block delimited by ---");return{yaml:e[1]??"",body:e[2]??""}}function WW(t,e){let n=t.get(e);return typeof n=="string"?n:void 0}function fYt(t,e){let n=t.get(e);return typeof n=="boolean"?n:void 0}function wbr(t){let e=t.get("metadata");if(!Lp(e))return[];let n=e.get("copilot-enabled-agents");return typeof n!="string"||n.trim().length===0?[]:n.split(",").map(r=>r.trim()).filter(r=>r.length>0)}function Av(t,e){let{yaml:n,body:r}=vbr(t),o=XZe(n,{keepSourceTokens:!0});if(o.errors.length>0)throw new ec(`SKILL.md frontmatter YAML is invalid: ${o.errors[0].message}`);if(!Lp(o.contents))throw new ec("SKILL.md frontmatter must be a YAML mapping");let i=WW(o,"name");if(!i)throw new ec("SKILL.md frontmatter is missing required field `name`");Twe(i,e);let s=WW(o,"description");if(s===void 0)throw new ec("SKILL.md frontmatter is missing required field `description`");return pYt(s),{frontmatter:{name:i,description:s,license:WW(o,"license"),compatibility:WW(o,"compatibility"),allowedTools:WW(o,"allowed-tools"),model:WW(o,"model"),disableModelInvocation:fYt(o,"disable-model-invocation"),userInvocable:fYt(o,"user-invocable"),enabledAgents:wbr(o)},body:r,doc:o}}function Twe(t,e){if(typeof t!="string"||t.length===0)throw new ec("Skill `name` must be a non-empty string");if(t.length>h$)throw new ec(`Skill \`name\` must be at most ${h$} characters (got ${t.length})`);if(!gQ.test(t))throw new ec(`Skill \`name\` must be lowercase a\u2013z, 0\u20139, and hyphens with no leading, trailing, or consecutive hyphens (got "${t}")`);if(t!==e)throw new ec(`Skill \`name\` ("${t}") must match the parent directory name ("${e}")`)}function pYt(t){if(typeof t!="string"||t.length===0)throw new ec("Skill `description` must be a non-empty string");if(t.length>g$)throw new ec(`Skill \`description\` must be at most ${g$} characters (got ${t.length})`)}function ME(t,e,n){n===void 0?t.has(e)&&t.delete(e):t.set(e,n)}function OE(t,e={}){let{doc:n,body:r}=t;return"name"in e&&ME(n,"name",e.name),"description"in e&&ME(n,"description",e.description),"license"in e&&ME(n,"license",e.license),"compatibility"in e&&ME(n,"compatibility",e.compatibility),"allowedTools"in e&&ME(n,"allowed-tools",e.allowedTools),"model"in e&&ME(n,"model",e.model),"disableModelInvocation"in e&&ME(n,"disable-model-invocation",e.disableModelInvocation),"userInvocable"in e&&ME(n,"user-invocable",e.userInvocable),e.enabledAgents!==void 0&&bbr(n,e.enabledAgents),`---
${n.toString().replace(/\n+$/,"")}
---
${r}`}function bbr(t,e){let n=t.get("metadata");Lp(n)||(n=new La,t.set("metadata",n));let r=n,o=e.join(","),i=new un(o),s=r.get("copilot-enabled-agents",!0);Ur(s)?i.type=s.type??i.type:o.length===0&&(i.type="QUOTE_DOUBLE"),r.set("copilot-enabled-agents",i)}var ybr,gQ,h$,g$,ec,NE=b(()=>{dYt();ybr=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n([\s\S]*))?$/,gQ=/^[a-z0-9]+(-[a-z0-9]+)*$/,h$=64,g$=1024;ec=class extends Error{constructor(e){super(e),this.name="SkillFormatError"}}});function Pwe(t,e){let n=t.replace(/[/\\]+$/,""),r=e.replace(/^[/\\]+/,"");return`${n}/${r}`}var e7e=b(()=>{gt()});async function yQ(t,e,n){let r=new Array(t.length),o=0,i=Math.min(e,t.length);return await Promise.all(Array.from({length:i},async()=>{for(;o<t.length;){let s=o;o+=1,r[s]=await n(t[s],s)}})),r}var t7e=b(()=>{});async function n7e(t){let{skillsFolderRelPath:e,skillsFolderAbsPath:n,adapter:r}=t;if(!await r.exists(e))return[];let o=await r.list(e);return(await yQ([...o.folders].sort(),_br,async s=>{let a=Nae(s),l=Fr(s,"SKILL.md"),c;try{c=await r.read(l)}catch{return null}let u;try{u=Av(c,a)}catch(m){let h=m instanceof ec||m instanceof Error?m.message:String(m);return W(`[skills] Skipping ${l}: ${h}`),null}let d=u.frontmatter,f=n!==null?Fr(n,a):s,p=Fr(f,"SKILL.md");return{name:d.name,description:d.description,filePath:p,dirPath:f,body:u.body,license:d.license,compatibility:d.compatibility,allowedTools:d.allowedTools,model:d.model,disableModelInvocation:d.disableModelInvocation,userInvocable:d.userInvocable,enabledAgents:d.enabledAgents,location:{kind:"canonical"}}})).filter(s=>s!==null)}var _br,r7e=b(()=>{pe();rp();t7e();NE();_br=16});function mYt(t,e){let n=e>>>0;for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return n>>>0}async function o7e(t,e){let n=await hYt(t,"",e);n.sort((i,s)=>i.relPath<s.relPath?-1:i.relPath>s.relPath?1:0);let r=2166136261,o=2216829733;for(let i of n){let s=`${i.relPath}-${i.content}`;r=mYt(s,r),o=mYt(s,o)}return r.toString(16).padStart(8,"0")+o.toString(16).padStart(8,"0")}async function hYt(t,e,n){let r;try{r=await n.list(t)}catch{return[]}let o=[];for(let i of r){let s=Fr(t,i),a=e.length===0?i:Fr(e,i),l=!1;try{l=await n.isSymlink(s)}catch{continue}if(l)continue;let c=!1;try{c=await n.isDirectory(s)}catch{c=!1}if(c){let d=await hYt(s,a,n);o.push(...d);continue}let u;try{u=await n.readFile(s)}catch{u="unreadable"}o.push({relPath:a,content:u})}return o}var i7e=b(()=>{rp()});async function s7e(t){let{vaultRootAbsPath:e,agentDirsProjectRel:n,fs:r}=t,o=[];return await Promise.all(Object.entries(n).map(async([i,s])=>{let a=Fr(e,s);if(!await gYt(r,a)||!await yYt(r,a))return;let l;try{l=await r.list(a)}catch(u){W(`[skills] Could not list ${a}: ${u instanceof Error?u.message:String(u)}`);return}let c=await Promise.all(l.sort().map(async u=>{let d=Fr(a,u),f=!1;try{f=await r.isSymlink(d)}catch{}if(f||!await yYt(r,d))return null;let p=Fr(d,"SKILL.md");if(!await gYt(r,p))return null;let m;try{m=await r.readFile(p)}catch{return null}let h;try{h=Av(m,u)}catch(y){let w=y instanceof ec||y instanceof Error?y.message:String(y);return W(`[skills] Skipping ${p}: ${w}`),null}let g=await o7e(d,r);return{agent:i,name:u,filePath:p,dirPath:d,contentHash:g,parsed:h}}));for(let u of c)u!==null&&o.push(u)})),o}async function gYt(t,e){try{return await t.exists(e)}catch{return!1}}async function yYt(t,e){try{return await t.isDirectory(e)}catch{return!1}}var a7e=b(()=>{pe();rp();i7e();NE()});function l7e(t,e){let n=t.map(i=>({...i})),r=new Set(t.map(i=>i.name)),o=new Map;for(let i of e){if(r.has(i.name))continue;let s=o.get(i.name);s===void 0?o.set(i.name,[i]):s.push(i)}for(let[i,s]of o){let a=new Map;for(let u of s){let d=a.get(u.contentHash);d===void 0?a.set(u.contentHash,[u]):d.push(u)}let l=Array.from(a.values()),c=l.length>1;for(let u of l){u.sort((h,g)=>h.agent.localeCompare(g.agent));let d=u[0],f=u.map(h=>h.agent),p=d.parsed.frontmatter,m={name:i,description:p.description,filePath:d.filePath,dirPath:d.dirPath,body:d.parsed.body,license:p.license,compatibility:p.compatibility,allowedTools:p.allowedTools,model:p.model,disableModelInvocation:p.disableModelInvocation,userInvocable:p.userInvocable,enabledAgents:f,location:{kind:"project",agentDirs:f},contentHash:d.contentHash};c&&(m.displayNameSuffix=` (${d.agent})`),n.push(m)}}return xbr(n)}function c7e(t,e){let n=t.name.localeCompare(e.name);if(n!==0)return n;let r=(t.displayNameSuffix??"").localeCompare(e.displayNameSuffix??"");return r!==0?r:t.dirPath.localeCompare(e.dirPath)}function xbr(t){return[...t].sort(c7e)}function vQ(t){return t.displayNameSuffix!==void 0?`${t.name}${t.displayNameSuffix}`:t.name}var wQ=b(()=>{});function bQ(t,e){if(!e.has(t))return t;for(let n=2;n<1e6;n++){let r=`${t}-${n}`;if(r.length>64)throw new Error(`Cannot suffix "${t}" without exceeding the 64-char name cap.`);if(Sbr.test(r)&&!e.has(r))return r}throw new Error(`Could not find a free suffix for "${t}".`)}var Sbr,Awe=b(()=>{Sbr=/^[a-z0-9]+(-[a-z0-9]+)*$/});function VW(t){if(t!==null&&typeof t=="object"&&"code"in t){let e=t.code;return typeof e=="string"?e:null}return null}var Ewe=b(()=>{});async function qW(t,e,n,r){let o=Fr(e,n);try{return await t.symlink(r,o),{ok:!0}}catch(i){let s=VW(i);if(s==="EPERM"||s==="EACCES"){let a=i instanceof Error?i.message:String(i);return W(`[skills] symlink EPERM at ${o}: ${a}`),{ok:!1,reason:"eperm",message:a}}throw i}}async function RE(t,e,n){let r=Fr(e,n);if(!await t.exists(r))return;let o=!1;try{o=await t.isSymlink(r)}catch{return}if(!o){W(`[skills] Refusing to remove real directory at ${r}`);return}try{await t.unlink(r)}catch(i){W(`[skills] Failed to unlink ${r}: ${i instanceof Error?i.message:String(i)}`)}}async function EI(t,e,n,r){let o=Fr(e,n);if(!await t.exists(o))return qW(t,e,n,r);let i=!1;try{i=await t.isSymlink(o)}catch{i=!1}if(i){try{await t.unlink(o)}catch(l){W(`[skills] Failed to unlink stale entry at ${o}: ${l instanceof Error?l.message:String(l)}`)}return qW(t,e,n,r)}let s=Fr(e,`.${n}.replacing`);if(await t.exists(s))try{await t.rmRecursive(s)}catch(l){W(`[skills] Could not remove stale aside ${s}: ${l instanceof Error?l.message:String(l)}`)}try{await Np(o,s)}catch(l){throw W(`[skills] Could not move ${o} aside: ${l instanceof Error?l.message:String(l)}`),l}let a=await qW(t,e,n,r);if(!a.ok){try{await Np(s,o)}catch(l){W(`[skills] Failed to restore ${o} from aside after EPERM: ${l instanceof Error?l.message:String(l)}`)}return a}try{await t.rmRecursive(s)}catch(l){W(`[skills] Failed to clean aside ${s} after relink: ${l instanceof Error?l.message:String(l)}`)}return{ok:!0}}async function Mwe(t,e,n){let r=fd(n),o=await Promise.all(Object.values(e).map(i=>Cbr(t,i,r)));return{removed:o.flatMap(i=>i.removed),errors:o.flatMap(i=>i.errors)}}async function Cbr(t,e,n){let r;try{r=await t.list(e)}catch{return{removed:[],errors:[]}}let o=[],i=[];return await Promise.all(r.map(async s=>{let a=Fr(e,s),l=!1;try{l=await t.isSymlink(a)}catch{return}if(!l)return;let c=await t.readlinkAbs(a);if(!(c===null||fd(c)!==n))try{await t.unlink(a),o.push(a)}catch(u){let d=u instanceof Error?u.message:String(u);i.push({path:a,reason:d})}})),{removed:o,errors:i}}var y$=b(()=>{pe();Ewe();rp();kW()});async function d7e(t){let{sourceName:e,sourceDirAbs:n,duplicateSourceDirsAbs:r,canonicalAbsRoot:o,enabledAgentsAfter:i,targetAgentDirsAbs:s,preTakenNames:a,fs:l}=t,c=new Set(a),u;try{u=bQ(e,c)}catch(g){return u7e(MI(g))}let d=Fr(o,u),f=Fr(d,"SKILL.md");try{await l.mkdirRecursive(o)}catch(g){return u7e(`Could not create canonical folder: ${MI(g)}`)}try{await Np(n,d)}catch(g){return u7e(`Could not move ${n} \u2192 ${d}: ${MI(g)}`)}let p;try{let g=await l.readFile(f);p=Av(g,e)}catch(g){let v=g instanceof ec||g instanceof Error?g.message:String(g);try{await Np(d,n)}catch(y){H(`[skills] migrateProjectSkill: rollback failed after parse error: ${MI(y)}`)}return{ok:!1,reason:v}}let m;try{m=OE(p,{...u!==e?{name:u}:{},enabledAgents:[...i]})}catch(g){try{await Np(d,n)}catch(v){H(`[skills] migrateProjectSkill: rollback failed after serialize error: ${MI(v)}`)}return{ok:!1,reason:`Could not serialize SKILL.md: ${MI(g)}`}}try{await l.writeFile(f,m)}catch(g){try{await Np(d,n)}catch(v){H(`[skills] migrateProjectSkill: rollback failed after write error: ${MI(v)}`)}return{ok:!1,reason:`Could not write SKILL.md: ${MI(g)}`}}for(let g of r)try{await l.rmRecursive(g)}catch(v){W(`[skills] migrateProjectSkill: could not remove duplicate ${g}: ${MI(v)}`)}let h=!1;for(let g of i){let v=s[g];if(v===void 0){W(`[skills] migrateProjectSkill: unknown agent dir for ${g}`);continue}let y=Fr(v,u);if(await l.exists(y)&&!await l.isSymlink(y).catch(()=>!1)){W(`[skills] migrateProjectSkill: ${g} slot ${y} holds a real directory (a different skill of the same name); skipping link to avoid clobbering it`);continue}let w=await EI(l,v,u,d);w.ok||(h=!0,W(`[skills] migrateProjectSkill: ${g} symlink failed (${w.reason}): ${w.message}`))}return h?{ok:!1,reason:"eperm",mutated:!0}:{ok:!0,resolvedName:u,newDirPath:d,newFilePath:f}}function f7e(t,e){if(t.location.kind!=="project")return[];let n=t.dirPath,r=[];for(let o of t.location.agentDirs){let i=e[o];if(i===void 0)continue;let s=Fr(i,t.name);s!==n&&r.push(s)}return r}function MI(t){return t instanceof Error?t.message:String(t)}function u7e(t){return{ok:!1,reason:t}}var p7e=b(()=>{pe();rp();kW();NE();Awe();y$()});function vYt(){let t=Pe("fs");return{...h7e(),async readFile(e){return t.promises.readFile(e,"utf-8")},async writeFile(e,n){await t.promises.writeFile(e,n,"utf-8")},async mkdirRecursive(e){await t.promises.mkdir(e,{recursive:!0})},list:e=>m7e(e,!0)}}async function m7e(t,e=!1){let n=Pe("fs");try{return await n.promises.readdir(t)}catch(r){return e&&W(`[skills] readdir ${t} failed: ${r instanceof Error?r.message:String(r)}`),[]}}async function kbr(t){let e=Pe("fs"),n=Pe("path");try{let r=await e.promises.readlink(t);return n.isAbsolute(r)?r:n.resolve(n.dirname(t),r)}catch{return null}}function h7e(){let t=Pe("fs"),e=Pe("path");return{async exists(n){try{return await t.promises.lstat(n),!0}catch{return!1}},async isDirectory(n){try{return(await t.promises.stat(n)).isDirectory()}catch{return!1}},async isSymlink(n){try{return(await t.promises.lstat(n)).isSymbolicLink()}catch{return!1}},async symlink(n,r){let o=process.platform==="win32"?"junction":"dir",i=e.isAbsolute(n)?n:e.resolve(n);await t.promises.mkdir(e.dirname(r),{recursive:!0}),await t.promises.symlink(i,r,o)},async unlink(n){try{await t.promises.unlink(n)}catch(r){if(VW(r)==="ENOENT")return;throw r}},async rmRecursive(n){await t.promises.rm(n,{recursive:!0,force:!0})}}}function wYt(){let t=Pe("fs");return{...h7e(),list:e=>m7e(e),async readFile(e){return t.promises.readFile(e,"utf-8")}}}function LE(){let t=Pe("fs");return{...h7e(),list:e=>m7e(e),readlinkAbs:kbr,async readFile(e){return t.promises.readFile(e,"utf-8")},async writeFile(e,n){await t.promises.writeFile(e,n,"utf-8")}}}var bYt=b(()=>{pe();Ewe();$n()});async function g7e(t){let{skills:e,canonicalAbsRoot:n,agentDirsAbs:r,fs:o}=t,i={created:[],removedOrphans:[],errors:[]},s=new Map(e.map(u=>[u.name,u])),a=e.flatMap(u=>u.enabledAgents.flatMap(d=>{let f=r[d];return f===void 0?[]:[()=>Ibr(o,f,u)]}));for(let u of await yQ(a,_Yt,d=>d()))u.created!==void 0&&i.created.push(u.created),u.error!==void 0&&i.errors.push(u.error);let c=(await Promise.all(Object.entries(r).map(async([u,d])=>{try{return{agent:u,agentDir:d,entries:await o.list(d)}}catch{return{agent:u,agentDir:d,entries:[]}}}))).flatMap(({agent:u,agentDir:d,entries:f})=>f.map(p=>()=>Tbr({fs:o,canonicalAbsRoot:n,skillByName:s,agent:u,agentDir:d,name:p})));for(let u of await yQ(c,_Yt,d=>d()))u?.removed!==void 0&&i.removedOrphans.push(u.removed),u?.error!==void 0&&i.errors.push(u.error);return i}async function Ibr(t,e,n){let r=Fr(e,n.name);try{if(!await t.exists(r)){let l=await qW(t,e,n.name,n.dirPath);return l.ok?{created:r}:{error:{path:r,reason:l.reason}}}if(!await t.isSymlink(r))return W(`[skills] Refusing to replace real directory at ${r} during reconcile`),{};let s=await t.readlinkAbs(r);if(s!==null&&fd(s)===fd(n.dirPath))return{};let a=await EI(t,e,n.name,n.dirPath);return a.ok?{created:r}:{error:{path:r,reason:a.reason}}}catch(o){let i=o instanceof Error?o.message:String(o);return{error:{path:r,reason:i}}}}async function Tbr(t){let{fs:e,canonicalAbsRoot:n,skillByName:r,agent:o,agentDir:i,name:s}=t;if(s.endsWith(".replacing"))return{};let a=Fr(i,s),l=!1;try{l=await e.isSymlink(a)}catch{return{}}if(!l)return{};let c=await e.readlinkAbs(a);if(c===null)return{};if(!Mvt(c,n))return{};let u=Nae(c)===s,d=r.get(s);if(d!==void 0&&u&&d.enabledAgents.includes(o))return{};try{return await RE(e,i,s),{removed:a}}catch(f){let p=f instanceof Error?f.message:String(f);return{error:{path:a,reason:p}}}}var _Yt,y7e=b(()=>{pe();rp();t7e();y$();_Yt=32});async function xYt(t){let{skill:e,agent:n,enabled:r,agentDirAbs:o,fs:i}=t,s=Pbr(e.enabledAgents,n,r);try{let a=await i.readFile(e.filePath),l=Av(a,e.name),c=OE(l,{enabledAgents:s});await i.writeFile(e.filePath,c)}catch(a){let l=a instanceof Error?a.message:String(a);return H(`[skills] toggleAgent: failed to rewrite ${e.filePath}`,a),{ok:!1,reason:l}}if(r){let a=await EI(i,o,e.name,e.dirPath);return a.ok?{ok:!0}:{ok:!1,reason:a.reason}}try{await RE(i,o,e.name)}catch(a){let l=a instanceof Error?a.message:String(a);return W(`[skills] toggleAgent: failed to remove link: ${l}`),{ok:!1,reason:l}}return{ok:!0}}async function SYt(t){let{skill:e,agentDirsAbs:n,fs:r}=t;await Promise.all(e.enabledAgents.map(async i=>{let s=n[i];if(s!==void 0)try{await RE(r,s,e.name)}catch(a){W(`[skills] deleteSkill: failed to remove link for ${i}: ${a instanceof Error?a.message:String(a)}`)}}));let o=await Mwe(r,n,e.dirPath);for(let i of o.errors)W(`[skills] deleteSkill: failed to remove stale link ${i.path}: ${i.reason}`);try{await r.rmRecursive(e.dirPath)}catch(i){let s=i instanceof Error?i.message:String(i);return H(`[skills] deleteSkill: failed to remove ${e.dirPath}`,i),{ok:!1,reason:s}}return{ok:!0}}function Pbr(t,e,n){let r=t.includes(e);return n&&!r?[...t,e]:!n&&r?t.filter(o=>o!==e):t}var CYt=b(()=>{pe();NE();y$()});function Abr(t){return typeof t=="string"&&t.length>0&&t.length<=h$&&gQ.test(t)}async function v7e(t){let{skill:e,patch:n,fs:r}=t;try{let o=await r.readFile(e.filePath),i=Av(o,e.name),s=OE(i,n);return await r.writeFile(e.filePath,s),{ok:!0}}catch(o){let i=o instanceof Error?o.message:String(o);return H(`[skills] updateProperties: failed to rewrite ${e.filePath}`,o),{ok:!1,reason:i}}}async function w7e(t){let{skill:e,newName:n,canonicalAbsRoot:r,agentDirsAbs:o,fs:i}=t;if(n===e.name)return{ok:!0,newDirPath:e.dirPath,newFilePath:e.filePath};if(!Abr(n))return{ok:!1,reason:"invalid"};let s=e.location.kind==="project",l=`${(s?PU(e.dirPath):r).replace(/[/\\]+$/,"")}/${n}`,c=`${l}/SKILL.md`;if(await i.exists(l))return{ok:!1,reason:"collision"};try{await Np(e.dirPath,l)}catch(d){let f=d instanceof Error?d.message:String(d);return H(`[skills] renameSkill: failed to rename ${e.dirPath} \u2192 ${l}`,d),{ok:!1,reason:f}}let u=!1;if(!s)for(let d of e.enabledAgents){let f=o[d];if(f===void 0)continue;try{await RE(i,f,e.name)}catch(m){W(`[skills] renameSkill: could not remove stale ${d} link for ${e.name}: ${m instanceof Error?m.message:String(m)}`)}let p=await EI(i,f,n,l);p.ok||(W(`[skills] renameSkill: ${d} symlink retarget failed (${p.reason}): ${p.message}`),u=!0)}try{let d=await i.readFile(c),f=Av(d,e.name);Twe(n,n);let p=OE(f,{name:n});await i.writeFile(c,p)}catch(d){let f=d instanceof Error?d.message:String(d);return H(`[skills] renameSkill: failed to rewrite name in ${c}`,d),{ok:!1,reason:f,mutated:!0}}return u?{ok:!1,reason:"eperm",mutated:!0}:{ok:!0,newDirPath:l,newFilePath:c}}var kYt=b(()=>{pe();rp();kW();NE();y$()});function IYt(t,e){let n=Mbr(e);return t.kind==="subtree-exists"||t.kind==="subtree-missing"?n===t.vaultRelPath||n.startsWith(`${t.vaultRelPath}/`):n===t.vaultRelPath}function Ebr(t,e){let n=fd(t),r=fd(e);return n===r?"":n.startsWith(`${r}/`)?n.slice(r.length+1):null}function Mbr(t){return t.replace(/\\/g,"/").replace(/^\/+|\/+$/g,"")}function TYt(t,e,n,r){let o=[];return Hb(o,t.filePath,r,i=>({kind:"modified",vaultRelPath:i})),Hb(o,`${n}/${t.name}`,r,i=>({kind:e?"exists":"missing",vaultRelPath:i})),o}function PYt(t,e,n){let r=[];Hb(r,t.dirPath,n,o=>({kind:"subtree-missing",vaultRelPath:o}));for(let o of Object.values(e))Hb(r,`${o}/${t.name}`,n,i=>({kind:"missing",vaultRelPath:i}));return r}function b7e(t,e){let n=[];return Hb(n,t.filePath,e,r=>({kind:"modified",vaultRelPath:r})),n}function _7e(t,e,n,r,o){let i=[],s=fd(n);Hb(i,t.dirPath,o,a=>({kind:"subtree-missing",vaultRelPath:a})),Hb(i,`${s}/${e}`,o,a=>({kind:"subtree-exists",vaultRelPath:a}));for(let a of Object.values(r))Hb(i,`${a}/${t.name}`,o,l=>({kind:"missing",vaultRelPath:l})),Hb(i,`${a}/${e}`,o,l=>({kind:"exists",vaultRelPath:l}));return i}function AYt(t,e){let n=[];for(let r of t.created)Hb(n,r,e,o=>({kind:"exists",vaultRelPath:o}));for(let r of t.removedOrphans)Hb(n,r,e,o=>({kind:"missing",vaultRelPath:o}));return n}function Hb(t,e,n,r){let o=Ebr(e,n);o!==null&&t.push(r(o))}var EYt=b(()=>{rp()});function $E(t){let e=t.vault.adapter;return e instanceof S7e.FileSystemAdapter?fd(e.getBasePath()):null}function xQ(){return Ar(OI,{store:eu})}function C7e(){return Ar(FE,{store:eu})}function k7e(){eu.set(FE,!1)}function GW(){return eu.get(OI)}function Rbr(t,e,n){let r=t.includes(e);return n&&!r?[...t,e]:!n&&r?t.filter(o=>o!==e):t}function OYt(t,e){let n={...t};return"description"in e&&typeof e.description=="string"&&(n.description=e.description),"license"in e&&(n.license=e.license),"compatibility"in e&&(n.compatibility=e.compatibility),"allowedTools"in e&&(n.allowedTools=e.allowedTools),"model"in e&&(n.model=e.model),"disableModelInvocation"in e&&(n.disableModelInvocation=e.disableModelInvocation),"userInvocable"in e&&(n.userInvocable=e.userInvocable),n}function NYt(t,e,n){let o=`${t.location.kind==="project"?fd(PU(t.dirPath)):fd(n)}/${e}`;return{...t,name:e,dirPath:o,filePath:`${o}/SKILL.md`}}function RYt(t,e){return t.dirPath===e.dirPath}function Lbr(t){return[...t].sort(c7e)}function LYt(t,e){if(t.length===0)return FYt;let n=t.map(r=>{let o=r.enabledAgents.includes(e)?"1":"0";return[r.name,o,r.description,r.allowedTools??"",r.model??"",String(r.disableModelInvocation??!1),String(r.userInvocable??!0),$Yt(r.body)].join("")}).sort();return`skills:v1:${$Yt(n.join(""))}`}function $Yt(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619);return(e>>>0).toString(16).padStart(8,"0")}function v$(){return M2()}function _Q(t,e){let n=t.vault.adapter;return n instanceof S7e.FileSystemAdapter?`${n.getBasePath().replace(/[/\\]+$/,"")}/${e}`:null}function x7e(t){return t.replace(/\\/g,"/").replace(/^\/+|\/+$/g,"")}function $br(t){let e=t.vault.adapter;return{exists:n=>e.exists(n),list:n=>e.list(n),read:n=>e.read(n)}}function DE(){return{ok:!1,code:"no-vault-path",message:"Vault has no on-disk path on this platform."}}function KW(t){return{ok:!1,code:"fs-error",message:t}}function DYt(t){return t==="eperm"?{ok:!1,code:"eperm",message:"Permission denied while creating a skill link."}:KW(t)}function Dbr(t){t.errors.some(e=>e.reason==="eperm")&&eu.set(FE,!0)}var S7e,Obr,Nbr,eu,OI,MYt,FE,Mf,qu,FYt,Owe=b(()=>{pe();Se();Is();Us();S7e=require("obsidian");rp();e7e();r7e();a7e();wQ();p7e();Awe();bYt();y7e();y$();CYt();kYt();EYt();Obr=250,Nbr=1e4,eu=sy(),OI=yo([]),MYt=yo(yC),FE=yo(!1),Mf=class Mf{constructor(e,n){this.app=e;this.agentDirsProjectRel=n;this.inFlight=null;this.inFlightFolder=null;this.queuedRefresh=!1;this.vaultEventRefs=[];this.reconcileDebounceTimer=null;this.skillSetSignatures=new Map;this.skillSetListeners=new Set;this.internalMutationDepth=0;this.pendingExpectations=[];this.safetyTimer=null;this.normalizedAgentDirs=Object.values(n).map(x7e)}static initialize(e,n){return Mf.instance===null&&(Mf.instance=new Mf(e,n),Mf.instance.subscribeToVaultEvents()),Mf.instance}getAgentDirsProjectRel(){return this.agentDirsProjectRel}static getInstance(){if(Mf.instance===null)throw new Error("SkillManager.getInstance called before initialize");return Mf.instance}static hasInstance(){return Mf.instance!==null}static resetForTesting(){Mf.instance!==null&&Mf.instance.dispose(),Mf.instance=null,eu.set(OI,[]),eu.set(MYt,yC),eu.set(FE,!1)}dispose(){for(let e of this.vaultEventRefs)this.app.vault.offref(e);this.vaultEventRefs=[],this.reconcileDebounceTimer!==null&&(window.clearTimeout(this.reconcileDebounceTimer),this.reconcileDebounceTimer=null),this.skillSetListeners.clear(),this.skillSetSignatures.clear(),this.inFlight=null,this.inFlightFolder=null,this.queuedRefresh=!1,this.internalMutationDepth=0,this.pendingExpectations=[],this.clearSafetyTimer(),Mf.instance===this&&(Mf.instance=null)}async refresh(){let e=v$();return this.inFlight!==null?(this.inFlightFolder!==e&&(this.queuedRefresh=!0),this.inFlight):(this.inFlight=Promise.resolve().then(()=>this.runRefreshLoop(e)).finally(()=>{this.inFlight=null,this.inFlightFolder=null,this.queuedRefresh=!1}),this.inFlight)}subscribeToSkillSetChange(e){return this.skillSetListeners.add(e),()=>this.skillSetListeners.delete(e)}computeSkillSetSignature(e){return LYt(GW(),e)}async runRefreshLoop(e){let n=e,r;do this.queuedRefresh=!1,this.inFlightFolder=n,r=await this.runOnce(n),this.queuedRefresh&&(n=v$());while(this.queuedRefresh);return r}async runOnce(e){let n=_Q(this.app,e),r=$br(this.app),o=$E(this.app);try{let i=await n7e({skillsFolderRelPath:e,skillsFolderAbsPath:n,adapter:r}),s=[];if(o!==null)try{s=await s7e({vaultRootAbsPath:o,agentDirsProjectRel:this.agentDirsProjectRel,fs:wYt()})}catch(u){W(`[skills] Project-skill walk failed: ${u instanceof Error?u.message:String(u)}`)}let a=l7e(i,s),l=0,c;if(o!==null&&n!==null)try{let u=a.filter(f=>f.location.kind==="canonical"),d=await this.runInternalMutation(()=>g7e({skills:u,canonicalAbsRoot:n,agentDirsAbs:this.resolveAgentDirsAbs(o),fs:LE()}),f=>AYt(f,o));l=d.errors.length,Dbr(d)}catch(u){c=u instanceof Error?u.message:String(u),l=1,W(`[skills] Reconciliation pass failed: ${c}`)}return eu.set(OI,a),eu.set(MYt,e),this.publishSkillSetChanges(a),j(`[skills] Discovered ${a.length} managed skill(s) under "${e}"`),{ok:!0,folder:e,skillCount:a.length,reconcileErrorCount:l,...c!==void 0?{reconcileError:c}:{}}}catch(i){return H("[skills] Discovery pass failed",i),{ok:!1,folder:e,skillCount:0,reconcileErrorCount:0,discoveryError:i instanceof Error?i.message:String(i)}}}async toggleAgent(e,n,r){let o=$E(this.app);if(o===null)return DE();let i=v$();if(_Q(this.app,i)===null)return DE();let s=LE(),a=this.resolveAgentDirAbs(o,n);if(a===null)return{ok:!1,code:"unknown-agent",message:`Unknown agent: ${n}`};let l=await this.runInternalMutation(()=>xYt({skill:e,agent:n,enabled:r,agentDirAbs:a,fs:s}),c=>c.ok||!c.ok&&c.reason==="eperm"?TYt(e,r,a,o):[]);return!l.ok&&l.reason==="eperm"&&eu.set(FE,!0),(l.ok||!l.ok&&l.reason==="eperm")&&this.replaceManagedSkill(e,{...e,enabledAgents:Rbr(e.enabledAgents,n,r)}),l.ok?{ok:!0}:DYt(l.reason)}async deleteSkill(e){let n=$E(this.app);if(n===null)return DE();let r=LE(),o=this.resolveAgentDirsAbs(n),i=await this.runInternalMutation(()=>SYt({skill:e,agentDirsAbs:o,fs:r}),s=>s.ok?PYt(e,o,n):[]);return i.ok&&this.removeManagedSkill(e),i.ok?{ok:!0}:KW(i.reason??"Unknown filesystem error.")}async updateProperties(e,n){let r=LE(),o=$E(this.app),i=await this.runInternalMutation(()=>v7e({skill:e,patch:n,fs:r}),s=>s.ok&&o!==null?b7e(e,o):[]);return i.ok&&this.replaceManagedSkill(e,OYt(e,n)),i.ok?{ok:!0}:KW(i.reason)}async saveProperties(e,n){let r=LE(),o=n.newName!==void 0&&n.newName!==e.name?n.newName:void 0,i=$E(this.app),s=e;if(o!==void 0){if(i===null)return DE();let l=v$(),c=_Q(this.app,l);if(c===null)return DE();let u=this.resolveAgentDirsAbs(i),d=await this.runInternalMutation(async()=>{let f=await w7e({skill:e,newName:o,canonicalAbsRoot:c,agentDirsAbs:u,fs:r});return(f.ok||!f.ok&&f.reason==="eperm")&&await this.cleanupLinksToSkill(r,i,e.dirPath),f},f=>f.ok||!f.ok&&f.reason==="eperm"?_7e(e,o,c,u,i):[]);if(!d.ok&&d.reason==="eperm"&&eu.set(FE,!0),!d.ok&&d.reason!=="eperm")return d.reason==="invalid"?{ok:!1,code:"invalid",message:"Skill name is invalid."}:d.reason==="collision"?{ok:!1,code:"collision",message:"A skill with that name already exists."}:(d.mutated===!0&&this.refresh(),KW(d.reason));s=NYt(e,o,c)}let a=await this.runInternalMutation(()=>v7e({skill:s,patch:n.patch,fs:r}),l=>l.ok&&i!==null?b7e(s,i):[]);return a.ok?(this.replaceManagedSkill(e,OYt(s,n.patch)),{ok:!0}):(o!==void 0&&this.replaceManagedSkill(e,s),KW(a.reason))}async renameSkill(e,n){let r=$E(this.app);if(r===null)return DE();let o=v$(),i=_Q(this.app,o);if(i===null)return DE();let s=LE(),a=this.resolveAgentDirsAbs(r),l=await this.runInternalMutation(async()=>{let c=await w7e({skill:e,newName:n,canonicalAbsRoot:i,agentDirsAbs:a,fs:s});return(c.ok||!c.ok&&c.reason==="eperm")&&await this.cleanupLinksToSkill(s,r,e.dirPath),c},c=>c.ok||!c.ok&&c.reason==="eperm"?_7e(e,n,i,a,r):[]);return!l.ok&&l.reason==="eperm"&&eu.set(FE,!0),l.ok||!l.ok&&l.reason==="eperm"?this.replaceManagedSkill(e,NYt(e,n,i)):l.mutated===!0&&this.refresh(),l.ok?{ok:!0}:l.reason==="invalid"?{ok:!1,code:"invalid",message:"Skill name is invalid."}:l.reason==="collision"?{ok:!1,code:"collision",message:"A skill with that name already exists."}:DYt(l.reason)}resolveCanonicalNameForMigration(e){let n=new Set(eu.get(OI).filter(r=>r.location.kind==="canonical").map(r=>r.name));return bQ(e,n)}getSuppressMigrationConfirm(){return!!Y().agentMode?.skills?.suppressMigrationConfirm}setSuppressMigrationConfirm(e){let n=Y().agentMode;!!n?.skills?.suppressMigrationConfirm!==e&&At("agentMode",{...n,skills:{...n.skills,suppressMigrationConfirm:e}})}async migrateProjectSkillForToggle(e,n,r){if(e.location.kind!=="project")return{ok:!1,reason:"Skill is not project-managed."};let o=$E(this.app);if(o===null)return{ok:!1,reason:"Vault has no on-disk path on this platform."};let i=v$(),s=_Q(this.app,i);if(s===null)return{ok:!1,reason:"Vault has no on-disk path on this platform."};let a=e.location.agentDirs,l;switch(r){case"expandToNewAgent":if(n===null)return{ok:!1,reason:"expandToNewAgent requires a targetAgent."};l=a.includes(n)?[...a]:[...a,n];break;case"disableLastAgent":l=[];break;case"consolidate":l=[...a];break}let c=this.resolveAgentDirsAbs(o),u=f7e(e,c),d=eu.get(OI).filter(p=>p.location.kind==="canonical").map(p=>p.name),f=await this.runInternalMutation(()=>d7e({sourceName:e.name,sourceDirAbs:e.dirPath,duplicateSourceDirsAbs:u,canonicalAbsRoot:s,enabledAgentsAfter:l,targetAgentDirsAbs:c,preTakenNames:d,fs:vYt()}));return!f.ok&&f.reason==="eperm"&&eu.set(FE,!0),await this.refresh(),f}async consolidateMirroredSkill(e,n){return n&&this.setSuppressMigrationConfirm(!0),this.migrateProjectSkillForToggle(e,null,"consolidate")}async removeProjectAgentDir(e,n){if(e.location.kind!=="project")return{ok:!1,code:"fs-error",message:"Skill is not project-managed."};let r=$E(this.app);if(r===null)return DE();let o=this.resolveAgentDirAbs(r,n);if(o===null)return{ok:!1,code:"unknown-agent",message:`Unknown agent: ${n}`};let i=LE(),s=`${o.replace(/[/\\]+$/,"")}/${e.name}`;if(await i.isSymlink(s).catch(()=>!1))return await this.refresh(),{ok:!0};try{await this.runInternalMutation(()=>i.rmRecursive(s))}catch(l){return KW(l instanceof Error?l.message:String(l))}return await this.refresh(),{ok:!0}}async runInternalMutation(e,n){this.internalMutationDepth+=1;try{let r=await e();return n!==void 0&&this.installExpectations(n(r)),r}finally{this.internalMutationDepth-=1}}clearScheduledReconcile(){this.reconcileDebounceTimer!==null&&(window.clearTimeout(this.reconcileDebounceTimer),this.reconcileDebounceTimer=null)}installExpectations(e){e.length!==0&&(this.pendingExpectations.push(...e),this.armSafetyTimer())}armSafetyTimer(){this.clearSafetyTimer(),this.safetyTimer=window.setTimeout(()=>{if(this.safetyTimer=null,this.pendingExpectations.length===0)return;let e=this.pendingExpectations.map(n=>n.vaultRelPath).join(", ");W(`[skills] Gave up waiting for vault events on: ${e}`),this.pendingExpectations=[],this.scheduleReconcile()},Nbr)}clearSafetyTimer(){this.safetyTimer!==null&&(window.clearTimeout(this.safetyTimer),this.safetyTimer=null)}tryMatchAndSuppress(e){let n=this.pendingExpectations.filter(r=>IYt(r,e));if(n.length===0)return!1;for(let r of n)this.verifyAndMaybeConsume(r);return!0}async verifyAndMaybeConsume(e){let n;try{n=await this.evaluateExpectation(e)}catch{n=!1}n&&this.consumeExpectation(e)}async evaluateExpectation(e){switch(e.kind){case"exists":case"subtree-exists":return this.app.vault.adapter.exists(e.vaultRelPath);case"missing":case"subtree-missing":return!await this.app.vault.adapter.exists(e.vaultRelPath);case"modified":return!0}}consumeExpectation(e){let n=this.pendingExpectations.indexOf(e);n!==-1&&(this.pendingExpectations.splice(n,1),this.pendingExpectations.length===0&&this.clearSafetyTimer())}replaceManagedSkill(e,n){let r=eu.get(OI),o=r.findIndex(s=>RYt(s,e)),i=o===-1?[...r,n]:[...r.slice(0,o),n,...r.slice(o+1)];this.publishManagedSkills(Lbr(i))}removeManagedSkill(e){let n=eu.get(OI);this.publishManagedSkills(n.filter(r=>!RYt(r,e)))}publishManagedSkills(e){eu.set(OI,e),this.publishSkillSetChanges(e)}async cleanupLinksToSkill(e,n,r){let o=await Mwe(e,this.resolveAgentDirsAbs(n),r);for(let i of o.errors)W(`[skills] Failed to remove stale skill link ${i.path}: ${i.reason}`)}subscribeToVaultEvents(){let e=n=>{this.handleVaultEvent(n.path)};this.vaultEventRefs.push(this.app.vault.on("create",e)),this.vaultEventRefs.push(this.app.vault.on("delete",e)),this.vaultEventRefs.push(this.app.vault.on("modify",e)),this.vaultEventRefs.push(this.app.vault.on("rename",(n,r)=>{this.handleVaultEvent(n.path,r)}))}handleVaultEvent(e,n){if(this.internalMutationDepth>0)return;let r=this.tryMatchAndSuppress(e),o=n!==void 0&&this.tryMatchAndSuppress(n);r||o||(this.isWatchedPath(e)||n!==void 0&&this.isWatchedPath(n))&&this.scheduleReconcile()}isWatchedPath(e){let n=x7e(e),r=x7e(v$());return n===r||n.startsWith(`${r}/`)?!0:this.normalizedAgentDirs.some(o=>n===o||n.startsWith(`${o}/`))}resolveAgentDirAbs(e,n){let r=this.agentDirsProjectRel[n];return r===void 0?null:Pwe(e,r)}resolveAgentDirsAbs(e){let n={};for(let[r,o]of Object.entries(this.agentDirsProjectRel))n[r]=Pwe(e,o);return n}scheduleReconcile(){this.clearScheduledReconcile(),this.reconcileDebounceTimer=window.setTimeout(()=>{this.reconcileDebounceTimer=null,this.refresh()},Obr)}publishSkillSetChanges(e){for(let n of Object.keys(this.agentDirsProjectRel)){let r=LYt(e,n),o=this.skillSetSignatures.get(n);if(o!==r&&(this.skillSetSignatures.set(n,r),!(o===void 0&&r===FYt))){j(`[skills] Skill set changed for ${n}; signature=${r}`);for(let i of this.skillSetListeners)try{i(n,r)}catch(s){H(`[skills] Skill-set listener failed for ${n}`,s)}}}}};Mf.instance=null;qu=Mf;FYt="skills:v1:0"});function I7e(t,e,n){if(n.length===0)return[];let r=new Set;for(let o of t)o.enabledAgents.includes(e)||o.enabledAgents.some(i=>n.includes(i))&&r.add(o.name);return Array.from(r).sort()}var UYt=b(()=>{});function Ubr(t,e,n){let r=[];if(t.location.kind==="project"){for(let o of t.location.agentDirs){let i=n[o];i!==void 0&&r.push({path:`${i.replace(/\/+$/,"")}/${t.name}/`,note:"project SKILL.md and supporting files"})}return r}r.push({path:`${e}/${t.name}/`,note:"canonical SKILL.md and supporting files"});for(let o of t.enabledAgents){let i=n[o];i!==void 0&&r.push({path:`${i}/${t.name}`,note:"symlink"})}return r}var jYt,Of,Fbr,SQ,T7e=b(()=>{yt();De();pe();Pa();Re();jYt=require("obsidian"),Of=L(B()),Fbr=({skill:t,skillsFolderRel:e,agentDirsProjectRel:n,onCancel:r,onConfirm:o})=>{let i=e.replace(/\/+$/,""),s=Ubr(t,i,n),a=t.location.kind==="project";return Of.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-3"},Of.default.createElement("div",{className:J("tw-flex tw-items-start tw-gap-2.5 tw-rounded-md tw-px-3.5 tw-py-2.5","tw-border tw-border-solid tw-bg-modifier-error-rgb/15 tw-border-modifier-error/80")},Of.default.createElement(Wr,{className:"tw-mt-0.5 tw-size-4 tw-shrink-0 tw-text-error","aria-hidden":"true"}),Of.default.createElement("p",{className:"tw-m-0 tw-text-ui-smaller tw-leading-relaxed tw-text-normal"},a?`This removes the skill ${s.length>1?"folders":"folder"} from your project. Vault sync / git is the only rollback path.`:"This removes the canonical copy and every agent symlink. Vault sync / git is the only rollback path.")),Of.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Of.default.createElement("div",{className:"tw-text-ui-smaller tw-text-muted"},"Will remove:"),Of.default.createElement("ul",{className:"tw-m-0 tw-list-none tw-space-y-1 tw-p-0 tw-font-mono tw-text-ui-smaller tw-text-normal"},s.map(({path:l,note:c})=>Of.default.createElement("li",{key:l,className:"tw-flex tw-items-baseline tw-gap-2"},Of.default.createElement("span",{className:"tw-text-faint"},"\u2022"),Of.default.createElement("span",{className:"tw-flex-1"},l,c!==null&&Of.default.createElement("span",{className:"tw-ml-1.5 tw-font-sans tw-text-smallest tw-text-faint"},c)))))),Of.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2 tw-pt-2"},Of.default.createElement(oe,{variant:"secondary",onClick:r},"Cancel"),Of.default.createElement(oe,{variant:"destructive",onClick:o},"Delete skill")))},SQ=class extends jYt.Modal{constructor(n,r,o,i,s){super(n);this.skill=r;this.skillsFolderRel=o;this.agentDirsProjectRel=i;this.onConfirm=s;this.root=null;this.setTitle(`Delete ${r.name}?`)}onOpen(){this.root=Er(this.contentEl,this.app),this.root.render(Of.default.createElement(Fbr,{skill:this.skill,skillsFolderRel:this.skillsFolderRel,agentDirsProjectRel:this.agentDirsProjectRel,onCancel:()=>this.close(),onConfirm:()=>{let n=this.onConfirm();n instanceof Promise&&n.catch(r=>H("DeleteConfirmModal onConfirm failed",r)),this.close()}}))}onClose(){this.root?.unmount(),this.root=null}}});function jbr(t){let e=t.skill.name;switch(t.variant){case"project-single":return`Move "${e}" to share with ${t.targetAgentDisplayName??"another agent"}?`;case"project-mirrored":return`Consolidate "${e}" and share with ${t.targetAgentDisplayName??"another agent"}?`;case"disable-last-agent":return`Move "${e}" to your shared folder before disabling ${t.targetAgentDisplayName??"this agent"}?`;case"proactive-consolidate":return`Consolidate "${e}" into your shared folder?`}}function Bbr(t){let e=t.targetAgentDisplayName??"another agent";switch(t.variant){case"project-single":return`This skill currently lives only in your ${Wbr(t)} project folder.
To enable it for ${e}, Copilot needs to move it to a shared location
so both agents stay in sync.`;case"project-mirrored":return`The same skill is currently duplicated in ${Vbr(t.sourceDuplicatePaths.length)}:`;case"disable-last-agent":return"This skill currently lives only in:";case"proactive-consolidate":return"The same skill is currently duplicated in:"}}function zbr(t){let e=t.targetAgentDisplayName??"this agent";switch(t.variant){case"project-single":return`You can still edit the skill exactly as before \u2014 there's just one copy now,
so changes are visible to both agents immediately.`;case"project-mirrored":return`After this, edits to the skill are visible to all ${t.actionLines.filter(n=>n.verb==="Create").length} agents.`;case"disable-last-agent":return`If you disable ${e}, the file has nowhere to live in its project folder.
Copilot can preserve it by moving the skill to your shared skills folder with
no agents enabled \u2014 you can toggle agents back on any time, or delete it later
from the Skills tab.`;case"proactive-consolidate":return`Editing, renaming, or deleting one copy would silently diverge from the others.
Copilot can consolidate them into a single shared location, with a shortcut in
each agent folder so all agents still see the skill.
After this, your edits stay in sync across all agents automatically.`}}function Hbr(t){let e=t.targetAgentDisplayName??"agent";switch(t.variant){case"project-single":case"project-mirrored":return`Move and enable ${e}`;case"disable-last-agent":return`Move and disable ${e}`;case"proactive-consolidate":return"Consolidate"}}function Wbr(t){if(t.skill.location.kind!=="project")return"agent";let[e]=t.skill.location.agentDirs;return e??"agent"}function Vbr(t){return t===2?"two project folders":t===3?"three project folders":`${t} project folders`}var BYt,ZW,P7e=b(()=>{pe();BYt=require("obsidian"),ZW=class extends BYt.Modal{constructor(n,r){super(n);this.confirmed=!1;this.suppressFuture=!1;this.args=r,this.setTitle(jbr(r))}onOpen(){let{contentEl:n}=this;if(n.empty(),n.addClass("tw-flex","tw-flex-col","tw-gap-3"),n.createEl("p",{cls:"tw-m-0 tw-text-ui-smaller tw-text-normal tw-whitespace-pre-line",text:Bbr(this.args)}).setAttr("data-test-id","migrate-confirm-body"),this.args.sourceDuplicatePaths.length>0){let f=n.createEl("ul",{cls:"tw-m-0 tw-list-none tw-space-y-1 tw-pl-0 tw-font-mono tw-text-ui-smaller tw-text-normal"});for(let p of this.args.sourceDuplicatePaths){let m=f.createEl("li",{cls:"tw-flex tw-items-baseline tw-gap-2"});m.createSpan({cls:"tw-text-faint",text:"\u2022"}),m.createSpan({cls:"tw-flex-1",text:p})}}this.args.resolvedCanonicalName!==this.args.skill.name&&n.createEl("p",{cls:"tw-m-0 tw-text-ui-smaller tw-text-warning",text:`The name "${this.args.skill.name}" is already taken in your shared folder. The migrated skill will be named "${this.args.resolvedCanonicalName}".`}),n.createDiv({cls:"tw-text-ui-smaller tw-text-muted",text:"Copilot will:"}).setAttr("data-test-id","migrate-confirm-will-header");let i=n.createEl("ul",{cls:"tw-m-0 tw-list-none tw-space-y-1 tw-pl-0 tw-font-mono tw-text-ui-smaller tw-text-normal"});for(let f of this.args.actionLines){let p=i.createEl("li",{cls:"tw-flex tw-items-baseline tw-gap-2"});p.createSpan({cls:"tw-text-faint",text:"\u2022"});let m=p.createSpan({cls:"tw-flex-1"});m.createSpan({cls:"tw-inline-block tw-min-w-[64px] tw-text-muted",text:f.verb}),m.createSpan({text:` ${f.detail}`}),f.note!==void 0&&f.note.length>0&&m.createSpan({cls:"tw-ml-1.5 tw-font-sans tw-text-smallest tw-text-faint",text:f.note})}let s=zbr(this.args);s!==null&&n.createEl("p",{cls:"tw-m-0 tw-text-ui-smaller tw-text-muted tw-whitespace-pre-line",text:s});let a=n.createEl("label",{cls:"tw-flex tw-items-center tw-gap-2 tw-text-ui-smaller tw-text-normal tw-cursor-pointer"}),l=a.createEl("input",{cls:"tw-size-checkbox",attr:{type:"checkbox"}});l.addEventListener("change",()=>{this.suppressFuture=l.checked}),a.createSpan({text:"Don't ask again for future migrations"});let c=n.createDiv({cls:"tw-flex tw-justify-end tw-gap-2 tw-pt-2"});c.createEl("button",{cls:"mod-secondary",text:"Cancel"}).addEventListener("click",()=>{this.close()}),c.createEl("button",{cls:"mod-cta",text:Hbr(this.args)}).addEventListener("click",()=>{this.confirmed=!0;let f=this.args.onConfirm(this.suppressFuture);f instanceof Promise&&f.catch(p=>H("MigrateSkillConfirmModal onConfirm failed",p)),this.close()})}onClose(){this.confirmed||this.args.onCancel?.(),this.contentEl.empty()}}});function Zbr(t){return{name:t.name,description:t.description,allowedTools:t.allowedTools??"",model:t.model??"",disableAutoInvocation:t.disableModelInvocation===!0,hideFromSlashMenu:t.userInvocable===!1}}function Ybr(t){return t.length===0?"Name is required.":t.length>h$?`Name must be at most ${h$} characters.`:gQ.test(t)?null:"Lowercase a\u2013z, 0\u20139, and hyphens only \u2014 no leading, trailing, or consecutive hyphens."}function Jbr(t){return t.trim().length===0?"Description is required.":t.length>g$?`Description must be at most ${g$} characters.`:null}var zYt,Qn,qbr,CQ,Nwe,Rwe,Kbr,A7e,E7e,Gbr,M7e=b(()=>{yt();RP();hl();xI();De();pe();Pa();zYt=require("obsidian"),Qn=L(B());NE();qbr=({skill:t,skillsFolderRel:e,collisionError:n,saving:r,onCancel:o,onSave:i})=>{let[s,a]=Qn.default.useState(()=>Zbr(t)),l=e.replace(/\/+$/,""),c=Ybr(s.name),u=Jbr(s.description),f=!(c!==null||u!==null)&&!r,p=()=>{if(!f)return;let m=s.name!==t.name,h=s.allowedTools.trim(),g=s.model.trim();i({nameChanged:m,newName:s.name,patch:{description:s.description,allowedTools:h.length>0?h:void 0,model:g.length>0?g:void 0,disableModelInvocation:s.disableAutoInvocation?!0:void 0,userInvocable:s.hideFromSlashMenu?!1:void 0}})};return Qn.default.createElement("div",{className:"tw-flex tw-flex-col",style:{maxHeight:"70vh"}},Qn.default.createElement("div",{className:"tw-mb-3 tw-text-[12.5px] tw-text-muted"},"Writes to"," ",Qn.default.createElement("code",{className:"tw-font-mono tw-text-[12px]"},l,"/",t.name,"/SKILL.md")),Qn.default.createElement("div",{className:"tw-flex-1 tw-overflow-y-auto tw-pr-1"},Qn.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Qn.default.createElement(Nwe,null,Qn.default.createElement(Rwe,{htmlFor:"properties-name"},"Name"),Qn.default.createElement(Ir,{id:"properties-name",type:"text",value:s.name,onChange:m=>a(h=>({...h,name:m.target.value})),"aria-invalid":c!==null||n,autoComplete:"off",spellCheck:!1}),c!==null?Qn.default.createElement(A7e,null,c):n?Qn.default.createElement(A7e,null,"A skill named \u201C",s.name,"\u201D already exists."):Qn.default.createElement(Kbr,null,"Lowercase, hyphenated. This is what users type after"," ",Qn.default.createElement("code",{className:"tw-font-mono"},"/")," in chat.")),Qn.default.createElement(Nwe,null,Qn.default.createElement(Rwe,{htmlFor:"properties-description"},"Description"),Qn.default.createElement(If,{id:"properties-description",value:s.description,onChange:m=>a(h=>({...h,description:m.target.value})),"aria-invalid":u!==null,spellCheck:!0,className:"tw-border-border tw-text-sm"}),Qn.default.createElement("div",{className:"tw-mt-0.5 tw-flex tw-items-center tw-justify-between"},u!==null?Qn.default.createElement(A7e,null,u):Qn.default.createElement("span",null),Qn.default.createElement("span",{className:J("tw-font-mono tw-text-[11px] tw-text-faint",s.description.length>g$&&"tw-text-error")},s.description.length," / ",g$))),Qn.default.createElement(Nwe,null,Qn.default.createElement(Rwe,{htmlFor:"properties-allowed-tools"},"Allowed tools"),Qn.default.createElement(Ir,{id:"properties-allowed-tools",type:"text",value:s.allowedTools,onChange:m=>a(h=>({...h,allowedTools:m.target.value})),placeholder:"Read Grep Bash(git:*)",className:"tw-font-mono",autoComplete:"off",spellCheck:!1})),Qn.default.createElement(Nwe,null,Qn.default.createElement(Rwe,{htmlFor:"properties-model"},"Model override ",Qn.default.createElement(E7e,null)),Qn.default.createElement(Ir,{id:"properties-model",type:"text",value:s.model,onChange:m=>a(h=>({...h,model:m.target.value})),placeholder:"claude-sonnet-4-20250514",className:"tw-font-mono",autoComplete:"off",spellCheck:!1})),Qn.default.createElement("label",{className:"tw-flex tw-cursor-pointer tw-items-start tw-gap-2.5"},Qn.default.createElement(Wl,{checked:s.disableAutoInvocation,onCheckedChange:m=>a(h=>({...h,disableAutoInvocation:m===!0})),className:"tw-mt-0.5"}),Qn.default.createElement("span",{className:"tw-flex tw-flex-col tw-gap-0.5"},Qn.default.createElement("span",{className:"tw-flex tw-items-center tw-gap-2 tw-text-sm tw-text-normal"},"Don't let Claude invoke this on its own",Qn.default.createElement(E7e,null)))),Qn.default.createElement("label",{className:"tw-flex tw-cursor-pointer tw-items-start tw-gap-2.5"},Qn.default.createElement(Wl,{checked:s.hideFromSlashMenu,onCheckedChange:m=>a(h=>({...h,hideFromSlashMenu:m===!0})),className:"tw-mt-0.5"}),Qn.default.createElement("span",{className:"tw-flex tw-flex-col tw-gap-0.5"},Qn.default.createElement("span",{className:"tw-flex tw-items-center tw-gap-2 tw-text-sm tw-text-normal"},"Hide from slash menu",Qn.default.createElement(E7e,null)))))),Qn.default.createElement("div",{className:"tw-mt-4 tw-flex tw-justify-end tw-gap-2 tw-border-t tw-border-solid tw-border-border tw-pt-3"},Qn.default.createElement(oe,{variant:"secondary",onClick:o,disabled:r},"Cancel"),Qn.default.createElement(oe,{variant:"default",onClick:p,disabled:!f},"Save")))},CQ=class extends zYt.Modal{constructor(n,r,o,i){super(n);this.skill=r;this.skillsFolderRel=o;this.onSaveCallback=i;this.root=null;this.collisionError=!1;this.saving=!1;this.setTitle(`Properties \xB7 ${r.name}`)}onOpen(){this.root=Er(this.contentEl,this.app),this.renderBody()}onClose(){this.root?.unmount(),this.root=null}renderBody(){this.root?.render(Qn.default.createElement(qbr,{key:this.skill.dirPath,skill:this.skill,skillsFolderRel:this.skillsFolderRel,collisionError:this.collisionError,saving:this.saving,onCancel:()=>this.close(),onSave:n=>{this.handleSave(n)}}))}async handleSave(n){this.saving=!0,this.collisionError=!1,this.renderBody();try{let r=await this.onSaveCallback(n);if(r==="close"){this.close();return}this.saving=!1,this.collisionError=r==="collision",this.renderBody()}catch(r){H("PropertiesModal save failed",r),this.saving=!1,this.renderBody()}}},Nwe=({children:t})=>Qn.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1"},t),Rwe=({htmlFor:t,children:e})=>Qn.default.createElement("label",{htmlFor:t,className:"tw-flex tw-items-center tw-gap-2 tw-text-[12.5px] tw-font-medium tw-text-normal"},e),Kbr=({children:t})=>Qn.default.createElement("div",{className:"tw-text-[11.5px] tw-text-muted"},t),A7e=({children:t})=>Qn.default.createElement("div",{className:"tw-text-[11.5px] tw-text-error"},t),E7e=()=>Qn.default.createElement("span",{className:"tw-flex tw-items-center tw-gap-1 tw-font-mono tw-text-[9.5px] tw-uppercase tw-tracking-wide tw-text-faint"},Qn.default.createElement("span",{className:"tw-bg-orange tw-inline-flex tw-size-3 tw-items-center tw-justify-center tw-rounded-[3px] tw-text-on-accent"},Qn.default.createElement(Gbr,null)),"Claude Code only"),Gbr=()=>Qn.default.createElement("svg",{viewBox:"0 0 32 32",className:"tw-size-[8px]",fill:"currentColor","aria-hidden":"true"},Qn.default.createElement("path",{d:"M16 3 L17.5 13.2 L24.5 5.5 L19.6 14.6 L29 13 L19.6 16 L29 19 L19.6 17.4 L24.5 26.5 L17.5 18.8 L16 29 L14.5 18.8 L7.5 26.5 L12.4 17.4 L3 19 L12.4 16 L3 13 L12.4 14.6 L7.5 5.5 L14.5 13.2 Z"}))});function O7e(t,e,n){if(t.location.kind==="canonical")return{kind:"canonical-toggle",enabled:n};let{agentDirs:r}=t.location,o=r.includes(e);return n?o?{kind:"no-op"}:{kind:"migrate-confirm",variant:r.length>=2?"project-mirrored":"project-single",targetAgent:e,action:"expandToNewAgent"}:o?r.length===1?{kind:"migrate-confirm",variant:"disable-last-agent",targetAgent:e,action:"disableLastAgent"}:{kind:"mirrored-remove-one",agent:e}:{kind:"no-op"}}var N7e=b(()=>{});var R7e,L7e,$7e=b(()=>{De();R7e=L(B()),L7e=({Icon:t,agentId:e,agentName:n,enabled:r,onClick:o,title:i,size:s="md"})=>R7e.default.createElement("div",{role:"button",tabIndex:0,onClick:o,onKeyDown:l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),o?.())},title:i,"aria-pressed":r,"aria-label":i??`${r?"Disable":"Enable"} ${n??e}`,className:J("tw-flex tw-items-center tw-justify-center tw-transition-transform","hover:tw--translate-y-px",s==="md"?"tw-size-[26px] tw-rounded-[7px]":"tw-size-5 tw-rounded-[5px]",r?"tw-bg-interactive-accent tw-text-on-accent":"tw-border tw-border-dashed tw-border-[var(--text-faint)] tw-bg-primary tw-text-faint tw-opacity-60 hover:tw-opacity-100")},R7e.default.createElement(t,{className:"tw-size-3.5"}))});function Xbr(t,e){if(t.location.kind!=="project")return null;let n=t.location.agentDirs;if(n.length===0)return null;if(n.length===1){let o=e[n[0]];return o!==void 0?`in ${o}`:null}let r=n.map(o=>e[o]).filter(o=>typeof o=="string").map(Qbr);return r.length===0?null:`mirrored in ${r.join(", ")}`}function Qbr(t){let e=t.replace(/\/+$/,""),n=e.lastIndexOf("/");return n===-1?e:e.slice(0,n)}function e_r(t,e){return t.find(n=>n.id===e)?.displayName??e}function t_r(t){let e=[];return t.disableModelInvocation===!0&&e.push({variant:"warn",label:"model-invoke off"}),t.userInvocable===!1&&e.push({variant:"default",label:"hidden from /"}),t.model!==void 0&&t.model.length>0&&e.push({variant:"solid",label:`claude \xB7 ${n_r(t.model)}`}),e}function n_r(t){return t.length<=22?t:`${t.slice(0,21)}\u2026`}function r_r(t,e){return e?`Enabled for ${t}`:`Disabled for ${t} \xB7 click to enable`}function s_r(t){let e=qu.getInstance(),n=HYt(),r;try{r=e.resolveCanonicalNameForMigration(t.skill.name)}catch(l){return new Wb.Notice(`Could not migrate ${t.skill.name}: ${l instanceof Error?l.message:String(l)}`),Promise.resolve()}let o=l_r({skill:t.skill,canonicalFolderRel:n,agentDirsProjectRel:t.agentDirsProjectRel,targetAgent:t.targetAgent,resolvedName:r,variant:t.variant}),i=t.skill.location.kind==="project"?t.skill.location.agentDirs:[],s=async l=>{l&&e.setSuppressMigrationConfirm(!0);let c=await e.migrateProjectSkillForToggle(t.skill,t.action==="expandToNewAgent"?t.targetAgent:null,t.action);if(!c.ok&&c.reason!=="eperm"){new Wb.Notice(`Could not migrate ${t.skill.name}: ${c.reason}`);return}t.action==="expandToNewAgent"?new Wb.Notice(`Moved ${t.skill.name} to ${n}/ and enabled ${t.targetAgentDisplayName}.`):new Wb.Notice(`Moved ${t.skill.name} to ${n}/ and disabled ${t.targetAgentDisplayName}.`)};if(e.getSuppressMigrationConfirm())return s(!1).catch(l=>{H("Suppressed migration commit failed",l)});let a=t.variant==="project-mirrored"||t.variant==="disable-last-agent"?i.map(l=>{let c=t.agentDirsProjectRel[l];return c===void 0?null:`<vault>/${c}/${t.skill.name}/`}).filter(l=>l!==null):[];return new ZW(t.app,{variant:t.variant,skill:t.skill,targetAgent:t.targetAgent,targetAgentDisplayName:t.targetAgentDisplayName,resolvedCanonicalName:r,sourceDuplicatePaths:a,actionLines:o,onConfirm:s}).open(),Promise.resolve()}function a_r(t){if(t.skill.location.kind!=="project"||t.skill.location.agentDirs.length<2)return Promise.resolve();let e=qu.getInstance(),n=HYt(),r;try{r=e.resolveCanonicalNameForMigration(t.skill.name)}catch(a){return new Wb.Notice(`Could not consolidate ${t.skill.name}: ${a instanceof Error?a.message:String(a)}`),Promise.resolve()}let o=c_r({skill:t.skill,canonicalFolderRel:n,agentDirsProjectRel:t.agentDirsProjectRel,resolvedName:r}),i=t.skill.location.agentDirs.map(a=>{let l=t.agentDirsProjectRel[a];return l===void 0?null:`<vault>/${l}/${t.skill.name}/`}).filter(a=>a!==null),s=async a=>{let l=await e.consolidateMirroredSkill(t.skill,a);if(!l.ok&&l.reason!=="eperm"){new Wb.Notice(`Could not consolidate ${t.skill.name}: ${l.reason}`);return}new Wb.Notice(`Consolidated ${t.skill.name} into ${n}/.`)};return e.getSuppressMigrationConfirm()?s(!1).catch(a=>{H("Suppressed consolidate failed",a)}):(new ZW(t.app,{variant:"proactive-consolidate",skill:t.skill,targetAgent:null,resolvedCanonicalName:r,sourceDuplicatePaths:i,actionLines:o,onConfirm:s}).open(),Promise.resolve())}function l_r(t){let{skill:e,canonicalFolderRel:n,agentDirsProjectRel:r,targetAgent:o,resolvedName:i,variant:s}=t,a=[];if(e.location.kind!=="project")return a;let l=e.location.agentDirs,c=l[0],u=r[c];if(u===void 0)return a;let d=`<vault>/${n}/${i}/`;a.push({verb:"Move",detail:`<vault>/${u}/${e.name}/ \u2192 ${d}`});for(let p of l.slice(1)){let m=r[p];m!==void 0&&a.push({verb:"Delete",detail:`<vault>/${m}/${e.name}/`,note:"(identical duplicate)"})}if(s==="disable-last-agent")return a.push({verb:"Not create",detail:"any shortcuts (no agents enabled)."}),a;let f=l.includes(o)?l:[...l,o];for(let p of f){let m=r[p];m!==void 0&&a.push({verb:"Create",detail:`<vault>/${m}/${i}`,note:"(shortcut to the new location)"})}return a}function c_r(t){let{skill:e,canonicalFolderRel:n,agentDirsProjectRel:r,resolvedName:o}=t;if(e.location.kind!=="project")return[];let i=e.location.agentDirs,s=[],a=i[0],l=r[a];if(l===void 0)return[];s.push({verb:"Move",detail:`<vault>/${l}/${e.name}/ \u2192 <vault>/${n}/${o}/`});for(let c of i.slice(1)){let u=r[c];u!==void 0&&s.push({verb:"Delete",detail:`<vault>/${u}/${e.name}/`,note:"(identical duplicate)"})}for(let c of i){let u=r[c];u!==void 0&&s.push({verb:"Create",detail:`<vault>/${u}/${o}`,note:"(shortcut to the new location)"})}return s}function HYt(){return M2()}var Wb,er,D7e,o_r,i_r,F7e=b(()=>{xk();Oc();De();Re();Wb=require("obsidian"),er=L(B());yt();ko();pe();Is();Owe();N7e();wQ();P7e();$7e();D7e=({skill:t,agents:e,agentDirsProjectRel:n,onEditSkillMd:r,onEditProperties:o,onRevealInVault:i,onDelete:s,containerRef:a})=>{let l=vn(),[c,u]=er.default.useState(!1),d=t_r(t),f=er.default.useMemo(()=>new Set(t.enabledAgents),[t.enabledAgents]),p=vQ(t),m=Xbr(t,n),h=t.location.kind==="project"?t.location.agentDirs.length:0,g=h>=2,v=g?`This skill is duplicated in ${h} agent folders. Editing one copy would silently diverge from the others. Migrate it to your shared folder first to enable edits.`:null,y=er.default.useCallback(async _=>{let S=qu.getInstance(),I=!f.has(_),C=O7e(t,_,I);switch(C.kind){case"no-op":return;case"canonical-toggle":{let k=await S.toggleAgent(t,_,C.enabled);!k.ok&&k.code!=="eperm"&&new Wb.Notice(`Could not ${C.enabled?"enable":"disable"} ${_}: ${k.message}`);return}case"mirrored-remove-one":{let k=await S.removeProjectAgentDir(t,C.agent);if(!k.ok){new Wb.Notice(`Could not remove ${t.name} from ${C.agent}: ${k.message}`);return}let T=(t.location.kind==="project"?t.location.agentDirs:[]).filter(E=>E!==C.agent),P=T.length===1?T[0]:T.join(", ");new Wb.Notice(`Removed ${t.name} from ${C.agent} project folder; still active in ${P}.`);return}case"migrate-confirm":{await s_r({app:l,skill:t,agentDirsProjectRel:n,variant:C.variant,targetAgent:C.targetAgent,targetAgentDisplayName:e_r(e,C.targetAgent),action:C.action});return}default:{let k=C;return}}},[e,n,l,f,t]),w=er.default.useCallback(()=>{a_r({app:l,skill:t,agentDirsProjectRel:n})},[n,l,t]);return er.default.createElement("div",{"data-menu-open":c?"true":void 0,className:J("tw-grid tw-grid-cols-[1fr_auto_auto] tw-items-center tw-gap-4","tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary","tw-px-3.5 tw-py-2.5","tw-transition-colors hover:tw-border-border-hover hover:tw-bg-primary-alt","data-[menu-open=true]:tw-bg-primary-alt data-[menu-open=true]:tw-border-normal/100")},er.default.createElement("div",{className:"tw-min-w-0"},er.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},er.default.createElement("span",{className:"tw-text-ui-small tw-font-semibold tw-text-normal"},p),d.map(_=>er.default.createElement(i_r,{key:_.label,variant:_.variant,label:_.label})),m!==null&&er.default.createElement("span",{className:"tw-truncate tw-text-ui-smaller tw-text-faint"},m)),t.description.length>0&&er.default.createElement("div",{className:"tw-mt-0.5 tw-max-w-[540px] tw-truncate tw-text-ui-smaller tw-text-muted"},t.description)),er.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},e.map(_=>{let S=f.has(_.id);return er.default.createElement(L7e,{key:_.id,Icon:_.Icon,agentId:_.id,agentName:_.displayName,enabled:S,onClick:()=>{y(_.id)},title:r_r(_.displayName,S)})})),er.default.createElement(up,{open:c,onOpenChange:u,modal:!1},er.default.createElement(dp,{asChild:!0},er.default.createElement(oe,{variant:"ghost",size:"icon",title:"More actions","aria-label":`More actions for ${t.name}`},er.default.createElement(vy,{className:"tw-size-4"}))),er.default.createElement(Ac,{align:"end",className:"tw-min-w-[180px]",container:a.current},g?er.default.createElement(o_r,{tooltip:v??"",onMigrate:w,onRevealInVault:i}):er.default.createElement(er.default.Fragment,null,er.default.createElement(co,{className:"tw-gap-2.5 tw-text-ui-small",onSelect:r},er.default.createElement(Qf,{className:"tw-size-3.5","aria-hidden":"true"}),"Edit SKILL.md"),er.default.createElement(co,{className:"tw-gap-2.5 tw-text-ui-small",onSelect:o},er.default.createElement(Ih,{className:"tw-size-3.5","aria-hidden":"true"}),"Properties\u2026"),er.default.createElement(co,{className:"tw-gap-2.5 tw-text-ui-small",onSelect:i},er.default.createElement(kw,{className:"tw-size-3.5","aria-hidden":"true"}),"Reveal in vault"),er.default.createElement(co,{className:"tw-gap-2.5 tw-text-ui-small tw-text-error focus:tw-bg-modifier-error-rgb/15 focus:tw-text-error",onSelect:s},er.default.createElement(Ts,{className:"tw-size-3.5","aria-hidden":"true"}),"Delete\u2026")))))};o_r=({tooltip:t,onMigrate:e,onRevealInVault:n})=>{let r=J("tw-cursor-not-allowed tw-gap-2.5 tw-text-ui-small tw-text-faint","data-[highlighted]:tw-bg-transparent data-[highlighted]:tw-text-faint");return er.default.createElement(sf,{delayDuration:120},er.default.createElement(co,{className:"tw-gap-2.5 tw-text-ui-small",onSelect:e},er.default.createElement(AG,{className:"tw-size-3.5","aria-hidden":"true"}),"Migrate to shared folder"),er.default.createElement(hr,null,er.default.createElement(gr,{asChild:!0},er.default.createElement(co,{className:r,"aria-disabled":"true",onSelect:o=>o.preventDefault()},er.default.createElement(Qf,{className:"tw-size-3.5","aria-hidden":"true"}),"Edit SKILL.md")),er.default.createElement(fr,{side:"left"},t)),er.default.createElement(hr,null,er.default.createElement(gr,{asChild:!0},er.default.createElement(co,{className:r,"aria-disabled":"true",onSelect:o=>o.preventDefault()},er.default.createElement(Ih,{className:"tw-size-3.5","aria-hidden":"true"}),"Properties\u2026")),er.default.createElement(fr,{side:"left"},t)),er.default.createElement(co,{className:"tw-gap-2.5 tw-text-ui-small",onSelect:n},er.default.createElement(kw,{className:"tw-size-3.5","aria-hidden":"true"}),"Reveal in vault"),er.default.createElement(hr,null,er.default.createElement(gr,{asChild:!0},er.default.createElement(co,{className:J(r,"tw-text-error/60"),"aria-disabled":"true",onSelect:o=>o.preventDefault()},er.default.createElement(Ts,{className:"tw-size-3.5","aria-hidden":"true"}),"Delete\u2026")),er.default.createElement(fr,{side:"left"},t)))},i_r=({variant:t,label:e})=>{let n=J("tw-rounded-sm tw-border tw-px-1.5 tw-py-0.5 tw-font-mono tw-text-smallest tw-font-medium tw-uppercase tw-tracking-wide");return er.default.createElement("span",{className:J(n,t==="warn"?"tw-border-dashed tw-border-warning tw-text-warning tw-bg-callout-warning/20":t==="solid"?"tw-border-solid tw-border-border tw-bg-primary-alt tw-text-normal":"tw-border-dashed tw-border-faint tw-text-muted")},e)}});var Vb,U7e,j7e=b(()=>{De();Re();Vb=L(B()),U7e=({folder:t})=>Vb.default.createElement("div",{className:J("tw-flex tw-flex-col tw-items-center tw-justify-center tw-gap-2","tw-min-h-[320px] tw-rounded-md tw-border tw-border-dashed tw-border-border","tw-p-12 tw-text-faint")},Vb.default.createElement("div",{className:J("tw-flex tw-items-center tw-justify-center","tw-rounded-md tw-border tw-border-dashed tw-border-border tw-p-3")},Vb.default.createElement(SG,{className:"tw-size-6 tw-text-faint","aria-hidden":"true"})),Vb.default.createElement("div",{className:"tw-text-smaller tw-font-medium tw-text-muted"},"No skills yet"),Vb.default.createElement("div",{className:"tw-max-w-[420px] tw-text-center tw-text-ui-smaller tw-text-faint"},"Skills you create or save into your shared folder show up here. Skills under"," ",Vb.default.createElement("code",null,".claude/skills/"),", ",Vb.default.createElement("code",null,".agents/skills/"),", or"," ",Vb.default.createElement("code",null,".opencode/skills/")," show up here automatically too."),Vb.default.createElement("div",{className:"tw-mt-3.5 tw-font-mono tw-text-smallest tw-text-faint"},"shared home \xB7 ",Vb.default.createElement("code",null,"<vault>/",t,"/")))});async function w$(t){try{let e=require("electron"),n=e.shell??e.remote?.shell;if(!n?.openPath){new Lwe.Notice(`Open this file manually: ${t}`);return}let r=await n.openPath(t);typeof r=="string"&&r.length>0&&(H(`openWithSystemDefault: shell.openPath failed for ${t}: ${r}`),new Lwe.Notice(`Could not open file: ${r}`))}catch(e){H(`openWithSystemDefault failed for ${t}:`,e),new Lwe.Notice(`Open this file manually: ${t}`)}}var Lwe,$we=b(()=>{pe();Lwe=require("obsidian")});function p_r(t,e){let n=e.trim().toLowerCase();return n.length===0?t:t.filter(r=>vQ(r).toLowerCase().includes(n)||r.description.toLowerCase().includes(n))}function m_r(t){return`${t} skill${t===1?"":"s"}`}function h_r(t,e){let n=t.vault.getAbstractFileByPath(e);if(n instanceof Ev.TFolder){let r=t.internalPlugins?.getPluginById?.("file-explorer");if(r?.enabled&&r.instance?.revealInFolder){r.instance.revealInFolder(n);return}W("[skills] File Explorer plugin unavailable; cannot reveal folder."),new Ev.Notice("File Explorer isn't enabled; can't reveal the folder.");return}new Ev.Notice(`Skill folder "${e}" isn't indexed by Obsidian \u2014 open it from your file manager.`)}function g_r(t){let e=t.vault.adapter;if(!(e instanceof Ev.FileSystemAdapter))return null;let n=e.getBasePath().toLowerCase();for(let{substr:r,brand:o}of u_r)if(n.includes(r))return o;return null}var Ev,Cr,u_r,B7e,d_r,f_r,WYt=b(()=>{wQ();Wm();T7e();j7e();M7e();Owe();F7e();hl();De();pe();Is();$we();_I();Se();Re();Ev=require("obsidian");ko();Cr=L(B()),u_r=[{substr:"onedrive",brand:"OneDrive"},{substr:"icloud",brand:"iCloud"},{substr:"dropbox",brand:"Dropbox"}],B7e=()=>{let t=vn(),e=xt(),n=Sw(e),r=(0,Cr.useMemo)(()=>ss().map(({id:w,displayName:_,Icon:S})=>({id:w,displayName:_,Icon:S})),[]),o=xQ(),i=C7e(),[s,a]=(0,Cr.useState)(""),l=(0,Cr.useRef)(null),[c,u]=(0,Cr.useState)(!1);(0,Cr.useEffect)(()=>{qu.getInstance().refresh()},[n]);let d=(0,Cr.useCallback)(w=>{let _=Sv(w,Hu(t));if(_!==w&&t.vault.getAbstractFileByPath(_)instanceof Ev.TFile){t.workspace.openLinkText(_,"",!0);return}w$(w)},[t]),f=(0,Cr.useCallback)(w=>{d(w.filePath)},[d]),p=(0,Cr.useCallback)(w=>{let _=Sv(w.dirPath,Hu(t));if(_===w.dirPath){new Ev.Notice("Could not resolve the skill folder inside this vault.");return}h_r(t,_)},[t]),m=(0,Cr.useMemo)(()=>p_r(o,s),[o,s]),h=n,g=(0,Cr.useCallback)(w=>{new CQ(t,w,h,async _=>{let I=await qu.getInstance().saveProperties(w,{newName:_.nameChanged?_.newName:void 0,patch:_.patch});return I.ok?"close":I.code==="collision"?"collision":(I.code==="invalid"||new Ev.Notice(`Could not update ${_.nameChanged?_.newName:w.name}: ${I.message}`),"stay")}).open()},[t,h]),v=(0,Cr.useCallback)(w=>{let _=qu.getInstance();new SQ(t,w,h,_.getAgentDirsProjectRel(),async()=>{let S=await _.deleteSkill(w);S.ok||new Ev.Notice(`Failed to delete ${w.name}: ${S.message}`)}).open()},[t,h]),y=(0,Cr.useMemo)(()=>g_r(t),[t]);return Cr.default.createElement("div",{ref:l,className:"tw-space-y-4"},Cr.default.createElement("section",null,Cr.default.createElement("div",{className:"tw-mb-4 tw-flex tw-flex-col tw-gap-2"},Cr.default.createElement("div",{className:"tw-text-xl tw-font-bold"},"Skills"),Cr.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Skills are instruction packets your agents can run - things like \u201Creview a diff\u201D or \u201Cwrite a release note\u201D. Skills you put under your shared folder, or directly inside an agent\u2019s own skills folder, show up here automatically.")),(i||y!==null&&!c)&&Cr.default.createElement("div",{className:"tw-mt-3 tw-flex tw-flex-col tw-gap-2"},i&&Cr.default.createElement(d_r,{onDismiss:k7e}),y!==null&&!c&&Cr.default.createElement(f_r,{brand:y,onDismiss:()=>u(!0)})),Cr.default.createElement("div",{className:"tw-mt-4 tw-flex tw-items-center tw-gap-2"},Cr.default.createElement("div",{className:"tw-relative tw-flex-1 sm:tw-flex-initial"},Cr.default.createElement(Iw,{className:"tw-pointer-events-none tw-absolute tw-left-2.5 tw-top-1/2 tw-size-4 tw--translate-y-1/2 tw-text-faint","aria-hidden":"true"}),Cr.default.createElement(Ir,{value:s,onChange:w=>a(w.target.value),placeholder:"Search skills\u2026",className:"!tw-w-full !tw-pl-8 sm:!tw-w-64","aria-label":"Search skills"})),Cr.default.createElement("span",{className:"tw-text-xs tw-text-muted"},m_r(o.length))),Cr.default.createElement("div",{className:"tw-mt-4"},o.length===0?Cr.default.createElement(U7e,{folder:h}):Cr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1.5"},m.length===0?Cr.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-dashed tw-border-border tw-bg-primary tw-px-3.5 tw-py-6 tw-text-center tw-text-ui-smaller tw-text-muted"},"No skills match \u201C",s,"\u201D."):m.map(w=>Cr.default.createElement(D7e,{key:w.dirPath,skill:w,agents:r,agentDirsProjectRel:qu.getInstance().getAgentDirsProjectRel(),onEditSkillMd:()=>f(w),onEditProperties:()=>g(w),onRevealInVault:()=>p(w),onDelete:()=>v(w),containerRef:l}))))))},d_r=({onDismiss:t})=>Cr.default.createElement("div",{className:J("tw-flex tw-items-start tw-gap-2.5 tw-rounded-md tw-border tw-border-solid tw-border-warning/100","tw-bg-callout-warning/20 tw-px-3.5 tw-py-2.5 tw-text-ui-smaller tw-text-warning"),role:"alert"},Cr.default.createElement(Wr,{className:"tw-mt-0.5 tw-size-4 tw-shrink-0","aria-hidden":"true"}),Cr.default.createElement("div",{className:"tw-flex-1"},Cr.default.createElement("span",{className:"tw-block tw-font-semibold"},"Windows needs Developer Mode for multi-agent fanout."),Cr.default.createElement("span",{className:"tw-mt-0.5 tw-block tw-text-normal"},"Creating shortcuts in your agent folders requires admin, or Settings \u2192 Privacy & security \u2192 For developers \u2192 Developer Mode. Until then, agent toggles flip in the file but no shortcut is created.")),Cr.default.createElement("button",{type:"button",onClick:t,style:{appearance:"none",border:0,background:"transparent",padding:0},className:"tw-px-1 tw-text-faint hover:tw-text-normal","aria-label":"Dismiss"},"\xD7")),f_r=({brand:t,onDismiss:e})=>Cr.default.createElement("div",{className:J("tw-flex tw-items-start tw-gap-2.5 tw-rounded-md tw-border tw-border-solid tw-border-blue/80","tw-bg-blue-rgb/10 tw-px-3.5 tw-py-2.5 tw-text-ui-smaller tw-text-normal"),role:"status"},Cr.default.createElement("div",{className:"tw-flex-1"},Cr.default.createElement("span",{className:"tw-block tw-font-semibold"},"This vault is inside ",t,"."),Cr.default.createElement("span",{className:"tw-mt-0.5 tw-block tw-text-muted"},"Sync sometimes replaces directory junctions with shortcuts. If a skill disappears from an agent after a sync, re-toggle it here to recreate the link.")),Cr.default.createElement("button",{type:"button",onClick:e,style:{appearance:"none",border:0,background:"transparent",padding:0},className:"tw-px-1 tw-text-faint hover:tw-text-normal","aria-label":"Dismiss"},"\xD7"))});var Dwe=b(()=>{NE();Owe();y7e();e7e();hNe();UYt();T7e();P7e();M7e();r7e();a7e();wQ();p7e();N7e();i7e();y$();Awe();kW();$7e();F7e();j7e();WYt()});function z7e(t){let e=`${qYt}/`;return typeof t!="string"||!t.startsWith(e)?null:t.slice(e.length)}function kQ(t){return t.startsWith(`${y_r}/`)}function bS(t){switch(t.origin.kind){case"byok":{let e=t.origin.catalogProviderId;return e?{id:e,native:!1}:t.providerType==="openai-compatible"?{id:t.providerId,native:!1}:null}case"copilot-plus":return{id:qYt,native:!1};case"agent":return{id:t.providerId,native:!0};default:return null}}function KYt(t,e){let n=bS(t);return n?n.native?e.info.id:`${n.id}/${e.info.id}`:null}function GYt(t,e){let n=e.configuredModels.find(o=>o.configuredModelId===t);if(!n)return null;let r=e.providers[n.providerId];return r?KYt(r,n):null}function v_r(t,e){return e?"ok":Fw(t)&&!t.apiKeyKeychainId?"missing_key":"ok"}function ZYt(t){let e=t.backends.opencode?.enabledModels??[];if(e.length===0)return VYt;let n=new Map;for(let o of t.configuredModels)n.set(o.configuredModelId,o);let r=[];for(let o of e){let i=n.get(o);if(!i)continue;let s=t.providers[i.providerId];if(!s)continue;let a=bS(s);if(!a)continue;let l=KYt(s,i);l&&r.push({baseModelId:l,name:i.info.displayName||i.info.id,description:i.info.description,credentialState:v_r(s,a.native),isFree:kQ(l),capabilities:Uw(i.info),needsSelfHostWarning:rx(s,t)})}return r.length===0?VYt:r}var qYt,y_r,VYt,Fwe=b(()=>{mp();qYt="copilot-plus";y_r="opencode";VYt=Object.freeze([])});function b_r(t){if(!(typeof t!="number"||!Number.isFinite(t)||t<=0))return Math.round(t*1e3)}function __r(t,e=Date.now()){let n=t?.used;if(!n)return{kind:"unavailable"};let r=[];for(let[o,i]of w_r){let s=n[o],a=QB(s?.usedPercent);a!==null&&r.push({id:o,label:i,percent:a,resetsAt:b_r(s?.resetsAt)})}return ez(r,e)}function x_r(t){if(typeof t!="string")return null;let e=/^\s*([\d.]+)\s*([KMkm])?\s*$/.exec(t);if(!e)return null;let n=Number(e[1]);if(!Number.isFinite(n)||n<=0)return null;let r=e[2]?.toUpperCase(),o=r==="M"?1024*1024:r==="K"?1024:1;return Math.round(n*o)}var w_r,Uwe,YYt=b(()=>{HR();_v();pe();w_r=[["five_hour","5h"],["weekly","Weekly"]];Uwe=class{constructor(){this.contextWindows=null;this.inFlight=null}async readPlanUsage(){let e=await Gi.getInstance().getUsage();return __r(e)}async readContextWindow(e){return e?(await this.loadCatalog())?.get(e)??null:null}async loadCatalog(){if(this.contextWindows)return this.contextWindows;this.inFlight??(this.inFlight=this.fetchCatalog().finally(()=>{this.inFlight=null}));let e=await this.inFlight;return e&&(this.contextWindows=e),e}async fetchCatalog(){let e=await Gi.getInstance().getModels();if(!e?.data)return j("[AgentMode] Copilot Plus catalog unavailable; context ring will retry"),null;let n=new Map;for(let r of e.data){let o=x_r(r?.context_length);r?.id&&o!==null&&n.set(r.id,o)}return n}}});function S_r(t){let e=t?.trim();return e||void 0}async function C_r(t,e,n){let{providerRegistry:r,backendConfigRegistry:o}=e,i={},s=[];for(let p of o.resolveEnabled("opencode")){if(p.state!=="ok")continue;let m=bS(p.provider);if(!m||m.native)continue;let h=p.provider.origin,g=h.kind==="byok"?h.catalogProviderId:void 0,v=!!g,y=i[m.id];if(!y){let S=await r.getApiKey(p.provider.providerId);if(!S&&W9(p.provider)){j(`[AgentMode] skipping ${m.id}/${p.configuredModel.info.id}: no API key in keychain`);continue}let I=p.provider.baseUrl;if(!v&&!I){j(`[AgentMode] skipping ${m.id}/${p.configuredModel.info.id}: ${h.kind} provider has no baseUrl`);continue}let C=v&&I&&QZt(g,I)?void 0:I;y={...v?{}:{npm:"@ai-sdk/openai-compatible",name:p.provider.displayName},options:{...S?{apiKey:S}:{},...C?{baseURL:C}:{},...h.kind==="copilot-plus"&&e.clientVersion?{headers:{"X-Client-Version":e.clientVersion}}:{}}},i[m.id]=y}y.models||(y.models={});let{info:w}=p.configuredModel,_={};w.modalities&&(_.modalities=w.modalities,w.modalities.input?.includes("image")&&(_.attachment=!0)),w.reasoning&&(_.reasoning=!0),y.models[w.id]=_,s.push(`${m.id}/${w.id}`)}s.length>0?j(`[AgentMode] injected ${s.length} model(s) into opencode config: ${s.join(", ")}`):Object.keys(i).length===0&&j("[AgentMode] no enabled BYOK models found; opencode will rely on its own auth. Add and enable models for opencode in Copilot settings to use Agent Mode end-to-end.");let a={provider:i},l=qu.hasInstance(),c=sP(),u=n?{external_directory:{[`${n}/**`]:"allow"}}:void 0;a.agent={[XYt]:{...u?{permission:u}:{},prompt:c},[H7e]:{mode:"primary",permission:{bash:"ask",edit:"ask",...u},prompt:c}},a.default_agent=H7e,l||j("[AgentMode] SkillManager not yet initialised at OpenCode spawn \u2014 shipping empty deny list; next session will pick it up.");let d=l?GW():[],f=I7e(d,kI.id,kI.crossDiscoveredAgents);if(f.length>0){let p=a.permission,h={...p?.skill??{}};for(let g of f)g in h||(h[g]="deny");a.permission={...p??{},skill:h},j(`[AgentMode] opencode deny list: ${f.length} cross-discovered skill(s) denied (${f.join(", ")})`)}return a}var JYt,H7e,XYt,QYt,b$,IQ,jwe,eJt=b(()=>{gt();pe();Se();mp();eZe();Dwe();O9();Vye();UX();Fwe();YYt();JYt={anthropic:"anthropic",openai:"openai",google:"google",groq:"groq",mistralai:"mistral",deepseek:"deepseek",openrouterai:"openrouter",xai:"xai","copilot-plus":"copilot-plus"},H7e="copilot-build",XYt="build",QYt={default:H7e,auto:XYt},jwe=class{constructor(e){this.id="opencode";this.displayName="opencode";Rt(this,b$);Rt(this,IQ,new Uwe);Et(this,b$,e)}async readPlanUsage(){return re(this,IQ).readPlanUsage()}planUsageAppliesTo(e){return z7e(e)!==null}async readContextWindow(e){return re(this,IQ).readContextWindow(z7e(e))}async buildSpawnDescriptor(e){let n=Y(),r=n.agentMode?.backends?.opencode?.binaryPath;if(!r)throw new Error("opencode binary not installed. Open Agent Mode settings and install it before starting a session.");let o=S_r(re(this,b$).getCacheRoot?.()),i=await C_r(n,re(this,b$),o),s=n.agentMode?.backends?.opencode?.envOverrides??{};o&&Object.prototype.hasOwnProperty.call(s,"OPENCODE_CONFIG_CONTENT")&&W("[AgentMode] opencode envOverrides.OPENCODE_CONFIG_CONTENT replaces the generated config; the context-cache external_directory allow rule is dropped \u2014 opencode will prompt on every snapshot read. Remove that override to restore silent cache access.");let a=await nW(re(this,b$).clientVersion,e.vaultBasePath);return{command:r,args:["acp","--cwd",e.vaultBasePath],env:{...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify(i),...a,...s}}}};b$=new WeakMap,IQ=new WeakMap});var tJt,nJt,rJt=b(()=>{tve();Se();tJt=L(B()),nJt=()=>{let t=xt();return tJt.default.createElement(fW,{backendDisplayName:"opencode",value:t.agentMode?.backends?.opencode?.envOverrides,onChange:e=>xC("opencode",{envOverrides:e}),hintExamples:["XDG_CONFIG_HOME","HTTPS_PROXY"]})}});var Bwe={};sr(Bwe,{cacheRoot:()=>NI,filesDir:()=>AQ,markersDir:()=>YW,remotesDir:()=>PQ,snapshotAbsPath:()=>W7e});function TQ(...t){return Pe("path").join(...t)}function NI(t){let e=Pe("os");return TQ(TU(e.homedir()),"vaults",Eae(t),"context-cache")}function PQ(t){return TQ(NI(t),"remotes")}function AQ(t){return TQ(NI(t),"files")}function YW(t,e){return TQ(NI(t),"markers",jl(e))}function W7e(t,e,n){return TQ(e==="file"?AQ(t):PQ(t),n)}var _$=b(()=>{Mae();$n();Py()});function jX(t){return V7e||(V7e=new Rve(t)),V7e}function I_r(t){for(let[e,n]of Object.entries(JYt))if(n===t)return e;return null}var oJt,iJt,V7e,k_r,EQ,kI,UX=b(()=>{jZt();KZt();ZZt();pe();Se();eJt();$ve();Fwe();rJt();q8e();_$();PX();H8e();oJt="mode",iJt=Object.freeze({}),V7e=null,k_r=new Set(["none","minimal","low","medium","high","xhigh","max"]),EQ={encode:t=>t.effort?`${t.baseModelId}/${t.effort}`:t.baseModelId,decode:t=>{if(!t)return{selection:{baseModelId:t,effort:null},provider:null};let e=t.split("/"),n=e.length>=2?I_r(e[0]):null,r=e[e.length-1];return e.length>=3&&k_r.has(r)?{selection:{baseModelId:e.slice(0,-1).join("/"),effort:r},provider:n}:{selection:{baseModelId:t,effort:null},provider:n}}};kI={id:"opencode",displayName:"opencode",Icon:GZt,selfHostable:!0,routesCopilotModels:!0,setupDescription:"Copilot Plus models, or any model on your own provider key. Copilot can download and manage the binary for you.",skillsProjectDir:".opencode/skills",crossDiscoveredAgents:["claude","codex"],restartOnManagedSkillsChange:!0,restartOnProviderConfigChange:!0,restartOnSystemPromptChange:!0,summarizesSessionTitle:!0,wire:EQ,getEnabledModelEntries(t){return[...ZYt(t)]},getWireBaseId(t,e){return GYt(t,e)},getInstallState(t){return Lve(TW(t.agentMode?.backends?.opencode))},getResolvedBinaryPath(t){return t.agentMode?.backends?.opencode?.binaryPath??null},subscribeInstallState(t,e){return zr((n,r)=>{let o=n.agentMode?.backends?.opencode,i=r.agentMode?.backends?.opencode;(o?.binaryPath!==i?.binaryPath||o?.binaryVersion!==i?.binaryVersion||o?.binarySource!==i?.binarySource)&&e()})},openInstallUI(t){new Dve(t.app,jX(t),{platform:W8e(process.platform)??process.platform,arch:V8e(process.arch)??process.arch}).open()},AbsentInstallActions:qZt,async upgrade(t){let e=jX(t),n=TW(Y().agentMode?.backends?.opencode);n.kind==="installed"&&(n.source==="custom"?await e.upgradeCustomBinary():await e.upgradeManaged())},async applySelection(t,e,n){let r=t.getState()?.model?.apply;if(r?.kind==="setConfigOption"&&r.effortConfigId){if((n?n.backendReportedCurrent?.baseModelId:t.getState()?.model?.current.baseModelId)!==e.baseModelId&&await t.applyModelWireId(EQ.encode({baseModelId:e.baseModelId,effort:null})),e.effort!==null){let i=t.getState()?.model?.apply,s=i?.kind==="setConfigOption"?i.effortConfigId:void 0;s&&await t.setConfigOption(s,e.effort)}return}await t.applyModelWireId(EQ.encode(e))},async prefetchEffortCatalog({proc:t,sessionId:e,modelState:n,enabledModels:r,isAborted:o}){if(n.apply.kind!=="setConfigOption")return iJt;let i=n.apply.configId,s=EQ.encode({baseModelId:n.current.baseModelId,effort:null}),a={};try{for(let l of r){if(o())break;if(l.credentialState==="ok")try{let u=(await t.setSessionConfigOption({sessionId:e,configId:i,value:EQ.encode({baseModelId:l.baseModelId,effort:null})})).model?.availableModels.find(d=>d.baseModelId===l.baseModelId);u&&u.effortOptions.length>0&&(a[l.baseModelId]=u.effortOptions)}catch(c){W(`[AgentMode] opencode effort prefetch for ${l.baseModelId} failed`,c)}}}finally{try{await t.setSessionConfigOption({sessionId:e,configId:i,value:s})}catch(l){W("[AgentMode] opencode effort prefetch: restore failed",l)}}return Object.keys(a).length>0?a:iJt},createBackendProcess(t){let{providerRegistry:e,backendConfigRegistry:n}=t.plugin.modelManagement;return kve(t,new jwe({providerRegistry:e,backendConfigRegistry:n,clientVersion:t.clientVersion,getCacheRoot:()=>NI(t.plugin.app)}))},SettingsPanel:nJt,async onPluginLoad(t){let e=jX(t);e.adoptPlugin(t),e.forgetSettledError(),await e.refreshInstallState()},getProbeSessionId(t){let e=t.agentMode?.backends?.opencode?.probeSessionId;return e&&e.length>0?e:void 0},async persistProbeSessionId(t,e){xC("opencode",{probeSessionId:t})},getModeMapping(t,e){return!e||!e.find(r=>r.id===oJt)?null:{kind:"configOption",configId:oJt,canonical:{...QYt}}}}});function x$(){return q7e||(q7e=[kI,vW,L8e]),q7e}function RI(t,e){return e.enableSelfHostMode&&!t.selfHostable}function MQ(t){let e=t.agentMode?.activeBackend??"opencode";return $a[e]??kI}function ss(){return Object.values($a)}function Hwe(){return K7e||(K7e=Object.freeze(new Set(Object.values($a).filter(t=>!t.selfHostable).map(t=>t.id)))),K7e}var $a,zwe,q7e,K7e,Wm=b(()=>{f9t();Ave();UX();$a={opencode:kI,claude:vW,codex:L8e},zwe="opencode",q7e=null;K7e=null});function JW(t){return t.replace(/[\x00-\x1F\x7F]/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function sJt(t){let e="";for(let n=0;n<t.length;n++){let r=t[n];if(r==="\\"&&n+1<t.length){let o=t[n+1];if(o==="\\"||o==='"'){e+=o,n++;continue}}e+=r}return e}function OQ(t){if(typeof t=="string")return t.trim()||void 0;if(typeof t=="number")return String(t)}var aJt=b(()=>{});var tr,_S=b(()=>{tr="__global__"});function Y7e(t){if(!(typeof t!="string"||t.trim().length===0))try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&typeof e.usedTokens=="number"&&typeof e.updatedAt=="number")return e}catch{}}var lJt,J7e,G7e,Z7e,Wwe,cJt=b(()=>{tA();gt();pe();Se();Is();ut();Jh();rp();lJt=require("obsidian"),J7e=require("obsidian");aJt();_S();G7e=100,Z7e="agent__";Wwe=class{constructor(e){this.app=e}async saveSession(e,n,r){if(e.length===0)return null;try{let o=this.formatChatContent(e),i=e[0].timestamp?.epoch??Date.now(),s=ST();await ao(this.app.vault,s);let a=r?.existingPath?this.resolveExistingFile(r.existingPath):null,l=a?await this.readExistingMeta(a):{},c=a?a.path:this.generateFileName(e,i,s,l.topic),u=this.generateNoteContent({chatContent:o,firstMessageEpoch:i,backendId:n,topic:l.topic,label:r?.label??l.label,modelKey:r?.modelKey,lastAccessedAt:l.lastAccessedAt,sessionId:r?.sessionId??l.sessionId,projectId:OQ(r?.projectId)??l.projectId,usage:r?.usage??l.usage});if(a&&xp(this.app,a.path))return await this.app.vault.modify(a,u),{path:a.path};if(!xp(this.app,c)&&await this.app.vault.adapter.exists(c))return await this.app.vault.adapter.write(c,u),{path:c};try{return{path:(await this.app.vault.create(c,u)).path}}catch(d){if(KR(d))return await this.app.vault.adapter.write(c,u),{path:c};if(cY(d)){W("[AgentChatPersistenceManager] Filename too long, falling back to minimal name");let f=`${s}/${Z7e}chat-${i}.md`;try{return{path:(await this.app.vault.create(f,u)).path}}catch(p){if(KR(p))return await this.app.vault.adapter.write(f,u),{path:f};throw p}}throw d}}catch(o){return H("[AgentChatPersistenceManager] Error saving session:",o),null}}async loadFile(e){let n;try{n=await this.app.vault.read(e)}catch{n=await this.app.vault.adapter.read(e.path)}let{frontmatter:r,body:o}=this.splitFrontmatter(n),i=(r.backendId??"").trim();if(!i)throw new Error(`Missing backendId in agent chat frontmatter: ${e.path}`);let s=r.topic?.trim()||void 0,a=r.agentLabel?.trim()||void 0,l=r.sessionId?.trim()||void 0,c=r.projectId?.trim()||tr,u=Y7e(r.usage),d=this.parseChatBody(o);return j(`[AgentChatPersistenceManager] Loaded ${d.length} messages from ${e.path} (backend=${i}, sessionId=${l??"none"}, projectId=${c})`),{messages:d,backendId:i,topic:s,label:a,sessionId:l,projectId:c,usage:u}}async getAgentChatHistoryFiles(){return(await qR(this.app,ST())).filter(n=>n.basename.startsWith(Z7e))}async updateTopic(e,n){await kx(this.app,e,{topic:n.trim()})}async deleteFile(e){let n=this.app.vault.getAbstractFileByPath(e);if(n){await Bc(this.app,n),new J7e.Notice("Chat moved to trash.");return}if(await this.app.vault.adapter.exists(e)){await this.app.vault.adapter.remove(e),new J7e.Notice("Chat deleted.");return}throw new Error("Chat file not found.")}resolveExistingFile(e){let n=this.app.vault.getAbstractFileByPath(e);return n instanceof lJt.TFile?n:null}async readExistingMeta(e){let n=this.app.metadataCache.getFileCache(e)?.frontmatter;if(n)return{topic:n.topic,label:n.agentLabel,lastAccessedAt:typeof n.lastAccessedAt=="number"?n.lastAccessedAt:void 0,sessionId:typeof n.sessionId=="string"?n.sessionId:void 0,projectId:OQ(n.projectId),usage:Y7e(n.usage)};try{let r=await uf(this.app,e.path);if(!r)return{};let o=r.lastAccessedAt?Number(r.lastAccessedAt):void 0;return{topic:r.topic,label:r.agentLabel,lastAccessedAt:o&&Number.isFinite(o)?o:void 0,sessionId:typeof r.sessionId=="string"?r.sessionId:void 0,projectId:OQ(r.projectId),usage:Y7e(r.usage)}}catch{return{}}}formatChatContent(e){return e.map(n=>{let r=n.timestamp?n.timestamp.display:"Unknown time",o=n.message.length===0&&n.fanout?Zpe(n.fanout,i=>i):n.message;return`**${n.sender}**: ${o}
[Timestamp: ${r}]`}).join(`
`)}parseChatBody(e){let n=[],r=/\*\*(user|ai)\*\*: ([\s\S]*?)(?=(?:\n\*\*(?:user|ai)\*\*: )|$)/g,o;for(;(o=r.exec(e))!==null;){let i=o[1]==="user"?ar:pl,a=o[2].trim().split(`
`),l=a.length,c="Unknown time";if(a[l-1]?.startsWith("[Timestamp: ")){let p=a[l-1].match(/\[Timestamp: (.*?)\]/);p&&(c=p[1],l--)}let u=a.slice(0,l).join(`
`).trim(),d=null;if(c!=="Unknown time"){let p=new Date(c);isNaN(p.getTime())||(d={epoch:p.getTime(),display:c,fileName:""})}let f=d?`loaded-${n.length}-${d.epoch}`:`loaded-${n.length}`;n.push({id:f,message:u,sender:i,isVisible:!0,timestamp:d})}return n}splitFrontmatter(e){let n=e.match(/^---\n([\s\S]*?)\n---/);if(!n)return{frontmatter:{},body:e};let r={};for(let o of n[1].split(`
`)){let i=o.match(/^(\w+):\s*(.+)/);if(!i)continue;let s=i[2].trim(),a;s.startsWith('"')&&s.endsWith('"')&&s.length>=2?a=sJt(s.slice(1,-1)):s.startsWith("'")&&s.endsWith("'")&&s.length>=2?a=s.slice(1,-1):a=s,r[i[1]]=a}return{frontmatter:r,body:e.slice(n[0].length).trim()}}generateFileName(e,n,r,o){let i=Y(),a=Cs(new Date(n)).fileName,l;if(o)l=o;else{let _=e.find(S=>S.sender===ar);l=_&&_.message.replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/[{}[\]]/g,"").split(/\s+/).slice(0,10).join(" ").replace(/[\\/:*?"<>|\x00-\x1F]/g,"").trim()||"Untitled Agent Chat"}let c=i.defaultConversationNoteName||"{$date}_{$time}__{$topic}",u=Z7e,d=xw(".md"),f=xw(u),p=c.replace("{$topic}","").replace("{$date}",a.split("_")[0]).replace("{$time}",a.split("_")[1]),m=xw(p),h=Math.max(20,G7e-d-f-m),g=l.replace(/\s+/g,"_"),v=_T(g,h);c=c.replace("{$topic}",v).replace("{$date}",a.split("_")[0]).replace("{$time}",a.split("_")[1]);let y=c.replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/[{}[\]]/g,"_").replace(/[\\/:*?"<>|\x00-\x1F]/g,"_"),w=`${u}${y}.md`;if(xw(w)>G7e){let _=G7e-d-f,S=_T(y,_);return Fr(r,`${u}${S}.md`)}return Fr(r,w)}generateNoteContent(e){let n=["---",`epoch: ${e.firstMessageEpoch}`,`mode: ${WF}`,`backendId: ${e.backendId}`],r=OQ(e.projectId);return r&&r!==tr&&n.push(`projectId: "${JW(r)}"`),e.sessionId&&n.push(`sessionId: "${JW(e.sessionId)}"`),e.topic&&n.push(`topic: "${JW(e.topic)}"`),e.label&&n.push(`agentLabel: "${JW(e.label)}"`),e.modelKey&&n.push(`modelKey: "${JW(e.modelKey)}"`),e.lastAccessedAt&&n.push(`lastAccessedAt: ${e.lastAccessedAt}`),e.usage&&n.push(`usage: '${JSON.stringify(e.usage)}'`),n.push("tags:"),n.push(` - ${Woe}`),n.push("---"),n.push(""),n.push(e.chatContent),n.join(`
`)}}});function T_r(t,e,n){let r=n.model?.availableModels.map(l=>l.baseModelId).join(", ")??"",o=n.mode?.options.map(l=>l.value).join(", ")??"",i=n.model?.current.baseModelId??"-",a=n.model?.availableModels.find(l=>l.baseModelId===i)?.effortOptions.map(l=>l.value??"default").join(", ")??"";j(`[AgentMode] preload ${t} (${e}): models=[${r}] (current=${i}), mode=[${o}] effort=[${a}]`)}var qwe,Vwe,uJt=b(()=>{pe();Se();qwe=require("obsidian");ok();Vwe=class{constructor(e,n,r){this.app=e;this.plugin=n;this.resolveDescriptor=r;this.warm=new Map;this.modelCatalogCache=new Map;this.effortCatalog=new Map;this.inflight=new Map;this.pendingRefresh=new Set;this.listeners=new Set;this.warmExitUnsubs=new Map;this.disposed=!1}getCachedModelCatalog(e){return this.modelCatalogCache.get(e)??null}getEffortCatalog(e){return this.effortCatalog.get(e)??null}clearCached(e){if(this.disposed)return;let n=!1;this.modelCatalogCache.delete(e)&&(n=!0),this.effortCatalog.delete(e)&&(n=!0);let r=this.warm.get(e);r&&(this.warm.delete(e),this.warmExitUnsubs.get(e)?.(),this.warmExitUnsubs.delete(e),r.proc.shutdown().catch(o=>{W(`[AgentMode] preload clearCached: shutdown of warm ${e} failed`,o)}),n=!0),n&&this.notify()}takeWarm(e){let n=this.warm.get(e);return n?(this.warm.delete(e),this.warmExitUnsubs.get(e)?.(),this.warmExitUnsubs.delete(e),n):null}getWarmProcs(){return Array.from(this.warm.entries(),([e,n])=>({backendId:e,proc:n.proc}))}preload(e){if(this.disposed)return Promise.resolve();let n=this.inflight.get(e);return n||this.startProbeChain(e)}refresh(e){if(this.disposed)return null;let n=this.inflight.get(e);return n?(this.pendingRefresh.add(e),n):this.getCachedModelCatalog(e)===null?null:(this.clearCached(e),this.startProbeChain(e))}startProbeChain(e){let n=this.runProbeChain(e).finally(()=>{this.inflight.delete(e),this.pendingRefresh.delete(e)});return this.inflight.set(e,n),n}async runProbeChain(e){let n=0;do this.pendingRefresh.delete(e),n>0&&this.clearCached(e),n+=1,await this.runProbe(e);while(this.pendingRefresh.has(e)&&!this.disposed)}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}shutdown(){this.disposed=!0,this.modelCatalogCache.clear(),this.effortCatalog.clear(),this.inflight.clear(),this.pendingRefresh.clear(),this.listeners.clear();for(let[e,n]of this.warm)this.warmExitUnsubs.get(e)?.(),n.proc.shutdown().catch(r=>{W(`[AgentMode] preload shutdown: warm ${e} shutdown failed`,r)});this.warm.clear(),this.warmExitUnsubs.clear()}notify(){for(let e of this.listeners)try{e()}catch(n){W("[AgentMode] preload listener threw",n)}}async runProbe(e){if(qwe.Platform.isMobile)return;let n=this.app.vault.adapter;if(!(n instanceof qwe.FileSystemAdapter))return;let r=n.getBasePath(),o=this.resolveDescriptor(e);if(!o){W(`[AgentMode] preload skipped: unknown backend ${e}`);return}if(o.getInstallState(Y()).kind!=="ready")return;let i=o.createBackendProcess({plugin:this.plugin,app:this.app,clientVersion:this.plugin.manifest.version,descriptor:o}),s=null;try{await i.start?.();let c=o.getProbeSessionId?.(Y());s=await this.fetchInitialState(i,o,e,c,r)}catch(c){H(`[AgentMode] preload ${e} failed`,c)}if(this.disposed||!s||!s.state.model&&!s.state.mode){s&&j(`[AgentMode] preload ${e}: agent did not report any initial state`);try{await i.shutdown()}catch(c){W(`[AgentMode] preload ${e}: shutdown failed`,c)}return}await this.runEffortPrefetch(e,o,i,s.sessionId,s.state);let a={proc:i},l=i.onExit(()=>{this.disposed||this.warm.get(e)===a&&(this.warm.delete(e),this.modelCatalogCache.delete(e),this.effortCatalog.delete(e),this.warmExitUnsubs.delete(e),this.notify())});this.warm.set(e,a),this.modelCatalogCache.set(e,{availableModels:s.state.model?.availableModels??null}),this.warmExitUnsubs.set(e,l),T_r(e,"session probe",s.state),this.notify()}async runEffortPrefetch(e,n,r,o,i){if(!n.prefetchEffortCatalog||!i.model)return;let s=n.getEnabledModelEntries?.(Y());if(!(!s||s.length===0))try{let a=await n.prefetchEffortCatalog({proc:r,sessionId:o,modelState:i.model,enabledModels:s,isAborted:()=>this.disposed});if(this.disposed)return;Object.keys(a).length>0&&this.effortCatalog.set(e,a)}catch(a){W(`[AgentMode] preload ${e}: effort prefetch failed`,a)}}async fetchInitialState(e,n,r,o,i){let s=[];o&&(s.push({label:`resumed probe session ${o}`,sessionId:o,run:()=>e.resumeSession({sessionId:o,cwd:i})}),s.push({label:`loaded probe session ${o}`,sessionId:o,run:()=>e.loadSession({sessionId:o,cwd:i})}));for(let{label:l,sessionId:c,run:u}of s)try{e.registerSessionHandler(c,()=>{});let d=await u();return j(`[AgentMode] preload ${r}: ${l}`),{sessionId:d.sessionId,state:d.state}}catch(d){d instanceof da||W(`[AgentMode] preload ${r}: ${l} failed (will fall back)`,d)}let a=await e.newSession({cwd:i});if(e.registerSessionHandler(a.sessionId,()=>{}),j(`[AgentMode] preload ${r}: created probe session ${a.sessionId}`),n.persistProbeSessionId)try{await n.persistProbeSessionId(a.sessionId,this.plugin)}catch(l){W(`[AgentMode] preload ${r}: persistProbeSessionId failed`,l)}return{sessionId:a.sessionId,state:a.state}}}});function LI(t,e){return`${t}:${e}`}function A_r(t){if(typeof t!="object"||t===null)return null;let e=t;if(typeof e.backendId!="string"||!e.backendId.trim()||typeof e.sessionId!="string"||!e.sessionId.trim())return null;let n=typeof e.createdAtMs=="number"&&e.createdAtMs>0?e.createdAtMs:null,r=typeof e.lastAccessedAtMs=="number"&&e.lastAccessedAtMs>0?e.lastAccessedAtMs:null;if(!n&&!r)return null;let o=typeof e.title=="string"&&e.title.trim()?e.title.trim():null;return{backendId:e.backendId,sessionId:e.sessionId,title:o,titleSource:o&&(e.titleSource==="user"||e.titleSource==="agent")?e.titleSource:void 0,createdAtMs:n??r,lastAccessedAtMs:r??n,projectId:typeof e.projectId=="string"&&e.projectId.trim()?e.projectId:void 0}}var P_r,dJt,fJt,Kwe,pJt=b(()=>{pe();P_r=500,dJt=500,fJt=500;Kwe=class{constructor(e,n){this.storage=e;this.filePath=n;this.entries=new Map;this.tombstones=new Map;this.loadPromise=null;this.saveTimer=null;this.writeChain=Promise.resolve()}async getEntries(){return await this.ensureLoaded(),Array.from(this.entries.values())}async getEntry(e,n){return await this.ensureLoaded(),this.entries.get(LI(e,n))??null}async recordSession(e){await this.ensureLoaded();let n=LI(e.backendId,e.sessionId);this.tombstones.delete(n);let r=this.entries.get(n),o=e.title==null;this.entries.set(n,{backendId:e.backendId,sessionId:e.sessionId,title:o?r?.title??null:e.title,titleSource:o?r?.titleSource:e.titleSource,createdAtMs:Math.min(e.createdAtMs,r?.createdAtMs??e.createdAtMs),lastAccessedAtMs:Math.max(e.lastAccessedAtMs,r?.lastAccessedAtMs??e.lastAccessedAtMs),projectId:e.projectId??r?.projectId}),this.scheduleSave()}async mergeDiscoveredSessions(e){await this.ensureLoaded();let n=!1;for(let r of e){let o=LI(r.backendId,r.sessionId);if(this.tombstones.has(o))continue;let i=this.entries.get(o),s=i?.titleSource==="user"||r.title==null,a={backendId:r.backendId,sessionId:r.sessionId,title:s?i?.title??null:r.title,titleSource:s?i?.titleSource:"agent",createdAtMs:Math.min(r.createdAtMs,i?.createdAtMs??r.createdAtMs),lastAccessedAtMs:Math.max(r.lastAccessedAtMs,i?.lastAccessedAtMs??r.lastAccessedAtMs),projectId:i?.projectId??r.projectId};(!i||i.title!==a.title||i.createdAtMs!==a.createdAtMs||i.lastAccessedAtMs!==a.lastAccessedAtMs||i.projectId!==a.projectId)&&(this.entries.set(o,a),n=!0)}n&&this.scheduleSave()}async setTitle(e,n,r){await this.ensureLoaded();let o=LI(e,n),i=this.entries.get(o);if(!i)return;let s=r.trim();this.entries.set(o,{...i,title:s||null,titleSource:s?"user":void 0}),this.scheduleSave()}async touch(e,n){await this.ensureLoaded();let r=LI(e,n),o=this.entries.get(r);o&&(this.entries.set(r,{...o,lastAccessedAtMs:Date.now()}),this.scheduleSave())}async deleteSession(e,n){await this.ensureLoaded();let r=LI(e,n);this.entries.delete(r),this.tombstones.set(r,Date.now()),this.scheduleSave()}async isTombstoned(e,n){return await this.ensureLoaded(),this.tombstones.has(LI(e,n))}async flush(){this.saveTimer!==null&&(window.clearTimeout(this.saveTimer),this.saveTimer=null,this.queueWrite()),await this.writeChain}ensureLoaded(){return this.loadPromise||(this.loadPromise=this.loadFromDisk()),this.loadPromise}async loadFromDisk(){try{if(!await this.storage.exists(this.filePath))return;let e=JSON.parse(await this.storage.read(this.filePath));if(!e||typeof e!="object")return;for(let n of Array.isArray(e.entries)?e.entries:[]){let r=A_r(n);r&&this.entries.set(LI(r.backendId,r.sessionId),r)}if(e.tombstones&&typeof e.tombstones=="object")for(let[n,r]of Object.entries(e.tombstones))typeof r=="number"&&r>0&&this.tombstones.set(n,r)}catch(e){W(`[AgentMode] failed to load agent session index at ${this.filePath}`,e)}}scheduleSave(){this.saveTimer!==null&&window.clearTimeout(this.saveTimer),this.saveTimer=window.setTimeout(()=>{this.saveTimer=null,this.queueWrite()},P_r)}queueWrite(){let e=this.serialize();this.writeChain=this.writeChain.then(()=>this.storage.write(this.filePath,e)).catch(n=>{W(`[AgentMode] failed to write agent session index at ${this.filePath}`,n)})}serialize(){let e=Array.from(this.entries.values());e.length>dJt&&(e=e.sort((o,i)=>i.lastAccessedAtMs-o.lastAccessedAtMs).slice(0,dJt),this.entries=new Map(e.map(o=>[LI(o.backendId,o.sessionId),o])));let n=Array.from(this.tombstones.entries());n.length>fJt&&(n=n.sort((o,i)=>i[1]-o[1]).slice(0,fJt),this.tombstones=new Map(n));let r={version:1,entries:e,tombstones:Object.fromEntries(n)};return JSON.stringify(r,null,2)}}});function mJt(){let{mkdir:t,readFile:e,stat:n,writeFile:r}=Pe("fs/promises"),o=Pe("path");return{exists:async i=>{try{return await n(i),!0}catch{return!1}},read:i=>e(i,"utf8"),write:async(i,s)=>{await t(o.dirname(i),{recursive:!0}),await r(i,s,"utf8")}}}var hJt=b(()=>{$n()});var NQ,gJt=b(()=>{pe();NQ=class{constructor(e){this.session=e;this.listeners=new Set;this.session.subscribe({onMessagesChanged:()=>this.notifyListeners(),onStatusChanged:()=>this.notifyListeners(),onModelChanged:()=>this.notifyListeners(),onCurrentPlanChanged:()=>this.notifyListeners(),onCurrentTodoListChanged:()=>this.notifyListeners()})}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notifyListeners(){for(let e of this.listeners)try{e()}catch(n){W("[AgentChatUIState] listener threw",n)}}sendMessage(e,n,r,o){let{userMessageId:i,turn:s}=this.session.sendPrompt(e,n,r,o);this.notifyListeners();let a=s.then(()=>{},l=>{H("[AgentMode] turn failed",l)});return{id:i,turn:a}}async cancel(){await this.session.cancel()}async deleteMessage(e){let n=this.session.getStatus();if(n==="running"||n==="awaiting_permission")return W("[AgentChatUIState] delete refused while turn is in flight"),!1;let r=this.session.store.deleteMessage(e);return r&&this.notifyListeners(),r}clearMessages(){this.session.store.clear(),this.notifyListeners()}getMessages(){return this.session.store.getDisplayMessages()}isStarting(){return this.session.getStatus()==="starting"}getBackendState(){return this.session.getState()}canSwitchModel(){return this.session.canSwitchModel()}canSwitchEffort(){return this.session.canSwitchEffort()}canSwitchMode(){return this.session.canSwitchMode()}hasPendingPlanPermission(){return this.session.hasPendingPlanPermission()}getPendingToolPermissions(){return this.session.getPendingToolPermissions()}resolveToolPermission(e,n){this.session.resolveToolPermission(e,n),this.notifyListeners()}getPendingAskUserQuestions(){return this.session.getPendingAskUserQuestions()}resolveAskUserQuestion(e,n){this.session.resolveAskUserQuestion(e,n),this.notifyListeners()}getCurrentPlan(){return this.session.getCurrentPlan()}getCurrentTodoList(){return this.session.getCurrentTodoList()}getSessionUsage(){return this.session.getSessionUsage()}getPlanUsage(){return this.session.getPlanUsage()}async resolvePlanProposal(e,n,r){let o=this.session.getCurrentPlan();if(!o||o.id!==e||o.decision!=="pending")return;if(!o.permissionGated||!o.pendingToolCallId){W("[AgentChatUIState] non-gated plan card has no resolution path");return}let i=n==="feedback"?r?.trim():void 0;this.session.resolvePlanProposalPermission(o.pendingToolCallId,n==="approve",i),this.session.finalizePlanDecision(o.id),this.notifyListeners()}}});function Zwe(){return Ar(E_r,{store:Pd})}function $p(){return Pd.get(Ad)}function mo(t){return Pd.get(Ad).find(e=>e.project.id===t)}function RQ(t){return Pd.get(Ad).find(e=>e.filePath===t)}function LQ(t){Pd.set(Ad,t)}function X7e(t,e){let n=Pd.get(Ad),r=n.findIndex(o=>o.filePath===t);if(r!==-1){let o=n.filter((s,a)=>a===r||s.project.id!==e.project.id),i=o.findIndex(s=>s.filePath===t);o[i]=e,Pd.set(Ad,o)}else{let o=n.filter(i=>i.project.id!==e.project.id);Pd.set(Ad,[...o,e])}}function S$(t){let e=Pd.get(Ad),n=e.findIndex(r=>r.project.id===t.project.id);if(n!==-1){let r=[...e];r[n]=t,Pd.set(Ad,r)}else Pd.set(Ad,[...e,t])}function yJt(t){let e=Pd.get(Ad);Pd.set(Ad,e.filter(n=>n.project.id!==t))}function UE(t){let e=Pd.get(Ad);Pd.set(Ad,e.filter(n=>n.filePath!==t))}function vJt(t){return Pd.sub(Ad,()=>{t(Pd.get(Ad))})}function Nf(t){let e=(0,Gwe.normalizePath)(t);XW.set(e,(XW.get(e)??0)+1)}function Ed(t){let e=(0,Gwe.normalizePath)(t),n=(XW.get(e)??0)-1;n<=0?XW.delete(e):XW.set(e,n)}function qb(t){return(XW.get((0,Gwe.normalizePath)(t))??0)>0}var Gwe,Pd,Ad,E_r,XW,Md=b(()=>{Us();Us();Gwe=require("obsidian"),Pd=sy(),Ad=yo([]),E_r=yo(t=>t(Ad).map(e=>e.project));XW=new Map});function Od(){return Vie()}function Nd(t){let e=(0,jE.normalizePath)(t).split("/");if(e.length<3)throw new Error(`Not a project config path: "${t}"`);return{projectFolderPath:e.slice(0,-1).join("/"),projectsRoot:e.slice(0,-2).join("/")}}function Q7e(){return(0,jE.normalizePath)(`${Od()}/${ff}`)}function $Q(t){return(0,jE.normalizePath)(`${Od()}/${t}`)}function BE(t,e){let n=e?(0,jE.normalizePath)(e):Od();return(0,jE.normalizePath)(`${n}/${t}/${Xh}`)}function C$(t){if(!(t instanceof jE.TFile)||t.extension!=="md")return!1;let e=Od();if(!t.path.startsWith(e+"/"))return!1;let n=t.path.slice(e.length+1);if(n.startsWith(`${ff}/`))return!1;let r=n.split("/");return!(r.length!==2||r[1]!==Xh)}function wJt(t){let e=Od();if(!t.startsWith(e+"/"))return null;let r=t.slice(e.length+1).split("/");return r.length!==2||r[1]!==Xh?null:r[0]||null}function xS(t){let n=(t||"").trim().replace(/[<>:"/\\|?*]/g,"_").replace(/[\x00-\x1F]/g,"_");return n=n.replace(/[. ]+$/g,""),(n==="."||n==="..")&&(n=n.replace(/\./g,"_")),/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(n)&&(n=`_${n}`),n||(n="_"),n}function bJt(t,e){let n=(e||"").trim()||t,r=xS(n);return r.toLowerCase()===ff&&(r=`_${r}`),r}function $I(t){return(t||"").split(`
`).map(e=>e.trim()).filter(Boolean)}async function eYe(t,e,n){try{let o=(await t.cachedRead(e)).replace(/^\uFEFF/,"").match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!o)return"";let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=o[1].match(new RegExp(`^${i}:\\s*(.+)$`,"m"));if(!s)return"";let a=s[1].trim();if(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))a=a.slice(1,-1);else{let l=a.indexOf(" #");l>0&&(a=a.slice(0,l).trim())}return a}catch{return""}}var jE,Mv=b(()=>{sA();Is();jE=require("obsidian")});function Ywe(t){return t?t.split(`
`).map(e=>e.trim()).filter(e=>e.length>0).join(`
`):""}function M_r(t){let e=t.contextSource;return{inclusions:Ywe(e?.inclusions),exclusions:Ywe(e?.exclusions),webUrls:Ywe(e?.webUrls),youtubeUrls:Ywe(e?.youtubeUrls)}}function DI(t){return JSON.stringify({source:M_r(t.project),filePath:t.filePath})}function SJt(t){return t!==null&&!t.includes(xJt)}function DQ(t,e){return JSON.stringify({context:DI(e),instructions:O_r(t,e)})}function O_r(t,e){let n=Nd(e.filePath).projectFolderPath,r=(0,_Jt.normalizePath)(`${n}/${df}`),o=HUt(t,r);return o?`agents:${o.stat.mtime}:${o.stat.size}`:r.split("/").some(i=>i.startsWith("."))?xJt:`legacy:${e.project.systemPrompt??""}`}function tYe(t,e){return`${t}#${e}`}function CJt(t,e){if(t===void 0)return!1;if(t===e)return!0;let n=t.lastIndexOf("#");return n<0?!1:t.slice(0,n)===e&&/^\d+$/.test(t.slice(n+1))}var _Jt,xJt,Jwe=b(()=>{db();Mv();_Jt=require("obsidian");xJt="agents:unverifiable"});function QW(t,e){let{inclusions:n,exclusions:r}=Fi({inclusions:e?.inclusions,exclusions:e?.exclusions,isProject:!0});return n?t.vault.getFiles().filter(o=>kJt.has(o.extension.toLowerCase())).filter(o=>ii(t,o,n,r,!0)).sort(IJt):nYe}function TJt(t,e){let{inclusions:n,exclusions:r}=Fi({inclusions:e?.inclusions,exclusions:e?.exclusions,isProject:!0});if(!n)return N_r;let o=t.vault.getFiles().filter(a=>ii(t,a,n,r,!0)).sort(IJt),i=o.filter(a=>kJt.has(a.extension.toLowerCase())),s=o.filter(a=>a.extension.toLowerCase()==="md").length;return{candidates:i.length>0?i:nYe,skippedMarkdownCount:s}}var kJt,nYe,IJt,N_r,Xwe=b(()=>{ha();kJt=new Set(["pdf","doc","docx","ppt","pptx","epub","rtf","xls","xlsx","png","jpg","jpeg","gif","bmp","tiff","webp"]),nYe=Object.freeze([]),IJt=(t,e)=>t.path.localeCompare(e.path);N_r=Object.freeze({candidates:nYe,skippedMarkdownCount:0})});function $_r(t,e){let n=PJt(t,r=>e.priority<=r.priority);t.splice(n+1,0,e)}function PJt(t,e){for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1}var bci,_ci,R_r,L_r,rYe,D_r,e6,oYe=b(()=>{bci=new Error("timeout while waiting for mutex to become available"),_ci=new Error("mutex already locked"),R_r=new Error("request for lock canceled"),L_r=function(t,e,n,r){function o(i){return i instanceof n?i:new n(function(s){s(i)})}return new(n||(n=Promise))(function(i,s){function a(u){try{c(r.next(u))}catch(d){s(d)}}function l(u){try{c(r.throw(u))}catch(d){s(d)}}function c(u){u.done?i(u.value):o(u.value).then(a,l)}c((r=r.apply(t,e||[])).next())})},rYe=class{constructor(e,n=R_r){this._value=e,this._cancelError=n,this._queue=[],this._weightedWaiters=[]}acquire(e=1,n=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((r,o)=>{let i={resolve:r,reject:o,weight:e,priority:n},s=PJt(this._queue,a=>n<=a.priority);s===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(s+1,0,i)})}runExclusive(e){return L_r(this,arguments,void 0,function*(n,r=1,o=0){let[i,s]=yield this.acquire(r,o);try{return yield n(i)}finally{s()}})}waitForUnlock(e=1,n=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,n)?Promise.resolve():new Promise(r=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),$_r(this._weightedWaiters[e-1],{resolve:r,priority:n})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let n=this._value;this._value-=e.weight,e.resolve([n,this._newReleaser(e.weight)])}_newReleaser(e){let n=!1;return()=>{n||(n=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let n=this._weightedWaiters[e-1];n&&(n.forEach(r=>r.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let n=this._value;n>0;n--){let r=this._weightedWaiters[n-1];if(!r)continue;let o=r.findIndex(i=>i.priority<=e);(o===-1?r:r.splice(0,o)).forEach(i=>i.resolve())}}}_couldLockImmediately(e,n){return(this._queue.length===0||this._queue[0].priority<n)&&e<=this._value}};D_r=function(t,e,n,r){function o(i){return i instanceof n?i:new n(function(s){s(i)})}return new(n||(n=Promise))(function(i,s){function a(u){try{c(r.next(u))}catch(d){s(d)}}function l(u){try{c(r.throw(u))}catch(d){s(d)}}function c(u){u.done?i(u.value):o(u.value).then(a,l)}c((r=r.apply(t,e||[])).next())})},e6=class{constructor(e){this._semaphore=new rYe(1,e)}acquire(){return D_r(this,arguments,void 0,function*(e=0){let[,n]=yield this._semaphore.acquire(1,e);return n})}runExclusive(e,n=0){return this._semaphore.runExclusive(()=>e(),1,n)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}});var Qwe={};sr(Qwe,{createNodeContextCacheFs:()=>t6});function t6(t){let e=Pe("fs"),n=Pe("path"),r=n.resolve(t),o=async(a,l,c=3)=>{let u;for(let d=0;d<c;d++)try{await e.promises.rename(a,l);return}catch(f){u=f,await new Promise(p=>window.setTimeout(p,200))}throw u},i=a=>{if(a.split(/[\\/]+/).includes(".."))throw new Error(`unsafe context-cache path (".." segment): ${a}`);if(n.isAbsolute(a))throw new Error(`unsafe context-cache path (absolute): ${a}`);let l=n.resolve(r,a),c=n.relative(r,l);if(c===""||!c.startsWith("..")&&!n.isAbsolute(c))return l;throw new Error(`unsafe context-cache path (escapes root): ${a}`)},s=async(a,l)=>{try{await e.promises.rm(a,{recursive:l,force:!0})}catch{}};return{async exists(a){let l=i(a);try{return await e.promises.stat(l),!0}catch{return!1}},async mkdirRecursive(a){await e.promises.mkdir(i(a),{recursive:!0})},async list(a){let l=i(a);try{return(await e.promises.readdir(l)).filter(u=>!u.startsWith(AJt))}catch{return[]}},async readText(a){return e.promises.readFile(i(a),"utf-8")},async writeText(a,l){let c=i(a);if(c===r)throw new Error(`refusing to write the cache root itself: ${a}`);let u=n.join(n.dirname(c),`${AJt}${n.basename(c)}-${Date.now()}-${(F_r++).toString(36)}-${Math.random().toString(36).slice(2,8)}`);try{await e.promises.writeFile(u,l,"utf-8"),await o(u,c)}catch(d){throw await s(u,!1),d}},async remove(a){await s(i(a),!1)},async clear(){await s(r,!0)}}}var AJt,F_r,n6=b(()=>{$n();AJt=".copilot-cache-tmp-",F_r=0});async function iYe(t){let{remotesDir:e,filesDir:n,markerDir:r,fs:o,converters:i,nowMs:s,onProgress:a}=t,l=t.forceRetryFailed??!1,c=t.withSourceLock??((v,y)=>y());await o.mkdirRecursive(e),await o.mkdirRecursive(n),await o.mkdirRecursive(r);let u=[],d=[],f=new Set,p=MJt(t.remotes,v=>`${v.type}:${v.url}`),m=MJt(t.files,v=>v.vaultPath);p.length>0&&a?.({phase:"prefetch",done:0,total:p.length});let h=0,g=await Promise.all(p.map(async v=>{let y={kind:v.type,source:v.url},w=Kb(v.type,v.url),_=FQ(v.type,v.url),S=await EJt(y,a,I=>c(w,()=>j_r(e,r,w,_,v,i,o,s,l,I)));return h+=1,a?.({phase:"prefetch",done:h,total:p.length}),{remote:v,result:S}}));for(let{remote:v,result:y}of g){let w=Kb(v.type,v.url),_=FQ(v.type,v.url);y.present&&u.push({type:v.type,source:v.url,cacheFileName:w}),y.failure&&(d.push(y.failure),y.markerWanted&&f.add(_))}m.length>0&&a?.({phase:"parse",done:0,total:m.length});for(let v=0;v<m.length;v++){let y=m[v],w={kind:"file",source:y.vaultPath},_=Kb("file",y.vaultPath),S=FQ("file",y.vaultPath),I=await EJt(w,a,C=>c(_,()=>B_r(n,r,_,S,y,i,o,s,l,C)));I.present&&u.push({type:"file",source:y.vaultPath,cacheFileName:_}),I.failure&&(d.push(I.failure),I.markerWanted&&f.add(S)),a?.({phase:"parse",done:v+1,total:m.length})}return{entries:u,wantedMarkerNames:f,failures:d}}async function EJt(t,e,n){let r=!1,o;try{o=await n(()=>{r=!0,e?.({phase:"itemStart",item:t})})}catch(i){o={present:!1,failure:{source:t.source,kind:t.kind,error:kt(i),usedStaleSnapshot:!1}}}return r&&(o.failure?e?.({phase:"itemFailed",item:t,failure:o.failure}):e?.({phase:"itemSettled",item:t})),o}async function j_r(t,e,n,r,o,i,s,a,l,c){let u=UQ(t,n),d=UQ(e,r),f=await DJt(s,u),p=`${o.type}:${o.url}`;if(f!==null&&f.fingerprint===p)return await r6(s,d),{present:!0};if(!l&&f===null){let m=await LJt(s,d);if(m!==null)return{present:!1,failure:{source:o.url,kind:o.type,error:m.error,usedStaleSnapshot:!1},markerWanted:!0}}try{c?.();let m=await i.fetchRemote(o);return await $Jt(s,u,o.type,o.url,p,m,a),await r6(s,d),{present:!0}}catch(m){let h=kt(m);W(`[project-context] fetch failed for ${o.url}: ${h}`);let g=f!==null,v=!1;return g?await r6(s,d):(await RJt(s,d,o.url,o.type,h,a),v=!0),{present:g,failure:{source:o.url,kind:o.type,error:h,usedStaleSnapshot:g},markerWanted:v}}}async function B_r(t,e,n,r,o,i,s,a,l,c){let u=UQ(t,n),d=UQ(e,r),f=await DJt(s,u),p=`${o.mtime}:${o.size}`;if(f!==null&&f.fingerprint===p)return await r6(s,d),{present:!0};if(!l&&f===null){let m=await LJt(s,d);if(m!==null&&m.fingerprint===p)return{present:!1,failure:{source:o.vaultPath,kind:"file",error:m.error,usedStaleSnapshot:!1},markerWanted:!0}}try{c?.();let m=await i.parseFile(await o.read(),o.ext);return await $Jt(s,u,"file",o.vaultPath,p,m,a),await r6(s,d),{present:!0}}catch(m){let h=kt(m);W(`[project-context] parse failed for ${o.vaultPath}: ${h}`);let g=f!==null,v=!1;return g?await r6(s,d):(await RJt(s,d,o.vaultPath,"file",h,a,p),v=!0),{present:g,failure:{source:o.vaultPath,kind:"file",error:h,usedStaleSnapshot:g},markerWanted:v}}}async function NJt(t,e,n){let r=await t.list(e);for(let o of r)n.has(o)||H_r.test(o)&&await t.remove(UQ(e,o))}function UQ(t,e){let n=t.replace(/\/+$/,""),r=e.replace(/^\/+/,"");return n?`${n}/${r}`:r}function Kb(t,e){return`${t}-${jl(e)}.md`}function FQ(t,e){return`failed-${t}-${jl(e)}.json`}async function r6(t,e){try{await t.remove(e)}catch(n){W(`[project-context] could not clear stale failure marker ${e}: ${kt(n)}`)}}async function RJt(t,e,n,r,o,i,s){let a={schemaVersion:tbe,source:n,kind:r,error:o,failedAt:i,...s!==void 0?{fingerprint:s}:{}};await t.writeText(e,JSON.stringify(a))}async function LJt(t,e){let n;try{n=await t.readText(e)}catch{return null}return sYe(n)}function sYe(t){try{let e=JSON.parse(t);return e.schemaVersion!==tbe||typeof e.source!="string"||typeof e.kind!="string"||typeof e.error!="string"||typeof e.failedAt!="number"?null:e}catch{return null}}async function $Jt(t,e,n,r,o,i,s){let a=new Date(s).toISOString(),l={schemaVersion:tbe,sourceType:n,...n==="file"?{sourcePath:r}:{sourceUrl:r},fetchedAt:a,fingerprint:o},c=i.trim(),u=`${ebe}
${JSON.stringify(l)}
${OJt}
# ${n==="file"?"File":n==="youtube"?"YouTube":"URL"}: ${r}
_Materialized ${a} \u2014 snapshot; refresh if the source changed._
${c}
`;await t.writeText(e,u)}async function DJt(t,e){let n;try{n=await t.readText(e)}catch{return null}return aYe(n)}function aYe(t){if(!t.startsWith(ebe))return null;let e=t.indexOf(`
${OJt}`,ebe.length);if(e<0)return null;let n=t.slice(ebe.length,e).trim();try{let r=JSON.parse(n);if(r.schemaVersion!==tbe)return null;let o=!!(r.sourceUrl??r.sourcePath);return!r.sourceType||!o||!r.fetchedAt||!r.fingerprint?null:r}catch{return null}}function MJt(t,e){let n=new Set,r=[];for(let o of t){let i=e(o);n.has(i)||(n.add(i),r.push(o))}return r}var U_r,ebe,OJt,tbe,z_r,H_r,o6=b(()=>{oK();pe();Py();U_r=["web","youtube","file"],ebe="<!-- copilot-context-cache",OJt="-->",tbe=1;z_r=U_r.join("|"),H_r=new RegExp(`^failed-(${z_r})-[0-9a-f]+\\.json$`)});function FJt(t){let e=new Map(t.materialized.filter(f=>!!f.snapshotAbsPath).map(f=>[`${f.type}:${f.source}`,f.snapshotAbsPath])),n=(f,p)=>{let m=e.get(`${f}:${p}`);return m?`${p} \u2192 \`${m}\``:p},r=f=>`\`${f.absPath??f.vaultPath}\``,o=[...t.folders.map(f=>FI("Included folders",r(f))),...t.properties.map(f=>FI("Included properties",f)),...t.notes.map(f=>FI("Included notes",r(f))),...t.extensions.map(f=>FI("Included file types",`\`${f}\``)),...t.tags.map(f=>FI("Included tags",f)),...t.webUrls.map(f=>FI("Included URLs",n("web",f))),...t.youtubeUrls.map(f=>FI("Included YouTube",n("youtube",f)))],i=[...t.materialized.filter(f=>f.type==="file").map(f=>FI("Materialized files",n(f.type,f.source))),...t.propertyNotes.map(f=>FI("Notes matching an included property",r(f)))],s=[...o,...i],a=s.length,l=s.slice(0,W_r),c=a-l.length,u=["<project_context>","Context sources for this project, with absolute paths. Folders and tags are","listed as sources, not expanded into member files \u2014 use your own search","(grep/glob/read) to enumerate them. Properties are listed as source labels and",'also expanded into the notes they match, under "Notes matching an included','property" (the label is listed first so it survives the entry cap).',"Materialized snapshots of URLs, YouTube transcripts, and PDFs/images are shown","inline as an absolute path after the source, formatted `<source> \u2192 <absolute path>`","\u2014 read that path directly. A source with no path isn't cached (not yet converted","or conversion failed); use the source itself."],d="";for(let f of l)f.section!==d&&(d=f.section,u.push("",`## ${d}`)),u.push(`- ${f.text}`);return c>0&&u.push("",`> Only the first ${l.length} of ${a} sources are listed; ${c} more are omitted. Use the declared context sources above with grep/glob/read to find the rest.`),u.push("</project_context>"),u.join(`
`)}function FI(t,e){return{section:t,text:e}}var W_r,UJt=b(()=>{W_r=100});function jJt(t){return t.absPath??t.vaultPath}function K_r(t){let e=HJt.get(t);return e||(e=new e6,HJt.set(t,e)),e}function qJt(t,e){return K_r(t).runExclusive(e)}function i6(t,e){let n=WJt(t).replace(/\/+$/,""),r=WJt(e).replace(/\/+$/,"");if(r===n)return"";let o=`${n}/`;if(!r.startsWith(o))throw new Error(`context-cache directory escapes root: ${e}`);return r.slice(o.length)}function WJt(t){return t.replace(/\\/g,"/")}async function cYe(t,e,n,r,o,i){let s=o??!1,a=mo(e),l=a?DI(a):void 0,c=i??l,u=nbe.get(e);if(u&&u.revision===c&&(!s||u.forceRetryFailed))return u.promise;let d=u?.promise,f=(async()=>(d&&await d.catch(()=>{}),G_r(t,e,n,r,s)))().finally(()=>{nbe.get(e)?.promise===f&&nbe.delete(e)});return nbe.set(e,{promise:f,forceRetryFailed:s,revision:c}),f}async function G_r(t,e,n,r,o){try{let i=mo(e);if(!i)return BJt;let s=DI(i),a=i.project.contextSource;if(!a)return{additionalDirectories:jQ,projectContextBlock:zJt,contextSignature:s};let l=VJt(a.webUrls),c=VJt(a.youtubeUrls),u=[...l.map(ne=>({type:"web",url:ne})),...c.map(ne=>({type:"youtube",url:ne}))],{inclusions:d,exclusions:f}=Fi({inclusions:a.inclusions,exclusions:a.exclusions,isProject:!0}),p=d?.folderPatterns??[],m=d?.notePatterns??[],h=d?.extensionPatterns??[],g=d?.tagPatterns??[],v=d?.propertyPatterns??[],y=Y_r(t),{entries:w,additionalDirectories:_}=J_r(t,p,n,y),S=X_r(t,m,y),I=new Set(S.map(jJt)),C=Q_r(t,v,f,y).filter(ne=>!I.has(jJt(ne))),k=d?QW(t,a).map(ne=>({vaultPath:ne.path,ext:ne.extension.toLowerCase(),mtime:ne.stat.mtime,size:ne.stat.size,read:()=>t.vault.readBinary(ne)})):[];if(!(u.length>0||k.length>0||p.length>0||m.length>0||h.length>0||g.length>0||v.length>0||_.length>0))return{additionalDirectories:jQ,projectContextBlock:zJt,contextSignature:s};r?.({phase:"resolve",resolved:k.length});let P=NI(t),E=t6(P),O=i6(P,PQ(t)),$=i6(P,AQ(t)),U=i6(P,YW(t,e)),{entries:V,wantedMarkerNames:K,failures:se}=await iYe({remotesDir:O,filesDir:$,markerDir:U,fs:E,converters:KJt(),remotes:u,files:k,nowMs:Date.now(),forceRetryFailed:o,onProgress:r,withSourceLock:qJt});r?.({phase:"failures",failures:se});let le=V.map(ne=>({...ne,snapshotAbsPath:W7e(t,ne.type,ne.cacheFileName)})),Q=FJt({folders:w,notes:S,extensions:h,tags:g,properties:v,propertyNotes:C,webUrls:l,youtubeUrls:c,materialized:le});return await NJt(E,U,K),j(`[project-context] materialized ${V.length} source(s) for ${e}; add-dir=${_.length}, failures=${se.length}`),{additionalDirectories:_.length>0?_:jQ,projectContextBlock:Q,contextSignature:s}}catch(i){let s=kt(i);return W(`[project-context] materialize failed for ${e}; continuing`,i),r?.({phase:"failures",failures:[{source:"Project context",kind:"file",error:s,usedStaleSnapshot:!1}]}),BJt}}function KJt(){return{fetchRemote:async t=>{let e=Gi.getInstance(),n=t.type==="youtube"?(await e.youtube4llm(t.url)).response?.transcript??"":(await e.url4llm(t.url)).response??"";if(!n.trim())throw new Error(`empty content for ${t.url}`);return n},parseFile:async(t,e)=>{let{response:n}=await Gi.getInstance().docs4llm(t,e),r=Z_r(n);if(!r.trim())throw new Error(`empty parse result for .${e}`);return r}}}async function GJt(t,e,n){if(!mo(e))return[{source:n.source,kind:n.kind,error:"Project not found",usedStaleSnapshot:!1}];let o=[],i=[];if(n.kind==="file"){let s=t.vault.getAbstractFileByPath(n.source);if(!(s instanceof s6.TFile))return[{source:n.source,kind:"file",error:"File not found in vault",usedStaleSnapshot:!1}];i=[{vaultPath:s.path,ext:s.extension.toLowerCase(),mtime:s.stat.mtime,size:s.stat.size,read:()=>t.vault.readBinary(s)}]}else o=[{type:n.kind,url:n.source}];try{let s=NI(t),a=t6(s),{failures:l}=await iYe({remotesDir:i6(s,PQ(t)),filesDir:i6(s,AQ(t)),markerDir:i6(s,YW(t,e)),fs:a,converters:KJt(),remotes:o,files:i,nowMs:Date.now(),forceRetryFailed:!0,withSourceLock:qJt});return l}catch(s){return[{source:n.source,kind:n.kind,error:kt(s),usedStaleSnapshot:!1}]}}function Z_r(t){if(typeof t=="string")return t;try{return JSON.stringify(t,null,2)}catch(e){return W(`[project-context] could not stringify docs4llm response: ${kt(e)}`),""}}function Y_r(t){let e=t.vault.adapter;return e instanceof s6.FileSystemAdapter?e:null}function J_r(t,e,n,r){let o=[],i=new Set;for(let s of e){let a=s.replace(/\/+$/,""),l=t.vault.getAbstractFileByPath(a);if(r&&l instanceof s6.TFolder){let c=r.getFullPath(l.path);o.push({vaultPath:a,absPath:c}),exr(n,c)||i.add(c)}else o.push({vaultPath:a})}return{entries:o,additionalDirectories:i.size>0?[...i]:jQ}}function X_r(t,e,n){if(e.length===0)return[];let r=n?t.vault.getFiles():[];return e.flatMap(o=>{let i=o.slice(2,-2);if(!n)return[{vaultPath:o}];let s=r.filter(a=>a.basename===i);return s.length===0?[{vaultPath:o}]:s.map(a=>({vaultPath:a.path,absPath:n.getFullPath(a.path)}))})}function Q_r(t,e,n,r){if(e.length===0)return V_r;let o={propertyPatterns:e};return t.vault.getMarkdownFiles().filter(i=>ii(t,i,o,n,!0)).sort((i,s)=>i.path.localeCompare(s.path)).map(i=>r?{vaultPath:i.path,absPath:r.getFullPath(i.path)}:{vaultPath:i.path})}function exr(t,e){let n=i=>i.replace(/\\/g,"/").replace(/\/+$/,""),r=n(t),o=n(e);return o===r||o.startsWith(`${r}/`)}function VJt(t){return t?t.split(`
`).map(e=>e.trim()).filter(e=>e.length>0):[]}var s6,jQ,V_r,q_r,lYe,BJt,zJt,nbe,HJt,ZJt=b(()=>{_v();oK();pe();Md();Jwe();ha();Xwe();oYe();s6=require("obsidian");n6();_$();o6();UJt();jQ=Object.freeze([]),V_r=Object.freeze([]);q_r=["<project_context>","This session runs in a project workspace: the working directory is the project's","folder. This project's context sources could not be loaded for this session.","</project_context>"].join(`
`),lYe=Object.freeze({additionalDirectories:jQ,projectContextBlock:q_r}),BJt=lYe,zJt=["<project_context>","This session runs in a project workspace: the working directory is the project's","folder. No context sources are configured for this project.","</project_context>"].join(`
`),nbe=new Map,HJt=new Map});function txr(t){return $p().some(r=>{let o=`${xS(r.project.id)}__`,i=`${r.project.id}__`;return t.startsWith(o)||t.startsWith(i)})}function uYe(t){if(typeof t=="string")return t.trim()||void 0;if(typeof t=="number")return String(t)}async function JJt(t,e){let n=t.metadataCache.getFileCache(e)?.frontmatter,r=n?.projectId;if(r===void 0&&!n)try{r=(await uf(t,e.path))?.projectId}catch{return}return uYe(r)}async function dYe(t,e){let n=t.vault.getAbstractFileByPath(e);if(n instanceof YJt.TFile)return JJt(t,n);try{let r=await uf(t,e);return uYe(r?.projectId)}catch{return}}async function rbe(t,e){return(await Promise.all(e.map(async r=>({file:r,projectId:await JJt(t,r)})))).filter(({file:r,projectId:o})=>!o&&!txr(r.basename)).map(({file:r})=>r)}function obe(t,e){let n=t.metadataCache.getFileCache(e)?.frontmatter;if(n?.topic&&typeof n.topic=="string"&&n.topic.trim())return n.topic.trim();let r=e.basename,o=n?.projectId,i=typeof o=="string"?o.trim():typeof o=="number"?String(o):"";if(i){let s=`${xS(i)}__`,a=`${i}__`;r.startsWith(s)?r=r.slice(s.length):r.startsWith(a)&&(r=r.slice(a.length))}else r=r.replace(/^[a-zA-Z0-9_-]+__/,"");return r.replace(/\{\$date\}|\d{8}/g,"").replace(/\{\$time\}|\d{6}/g,"").replace(/[@_]/g," ").replace(/\s+/g," ").trim()}function ibe(t,e){let n=t.metadataCache.getFileCache(e)?.frontmatter;return n&&n.epoch?new Date(n.epoch):new Date(e.stat.ctime)}function BQ(t,e){let r=t.metadataCache.getFileCache(e)?.frontmatter?.lastAccessedAt;if(typeof r=="number"&&Number.isFinite(r)&&r>0)return r;if(typeof r=="string"){let o=Number(r);if(Number.isFinite(o)&&o>0)return o;let i=Date.parse(r);if(Number.isFinite(i))return i}return null}function sbe(t,e,n){let r=ibe(t,e),o=BQ(t,e),i=n.getEffectiveLastUsedAt(e.path,o??r.getTime()),s=t.metadataCache.getFileCache(e)?.frontmatter,a=s?.backendId,l=typeof a=="string"&&a.trim()?a.trim():void 0,c=uYe(s?.projectId);return{id:e.path,title:obe(t,e),createdAt:r,lastAccessedAt:new Date(i),backendId:l,projectId:c}}function XJt(t,e){let n=obe(t,e),r=ibe(t,e),o=Cs(r);return`${n} - ${o.display}`}var YJt,zQ=b(()=>{Mv();Md();ut();Jh();YJt=require("obsidian")});function eXt(t){if(t.kind==="tool_call")return`tool:${t.id}`;if(t.kind==="plan")return"plan"}function rxr(t,e){if(t===e)return!0;if(t.kind!==e.kind)return!1;switch(t.kind){case"text":return e.kind!=="text"?!1:t.text===e.text;case"thought":return e.kind!=="thought"?!1:t.text===e.text;case"plan":return e.kind!=="plan"?!1:ixr(t.entries,e.entries);case"tool_call":return e.kind!=="tool_call"?!1:t.id===e.id&&t.title===e.title&&t.toolKind===e.toolKind&&t.status===e.status&&t.vendorToolName===e.vendorToolName&&t.parentToolCallId===e.parentToolCallId&&oxr(t.progress,e.progress)&&lxr(t.input,e.input)&&sxr(t.locations,e.locations)&&axr(t.output,e.output)}}function oxr(t,e){return t===e?!0:!t||!e?t===e:t.description===e.description&&t.toolName===e.toolName&&t.toolUses===e.toolUses&&t.durationMs===e.durationMs&&t.totalTokens===e.totalTokens}function ixr(t,e){return t===e?!0:t.length!==e.length?!1:t.every((n,r)=>n.content===e[r].content&&n.priority===e[r].priority&&n.status===e[r].status)}function sxr(t,e){return t===e?!0:!t||!e?t===e:t.length!==e.length?!1:t.every((n,r)=>n.path===e[r].path&&n.line===e[r].line)}function axr(t,e){return t===e?!0:!t||!e?t===e:t.length!==e.length?!1:t.every((n,r)=>{let o=e[r];return n.type!==o.type?!1:n.type==="diff"&&o.type==="diff"?n.path===o.path&&n.oldText===o.oldText&&n.newText===o.newText:n.type==="text"&&o.type==="text"?nXt(n.text)===nXt(o.text):!1})}function lxr(t,e){return t===e?!0:tXt(t)===tXt(e)}function tXt(t){let e;try{e=JSON.stringify(t)}catch{e=String(t)}return e.length<=nxr?e:`${e.length}:${e.slice(0,QJt)}:${e.slice(-QJt)}`}function nXt(t){return t.length<=fYe*2?t:`${t.length}:${t.slice(0,fYe)}:${t.slice(-fYe)}`}var nxr,QJt,fYe,abe,rXt=b(()=>{pe();tA();gt();ut();nxr=8e3,QJt=512,fYe=128;abe=class{constructor(){this.messages=[];this.displayCache=new Map;this.lastDisplay=null}generateId(){return`msg-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}touch(e){e.version+=1,this.lastDisplay=null}addMessage(e){let n=e.id||this.generateId(),r=e.timestamp||Cs(new Date);return this.messages.push({id:n,displayText:e.message,sender:e.sender,timestamp:r,context:e.context,isVisible:e.isVisible!==!1,isErrorMessage:e.isErrorMessage,content:e.content,parts:e.parts,turnStopReason:e.turnStopReason,turnDurationMs:e.turnDurationMs,version:0}),this.lastDisplay=null,n}markTurnComplete(e,n,r){let o=this.messages.find(i=>i.id===e);return!o||o.turnStopReason!==void 0?!1:(o.turnStopReason=n,o.turnDurationMs=Math.max(0,r),this.touch(o),!0)}extendTurnDuration(e,n){let r=this.messages.find(i=>i.id===e);if(!r||r.turnDurationMs===void 0)return!1;let o=Math.max(0,n);return o<=r.turnDurationMs?!1:(r.turnDurationMs=o,this.touch(r),!0)}setFanout(e,n){let r=this.messages.find(o=>o.id===e);return r?(r.fanout=n,this.touch(r),!0):!1}appendDisplayText(e,n){let r=this.messages.find(o=>o.id===e);return r?(r.displayText+=n,this.touch(r),!0):!1}appendAgentText(e,n){let r=this.messages.find(i=>i.id===e);if(!r)return!1;r.displayText+=n,r.parts||(r.parts=[]);let o=r.parts[r.parts.length-1];return o&&o.kind==="text"?o.text+=n:r.parts.push({kind:"text",text:n}),this.touch(r),!0}appendAgentThought(e,n){let r=this.messages.find(i=>i.id===e);if(!r)return!1;r.parts||(r.parts=[]);let o=r.parts[r.parts.length-1];return o&&o.kind==="thought"?o.text+=n:r.parts.push({kind:"thought",text:n}),this.touch(r),!0}upsertAgentPart(e,n){let r=this.messages.find(i=>i.id===e);if(!r)return!1;r.parts||(r.parts=[]);let o=eXt(n);if(o!==void 0){let i=r.parts.findIndex(s=>eXt(s)===o);if(i!==-1)return rxr(r.parts[i],n)?!1:(r.parts[i]=n,this.touch(r),!0)}return r.parts.push(n),this.touch(r),!0}findMessageIdWithToolCall(e){for(let n=this.messages.length-1;n>=0;n--){let r=this.messages[n];if(r.parts?.some(o=>o.kind==="tool_call"&&o.id===e))return r.id}}markMessageError(e,n,r){let o=this.messages.find(s=>s.id===e);if(!o)return!1;o.isErrorMessage=!0,r!==void 0&&(o.turnDurationMs=Math.max(0,r));let i=o.displayText.length>0?`
`:"";return o.displayText+=`${i}**Error:** ${n}`,this.touch(o),!0}hasAssistantActivity(e){let n=this.messages.find(r=>r.id===e);return n?n.displayText.trim().length>0?!0:(n.parts??[]).some(r=>r.kind==="text"||r.kind==="thought"?r.text.trim().length>0:!0):!1}deleteMessage(e){let n=this.messages.findIndex(r=>r.id===e);return n===-1?!1:(this.messages.splice(n,1),this.displayCache.delete(e),this.lastDisplay=null,!0)}clear(){this.messages=[],this.displayCache.clear(),this.lastDisplay=null}truncateAfterMessageId(e){let n=this.messages.findIndex(r=>r.id===e);if(n!==-1){for(let r of this.messages.slice(n+1))this.displayCache.delete(r.id);this.messages=this.messages.slice(0,n+1),this.lastDisplay=null}}getDisplayMessages(){if(this.lastDisplay!==null)return this.lastDisplay;let e=this.messages.filter(n=>n.isVisible).map(n=>this.adaptCached(n));return this.lastDisplay=e,e}getMessage(e){let n=this.messages.find(r=>r.id===e);return n?this.adaptCached(n):void 0}adaptCached(e){let n=this.displayCache.get(e.id);if(n&&n.version===e.version)return n.view;let r=this.toAgentChatMessage(e);return this.displayCache.set(e.id,{version:e.version,view:r}),r}loadMessages(e){this.clear();for(let n of e){let r=n.sender===ar?void 0:K4e(n.message)??void 0;this.messages.push({id:n.id||this.generateId(),displayText:n.message,sender:n.sender,timestamp:n.timestamp,context:n.context,isVisible:n.isVisible!==!1,isErrorMessage:n.isErrorMessage,content:n.content,parts:n.parts,turnStopReason:n.turnStopReason,turnDurationMs:n.turnDurationMs,fanout:r,version:0})}j(`[AgentMessageStore] Loaded ${e.length} messages`)}getDebugInfo(){return{totalMessages:this.messages.length,visibleMessages:this.messages.filter(e=>e.isVisible).length}}toAgentChatMessage(e){return{id:e.id,message:e.displayText,sender:e.sender,timestamp:e.timestamp,isVisible:e.isVisible,context:e.context,isErrorMessage:e.isErrorMessage,content:e.content,parts:e.parts,turnStopReason:e.turnStopReason,turnDurationMs:e.turnDurationMs,...e.fanout?{fanout:rUt(e.fanout)}:{}}}}});function lbe(t){let e=t.find(r=>r.sender===ar&&r.message.trim());if(!e)return null;let n=e.message.replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/\s+/g," ").trim();return n?n.length<=oXt?n:`${n.slice(0,oXt).trimEnd()}\u2026`:null}function pYe(t,e){let n=new Map;for(let o of e)n.set(`${o.backendId}:${o.sessionId}`,o);let r=[];for(let{item:o,backendId:i,sessionId:s}of t){let a=i&&s?`${i}:${s}`:null,l=a?n.get(a):void 0;if(l&&a){n.delete(a),r.push({...o,lastAccessedAt:l.lastAccessedAtMs>o.lastAccessedAt.getTime()?new Date(l.lastAccessedAtMs):o.lastAccessedAt,projectId:o.projectId??l.projectId});continue}r.push(o)}for(let o of n.values())r.push({id:B5(o.backendId,o.sessionId),title:o.title??cxr,createdAt:new Date(o.createdAtMs),lastAccessedAt:new Date(o.lastAccessedAtMs),backendId:o.backendId,projectId:o.projectId});return r}var cxr,oXt,mYe=b(()=>{gt();H5();cxr="Untitled chat",oXt=60});function zE(t){try{let e=new URL(t),n=e.hostname.replace(/^www\./,"").replace(/^m\./,"");return n==="youtube.com"&&e.pathname==="/watch"?e.searchParams.get("v"):n==="youtu.be"&&e.pathname.length>1?e.pathname.slice(1).split("/")[0]:(n==="youtube.com"&&e.pathname.startsWith("/shorts/")||n==="youtube.com"&&e.pathname.startsWith("/embed/"))&&e.pathname.split("/")[2]||null}catch{return null}}function hYe(t){return zE(t)!==null}var cbe=b(()=>{});function HQ(t){if(!t)return!1;let e=t.view;return!e||typeof e!="object"?!1:typeof e.getViewType=="function"&&e.getViewType()===k$}function a6(t){let e=t.view?.webview;if(!e||typeof e!="object"||typeof e.executeJavaScript!="function")throw new gYe("Web Viewer webview is unavailable. The view may not be fully initialized.");return e}var k$,fbe,kg,ube,dbe,gYe,HE,l6=b(()=>{k$="webviewer",fbe={OPEN:"webviewer:open",SAVE_TO_VAULT:"webviewer:save-to-vault"},kg=class t extends Error{constructor(e){super(e),this.name="WebViewerError",Object.setPrototypeOf(this,t.prototype)}},ube=class t extends kg{constructor(e){super(e),this.name="WebViewerUnsupportedError",Object.setPrototypeOf(this,t.prototype)}},dbe=class t extends kg{constructor(e){super(e),this.name="WebViewerLeafNotFoundError",Object.setPrototypeOf(this,t.prototype)}},gYe=class t extends kg{constructor(e){super(e),this.name="WebviewUnavailableError",Object.setPrototypeOf(this,t.prototype)}},HE=class t extends kg{constructor(e){super(e),this.name="WebViewerTimeoutError",Object.setPrototypeOf(this,t.prototype)}}});function uxr(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)n.hasOwnProperty(r)&&(t[r]=n[r])}return t}function bYe(t,e){return Array(e+1).join(t)}function aXt(t){return t.replace(/^\n*/,"")}function lXt(t){for(var e=t.length;e>0&&t[e-1]===`
`;)e--;return t.substring(0,e)}function cXt(t){return lXt(aXt(t))}function _Ye(t){return xYe(t,dxr)}function dXt(t){return xYe(t,uXt)}function fxr(t){return pXt(t,uXt)}function pxr(t){return xYe(t,fXt)}function mxr(t){return pXt(t,fXt)}function xYe(t,e){return e.indexOf(t.nodeName)>=0}function pXt(t,e){return t.getElementsByTagName&&e.some(function(n){return t.getElementsByTagName(n).length})}function pbe(t){return t?t.replace(/(\n+\s*)+/g,`
`):""}function mXt(t){this.options=t,this._keep=[],this._remove=[],this.blankRule={replacement:t.blankReplacement},this.keepReplacement=t.keepReplacement,this.defaultRule={replacement:t.defaultReplacement},this.array=[];for(var e in t.rules)this.array.push(t.rules[e])}function yYe(t,e,n){for(var r=0;r<t.length;r++){var o=t[r];if(hxr(o,e,n))return o}}function hxr(t,e,n){var r=t.filter;if(typeof r=="string"){if(r===e.nodeName.toLowerCase())return!0}else if(Array.isArray(r)){if(r.indexOf(e.nodeName.toLowerCase())>-1)return!0}else if(typeof r=="function"){if(r.call(t,e,n))return!0}else throw new TypeError("`filter` needs to be a string, array, or function")}function gxr(t){var e=t.element,n=t.isBlock,r=t.isVoid,o=t.isPre||function(d){return d.nodeName==="PRE"};if(!(!e.firstChild||o(e))){for(var i=null,s=!1,a=null,l=iXt(a,e,o);l!==e;){if(l.nodeType===3||l.nodeType===4){var c=l.data.replace(/[ \r\n\t]+/g," ");if((!i||/ $/.test(i.data))&&!s&&c[0]===" "&&(c=c.substr(1)),!c){l=vYe(l);continue}l.data=c,i=l}else if(l.nodeType===1)n(l)||l.nodeName==="BR"?(i&&(i.data=i.data.replace(/ $/,"")),i=null,s=!1):r(l)||o(l)?(i=null,s=!0):i&&(s=!1);else{l=vYe(l);continue}var u=iXt(a,l,o);a=l,l=u}i&&(i.data=i.data.replace(/ $/,""),i.data||vYe(i))}}function vYe(t){var e=t.nextSibling||t.parentNode;return t.parentNode.removeChild(t),e}function iXt(t,e,n){return t&&t.parentNode===e||n(e)?e.nextSibling||e.parentNode:e.firstChild||e.nextSibling||e.parentNode}function yxr(){var t=SYe.DOMParser,e=!1;try{new t().parseFromString("","text/html")&&(e=!0)}catch{}return e}function vxr(){var t=function(){};return wxr()?t.prototype.parseFromString=function(e){var n=new window.ActiveXObject("htmlfile");return n.designMode="on",n.open(),n.write(e),n.close(),n}:t.prototype.parseFromString=function(e){var n=document.implementation.createHTMLDocument("");return n.open(),n.write(e),n.close(),n},t}function wxr(){var t=!1;try{document.implementation.createHTMLDocument("").open()}catch{SYe.ActiveXObject&&(t=!0)}return t}function _xr(t,e){var n;if(typeof t=="string"){var r=xxr().parseFromString('<x-turndown id="turndown-root">'+t+"</x-turndown>","text/html");n=r.getElementById("turndown-root")}else n=t.cloneNode(!0);return gxr({element:n,isBlock:_Ye,isVoid:dXt,isPre:e.preformattedCode?Sxr:null}),n}function xxr(){return wYe=wYe||new bxr,wYe}function Sxr(t){return t.nodeName==="PRE"||t.nodeName==="CODE"}function Cxr(t,e){return t.isBlock=_Ye(t),t.isCode=t.nodeName==="CODE"||t.parentNode.isCode,t.isBlank=kxr(t),t.flankingWhitespace=Ixr(t,e),t}function kxr(t){return!dXt(t)&&!pxr(t)&&/^\s*$/i.test(t.textContent)&&!fxr(t)&&!mxr(t)}function Ixr(t,e){if(t.isBlock||e.preformattedCode&&t.isCode)return{leading:"",trailing:""};var n=Txr(t.textContent);return n.leadingAscii&&sXt("left",t,e)&&(n.leading=n.leadingNonAscii),n.trailingAscii&&sXt("right",t,e)&&(n.trailing=n.trailingNonAscii),{leading:n.leading,trailing:n.trailing}}function Txr(t){var e=t.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/);return{leading:e[1],leadingAscii:e[2],leadingNonAscii:e[3],trailing:e[4],trailingNonAscii:e[5],trailingAscii:e[6]}}function sXt(t,e,n){var r,o,i;return t==="left"?(r=e.previousSibling,o=/ $/):(r=e.nextSibling,o=/^ /),r&&(r.nodeType===3?i=o.test(r.nodeValue):n.preformattedCode&&r.nodeName==="CODE"?i=!1:r.nodeType===1&&!_Ye(r)&&(i=o.test(r.textContent))),i}function mbe(t){if(!(this instanceof mbe))return new mbe(t);var e={rules:Rf,headingStyle:"setext",hr:"* * *",bulletListMarker:"*",codeBlockStyle:"indented",fence:"```",emDelimiter:"_",strongDelimiter:"**",linkStyle:"inlined",linkReferenceStyle:"full",br:" ",preformattedCode:!1,blankReplacement:function(n,r){return r.isBlock?`
`:""},keepReplacement:function(n,r){return r.isBlock?`
`+r.outerHTML+`
`:r.outerHTML},defaultReplacement:function(n,r){return r.isBlock?`
`+n+`
`:n}};this.options=uxr({},e,t),this.rules=new mXt(this.options)}function hXt(t){var e=this;return Pxr.call(t.childNodes,function(n,r){r=new Cxr(r,e.options);var o="";return r.nodeType===3?o=r.isCode?r.nodeValue:e.escape(r.nodeValue):r.nodeType===1&&(o=Mxr.call(e,r)),gXt(n,o)},"")}function Exr(t){var e=this;return this.rules.forEach(function(n){typeof n.append=="function"&&(t=gXt(t,n.append(e.options)))}),t.replace(/^[\t\r\n]+/,"").replace(/[\t\r\n\s]+$/,"")}function Mxr(t){var e=this.rules.forNode(t),n=hXt.call(this,t),r=t.flankingWhitespace;return(r.leading||r.trailing)&&(n=n.trim()),r.leading+e.replacement(n,t,this.options)+r.trailing}function gXt(t,e){var n=lXt(t),r=aXt(e),o=Math.max(t.length-n.length,e.length-r.length),i=`
`.substring(0,o);return n+i+r}function Oxr(t){return t!=null&&(typeof t=="string"||t.nodeType&&(t.nodeType===1||t.nodeType===9||t.nodeType===11))}var dxr,uXt,fXt,Rf,SYe,bxr,wYe,Pxr,Axr,yXt,vXt=b(()=>{dxr=["ADDRESS","ARTICLE","ASIDE","AUDIO","BLOCKQUOTE","BODY","CANVAS","CENTER","DD","DIR","DIV","DL","DT","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","FRAMESET","H1","H2","H3","H4","H5","H6","HEADER","HGROUP","HR","HTML","ISINDEX","LI","MAIN","MENU","NAV","NOFRAMES","NOSCRIPT","OL","OUTPUT","P","PRE","SECTION","TABLE","TBODY","TD","TFOOT","TH","THEAD","TR","UL"];uXt=["AREA","BASE","BR","COL","COMMAND","EMBED","HR","IMG","INPUT","KEYGEN","LINK","META","PARAM","SOURCE","TRACK","WBR"];fXt=["A","TABLE","THEAD","TBODY","TFOOT","TH","TD","IFRAME","SCRIPT","AUDIO","VIDEO"];Rf={};Rf.paragraph={filter:"p",replacement:function(t){return`
`+t+`
`}};Rf.lineBreak={filter:"br",replacement:function(t,e,n){return n.br+`
`}};Rf.heading={filter:["h1","h2","h3","h4","h5","h6"],replacement:function(t,e,n){var r=Number(e.nodeName.charAt(1));if(n.headingStyle==="setext"&&r<3){var o=bYe(r===1?"=":"-",t.length);return`
`+t+`
`+o+`
`}else return`
`+bYe("#",r)+" "+t+`
`}};Rf.blockquote={filter:"blockquote",replacement:function(t){return t=cXt(t).replace(/^/gm,"> "),`
`+t+`
`}};Rf.list={filter:["ul","ol"],replacement:function(t,e){var n=e.parentNode;return n.nodeName==="LI"&&n.lastElementChild===e?`
`+t:`
`+t+`
`}};Rf.listItem={filter:"li",replacement:function(t,e,n){var r=n.bulletListMarker+" ",o=e.parentNode;if(o.nodeName==="OL"){var i=o.getAttribute("start"),s=Array.prototype.indexOf.call(o.children,e);r=(i?Number(i)+s:s+1)+". "}var a=/\n$/.test(t);return t=cXt(t)+(a?`
`:""),t=t.replace(/\n/gm,`
`+" ".repeat(r.length)),r+t+(e.nextSibling?`
`:"")}};Rf.indentedCodeBlock={filter:function(t,e){return e.codeBlockStyle==="indented"&&t.nodeName==="PRE"&&t.firstChild&&t.firstChild.nodeName==="CODE"},replacement:function(t,e,n){return`
`+e.firstChild.textContent.replace(/\n/g,`
`)+`
`}};Rf.fencedCodeBlock={filter:function(t,e){return e.codeBlockStyle==="fenced"&&t.nodeName==="PRE"&&t.firstChild&&t.firstChild.nodeName==="CODE"},replacement:function(t,e,n){for(var r=e.firstChild.getAttribute("class")||"",o=(r.match(/language-(\S+)/)||[null,""])[1],i=e.firstChild.textContent,s=n.fence.charAt(0),a=3,l=new RegExp("^"+s+"{3,}","gm"),c;c=l.exec(i);)c[0].length>=a&&(a=c[0].length+1);var u=bYe(s,a);return`
`+u+o+`
`+i.replace(/\n$/,"")+`
`+u+`
`}};Rf.horizontalRule={filter:"hr",replacement:function(t,e,n){return`
`+n.hr+`
`}};Rf.inlineLink={filter:function(t,e){return e.linkStyle==="inlined"&&t.nodeName==="A"&&t.getAttribute("href")},replacement:function(t,e){var n=e.getAttribute("href");n&&(n=n.replace(/([()])/g,"\\$1"));var r=pbe(e.getAttribute("title"));return r&&(r=' "'+r.replace(/"/g,'\\"')+'"'),"["+t+"]("+n+r+")"}};Rf.referenceLink={filter:function(t,e){return e.linkStyle==="referenced"&&t.nodeName==="A"&&t.getAttribute("href")},replacement:function(t,e,n){var r=e.getAttribute("href"),o=pbe(e.getAttribute("title"));o&&(o=' "'+o+'"');var i,s;switch(n.linkReferenceStyle){case"collapsed":i="["+t+"][]",s="["+t+"]: "+r+o;break;case"shortcut":i="["+t+"]",s="["+t+"]: "+r+o;break;default:var a=this.references.length+1;i="["+t+"]["+a+"]",s="["+a+"]: "+r+o}return this.references.push(s),i},references:[],append:function(t){var e="";return this.references.length&&(e=`
`+this.references.join(`
`)+`
`,this.references=[]),e}};Rf.emphasis={filter:["em","i"],replacement:function(t,e,n){return t.trim()?n.emDelimiter+t+n.emDelimiter:""}};Rf.strong={filter:["strong","b"],replacement:function(t,e,n){return t.trim()?n.strongDelimiter+t+n.strongDelimiter:""}};Rf.code={filter:function(t){var e=t.previousSibling||t.nextSibling,n=t.parentNode.nodeName==="PRE"&&!e;return t.nodeName==="CODE"&&!n},replacement:function(t){if(!t)return"";t=t.replace(/\r?\n|\r/g," ");for(var e=/^`|^ .*?[^ ].* $|`$/.test(t)?" ":"",n="`",r=t.match(/`+/gm)||[];r.indexOf(n)!==-1;)n=n+"`";return n+e+t+e+n}};Rf.image={filter:"img",replacement:function(t,e){var n=pbe(e.getAttribute("alt")),r=e.getAttribute("src")||"",o=pbe(e.getAttribute("title")),i=o?' "'+o+'"':"";return r?"!["+n+"]("+r+i+")":""}};mXt.prototype={add:function(t,e){this.array.unshift(e)},keep:function(t){this._keep.unshift({filter:t,replacement:this.keepReplacement})},remove:function(t){this._remove.unshift({filter:t,replacement:function(){return""}})},forNode:function(t){if(t.isBlank)return this.blankRule;var e;return(e=yYe(this.array,t,this.options))||(e=yYe(this._keep,t,this.options))||(e=yYe(this._remove,t,this.options))?e:this.defaultRule},forEach:function(t){for(var e=0;e<this.array.length;e++)t(this.array[e],e)}};SYe=typeof window<"u"?window:{};bxr=yxr()?SYe.DOMParser:vxr();Pxr=Array.prototype.reduce,Axr=[[/\\/g,"\\\\"],[/\*/g,"\\*"],[/^-/g,"\\-"],[/^\+ /g,"\\+ "],[/^(=+)/g,"\\$1"],[/^(#{1,6}) /g,"\\$1 "],[/`/g,"\\`"],[/^~~~/g,"\\~~~"],[/\[/g,"\\["],[/\]/g,"\\]"],[/^>/g,"\\>"],[/_/g,"\\_"],[/^(\d+)\. /g,"$1\\. "]];mbe.prototype={turndown:function(t){if(!Oxr(t))throw new TypeError(t+" is not a string, or an element/document/fragment node.");if(t==="")return"";var e=hXt.call(this,new _xr(t,this.options));return Exr.call(this,e)},use:function(t){if(Array.isArray(t))for(var e=0;e<t.length;e++)this.use(t[e]);else if(typeof t=="function")t(this);else throw new TypeError("plugin must be a Function or an Array of Functions");return this},addRule:function(t,e){return this.rules.add(t,e),this},keep:function(t){return this.rules.keep(t),this},remove:function(t){return this.rules.remove(t),this},escape:function(t){return Axr.reduce(function(e,n){return e.replace(n[0],n[1])},t)}};yXt=mbe});function c6(t){return typeof t=="object"&&t!==null}function u6(t){if(typeof t=="string")return t;if(t==null)return"";try{return typeof t=="object"?JSON.stringify(t):typeof t=="function"||typeof t=="symbol"||typeof t=="bigint"?t.toString():typeof t=="number"||typeof t=="boolean"?String(t):""}catch{return""}}function xXt(t){return t instanceof Error?t.message:u6(t)}async function Nxr(t){await new Promise(e=>window.setTimeout(e,t))}async function SXt(t,e,n,r){let o=Date.now();for(;;){if(t())return;if(Date.now()-o>=e)throw new kg(`${r} timed out after ${e}ms`);await Nxr(n)}}function wXt(t,e){let n=(t??"").trim();if(!n)return"";if(!e)return n;try{return new URL(n,e).href}catch{return n}}function bXt(t){let e=(t??"").trim();return e?/[\s)]/.test(e)?`<${e}>`:e:""}function Rxr(t){let e=new yXt({headingStyle:"atx",hr:"---",bulletListMarker:"-",codeBlockStyle:"fenced",fence:"```",emDelimiter:"*",strongDelimiter:"**",linkStyle:"inlined"});return e.remove(["script","style","noscript"]),e.addRule("webviewer-link",{filter:"a",replacement:(n,r)=>{let o=r,i=o.getAttribute("href")??"",s=bXt(wXt(i,t)),a=n?.trim()||o.textContent||s;return s?`[${a}](${s})`:a}}),e.addRule("webviewer-image",{filter:"img",replacement:(n,r)=>{let o=r,i=o.getAttribute("alt")??"",s=o.getAttribute("src")??"",a=bXt(wXt(s,t));return a?`![${i}](${a})`:""}}),e}function CYe(t,e){if(!t.trim())return"";let n=Rxr(e),i=new DOMParser().parseFromString(`<div>${t}</div>`,"text/html").body.firstElementChild;return i?n.turndown(i).replace(/\n{3,}/g,`
`).trim():""}function kYe(t){let e=t.commands;return!e||!c6(e)||typeof e.executeCommandById!="function"?null:e}function CXt(t,e){let n=kYe(t);if(!n)return!1;if(n.commands){if(n.commands instanceof Map)return n.commands.has(e);if(typeof n.commands=="object")return e in n.commands}return typeof n.listCommands=="function"?n.listCommands().some(o=>o.id===e):!1}function kXt(t,e){return t.workspace.getLeavesOfType(k$).includes(e)}function _Xt(t){if(!c6(t)||t.enabled!==!0)return null;let e=t.instance;if(!e||!c6(e))return null;let n=e;return typeof n.openUrl=="function"||typeof n.handleOpenUrl=="function"?n:null}function IXt(t,e){let n=t.internalPlugins;if(!n||!c6(n))return null;let r=n.plugins;if(!r)return null;let o=r instanceof Map?r.get(k$):c6(r)?r[k$]:null;if(o){let s=_Xt(o);if(s)return s}let i;if(r instanceof Map)i=Array.from(r.values());else if(c6(r))i=Object.values(r);else return e&&e(),null;for(let s of i){let a=_Xt(s);if(a)return a}return null}var hbe=b(()=>{vXt();l6()});function d6(t){return{url:typeof t.view?.url=="string"?t.view.url:"",title:typeof t.view?.title=="string"?t.view.title:"",faviconUrl:typeof t.view?.faviconUrl=="string"?t.view.faviconUrl:"",mode:t.view?.mode==="reader"?"reader":"webview"}}async function TXt(t,e={}){let{signal:n}=e;if(n?.aborted)throw new HE("Operation was aborted");try{let r=Promise.resolve(t.view.getReaderModeContent());if(!n){let i=await r;return typeof i?.md=="string"?i.md:""}let o=await new Promise((i,s)=>{let a=()=>{s(new HE("Operation was aborted"))};n.addEventListener("abort",a,{once:!0}),r.then(l=>{n.removeEventListener("abort",a),i(l)}).catch(l=>{n.removeEventListener("abort",a),s(l instanceof Error?l:new Error(String(l)))})});return typeof o?.md=="string"?o.md:""}catch(r){throw r instanceof HE||H("Failed to get reader mode content:",r),r}}async function gbe(t,e=!0){let n=a6(t),r='(() => { try { return window.getSelection?.()?.toString?.() ?? ""; } catch { return ""; } })()';try{let o=await n.executeJavaScript(r),i=u6(o);return e?i.trim():i}catch(o){throw H("Failed to get selected text:",o),o}}async function ybe(t){let e=a6(t),n="";try{n=typeof e.getURL=="function"?e.getURL():""}catch{n=t.view?.url??""}let r=`(() => {
const sel = window.getSelection();
if (!sel || sel.rangeCount === 0 || sel.isCollapsed) return "";
const div = document.createElement("div");
for (let i = 0; i < sel.rangeCount; i++) div.appendChild(sel.getRangeAt(i).cloneContents());
return div.innerHTML;
})()`,o="";try{let i=await e.executeJavaScript(r);o=u6(i)}catch(i){throw H("Failed to get selection HTML:",i),i}try{return CYe(o,n)}catch(i){throw H("Failed to convert HTML to Markdown:",i),i}}async function PXt(t){let e=a6(t),n="";try{n=typeof e.getURL=="function"?e.getURL():""}catch{n=t.view?.url??""}let r=`(() => {
const clone = document.body.cloneNode(true);
clone.querySelectorAll('script, style, noscript').forEach(el => el.remove());
return clone.innerHTML;
})()`,o="";try{let i=await e.executeJavaScript(r);o=u6(i)}catch(i){throw H("Failed to get page HTML:",i),i}try{return CYe(o,n)}catch(i){throw H("Failed to convert page HTML to Markdown:",i),i}}async function AXt(t,e=!0){let n=a6(t),r=e?'(() => { try { return document.documentElement?.outerHTML ?? ""; } catch { return ""; } })()':'(() => { try { return document.body?.outerHTML ?? ""; } catch { return ""; } })()';try{let o=await n.executeJavaScript(r);return u6(o)}catch(o){throw H("Failed to get HTML:",o),o}}function Lxr(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.videoId=="string"&&typeof e.title=="string"&&typeof e.channel=="string"&&(e.description===void 0||typeof e.description=="string")&&(e.uploadDate===void 0||typeof e.uploadDate=="string")&&(e.duration===void 0||typeof e.duration=="string")&&(e.genre===void 0||typeof e.genre=="string")&&Array.isArray(e.transcript)&&e.transcript.every(n=>typeof n=="object"&&n!==null&&typeof n.timestamp=="string"&&typeof n.text=="string")}async function EXt(t,e={}){let n=a6(t),{timeoutMs:r=1e4}=e,o=Math.ceil(r/500),i="";try{i=typeof n.getURL=="function"?n.getURL():""}catch{i=""}i||(i=t.view?.url??"");let s=zE(i);if(!s)throw new Error("Not a YouTube video page");let a=`(async () => {
const videoId = ${JSON.stringify(s)};
// =========================================================================
// Step 1: Extract video metadata from JSON-LD (structured data)
// JSON-LD is more reliable than DOM selectors as it's machine-readable
// =========================================================================
let title = '';
let channel = '';
let description = '';
let uploadDate = '';
let duration = '';
let genre = '';
// Helper to extract fields from a VideoObject schema
const extractVideoObject = (data) => {
if (!data || data['@type'] !== 'VideoObject') return;
if (!title && data.name && typeof data.name === 'string') {
title = data.name;
}
if (!description && data.description && typeof data.description === 'string') {
description = data.description;
}
if (!uploadDate && data.uploadDate && typeof data.uploadDate === 'string') {
uploadDate = data.uploadDate;
}
// JSON-LD duration is ISO 8601 format (e.g., "PT12M34S"), convert to readable format
if (!duration && data.duration && typeof data.duration === 'string') {
const match = data.duration.match(/PT(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?/);
if (match) {
const h = match[1] ? match[1] + ':' : '';
const m = match[2] || '0';
const s = match[3] || '0';
duration = h + (h ? m.padStart(2, '0') : m) + ':' + s.padStart(2, '0');
}
}
if (!genre && data.genre) {
genre = Array.isArray(data.genre) ? data.genre.join(', ') : String(data.genre);
}
// author can be string, object {name}, or array [{name}]
if (!channel && data.author) {
const author = data.author;
if (typeof author === 'string') {
channel = author;
} else if (Array.isArray(author) && author[0]?.name) {
channel = String(author[0].name);
} else if (author?.name) {
channel = String(author.name);
}
}
};
// Parse all JSON-LD scripts, handling various formats (@graph, array, single object)
const ldJsonEls = document.querySelectorAll('script[type="application/ld+json"]');
for (const el of ldJsonEls) {
try {
const data = JSON.parse(el.textContent || '');
if (Array.isArray(data)) {
for (const item of data) {
extractVideoObject(item);
}
} else if (data['@graph'] && Array.isArray(data['@graph'])) {
for (const item of data['@graph']) {
extractVideoObject(item);
}
} else {
extractVideoObject(data);
}
// Stop if we have all essential fields
if (title && channel && description) break;
} catch {}
}
// =========================================================================
// Step 2: Fallback to DOM selectors for missing metadata
// =========================================================================
if (!title) {
title = document.querySelector('h1.ytd-watch-metadata yt-formatted-string')?.textContent?.trim()
|| document.querySelector('#title h1')?.textContent?.trim() || '';
}
if (!channel) {
channel = document.querySelector('#owner #channel-name a')?.textContent?.trim()
|| document.querySelector('#channel-name a')?.textContent?.trim()
|| document.querySelector('#channel-name')?.textContent?.trim() || '';
}
if (!duration) {
duration = document.querySelector('#ytd-player .ytp-time-duration')?.textContent?.trim() || '';
}
// =========================================================================
// Step 3: Find or open the transcript panel
// Reason: YouTube has two coexisting transcript panel DOM structures:
// - Classic ("In this video"): ytd-transcript-segment-renderer
// - Modern ("Transcript"): transcript-segment-view-model
// YouTube selects the panel type server-side per video. We must support both.
// All segment queries are scoped to the panel to avoid false matches.
// =========================================================================
// Reason: Find panel by checking for transcript segment elements inside it,
// rather than relying on fragile target-id strings that YouTube changes.
// Prefer visible panels to avoid picking up hidden/stale panels YouTube
// leaves in the DOM during page transitions.
const findTranscriptPanel = () => {
const panels = document.querySelectorAll('ytd-engagement-panel-section-list-renderer');
for (const panel of panels) {
const hasSegments = panel.querySelector('ytd-transcript-segment-renderer')
|| panel.querySelector('transcript-segment-view-model');
if (!hasSegments) continue;
const style = window.getComputedStyle(panel);
if (style.display !== 'none' && style.visibility !== 'hidden') return panel;
}
return null;
};
// Reason: Auto-detect classic vs modern layout and use the correct selectors
// for each. Queries are scoped to the panel to prevent matching unrelated UI.
const extractFromPanel = (panel) => {
const classicSegs = panel.querySelectorAll('ytd-transcript-segment-renderer');
if (classicSegs.length > 0) {
return [...classicSegs].map(seg => ({
timestamp: seg.querySelector('.segment-timestamp')?.textContent?.trim() || '',
text: seg.querySelector('yt-formatted-string.segment-text, .segment-text')?.textContent?.trim() || ''
})).filter(t => t.timestamp && t.text);
}
const modernSegs = panel.querySelectorAll('transcript-segment-view-model');
if (modernSegs.length > 0) {
return [...modernSegs].map(seg => ({
timestamp: seg.querySelector('.ytwTranscriptSegmentViewModelTimestamp')?.textContent?.trim() || '',
text: [...seg.querySelectorAll('span.yt-core-attributed-string')].map(s => s.textContent || '').join('').trim() || ''
})).filter(t => t.timestamp && t.text);
}
return null;
};
let panel = findTranscriptPanel();
let needClose = false;
if (!panel) {
const btn = document.querySelector('ytd-video-description-transcript-section-renderer button')
|| document.querySelector('ytd-video-description-transcript-section-renderer [role="button"]');
if (btn) {
btn.click();
needClose = true;
// Poll for the panel container to appear (not individual segments)
for (let i = 0; i < ${o}; i++) {
await new Promise(r => setTimeout(r, 500));
panel = findTranscriptPanel();
if (panel) break;
}
}
}
// =========================================================================
// Step 4: Extract transcript segments from the panel
// =========================================================================
// Reason: Close via captured panel element rather than hardcoded target-id.
// This is resilient to YouTube changing the target-id string.
const closePanel = () => {
if (!needClose || !panel) return;
const closeBtn = panel.querySelector('#visibility-button button')
|| panel.querySelector('#visibility-button [role="button"]');
if (closeBtn) closeBtn.click();
};
try {
const transcript = panel ? (extractFromPanel(panel) || []) : [];
return { videoId, title, channel, description, uploadDate, duration, genre, transcript };
} finally {
closePanel();
}
})()`,l=await n.executeJavaScript(a);if(!Lxr(l))throw new Error("Invalid transcript data structure");return l}async function MXt(t,e,n={}){let{preferCommand:r=!0,focusLeafBeforeCommand:o=!0}=n;if(r)try{return await e(fbe.SAVE_TO_VAULT,{leaf:t,focusLeaf:o}),j("Saved via webviewer:save-to-vault command"),{method:"command"}}catch(i){W("save-to-vault command failed, falling back:",i)}try{return await Promise.resolve(t.view.saveAsMarkdown()),j("Saved via view.saveAsMarkdown()"),{method:"view.saveAsMarkdown"}}catch(i){throw H("Failed to save Web Viewer page:",i),i}}var IYe=b(()=>{pe();cbe();l6();hbe();cbe()});function Lf(t){if(typeof t!="string")return null;let e=t.trim();return e||null}function f6(t){if(typeof t!="string")return null;let e=t.trim();if(!e)return null;try{let n=new URL(e);n.hash="",(n.protocol==="http:"&&n.port==="80"||n.protocol==="https:"&&n.port==="443")&&(n.port=""),n.pathname!=="/"&&(n.pathname=n.pathname.replace(/\/+$/,""));let r=Array.from(n.searchParams.entries());return r.length>0?(r.sort(([o,i],[s,a])=>o!==s?o.localeCompare(s):i.localeCompare(a)),n.search=`?${new URLSearchParams(r).toString()}`):n.search="",n.toString()}catch{return e}}function NXt(t){return Lf(t)??void 0}function TYe(t){let e=Lf(t.url);if(!e)return null;let n=NXt(t.title),r=NXt(t.faviconUrl);return{url:e,title:n,faviconUrl:r,isLoaded:t.isLoaded,isActive:t.isActive?!0:void 0}}function UI(t){let e=new Map;for(let n of t){let r=TYe(n);if(!r)continue;let o=e.get(r.url);if(!o){e.set(r.url,r);continue}e.set(r.url,{...o,title:r.title??o.title,faviconUrl:r.faviconUrl??o.faviconUrl,isLoaded:r.isLoaded??o.isLoaded,isActive:o.isActive||r.isActive?!0:void 0})}return Array.from(e.values())}function RXt(t){let e=UI(t),n=!1;return e.map(r=>{if(!r.isActive)return r;if(!n)return n=!0,r;let{isActive:o,...i}=r;return i})}var I$=b(()=>{});var $xr,vbe,LXt=b(()=>{pe();hbe();l6();I$();$xr=["did-finish-load","page-favicon-updated","page-title-updated"],vbe=class t{constructor(e){this.lastActiveLeaf=null;this.activeWebTabState={activeWebTabForMentions:null,activeOrLastWebTab:null};this.activeWebTabLeaf=null;this.activeWebTabListeners=new Set;this.activeWebTabTrackingRefs=null;this.activeWebTabTrackingPreserveViewTypes=[];this.webviewLoadListeners=new Map;this.webviewLoadCallbacks=new Set;this.cancelScheduledWebviewLoadNotify=null;this.app=e.app,this.isSupportedPlatform=e.isSupportedPlatform,this.getActiveLeaf=e.getActiveLeaf,this.getLeaves=e.getLeaves,this.getPageInfo=e.getPageInfo}getLastActiveLeaf(){let e=this.lastActiveLeaf;return!e||!HQ(e)?(this.lastActiveLeaf=null,null):kXt(this.app,e)?e:(this.lastActiveLeaf=null,null)}findLeafByUrl(e,n={}){let r=e.trim();if(!r)return null;let o=this.getLeaves();for(let u of o)if(u?.view?.url===r)return u;let i=f6(r);if(!i)return null;let s=[];for(let u of o){let d=u?.view?.url;if(!d)continue;f6(d)===i&&s.push(u)}if(s.length===0)return null;if(s.length===1)return s[0];let a=(n.title??"").trim();if(a){let u=a.toLowerCase(),d=[];for(let f of s)try{let m=(this.getPageInfo(f).title||"").trim();m&&m.toLowerCase()===u&&d.push(f)}catch{}if(d.length===1)return d[0];if(d.length>1){let f=this.getActiveLeaf();if(f&&d.includes(f))return f;let p=this.getLastActiveLeaf();return p&&d.includes(p)?p:(W("[WebViewerStateManager] Multiple leaves matched URL + title; returning first match.",{url:r,title:a,matches:d.length}),d[0])}}let l=this.getActiveLeaf();if(l&&s.includes(l))return l;let c=this.getLastActiveLeaf();return c&&s.includes(c)?c:(W("[WebViewerStateManager] Multiple leaves matched URL; returning first match as fallback.",{url:r,matches:s.length}),s[0])}getActiveWebTabState(){return this.activeWebTabState}subscribeActiveWebTabState(e){return this.activeWebTabListeners.add(e),()=>{this.activeWebTabListeners.delete(e)}}subscribeToWebviewLoad(e){return this.webviewLoadCallbacks.add(e),()=>{this.webviewLoadCallbacks.delete(e)}}startActiveWebTabTracking(e={}){this.activeWebTabTrackingRefs&&this.stopActiveWebTabTracking(),this.activeWebTabTrackingPreserveViewTypes=[...e.preserveOnViewTypes??[]];let n=this.app.workspace.on("active-leaf-change",o=>{try{HQ(o)&&(this.lastActiveLeaf=o)}catch(i){W("WebViewerStateManager failed to track active leaf:",i)}this.recomputeActiveWebTabState({trigger:"active-leaf-change",activeLeaf:o}),this.subscribeToWebviewLoadEvents()}),r=this.app.workspace.on("layout-change",()=>{this.recomputeActiveWebTabState({trigger:"layout-change"}),this.subscribeToWebviewLoadEvents()});return this.activeWebTabTrackingRefs={activeLeafRef:n,layoutRef:r},this.recomputeActiveWebTabState({trigger:"active-leaf-change",activeLeaf:this.app.workspace.getMostRecentLeaf()}),this.subscribeToWebviewLoadEvents(),this.activeWebTabTrackingRefs}subscribeToWebviewLoadEvents(){if(!this.isSupportedPlatform()){this.cleanupWebviewLoadListeners();return}try{let e=this.getLeaves(),n=new Set;for(let o of e){let i=o.view?.webview;if(i&&typeof i.addEventListener=="function"&&typeof i.removeEventListener=="function"){n.add(i);let s=this.webviewLoadListeners.get(i);if(s&&s.leaf===o)continue;if(s){for(let c of s.events)i.removeEventListener(c,s.handler);this.webviewLoadListeners.delete(i)}let a=()=>{this.recomputeActiveWebTabState({trigger:"webview-metadata",loadedLeaf:o}),this.scheduleWebviewLoadCallbackNotification()},l={leaf:o,handler:a,events:$xr};for(let c of l.events)i.addEventListener(c,a);this.webviewLoadListeners.set(i,l)}}let r=[];for(let o of this.webviewLoadListeners.keys())n.has(o)||r.push(o);for(let o of r){let i=this.webviewLoadListeners.get(o);if(i){try{for(let s of i.events)o.removeEventListener(s,i.handler)}catch{}this.webviewLoadListeners.delete(o)}}}catch{}}cleanupWebviewLoadListeners(){for(let[e,{handler:n,events:r}]of this.webviewLoadListeners)try{if(typeof e.removeEventListener=="function")for(let o of r)e.removeEventListener(o,n)}catch{}this.webviewLoadListeners.clear()}scheduleWebviewLoadCallbackNotification(){if(this.cancelScheduledWebviewLoadNotify)return;let e=n=>{if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){let o=window.requestAnimationFrame(()=>n());return()=>window.cancelAnimationFrame(o)}let r=window.setTimeout(n,0);return()=>window.clearTimeout(r)};this.cancelScheduledWebviewLoadNotify=e(()=>{this.cancelScheduledWebviewLoadNotify=null,this.notifyWebviewLoadCallbacks()})}notifyWebviewLoadCallbacks(){for(let e of this.webviewLoadCallbacks)try{e()}catch{}}stopActiveWebTabTracking(){this.activeWebTabTrackingRefs=null,this.cleanupWebviewLoadListeners(),this.cancelScheduledWebviewLoadNotify?.(),this.cancelScheduledWebviewLoadNotify=null,this.activeWebTabState={activeWebTabForMentions:null,activeOrLastWebTab:null},this.activeWebTabLeaf=null,this.lastActiveLeaf=null,this.activeWebTabTrackingPreserveViewTypes=[]}recomputeActiveWebTabState(e){if(!this.isSupportedPlatform()){this.setActiveWebTabState({activeWebTabForMentions:null,activeOrLastWebTab:null}),this.activeWebTabLeaf=null;return}let n=this.getActiveLeaf();if(e.trigger==="webview-metadata"){let s=e.loadedLeaf;if(!(s===this.activeWebTabLeaf||s===n))return}let r=this.activeWebTabLeaf,o=this.activeWebTabState.activeWebTabForMentions;if(n)r=n,o=this.toWebTabContext(n);else if(e.trigger==="active-leaf-change"){let s=e.activeLeaf?.view?.getViewType();!!(s&&this.activeWebTabTrackingPreserveViewTypes.includes(s))||(r=null,o=null)}if(e.trigger!=="webview-metadata"&&r&&(this.getLeaves().includes(r)||(r=null,o=null)),e.trigger==="layout-change")r&&(o=this.toWebTabContext(r));else if(e.trigger==="webview-metadata"){let s=e.loadedLeaf;r=s,o=this.toWebTabContext(s)}this.activeWebTabLeaf=r;let i=this.computeActiveOrLastWebTabContext();this.setActiveWebTabState({activeWebTabForMentions:o,activeOrLastWebTab:i})}computeActiveOrLastWebTabContext(){try{let e=this.getActiveLeaf()??this.getLastActiveLeaf();return e?this.toWebTabContext(e):null}catch{return null}}toWebTabContext(e){try{let n=this.getPageInfo(e),r=(n.url||"").trim();if(!r)return null;let o=(n.title||"").trim(),i=(n.faviconUrl||"").trim();return{url:r,title:o||void 0,faviconUrl:i||void 0}}catch{return null}}setActiveWebTabState(e){let n=this.activeWebTabState;t.areWebTabContextsEqual(n.activeWebTabForMentions,e.activeWebTabForMentions)&&t.areWebTabContextsEqual(n.activeOrLastWebTab,e.activeOrLastWebTab)||(this.activeWebTabState=e,this.notifyActiveWebTabListeners())}notifyActiveWebTabListeners(){for(let e of this.activeWebTabListeners)try{e(this.activeWebTabState)}catch(n){W("[WebViewerStateManager] Error in Active Web Tab listener:",n)}}static areWebTabContextsEqual(e,n){return e===n?!0:!e||!n?!1:e.url===n.url&&e.title===n.title&&e.faviconUrl===n.faviconUrl}}});var wbe,$Xt=b(()=>{pe();$n();IYe();hbe();LXt();l6();wbe=class{constructor(e){this.internalPluginApi=null;this.internalApiWarned=!1;this.app=e,this.stateManager=new vbe({app:e,isSupportedPlatform:()=>this.isSupportedPlatform(),getActiveLeaf:()=>this.getActiveLeaf(),getLeaves:()=>this.getLeaves(),getPageInfo:n=>d6(n)})}isSupportedPlatform(){return Ln()}getAvailability(){let e=this.isSupportedPlatform()?"desktop":"mobile";return this.isSupportedPlatform()?this.getLeaves().length>0?{supported:!0,available:!0,platform:e}:this.getInternalPluginApi()?{supported:!0,available:!0,platform:e}:CXt(this.app,fbe.OPEN)?{supported:!0,available:!0,platform:e,reason:"No Web Viewer leaves open, but Web Viewer commands are registered."}:{supported:!0,available:!1,platform:e,reason:"Web Viewer does not appear available."}:{supported:!1,available:!1,platform:e,reason:"Web Viewer is not supported on mobile platforms."}}assertAvailable(){let e=this.getAvailability();if(!e.supported)throw new ube(e.reason??"Web Viewer unsupported.");if(!e.available)throw new kg(e.reason??"Web Viewer is not available.")}getLeaves(){return this.isSupportedPlatform()?this.app.workspace.getLeavesOfType(k$):[]}getActiveLeaf(){let e=this.app.workspace.getMostRecentLeaf();return HQ(e)?e:null}getLastActiveLeaf(){return this.stateManager.getLastActiveLeaf()}async resolveLeaf(e={}){this.assertAvailable();let{strategy:n="active-or-last",focus:r=!1,requireWebviewReady:o=!1,timeoutMs:i=15e3}=e,s=this.getActiveLeaf();if(s)return r&&this.app.workspace.setActiveLeaf(s,{focus:!0}),o&&await this.waitForWebviewReady(s,i),s;if(n==="active-or-last"||n==="active-or-last-or-any"){let a=this.getLastActiveLeaf();if(a)return r&&this.app.workspace.setActiveLeaf(a,{focus:!0}),o&&await this.waitForWebviewReady(a,i),a}if(n==="active-or-last-or-any"){let a=this.getLeaves()[0];if(a)return r&&this.app.workspace.setActiveLeaf(a,{focus:!0}),o&&await this.waitForWebviewReady(a,i),a}throw new dbe("No Web Viewer leaf found.")}async waitForWebviewReady(e,n){let r=e.view;r.webviewMounted===void 0||r.webviewFirstLoadFinished===void 0||r.webviewMounted&&r.webviewFirstLoadFinished||await SXt(()=>!!(r.webviewMounted&&r.webviewFirstLoadFinished),n,100,"Waiting for Web Viewer webview ready")}findLeafByUrl(e,n={}){return this.stateManager.findLeafByUrl(e,n)}getActiveWebTabState(){return this.stateManager.getActiveWebTabState()}subscribeActiveWebTabState(e){return this.stateManager.subscribeActiveWebTabState(e)}subscribeToWebviewLoad(e){return this.stateManager.subscribeToWebviewLoad(e)}startActiveWebTabTracking(e={}){return this.stateManager.startActiveWebTabTracking(e)}stopActiveWebTabTracking(){this.stateManager.stopActiveWebTabTracking()}async executeCommand(e,n={}){let r=kYe(this.app);if(!r)throw new kg("Command manager unavailable.");let{leaf:o,focusLeaf:i=!1}=n;o&&i&&this.app.workspace.setActiveLeaf(o,{focus:!0});try{if(r.executeCommandById(e)===!1)throw new kg(`Command returned false: ${e}`)}catch(s){throw H(`Failed to execute command ${e}:`,s),new kg(`Failed to execute command ${e}: ${xXt(s)}`)}}getInternalPluginApi(){if(this.internalPluginApi)return this.internalPluginApi;let e=IXt(this.app,()=>{this.internalApiWarned||(this.internalApiWarned=!0,W("[WebViewerService] internalPlugins.plugins has unexpected structure. Web Viewer integration may not work correctly."))});return e&&(this.internalPluginApi=e),e}getPageInfo(e){return d6(e)}async getReaderModeMarkdown(e,n){return TXt(e,n)}async getSelectedText(e,n=!0){return gbe(e,n)}async getSelectedMarkdown(e){return ybe(e)}async getPageMarkdown(e){return PXt(e)}async getHtml(e,n=!0){return AXt(e,n)}getYouTubeVideoId(e){return zE(e)}isYouTubeVideoUrl(e){return hYe(e)}async getYouTubeTranscript(e,n){return EXt(e,n)}async saveToVault(e,n={}){return MXt(e,(r,o)=>this.executeCommand(r,o),n)}}});var FXt={};sr(FXt,{getWebViewerMarkdown:()=>Dxr,getWebViewerPageInfo:()=>jxr,getWebViewerSelectedMarkdown:()=>Uxr,getWebViewerSelectedText:()=>Fxr,getWebViewerService:()=>Sl,resolveWebViewerLeaf:()=>p6,saveWebViewerToVault:()=>Bxr,startActiveWebTabTracking:()=>PYe});function Sl(t){let e=DXt.get(t);if(e)return e;let n=new wbe(t);return DXt.set(t,n),n}function PYe(t,e){return Sl(t).startActiveWebTabTracking(e)}async function p6(t,e){return Sl(t).resolveLeaf(e)}async function Dxr(t,e){let n=await p6(t,e);return Sl(t).getReaderModeMarkdown(n)}async function Fxr(t,e=!0,n){let r=await p6(t,n);return Sl(t).getSelectedText(r,e)}async function Uxr(t,e){let n=await p6(t,e);return Sl(t).getSelectedMarkdown(n)}async function jxr(t,e){let n=await p6(t,e);return Sl(t).getPageInfo(n)}async function Bxr(t,e,n){let r=await p6(t,{...n,focus:!0});return Sl(t).saveToVault(r,e)}var DXt,T$=b(()=>{$Xt();DXt=new WeakMap});var WQ,WE,bbe=b(()=>{es();gt();pe();nY();T$();l6();ut();I$();WQ=require("obsidian");gt();WE=class t{constructor(e){this.app=e}static getInstance(e){if(!t.instance){if(!e)throw new Error("ContextProcessor.getInstance() requires `app` on first call (seed it at plugin load).");t.instance=new t(e)}return t.instance}async processEmbeddedPDFs(e,n,r){let o=/!\[\[(.*?\.pdf)\]\]/g,i=[...e.matchAll(o)];for(let s of i){let a=s[1],l=n.getAbstractFileByPath(a);if(l instanceof WQ.TFile)try{let c=await r.parseFile(l,n);e=e.replace(s[0],`
<${Y5}>
<name>${a}</name>
<content>
${c}
</content>
</${Y5}>
`)}catch(c){H(`Error processing embedded PDF ${a}:`,c),e=e.replace(s[0],`
<${Y5}>
<name>${a}</name>
<error>Could not process PDF</error>
</${Y5}>
`)}}return e}async processDataviewBlocks(e,n){let r=this.app.plugins?.plugins?.dataview;if(!r)return e;let o=r.api;if(!o)return e;let i=/```(dataview|dataviewjs)\s*\n([\s\S]*?)```/g,s=[...e.matchAll(i)];for(let a=s.length-1;a>=0;a--){let l=s[a],c=l[1],u=l[2].trim(),d=l.index,f=d+l[0].length;try{let p=await Promise.race([this.executeDataviewQuery(o,u,c,n),new Promise((g,v)=>window.setTimeout(()=>v(new Error("Query timeout")),5e3))]),m=typeof p=="string"?p:JSON.stringify(p),h=`
<${J5}>
<query_type>${c}</query_type>
<original_query>
${u}
</original_query>
<executed_result>
${m}
</executed_result>
</${J5}>
`;e=e.slice(0,d)+h+e.slice(f)}catch(p){H("Error executing Dataview query:",p);let m=`
<${J5}>
<query_type>${c}</query_type>
<original_query>
${u}
</original_query>
<error>${p instanceof Error?p.message:"Query execution failed"}</error>
</${J5}>
`;e=e.slice(0,d)+m+e.slice(f)}}return e}async executeDataviewQuery(e,n,r,o){if(r==="dataviewjs")return"[DataviewJS execution not yet supported - showing original query]";let i=await e.query(n,o);if(!i.successful)throw new Error(i.error??"Query failed");return this.formatDataviewResult(i.value)}formatDataviewResult(e){return e?e.type==="list"?this.formatDataviewList(e.values):e.type==="table"?this.formatDataviewTable(e.headers??[],e.values):e.type==="task"?this.formatDataviewTasks(e.values):Array.isArray(e)?e.map(n=>this.formatDataviewValue(n)).join(`
`):JSON.stringify(e):"No results"}formatDataviewList(e){return!e||e.length===0?"No results":e.map(n=>`- ${this.formatDataviewValue(n)}`).join(`
`)}formatDataviewTable(e,n){if(!n||n.length===0)return"No results";let r=`| ${e.join(" | ")} |
`;r+=`| ${e.map(()=>"---").join(" | ")} |
`;for(let o of n)r+=`| ${o.map(i=>this.formatDataviewValue(i)).join(" | ")} |
`;return r}formatDataviewTasks(e){return!e||e.length===0?"No results":e.map(n=>`- ${n.completed?"[x]":"[ ]"} ${this.formatDataviewValue(n.text??n)}`).join(`
`)}formatDataviewValue(e){return e==null?"":e&&typeof e=="object"&&"path"in e?`[[${e.path}]]`:Array.isArray(e)?e.map(n=>this.formatDataviewValue(n)).join(", "):typeof e=="object"?JSON.stringify(e):`${e}`}async buildMarkdownContextContent(e,n,r,o){let i=await r.parseFile(e,n);return i=await this.processEmbeddedNotes(i,e,n,r,o),sd(o)&&(i=await this.processEmbeddedPDFs(i,n,r)),await this.processDataviewBlocks(i,e.path)}async processEmbeddedNotes(e,n,r,o,i){let s=/!\[\[([^\]]+)\]\]/g,a,l=0,c="";for(;(a=s.exec(e))!==null;){c+=e.slice(l,a.index);let u=a[1].trim(),d=await this.buildEmbeddedNoteBlock(u,a[0],n,r,o,i);c+=d,l=a.index+a[0].length}return c+=e.slice(l),c}async buildEmbeddedNoteBlock(e,n,r,o,i,s){let a=this.parseEmbeddedLinkTarget(e);if(!a)return n;let l=a.path===null?r:this.app.metadataCache.getFirstLinkpathDest(a.path,r.path);if(!(l instanceof WQ.TFile))return this.formatEmbeddedNoteBlock({title:a.path??r.basename,path:a.path??r.path,heading:a.heading,blockId:a.blockId,error:"Embedded note not found"});if(l.extension!=="md")return n;try{let c=await i.parseFile(l,o);if(a.heading||a.blockId){let u=this.extractMarkdownSegment(l,c,a);if(!u.found){let d=a.blockId?`block reference "${a.blockId}"`:`heading "${a.heading??""}"`;throw new Error(`Embedded note ${d} not found in ${l.path}`)}c=u.content}return sd(s)&&(c=await this.processEmbeddedPDFs(c,o,i)),c=await this.processDataviewBlocks(c,l.path),this.formatEmbeddedNoteBlock({title:l.basename,path:l.path,heading:a.heading,blockId:a.blockId,content:c})}catch(c){W("Failed to process embedded note",c);let u=c instanceof Error?c.message:"Could not process embedded note";return this.formatEmbeddedNoteBlock({title:l.basename,path:l.path,heading:a.heading,blockId:a.blockId,error:u})}}parseEmbeddedLinkTarget(e){if(!e)return null;let n=e.indexOf("|"),o=(n>=0?e.slice(0,n):e).trim();if(!o)return{path:null};let i,s,a=o.indexOf("#^");a!==-1&&(i=o.slice(a+2).trim(),o=o.slice(0,a));let l=o.indexOf("#");return l!==-1&&(s=o.slice(l+1).trim(),o=o.slice(0,l)),{path:o.length>0?o:null,heading:s&&s.length>0?s:void 0,blockId:i&&i.length>0?i:void 0}}extractMarkdownSegment(e,n,r){let o=this.app.metadataCache.getFileCache(e);if(r.blockId){let i=o?.blocks?.[r.blockId],s=i?.position?.start?.offset,a=i?.position?.end?.offset;return s===void 0||a===void 0?{content:"",found:!1}:{content:n.slice(s,a),found:!0}}if(r.heading){let i=o?.headings??[],s=this.normalizeHeadingForMatch(r.heading),a=i.findIndex(d=>this.normalizeHeadingForMatch(d.heading)===s);if(a===-1)return{content:"",found:!1};let l=i[a],c=l.position?.start?.offset??0,u=n.length;for(let d=a+1;d<i.length;d++)if(i[d].level<=l.level){u=i[d].position?.start?.offset??u;break}return{content:n.slice(c,u),found:!0}}return{content:n,found:!0}}normalizeHeadingForMatch(e){return e.trim().toLowerCase().replace(/\s+/g," ")}formatEmbeddedNoteBlock(e){let{title:n,path:r,heading:o,blockId:i,content:s,error:a}=e,l=`
<${JPe}>
<title>${n}</title>
<path>${r}</path>`;return o&&(l+=`
<heading>${o}</heading>`),i&&(l+=`
<block_id>${i}</block_id>`),a?l+=`
<error>${a}</error>`:l+=`
<content>
${s??""}
</content>`,l+=`
</${JPe}>
`,l}async processContextNotes(e,n,r,o,i,s,a){let l="",c=async(d,f=G5)=>{try{if(e.has(d.path)){j(`Skipping note ${d.path} as it was included via custom prompt.`);return}if(!n.supportsExtension(d.extension)){W(`Unsupported file type: ${d.extension}`);return}if(!sd(a)&&!Rie(d)){W(`File type ${d.extension} requires Copilot Plus mode for context processing.`),new WQ.Notice(Zoe.NON_MARKDOWN_FILES_RESTRICTED);return}let p=d.extension==="md"?await this.buildMarkdownContextContent(d,r,n,a):await n.parseFile(d,r),m=await r.adapter.stat(d.path),h=m?new Date(m.ctime).toISOString():"Unknown",g=m?new Date(m.mtime).toISOString():"Unknown";l+=`
<${f}>
<title>${Si(d.basename)}</title>
<path>${d.path}</path>
<ctime>${h}</ctime>
<mtime>${g}</mtime>
<content>
${p}
</content>
</${f}>`}catch(p){H(`Error processing file ${d.path}:`,p),l+=`
<${f}_error>
<title>${Si(d.basename)}</title>
<path>${d.path}</path>
<error>[Error: Could not process file]</error>
</${f}_error>`}},u=new Set;i&&s&&(await c(s,"active_note"),u.add(s.path));for(let d of o)u.has(d.path)||(await c(d),u.add(d.path));return l}async hasEmbeddedPDFs(e){return/!\[\[(.*?\.pdf)\]\]/g.test(e)}async addNoteToContext(e,n,r,o,i,s){if(r.some(c=>c.path===e.path))return;let a=await n.read(e),l=await this.hasEmbeddedPDFs(a);o&&e.path===o.path&&s(!0),i(c=>[...c,Object.assign(e,{wasAddedViaReference:!0,hasEmbeddedPDFs:l})])}processSelectedTextContexts(){let e=hy();if(!e||e.length===0)return"";let n="";for(let r of e)r.sourceType==="web"?n+=`
<${qF}>
<title>${Si(r.title)}</title>
<url>${Si(r.url)}</url>
<content>
${Si(r.content)}
</content>
</${qF}>`:n+=`
<${Xp}>
<title>${Si(r.noteTitle)}</title>
<path>${Si(r.notePath)}</path>
<start_line>${r.startLine.toString()}</start_line>
<end_line>${r.endLine.toString()}</end_line>
<content>
${r.content}
</content>
</${Xp}>`;return n}async processContextWebTabs(e){if(!e||e.length===0)return"";let n=2500,r=8e3,o=15e3,i=2,s=(y,w)=>{let _=[`
<${y}>`,`
<title>${Si(w.title)}</title>`,`
<url>${Si(w.url)}</url>`];return w.mode&&_.push(`
<mode>${Si(w.mode)}</mode>`),w.error?_.push(`
<error>${Si(w.error)}</error>`):w.content!==void 0&&_.push(`
<content>
${Si(w.content)}
</content>`),_.push(`
</${y}>`),_.join("")},a=y=>{let w=[`
<${eAe}>`,`
<title>${Si(y.title)}</title>`,`
<url>${Si(y.url)}</url>`,`
<video_id>${Si(y.videoId)}</video_id>`];y.isActive&&w.push(`
<is_active>true</is_active>`),y.channel&&w.push(`
<channel>${Si(y.channel)}</channel>`),y.uploadDate&&w.push(`
<upload_date>${Si(y.uploadDate)}</upload_date>`),y.duration&&w.push(`
<duration>${Si(y.duration)}</duration>`),y.genre&&w.push(`
<genre>${Si(y.genre)}</genre>`),y.description&&w.push(`
<description>${Si(y.description)}</description>`),y.error&&w.push(`
<error>${Si(y.error)}</error>`);let _=y.transcript||"No transcript available for this video";return w.push(`
<content>
${Si(_)}
</content>`),w.push(`
</${eAe}>`),w.join("")},l=null,c=[],u=new Set,d=new Set,f=Sl(this.app),p=y=>{let w=f.getYouTubeVideoId(y);return w?d.has(w)?!0:(d.add(w),!1):u.has(y)?!0:(u.add(y),!1)};for(let y of e){let w=Lf(y.url);w&&y.isActive&&!l&&(l={...y,url:w},p(w))}for(let y of e){let w=Lf(y.url);!w||p(w)||c.push({...y,url:w})}if(!l&&c.length===0)return"";let m=f.getAvailability();if(!m.supported||!m.available){let y=m.reason??(m.supported?"Web Viewer is not available.":"Web Viewer is not supported on this platform."),w=[];l&&w.push(s(Voe,{title:l.title||"Unknown",url:l.url,error:y}));for(let _ of c)w.push(s(QPe,{title:_.title||"Unknown",url:_.url,error:y}));return w.join("")}let h=async(y,w)=>{try{let _=y.url,S=f.getYouTubeVideoId(_);if(S)return await g(y,S,w===Voe);let I=f.findLeafByUrl(_,{title:y.title});if(!I)return s(w,{title:y.title||"Unknown",url:_,error:"Web tab not found or closed"});let C=f.getPageInfo(I),k=I.view;if(!(k.webviewMounted===void 0||k.webviewFirstLoadFinished===void 0?!0:!!(k.webviewMounted&&k.webviewFirstLoadFinished)))try{await f.waitForWebviewReady(I,n),C=f.getPageInfo(I)}catch(O){return W(`Web tab content not loaded yet for ${_}:`,O),s(w,{title:C.title||y.title||"Untitled",url:C.url||_,mode:C.mode,error:"Web tab content not loaded yet"})}let P=new AbortController,E=window.setTimeout(()=>{P.abort()},r);try{let O=await f.getReaderModeMarkdown(I,{signal:P.signal});return C=f.getPageInfo(I),s(w,{title:C.title||y.title||"Untitled",url:C.url||_,mode:C.mode,content:O})}finally{window.clearTimeout(E)}}catch(_){return H(`Error processing web tab ${y.url}:`,_),s(w,{title:y.title||"Unknown",url:y.url,error:_ instanceof HE?"Web tab content extraction timed out":"Could not process web tab"})}},g=async(y,w,_)=>{try{let S=null,I=y.url;for(let E of f.getLeaves()){let O=f.getPageInfo(E).url;if(f.getYouTubeVideoId(O)===w){S=E,I=O;break}}if(!S)return a({title:y.title||"YouTube Video",url:y.url,videoId:w,isActive:_,error:"Web tab not found or closed"});let C=S.view;if(!(C.webviewMounted===void 0||C.webviewFirstLoadFinished===void 0?!0:!!(C.webviewMounted&&C.webviewFirstLoadFinished)))try{await f.waitForWebviewReady(S,n)}catch(E){return W(`YouTube tab content not loaded yet for ${I}:`,E),a({title:y.title||"YouTube Video",url:I,videoId:w,isActive:_,error:"Web tab content not loaded yet"})}let T=await f.getYouTubeTranscript(S,{timeoutMs:o}),P=T.transcript.length>0?T.transcript.map(E=>`${E.timestamp}: ${E.text}`).join(`
`):void 0;return a({title:T.title||y.title||"YouTube Video",url:I,videoId:T.videoId,channel:T.channel,description:T.description,uploadDate:T.uploadDate,duration:T.duration,genre:T.genre,transcript:P,isActive:_})}catch(S){return W(`YouTube transcript extraction failed for ${y.url}:`,S),a({title:y.title||"YouTube Video",url:y.url,videoId:w,isActive:_,error:S instanceof Error?S.message:"Failed to extract video info"})}},v=[];if(l){let y=await h(l,Voe);v.push(y)}for(let y=0;y<c.length;y+=i){let w=c.slice(y,y+i),_=await Promise.all(w.map(S=>h(S,QPe)));v.push(..._)}return v.join("")}}});function AYe(t){let{mentionedAgentIds:e,installedAgentIds:n}=t,r=[],o=new Set;for(let i of e)o.has(i)||n.has(i)&&(o.add(i),r.push(i));return r.length>0?r:UXt}function VQ(t,e){return!(t.length===0||t.length===1&&t[0]===e)}var UXt,EYe=b(()=>{UXt=Object.freeze([])});function BXt(t,e){return!t||!t.model||!e||!t.model.availableModels.find(r=>r.baseModelId===e.baseModelId)||t.model.current.baseModelId===e.baseModelId?t:{...t,model:{...t.model,current:{...t.model.current,baseModelId:e.baseModelId}}}}function Kxr(t,e){return`${t} finished the turn without returning any assistant text or tool activity (stop reason: ${e}). Try again, or switch models if this repeats.`}function Gxr(t){let e=kt(t),n=Zxr(t);return!n||e.includes(n)?e:`${e}
${n}`}function Zxr(t){let e=qQ(t,new Set);if(!e)return null;let n=typeof e.type=="string"?e.type:"ProviderError",r=typeof e.message=="string"?e.message:null;return r?`${n}: ${r}`:n}function qQ(t,e){if(t===null||typeof t!="object"||e.has(t))return null;e.add(t);let n=t,r=n.error;if(r&&typeof r=="object"){let i=r;if(typeof i.message=="string"||typeof i.type=="string")return{type:i.type,message:i.message}}if(typeof n.message=="string"){let i=Yxr(n.message);if(i){let s=qQ(i,e);if(s)return s}}if(n.data){let i=qQ(n.data,e);if(i)return i}if(Array.isArray(n.errors))for(let i of n.errors){let s=qQ(i,e);if(s)return s}let o=n.cause;return o?qQ(o,e):null}function Yxr(t){let e=t.trim();if(!e.startsWith("{"))return null;try{let n=JSON.parse(e);return n&&typeof n=="object"?n:null}catch{return null}}function Jxr(t,e){let n=(e??[]).filter(o=>o.type==="image");if(n.length===0)return;let r=[];t.trim()&&r.push({type:"text",text:t});for(let o of n)r.push({type:"image_url",image_url:{url:`data:${o.mimeType};base64,${o.data}`}});return r}function zXt(t,e,n,r,o,i,s){let a=[o?.trim()||null,s?.trim()||null,i?.trim()||null,tSr(e),eSr(e),r?.trim()||null].filter(d=>!!d),l=a.length>0?a.join(`
`):null,c=l?`${l}
<user-message>
${t}
</user-message>`:t,u=n??[];return u.length===0?[{type:"text",text:c}]:[{type:"text",text:c},...u]}function Xxr(t){let e=t.findIndex(o=>o.type==="text");if(e===-1)return[{type:"text",text:V4e},...t];let n=t[e],r=t.slice();return r[e]={type:"text",text:`${V4e}
${n.text}`},r}async function Qxr(t){let e=t?.webTabs;return!e||e.length===0?"":(await WE.getInstance().processContextWebTabs(e)).trim()}function eSr(t){let e=(t?.selectedTextContexts??[]).filter(oz);return e.length===0?null:e.map(n=>[`<${qF}>`,`<title>${Si(n.title)}</title>`,`<url>${Si(n.url)}</url>`,`<content>
${Si(n.content)}
</content>`,`</${qF}>`].join(`
`)).join(`
`)}function tSr(t){if(!t)return null;let e=(t.notes??[]).map(o=>o.path).filter(Boolean),n=(t.selectedTextContexts??[]).filter(iz);if(e.length===0&&n.length===0)return null;let r=["<copilot-context>","The user attached the following vault items. The vault is your current working directory; use the Read tool to inspect them when relevant."];if(e.length>0){r.push("","Notes:");for(let o of e)r.push(`- ${o}`)}if(n.length>0){r.push("","Selected excerpts (already inlined; no need to re-read):");for(let o of n){r.push(`- ${o.notePath} (lines ${o.startLine}-${o.endLine}):`);for(let i of o.content.split(`
`))r.push(` ${i}`)}}return r.push("</copilot-context>"),r.join(`
`)}function nSr(t){return t.type==="text"?t.text:""}function HXt(t){return{kind:"tool_call",id:t.toolCallId,title:t.title,toolKind:t.kind,status:t.status??"pending",input:t.rawInput,output:qXt(t.content),locations:t.locations?.map(e=>({path:e.path,line:e.line??void 0})),vendorToolName:t.vendorToolName,mcpServer:t.mcpServer,parentToolCallId:t.parentToolCallId,progress:t.progress}}function OYe(t){let e=t.rawInput,n=e?.plan;if(typeof n!="string"||!t.isPlanProposal&&t.kind!=="switch_mode")return null;let r=typeof e?.planFilePath=="string"?e.planFilePath:void 0;return{plan:n,planFilePath:r}}function rSr(t){for(let e of t.split(`
`)){let n=e.trim();if(n)return n.replace(/^#+\s*/,"").slice(0,80)}return"Plan proposal"}function oSr(t,e){let n=t&&t.kind==="tool_call"?t:{kind:"tool_call",id:e.toolCallId,title:e.title??"Tool call",status:"pending"};return n.kind!=="tool_call"?n:{...n,title:e.title??n.title,toolKind:e.kind??n.toolKind,status:e.status??n.status,input:e.rawInput!==void 0?e.rawInput:n.input,output:e.content!==void 0&&e.content!==null?qXt(e.content):n.output,locations:e.locations!==void 0&&e.locations!==null?e.locations.map(r=>({path:r.path,line:r.line??void 0})):n.locations,vendorToolName:e.vendorToolName??n.vendorToolName,mcpServer:e.mcpServer??n.mcpServer,parentToolCallId:e.parentToolCallId??n.parentToolCallId,progress:e.progress===void 0?n.progress:{...n.progress,...e.progress}}}function qXt(t){if(!t)return;let e=[];for(let n of t)n.type==="content"&&n.content.type==="text"?e.push(iSr(n.content.text)):n.type==="diff"&&e.push({type:"diff",path:n.path,oldText:n.oldText??null,newText:n.newText});return e.length>0?e:void 0}function iSr(t){if(t.length<=MYe)return{type:"text",text:t};let e=t.length-MYe;return{type:"text",text:t.slice(0,MYe)+`
[Display trimmed: ${e.toLocaleString()} more characters. The agent received the full output.]`}}function WXt(t,e){for(let n of e){let r=t.options.find(o=>o.kind===n);if(r)return{outcome:{outcome:"selected",optionId:r.optionId}}}return{outcome:{outcome:"cancelled"}}}function sSr(t){return{kind:"plan",entries:t.entries.map(e=>({content:e.content,priority:e.priority,status:e.status}))}}var NYe,MYe,zxr,Hxr,Wxr,Vxr,jXt,qxr,VXt,KQ,KXt=b(()=>{gt();pe();rXt();_S();rz();rY();ut();vc();ok();mYe();bbe();nY();EYe();tA();Gf();NYe="New session",MYe=256e3,zxr=1e3,Hxr=[],Wxr=[],Vxr=Object.freeze({}),jXt=Object.freeze([]),qxr=Object.freeze([]);VXt=new Set(["idle","error","awaiting_permission"]),KQ=class t{constructor(e){this.store=new abe;this.backendSessionId=null;this.projectContextBlock=null;this.firstPromptSent=!1;this.cachedStatus="starting";this.startupFailed=!1;this.startupSettled=!1;this.lastTurnError=!1;this.lastMentionedAgents=jXt;this.pendingFanoutContext=[];this.placeholderId=null;this.currentTurnHadRoutedToolActivity=!1;this.currentMessageIds=new Set;this.settledStream=null;this.cancelledPromptDrain=null;this.cancelledTurnActivity=0;this.cancelledMessageIds=new Set;this.abortController=null;this.listeners=new Set;this.unregisterSessionHandler=null;this.currentState=null;this.label=null;this.labelSource=null;this.disposed=!1;this.pendingPlanResolvers=new Map;this.pendingToolResolvers=new Map;this.pendingQuestionResolvers=new Map;this.currentPlan=null;this.currentTodoList=null;this.currentTodoListSignature=null;this.currentUsage=null;this.currentPlanUsage=null;this.planSeq=0;this.decidedPlanToolCallIds=new Set;this.needsAttention=!1;this.notifyScheduled=!1;this.notifyHandle=null;if(this.backend=e.backend,this.internalId=e.internalId,this.chatInputId=e.chatInputId??Co(),this.backendId=e.backendId,this.projectId=e.projectId??tr,this.cwd=e.cwd??null,this.getDescriptor=e.getDescriptor??null,this.runFanoutTurn=e.runFanoutTurn??null,this.getDisplayName=e.getDisplayName??null,this.getApp=e.getApp??null,this.getProjectContextUpdatesFn=e.getProjectContextUpdates??null,this.markProjectContextUpdatesDeliveredFn=e.markProjectContextUpdatesDelivered??null,this.contextReady="contextReady"in e?e.contextReady??null:null,"backendSessionId"in e){this.backendSessionId=e.backendSessionId;let n=e.initialState??null;this.currentState=BXt(n,e.defaultModelSelection),this.unregisterSessionHandler=this.backend.registerSessionHandler(e.backendSessionId,r=>this.handleSessionEvent(r)),e.defaultModelSelection&&n?this.ready=this.confirmSeededSelection(e.defaultModelSelection,n).finally(()=>{this.startupSettled=!0,this.recomputeStatusIfChanged()}):(this.startupSettled=!0,this.ready=Promise.resolve()),this.cachedStatus=this.getStatus()}else this.currentState=null,this.ready=this.initialize(e)}static start(e){return new t(e)}getBackendSessionId(){return this.backendSessionId}async initialize(e){let{backend:n,cwd:r,defaultModelSelection:o}=e;try{let i=this.contextReady?await this.contextReady:null,s=i?.additionalDirectories??qxr;if(this.projectContextBlock=i?.projectContextBlock??null,this.disposed)return;let a=await n.newSession({cwd:r,projectId:this.projectId,additionalDirectories:s});if(this.disposed)return;let l=a.state.model?`model=${a.state.model.current.baseModelId} (available: ${a.state.model.availableModels.map(c=>c.baseModelId).join(", ")})`:"agent did not report model state";if(j(`[AgentMode] session ${a.sessionId} ${l}`),this.backendSessionId=a.sessionId,this.currentState=BXt(a.state,o),this.unregisterSessionHandler=this.backend.registerSessionHandler(a.sessionId,c=>this.handleSessionEvent(c)),this.disposed){this.unregisterSessionHandler(),this.unregisterSessionHandler=null;return}this.recomputeStatusIfChanged(),this.notifyModelChanged(),o&&await this.confirmSeededSelection(o,a.state),this.startupSettled=!0,this.recomputeStatusIfChanged()}catch(i){if(this.disposed)return;throw W(`[AgentMode] session/new failed for ${this.internalId}`,i),this.startupFailed=!0,this.recomputeStatusIfChanged(),i instanceof Error?i:new Error(kt(i))}}getState(){return this.currentState}async setModel(e){if(this.getStatus()==="closed")throw new Error("Session is closed");if(!this.backendSessionId)throw new Error("Session is still starting");let n=await this.backend.setSessionModel({sessionId:this.backendSessionId,modelId:e});this.dropUsageWindowOnModelChange(n),this.currentState=n,this.notifyModelChanged()}async applyModelWireId(e){let n=this.currentState?.model?.apply;if(n?.kind==="setConfigOption"){await this.setConfigOption(n.configId,e);return}await this.setModel(e)}async confirmSeededSelection(e,n){let r=this.getDescriptor?.();if(!r)return;let o=r.wire.encode(e),i=n.model?r.wire.encode(n.model.current):null,s=n.model?.current.effort??null;if(o===i&&e.effort===s)return;let a=n.model?.apply?.kind==="setConfigOption";try{if(a&&e.effort===null&&s!==null){await this.applyModelWireId(r.wire.encode(e));return}await r.applySelection(this,e,{backendReportedCurrent:n.model?.current??null})}catch(l){W(`[AgentMode] could not apply seeded selection ${o}; reverting seed`,l),this.currentState=n,this.notifyModelChanged()}}async setConfigOption(e,n){if(this.getStatus()==="closed")throw new Error("Session is closed");if(!this.backendSessionId)throw new Error("Session is still starting");let r=await this.backend.setSessionConfigOption({sessionId:this.backendSessionId,configId:e,value:n});this.dropUsageWindowOnModelChange(r),this.currentState=r,this.notifyModelChanged(),this.clearCurrentPlanIfModeLeft()}async setMode(e){if(this.getStatus()==="closed")throw new Error("Session is closed");if(!this.backendSessionId)throw new Error("Session is still starting");let n=await this.backend.setSessionMode({sessionId:this.backendSessionId,modeId:e});this.currentState=n,this.notifyModelChanged(),this.clearCurrentPlanIfModeLeft()}canSwitchModel(){return this.getStatus()==="starting"?!1:this.currentState?.model?.apply.kind==="setConfigOption"?this.backend.isSetSessionConfigOptionSupported():this.backend.isSetSessionModelSupported()}canSwitchEffort(){if(this.getStatus()==="starting")return!1;let e=this.getDescriptor?.();return e?e.wire.effortConfigFor?this.backend.isSetSessionConfigOptionSupported():this.currentState?.model?.apply.kind==="setConfigOption"?this.backend.isSetSessionConfigOptionSupported():this.backend.isSetSessionModelSupported():null}canSwitchMode(){if(this.getStatus()==="starting")return!1;let e=this.currentState?.mode;if(!e)return null;let n=e.options[0];if(!n)return null;let r=e.apply[n.value];return r?r.kind==="setConfigOption"?this.backend.isSetSessionConfigOptionSupported():this.backend.isSetSessionModeSupported():null}getStatus(){return this.disposed?"closed":this.startupFailed?"error":this.backendSessionId===null||!this.startupSettled?"starting":this.pendingPlanResolvers.size+this.pendingToolResolvers.size+this.pendingQuestionResolvers.size>0?"awaiting_permission":this.abortController!==null?"running":this.lastTurnError?"error":"idle"}getNeedsAttention(){return this.needsAttention}markNeedsAttention(){this.needsAttention||(this.needsAttention=!0,this.notifyNeedsAttentionChanged())}clearNeedsAttention(){this.needsAttention&&(this.needsAttention=!1,this.notifyNeedsAttentionChanged())}notifyNeedsAttentionChanged(){for(let e of this.listeners)try{e.onNeedsAttentionChanged?.(this.needsAttention)}catch(n){W("[AgentMode] needs-attention listener threw",n)}}hasUserVisibleMessages(){return this.store.getDisplayMessages().length>0}loadDisplayMessages(e){this.store.loadMessages(e),this.notifyMessages()}getLabel(){return this.label}getLabelSource(){return this.labelSource}setLabel(e){let n=e?.trim()?e.trim():null;n!==this.label&&(this.label=n,this.labelSource=n?"user":null,this.notifyLabelChanged())}restoreLabel(e,n){n==="user"?this.setLabel(e):this.applyAgentLabel(e)}backendSummarizesTitle(){return this.getDescriptor?.()?.summarizesSessionTitle??!0}applyAgentLabel(e){if(this.labelSource==="user")return;let n=e?.trim()?e.trim():null;n!==this.label&&(this.label=n,this.labelSource=n?"agent":null,this.notifyLabelChanged())}notifyLabelChanged(){for(let e of this.listeners)try{e.onLabelChanged?.()}catch(n){W("[AgentMode] label listener threw",n)}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}sendPrompt(e,n,r,o){let i=this.getStatus();if(i==="starting")throw new Error("Session is still starting");if(i==="running"||i==="awaiting_permission")throw new Error("Session already has a turn in flight");if(i==="closed")throw new Error("Session is closed");let s={message:e,sender:ar,timestamp:Cs(new Date),isVisible:!0,context:n,content:Jxr(e,r)},a=this.store.addMessage(s),l=Date.now(),c={message:"",sender:pl,timestamp:Cs(new Date(l)),isVisible:!0,parts:[]};this.placeholderId=this.store.addMessage(c),this.currentMessageIds=new Set,this.currentTurnHadRoutedToolActivity=!1,this.notifyMessages(),this.label===null&&!this.backendSummarizesTitle()&&this.applyAgentLabel(lbe(this.store.getDisplayMessages())),this.lastMentionedAgents=o&&o.length>0?o:jXt,this.abortController=new AbortController,this.lastTurnError=!1,this.recomputeStatusIfChanged();let u=this.runTurn(e,a,n,l,r);return{userMessageId:a,turn:u}}getLastMentionedAgents(){return this.lastMentionedAgents}async runTurn(e,n,r,o,i){let s=this.placeholderId,a=this.backendSessionId,l=this.abortController.signal;try{let c=this.cancelledPromptDrain;c&&await Promise.race([c,new Promise(S=>{l.addEventListener("abort",()=>S(),{once:!0})})]);let d=(r?.webTabs?.length??0)>0?await Qxr(r):"",f=!this.firstPromptSent,p=f?this.projectContextBlock:null,m=this.getProjectContextUpdatesFn?.()??null,h=m?.block??null;if(this.runFanoutTurn&&VQ(this.lastMentionedAgents,this.backendId)&&s){if(!await this.ensureMultiAgentEntitlement())return this.blockFanoutForEntitlement(s,o);let S=lUt(this.priorDisplayMessages(n,s),sUt),I=zXt(e,r,i,d,p,S,h);return await this.runFanoutPath(s,e,I,o)}let g=iUt(this.pendingFanoutContext),v=zXt(e,r,i,d,p,g,h),y={sessionId:a,prompt:v},w=!l.aborted,_={stopReason:"cancelled"};if(w){let S=this.backend.prompt(y);if(_=await Promise.race([S,new Promise(I=>{l.addEventListener("abort",()=>I({stopReason:"cancelled"}),{once:!0})})]),l.aborted){let C=S.then(()=>{},()=>{}).then(async()=>{let k;do k=this.cancelledTurnActivity,await new Promise(T=>window.setTimeout(T,zxr));while(k!==this.cancelledTurnActivity)});this.cancelledPromptDrain=C,C.then(()=>{this.cancelledPromptDrain===C&&(this.cancelledPromptDrain=null)}),_={stopReason:"cancelled"}}}if(g!==null&&_.stopReason!=="cancelled"&&(this.pendingFanoutContext=[]),f&&w&&(this.firstPromptSent=!0),m&&w&&this.markProjectContextUpdatesDeliveredFn?.(m.epoch),s&&_.stopReason!=="cancelled"&&!this.currentTurnHadRoutedToolActivity&&!this.store.hasAssistantActivity(s)){let S=Kxr(this.backendId,_.stopReason);W(`[AgentMode] ${this.backendId} completed a turn without assistant text or tool activity (stopReason=${_.stopReason})`),this.store.markMessageError(s,S)}return s&&this.store.markTurnComplete(s,_.stopReason,Date.now()-o)&&this.notifyMessages(),s&&_.stopReason!=="cancelled"?this.settledStream={placeholderId:s,messageIds:this.currentMessageIds,turnStartedAtMs:o}:_.stopReason==="cancelled"&&(this.settledStream=null),this.currentMessageIds=new Set,this.placeholderId===s&&(this.placeholderId=null),_.stopReason==="end_turn"&&this.pollSessionTitle(),_.stopReason}catch(c){throw W("[AgentMode] prompt failed",c),s&&(this.store.markMessageError(s,Gxr(c),Date.now()-o),this.notifyMessages()),this.lastTurnError=!0,this.currentMessageIds=new Set,this.placeholderId===s&&(this.placeholderId=null),c}finally{this.abortController=null,this.recomputeStatusIfChanged()}}ensureMultiAgentEntitlement(){return GXt(this.getApp?.())}blockFanoutForEntitlement(e,n){return ZXt(),this.store.markMessageError(e,"Multi-agent QA is a Copilot Plus feature. Upgrade to mention more than one agent in a turn."),this.store.markTurnComplete(e,"refusal",Date.now()-n),this.currentMessageIds=new Set,this.placeholderId===e&&(this.placeholderId=null),this.notifyMessages(),"refusal"}async runFanoutPath(e,n,r,o){let i=this.abortController?.signal??new AbortController().signal,s={agents:this.lastMentionedAgents,mainAgent:this.backendId,prompt:Xxr(r),originalPromptText:n,signal:i,onChange:d=>{this.store.setFanout(e,d),this.scheduleNotifyMessages()}},a=await this.runFanoutTurn(s);this.store.setFanout(e,a);let l=i.aborted?"cancelled":"end_turn",c=Object.values(a.answers).some(d=>d.text.trim().length>0);if(a.summary.text.trim().length>0||c){let d=Zpe(a,m=>this.displayNameFor(m));this.store.appendAgentText(e,d);let f=a.summary.text.trim(),p=a.summary.complete&&f.length>0?f:c?oY(a,m=>this.displayNameFor(m)):"";p&&this.pendingFanoutContext.push({question:n,summary:p})}return this.store.markTurnComplete(e,l,Date.now()-o)&&this.notifyMessages(),this.placeholderId===e&&(this.placeholderId=null),l}priorDisplayMessages(e,n){return this.store.getDisplayMessages().filter(r=>r.id!==e&&r.id!==n)}displayNameFor(e){return this.getDisplayName?.(e)??e}async cancel(){let e=this.getStatus();if(!(e!=="running"&&e!=="awaiting_permission")&&this.backendSessionId){this.abortController?.abort(),this.settledStream=null;for(let n of this.currentMessageIds)this.cancelledMessageIds.add(n);this.currentMessageIds=new Set,this.pendingToolResolvers.size>0&&(this.flushResolvers(this.pendingToolResolvers),this.notifyMessages()),this.pendingQuestionResolvers.size>0&&(this.flushQuestionResolvers(),this.notifyMessages());try{await this.backend.cancel({sessionId:this.backendSessionId})}catch(n){W("[AgentMode] cancel notification failed",n)}}}async dispose(){this.disposed=!0,this.unregisterSessionHandler?.(),this.unregisterSessionHandler=null,this.flushResolvers(this.pendingPlanResolvers),this.flushResolvers(this.pendingToolResolvers),this.flushQuestionResolvers(),this.decidedPlanToolCallIds.clear(),this.currentPlan=null,this.currentTodoList=null,this.currentTodoListSignature=null,this.settledStream=null,this.cancelledPromptDrain=null,this.cancelledMessageIds.clear(),this.currentMessageIds=new Set,this.recomputeStatusIfChanged(),this.cancelScheduledNotify(),this.listeners.clear()}handlePlanProposalPermission(e){let n=e.toolCall.toolCallId,r=OYe({kind:e.toolCall.kind,rawInput:e.toolCall.rawInput,isPlanProposal:e.toolCall.isPlanProposal});return r&&this.publishGatedPlan(n,r),new Promise(o=>{this.pendingPlanResolvers.set(n,{request:e,resolve:o}),this.recomputeStatusIfChanged(),this.notifyMessages()})}resolvePlanProposalPermission(e,n,r){let o=this.pendingPlanResolvers.get(e);if(!o)return;this.pendingPlanResolvers.delete(e);let i=WXt(o.request,n?Wpe:tY),s=!n&&r?{...i,denyMessage:r}:i;o.resolve(s),this.recomputeStatusIfChanged(),this.notifyMessages()}getCurrentPlan(){return this.currentPlan}getCurrentTodoList(){return this.currentTodoList}getSessionUsage(){return this.currentUsage}getPlanUsage(){return this.currentPlanUsage}seedSessionUsage(e){e&&(this.currentUsage=e,this.notifyMessages(),e.contextWindow===void 0&&this.fillSeededContextWindow(e))}async fillSeededContextWindow(e){if(!this.backend.readContextWindow)return;try{await this.ready}catch{return}let n=this.currentState?.model?.current.baseModelId??null;if(!n)return;let r=null;try{r=await this.backend.readContextWindow(n)}catch{return}r&&this.currentUsage===e&&this.currentState?.model?.current.baseModelId===n&&(this.currentUsage={...e,contextWindow:r},this.notifyMessages())}applyUsageUpdate(e){e.contextWindow===void 0&&this.currentUsage?.contextWindow!==void 0||(this.currentUsage=e,this.notifyMessages())}dropUsageWindowOnModelChange(e){let n=this.currentState?.model?.current.baseModelId,r=e?.model?.current.baseModelId;!n||!r||n===r||this.currentUsage?.contextWindow!==void 0&&(this.currentUsage={...this.currentUsage,contextWindow:void 0},this.notifyMessages())}finalizePlanDecision(e){return!this.currentPlan||this.currentPlan.id!==e?!1:(this.currentPlan.pendingToolCallId&&this.decidedPlanToolCallIds.add(this.currentPlan.pendingToolCallId),this.currentPlan=null,this.notifyCurrentPlanChanged(),!0)}setCurrentPlan(e){if(!this.currentPlan){this.planSeq+=1,this.currentPlan={...e,id:`plan-${this.internalId}-${this.planSeq}`,revision:1,decision:"pending"},this.notifyCurrentPlanChanged();return}let n=this.currentPlan,r=n.body!==e.body;(r||n.title!==e.title||n.sourceFilePath!==e.sourceFilePath||n.permissionGated!==e.permissionGated||n.pendingToolCallId!==e.pendingToolCallId||n.decision!=="pending")&&(this.currentPlan={...n,...e,revision:r?n.revision+1:n.revision,decision:"pending"},this.notifyCurrentPlanChanged())}clearCurrentPlanIfModeLeft(){if(!this.currentPlan)return;let e=this.getDescriptor?.();if(!e||!e.getModeMapping||this.isCurrentlyInPlanMode())return;let n=this.currentPlan.pendingToolCallId;n&&(this.resolvePlanProposalPermission(n,!1),this.decidedPlanToolCallIds.add(n)),this.currentPlan=null,this.notifyCurrentPlanChanged()}waitForIdle(){let e=n=>n==="idle"||n==="error"||n==="closed";return this.disposed||e(this.getStatus())?Promise.resolve():new Promise(n=>{let r=this.subscribe({onMessagesChanged:()=>{},onStatusChanged:o=>{e(o)&&(r(),n())}})})}hasPendingPlanPermission(){return this.pendingPlanResolvers.size>0}handleToolPermission(e){let n=e.toolCall.toolCallId;return new Promise(r=>{this.pendingToolResolvers.set(n,{request:e,resolve:r}),this.recomputeStatusIfChanged(),this.notifyMessages()})}resolveToolPermission(e,n){let r=this.pendingToolResolvers.get(e);r&&(this.pendingToolResolvers.delete(e),r.resolve({outcome:{outcome:"selected",optionId:n}}),this.recomputeStatusIfChanged(),this.notifyMessages())}getPendingToolPermissions(){return this.pendingToolResolvers.size===0?Hxr:Array.from(this.pendingToolResolvers.values(),e=>e.request)}handleAskUserQuestion(e){let n=e.requestId;return new Promise(r=>{this.pendingQuestionResolvers.set(n,{request:e,resolve:r}),this.recomputeStatusIfChanged(),this.notifyMessages()})}resolveAskUserQuestion(e,n){let r=this.pendingQuestionResolvers.get(e);r&&(this.pendingQuestionResolvers.delete(e),r.resolve(n),this.recomputeStatusIfChanged(),this.notifyMessages())}getPendingAskUserQuestions(){return this.pendingQuestionResolvers.size===0?Wxr:Array.from(this.pendingQuestionResolvers.values(),e=>e.request)}flushResolvers(e){for(let{request:n,resolve:r}of e.values())r(WXt(n,tY));e.clear(),this.recomputeStatusIfChanged()}flushQuestionResolvers(){for(let{resolve:e}of this.pendingQuestionResolvers.values())e(Vxr);this.pendingQuestionResolvers.clear(),this.recomputeStatusIfChanged()}handleSessionEvent(e){let n=e.update,r=n.sessionUpdate==="tool_call_update"?this.store.findMessageIdWithToolCall(n.toolCallId):void 0,o=r?this.store.getMessage(r)?.turnStopReason:void 0,i=r!==void 0&&o!==void 0&&o!=="cancelled";if(this.cancelledPromptDrain||this.abortController?.signal.aborted)switch(n.sessionUpdate){case"agent_message_chunk":case"agent_thought_chunk":this.cancelledTurnActivity+=1,n.messageId&&this.cancelledMessageIds.add(n.messageId),W(`[AgentMode] dropping ${n.sessionUpdate} from cancelled turn ${this.internalId}`);return;case"tool_call":case"plan":this.cancelledTurnActivity+=1,W(`[AgentMode] dropping ${n.sessionUpdate} from cancelled turn ${this.internalId}`);return;case"tool_call_update":if(i)break;this.cancelledTurnActivity+=1,W(`[AgentMode] dropping ${n.sessionUpdate} from cancelled turn ${this.internalId}`);return}if(n.sessionUpdate==="plan"&&this.applyCurrentTodoList(n.entries)&&this.notifyCurrentTodoListChanged(),n.sessionUpdate==="session_info_update"){this.backendSummarizesTitle()&&this.applyAgentLabel(n.title);return}if(n.sessionUpdate==="state_changed"){this.dropUsageWindowOnModelChange(n.state),this.currentState=n.state,this.notifyModelChanged(),this.clearCurrentPlanIfModeLeft();return}if(n.sessionUpdate==="current_mode_update"||n.sessionUpdate==="config_option_update")return;if(n.sessionUpdate==="usage_update"){this.applyUsageUpdate(n.usage);return}if(n.sessionUpdate==="plan_usage_update"){this.currentPlanUsage=n.planUsage,this.notifyMessages();return}if(n.sessionUpdate==="agent_message_chunk"||n.sessionUpdate==="agent_thought_chunk"){let l=nSr(n.content);if(!l)return;let c=this.resolveContentTarget(n.messageId);if(!c){W(`[AgentMode] dropping ${n.sessionUpdate} \u2014 no target for ${this.internalId}`);return}(n.sessionUpdate==="agent_message_chunk"?this.store.appendAgentText(c,l):this.store.appendAgentThought(c,l))&&(c===this.settledStream?.placeholderId&&this.store.extendTurnDuration(c,Date.now()-this.settledStream.turnStartedAtMs),this.scheduleNotifyMessages());return}let s=this.placeholderId,a=i?r:s;if(!a){W(`[AgentMode] dropping session/update \u2014 no placeholder for ${this.internalId}`);return}switch(n.sessionUpdate){case"tool_call":{let l=OYe({kind:n.kind,rawInput:n.rawInput,isPlanProposal:n.isPlanProposal});if(l){this.publishGatedPlan(n.toolCallId,l),this.store.upsertAgentPart(a,HXt(n))&&this.scheduleNotifyMessages();return}this.store.upsertAgentPart(a,HXt(n))&&this.scheduleNotifyMessages();return}case"tool_call_update":{a!==s&&(this.currentTurnHadRoutedToolActivity=!0);let l=this.findToolCallPart(a,n.toolCallId),c=oSr(l,n);if(c.kind==="tool_call"){let u=OYe({kind:n.kind??c.toolKind,rawInput:c.input,isPlanProposal:n.isPlanProposal});u&&this.publishGatedPlan(c.id,u)}this.store.upsertAgentPart(a,c)&&this.scheduleNotifyMessages();return}case"plan":{this.store.upsertAgentPart(a,sSr(n))&&this.scheduleNotifyMessages();return}default:j(`[AgentMode] ignoring session/update kind=${n.sessionUpdate}`);return}}resolveContentTarget(e){if(this.cancelledPromptDrain||this.abortController?.signal.aborted||e!==void 0&&this.cancelledMessageIds.has(e))return null;if(e&&this.settledStream?.messageIds.has(e))return this.settledStream.placeholderId;let n=this.placeholderId;return n?(e&&this.currentMessageIds.add(e),n):null}findToolCallPart(e,n){return this.store.getMessage(e)?.parts?.find(o=>o.kind==="tool_call"&&o.id===n)}publishGatedPlan(e,n){if(this.decidedPlanToolCallIds.has(e))return;let r=this.currentPlan?.pendingToolCallId;r&&r!==e&&this.resolvePlanProposalPermission(r,!1);let o=rSr(n.plan);this.setCurrentPlan({body:n.plan,title:o,sourceFilePath:n.planFilePath,permissionGated:!0,pendingToolCallId:e})}isCurrentlyInPlanMode(){return this.currentState?.mode?.current==="plan"}recomputeStatusIfChanged(){let e=this.getStatus();if(e!==this.cachedStatus){this.cachedStatus=e;for(let n of this.listeners)try{n.onStatusChanged(e)}catch(r){W("[AgentMode] status listener threw",r)}}}notifyMessages(){this.cancelScheduledNotify();for(let e of this.listeners)try{e.onMessagesChanged()}catch(n){W("[AgentMode] messages listener threw",n)}}scheduleNotifyMessages(){if(this.notifyScheduled)return;this.notifyScheduled=!0;let e=()=>{this.notifyHandle=null,this.notifyScheduled=!1,this.notifyMessages()};typeof requestAnimationFrame<"u"?this.notifyHandle=window.requestAnimationFrame(e):this.notifyHandle=window.setTimeout(e,16)}cancelScheduledNotify(){this.notifyScheduled&&(this.notifyScheduled=!1,this.notifyHandle!==null&&(typeof cancelAnimationFrame<"u"&&typeof this.notifyHandle=="number"?cancelAnimationFrame(this.notifyHandle):window.clearTimeout(this.notifyHandle),this.notifyHandle=null))}async pollSessionTitle(){if(this.labelSource!=="user"&&this.backendSummarizesTitle())try{let r=(await this.backend.listSessions(this.cwd?{cwd:this.cwd}:{})).sessions.find(o=>o.sessionId===this.backendSessionId)?.title?.trim();if(!r||r.startsWith(NYe))return;this.applyAgentLabel(r)}catch(e){if(e instanceof da)return;W(`[AgentMode] session/list title poll failed for ${this.internalId}`,e)}}notifyModelChanged(){for(let e of this.listeners)try{e.onModelChanged?.()}catch(n){W("[AgentMode] model listener threw",n)}}applyCurrentTodoList(e){let n=e.map(o=>({content:o.content,status:o.status})),r=n.length>0?JSON.stringify(n):null;return r===this.currentTodoListSignature?!1:(this.currentTodoList=n.length>0?n:null,this.currentTodoListSignature=r,!0)}notifyCurrentTodoListChanged(){for(let e of this.listeners)try{e.onCurrentTodoListChanged?.()}catch(n){W("[AgentMode] todo-list listener threw",n)}}notifyCurrentPlanChanged(){for(let e of this.listeners)try{e.onCurrentPlanChanged?.()}catch(n){W("[AgentMode] plan listener threw",n)}}}});async function RYe(t,e){if(!e)return;let n=t.getState()?.mode;if(!n||n.current===e)return;let r=n.apply[e];if(r)try{r.kind==="setMode"?await t.setMode(r.nativeId):await t.setConfigOption(r.configId,r.value)}catch(o){if(o instanceof da)return;W(`[AgentMode] could not replay persisted mode "${e}"`,o)}}var YXt=b(()=>{pe();ok()});function aSr(t){let e=t.update;return e.sessionUpdate!=="agent_message_chunk"||e.content.type!=="text"?null:e.content.text}function lSr(t){let e={};for(let n of t)e[n]={backendId:n,status:"running",text:""};return{answers:e,summary:{status:"pending",text:""}}}var _be,JXt=b(()=>{pe();ut();tA();_be=class{constructor(e){this.host=e}async run(e){let n=lSr(e.agents);return e.onChange(n),await Promise.all(e.agents.map(r=>this.runAgent(r,n,e))),e.signal.aborted||await this.runSummary(n,e),n}async runAgent(e,n,r){let o=n.answers[e],i=s=>{o.status==="running"&&(s(),r.onChange(n))};try{let s=await this.runReadOnlySubSession({backendId:e,prompt:r.prompt,signal:r.signal,onText:a=>i(()=>o.text+=a)});i(()=>o.status=s==="aborted"?"cancelled":"done")}catch(s){i(()=>{W(`[AgentMode] fan-out agent ${e} failed`,s),o.status="error",o.error=kt(s)})}}async runSummary(e,n){let r=Kpe(e),o=cUt(n.originalPromptText,r,i=>this.host.getDisplayName(i));if(!o){e.summary.status="done",e.summary.text=oUt,e.summary.complete=!0,n.onChange(e);return}e.summary.status="streaming",n.onChange(e);try{await this.runReadOnlySubSession({backendId:n.mainAgent,prompt:o,signal:n.signal,onText:s=>{e.summary.text+=s,n.onChange(e)}})==="done"&&(e.summary.complete=!0)}catch(i){W("[AgentMode] fan-out summary failed",i)}finally{e.summary.status="done",n.onChange(e)}}async runReadOnlySubSession(e){let{backendId:n,prompt:r,signal:o,onText:i}=e,s=async(a,l)=>{let c=null,u=null,d=null,f=null;try{let p=await this.host.ensureBackendForFanout(n);c=p.proc;let m=p.descriptor,h=await c.newSession({cwd:this.host.getCwd()??""});u=h.sessionId,d=this.host.registerReadOnlySession(u),this.host.excludeSubSessionFromHistory(n,u),f=c.registerSessionHandler(u,_=>{let S=aSr(_);S!==null&&i(S)});let g=h.state.model?.apply??null;if(await Promise.all([this.applyReadOnlyMode(c,m,u),this.applyDefaultModel(c,m,n,u,g)]),l())return"done";let v=c,y=u,w=v.prompt({sessionId:u,prompt:r});return a(w,()=>{v.cancel({sessionId:y}).catch(()=>{})}),await w,l()||await this.awaitTrailingChunks(),"done"}finally{f?.(),d?.(),c&&u&&c.cancel({sessionId:u}).catch(()=>{})}};return this.runAttemptWithTimeout((a,l)=>s(a,l),o)}awaitTrailingChunks(){return new Promise(e=>{window.setTimeout(e,nUt)})}runAttemptWithTimeout(e,n){return new Promise((r,o)=>{let i=!1,s=null,a=null,l=()=>{window.clearTimeout(f),n.removeEventListener("abort",d)},c=m=>{if(s===null){m();return}a?.();let h=window.setTimeout(()=>{W("[AgentMode] fan-out prompt did not settle within the cancel grace; reusing backend anyway"),m()},tUt);s.then(()=>{window.clearTimeout(h),m()})},u=m=>{i||(i=!0,l(),c(m))},d=()=>u(()=>r("aborted")),f=window.setTimeout(()=>u(()=>o(new Error(eUt))),Q2t);if(n.addEventListener("abort",d,{once:!0}),n.aborted){u(()=>r("aborted"));return}e((m,h)=>{s=m.then(()=>{},()=>{}),a=h,i&&(h(),m.catch(()=>{}))},()=>i).then(()=>{i||(i=!0,l(),r(n.aborted?"aborted":"done"))},m=>{i||(i=!0,l(),o(m instanceof Error?m:new Error(kt(m))))})})}async applyReadOnlyMode(e,n,r){let o=n.getModeMapping?.(null,null);if(o?.kind!=="setMode")return;let i=o.readOnlyModeId;if(i)try{await e.setSessionMode({sessionId:r,modeId:i})}catch(s){W(`[AgentMode] fan-out read-only mode failed for ${n.id}`,s)}}async applyDefaultModel(e,n,r,o,i){let s=this.host.getDefaultSelection(r);if(s)try{if(i?.kind==="setConfigOption"){await this.applyConfigOptionModel(e,n,o,s,i);return}if(await e.setSessionModel({sessionId:o,modelId:n.wire.encode(s)}),s.effort!==null){let a=n.wire.effortConfigFor?.(s.baseModelId);a&&await e.setSessionConfigOption({sessionId:o,configId:a.id,value:s.effort})}}catch(a){W(`[AgentMode] fan-out default model failed for ${r}`,a)}}async applyConfigOptionModel(e,n,r,o,i){let s=n.wire.encode({baseModelId:o.baseModelId,effort:null}),a=await e.setSessionConfigOption({sessionId:r,configId:i.configId,value:s});if(o.effort===null)return;let l=a.model?.apply,c=l?.kind==="setConfigOption"?l.effortConfigId:i.effortConfigId;c&&await e.setSessionConfigOption({sessionId:r,configId:c,value:o.effort})}}});function LYe(t,e){if(e===tr)return t;let n=Pe("path"),r=mo(e);if(!r)throw new m6(e);return n.join(t,n.dirname(r.filePath))}function XXt(t,e){let n=Pe("path"),r=i=>i.replace(/[/\\]+$/,""),o=r(e);if(o!==r(t)){for(let i of $p())if(o===r(n.join(t,n.dirname(i.filePath))))return i.project.id}}function QXt(t,e,n){return n&&t.includes(n)?n:t.length===0?null:t[Math.min(e,t.length-1)]}var m6,eQt=b(()=>{Md();_S();$n();m6=class extends Error{constructor(n){super(`Project "${n}" is no longer available.`);this.projectId=n;this.name="OrphanedProjectError"}}});function uSr(t,e){let{inclusions:n,exclusions:r}=Fi({inclusions:e.project.contextSource?.inclusions,exclusions:e.project.contextSource?.exclusions,isProject:!0});if(!n)return!1;if(t.kind==="metadata")return(n.propertyPatterns?.length??0)>0&&t.isMarkdown&&tQt(t.path);let o=t.oldPath?[t.path,t.oldPath]:[t.path],i=t.isFolder&&(t.kind==="rename"||t.kind==="delete"),s=dSr(n,r)&&o.some(l=>!t$(l)),a=fSr(n,r)&&o.some(tQt);return(s||a)&&(t.isMarkdown||o.some(c=>c.toLowerCase().endsWith(".md"))||i)?!0:t.isFolder?t.kind==="create"?(n.folderPatterns??[]).some(l=>h6(l)===t.path):i?(n.folderPatterns??[]).some(l=>o.some(c=>mSr(c,l)))?!0:(n.notePatterns?.length??0)>0||(n.extensionPatterns?.length??0)>0:!1:o.some(l=>pSr(l,n))}function dSr(t,e){return(t.tagPatterns?.length??0)>0||(e?.tagPatterns?.length??0)>0}function fSr(t,e){return(t.propertyPatterns?.length??0)>0||(e?.propertyPatterns?.length??0)>0}function tQt(t){return!t$(t)&&!ZH(t)}function pSr(t,e){if(t$(t))return!1;let n=t.toLowerCase();if((e.extensionPatterns??[]).some(o=>n.endsWith(o.slice(1).toLowerCase()))||(e.folderPatterns??[]).some(o=>$Ye(t,h6(o))))return!0;let r=hSr(t);return(e.notePatterns??[]).some(o=>o.slice(2,-2)===r)}function mSr(t,e){let n=h6(t),r=h6(e);return $Ye(n,r)||$Ye(r,n)}function $Ye(t,e){return e.length===0?!1:t===e||t.startsWith(`${e}/`)}function hSr(t){return(t.split("/").pop()??t).replace(/\.[^/.]+$/,"")}function h6(t){return(0,g6.normalizePath)(t).replace(/^\/+/,"").replace(/\/+$/,"")}var g6,cSr,xbe,nQt=b(()=>{pe();Md();ha();AC();g6=require("obsidian"),cSr=2e3,xbe=class{constructor(e,n=cSr){this.app=e;this.vaultRefs=[];this.metadataRefs=[];this.pending=[];this.epochs=new Map;this.listeners=new Set;this.disposed=!1;this.debouncedDrain=Ba(()=>this.drain(),n,{trailing:!0}),this.vaultRefs.push(this.app.vault.on("create",r=>this.enqueue("create",r))),this.vaultRefs.push(this.app.vault.on("modify",r=>this.enqueue("modify",r))),this.vaultRefs.push(this.app.vault.on("delete",r=>this.enqueue("delete",r))),this.vaultRefs.push(this.app.vault.on("rename",(r,o)=>this.enqueue("rename",r,o))),this.metadataRefs.push(this.app.metadataCache.on("changed",r=>this.enqueue("metadata",r)))}getEpoch(e){return this.epochs.get(e)??0}bumpEpoch(e){let n=this.getEpoch(e)+1;return this.epochs.set(e,n),n}onContentChanged(e){return this.listeners.add(e),()=>this.listeners.delete(e)}flushNow(){this.debouncedDrain.flush()}dispose(){this.disposed=!0,this.debouncedDrain.cancel();for(let e of this.vaultRefs)this.app.vault.offref(e);this.vaultRefs.length=0;for(let e of this.metadataRefs)this.app.metadataCache.offref(e);this.metadataRefs.length=0,this.pending.length=0,this.listeners.clear(),this.epochs.clear()}enqueue(e,n,r){this.disposed||(this.pending.push({kind:e,isFolder:n instanceof g6.TFolder,isMarkdown:n instanceof g6.TFile&&n.extension==="md",path:h6(n.path),oldPath:r?h6(r):void 0}),this.debouncedDrain())}drain(){let e=this.pending.splice(0);if(e.length===0)return;let n=new Set;for(let r of $p())try{e.some(o=>uSr(o,r))&&n.add(r.project.id)}catch(o){W(`[project-content] scope match failed for project ${r.project.id}`,o)}for(let r of n){this.bumpEpoch(r);for(let o of this.listeners)try{o(r)}catch(i){W(`[project-content] content-change listener failed for ${r}`,i)}}}}});function rQt(){return gSr}var gSr,oQt=b(()=>{gSr=["<project_context_updates>","Project sources may have changed; re-check the declared project context before answering.","</project_context_updates>"].join(`
`)});async function GQ(t,e,n,r,o){let i=$I(n.contextSource?.webUrls||""),s=$I(n.contextSource?.youtubeUrls||"");await t.fileManager.processFrontMatter(e,a=>{a[Tm]=n.id.trim(),a[GR]=(n.name||r).trim(),a[ZR]=(n.description||"").trim(),a[YR]=(n.projectModelKey||"").trim(),n.modelConfigs?.temperature!=null?a[oA]=n.modelConfigs.temperature:delete a[oA],n.modelConfigs?.maxTokens!=null?a[iA]=n.modelConfigs.maxTokens:delete a[iA],a[XR]=n.contextSource?.inclusions||"",a[QR]=n.contextSource?.exclusions||"",a[eL]=i,a[tL]=s,a[JR]=o.createdMs,a[fb]=o.lastUsedMs})}function Sbe(t,e){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let n=Number(t);if(Number.isFinite(n))return n}return e}function y6(t,e){return typeof t=="string"?t:e}function iQt(t){return Array.isArray(t)?t.filter(e=>typeof e=="string").map(e=>e.trim()).filter(Boolean):typeof t=="string"?t.split(`
`).map(e=>e.trim()).filter(Boolean):[]}function sQt(t){return t.replace(/\n\s*/g,"").replace(/\r/g,"")}function aQt(t){return(t||[]).map(e=>e.trim()).filter(Boolean).join(`
`)}async function P$(t,e){let n=t.vault.getAbstractFileByPath(e.path),r=n instanceof jI.TFile,o=r?await t.vault.read(n):await t.vault.adapter.read(e.path),i=fy(o,{trimStart:!1}),s,a=o.replace(/^\uFEFF/,"").match(/^---\r?\n([\s\S]*?)\r?\n---/);if(a)try{let E=(0,jI.parseYaml)(a[1]);E&&typeof E=="object"&&(s=E)}catch{return W(`[Projects] Failed to parse YAML frontmatter from file: ${e.path}`),null}!s&&r&&(s=t.metadataCache.getFileCache(n)?.frontmatter);let l=wJt(e.path);if(!l)return W(`[Projects] Cannot extract folder name from path, ignoring file: ${e.path}`),null;let c=s?.[Tm],u=typeof c=="number"&&Number.isFinite(c)?String(c):y6(c,"");if(!u.trim())return W(`[Projects] Missing ${Tm} in frontmatter, skipping file: ${e.path}`),null;let d=u.trim(),p=y6(s?.[GR],"").trim()||l,m=y6(s?.[ZR],"").trim(),h=y6(s?.[YR],"").trim(),g=Sbe(s?.[oA],NaN),v=Sbe(s?.[iA],NaN),y=y6(s?.[XR],""),w=y6(s?.[QR],""),_=sQt(y),S=sQt(w),I=iQt(s?.[eL]),C=iQt(s?.[tL]),k=Sbe(s?.[JR],e.stat?.ctime??0),T=Sbe(s?.[fb],0),P={};return Number.isFinite(g)&&(P.temperature=g),Number.isFinite(v)&&v>0&&(P.maxTokens=v),{project:{...VUt,id:d,name:p,description:m||"",systemPrompt:i,projectModelKey:h,modelConfigs:P,contextSource:{inclusions:_||"",exclusions:S||"",webUrls:aQt(I),youtubeUrls:aQt(C)},created:Number.isFinite(k)&&k>0?k:0,UsageTimestamps:Number.isFinite(T)&&T>0?T:0},filePath:e.path,folderName:l}}async function Cbe(t){let e=Od(),n=t.vault.getAbstractFileByPath(e),r=[];if(n instanceof jI.TFolder)for(let a of n.children){if(!(a instanceof jI.TFolder)||a.name===ff)continue;let l=a.children.find(c=>c instanceof jI.TFile&&c.name===Xh);l instanceof jI.TFile&&r.push(l)}else if(await t.vault.adapter.exists(e)){let{resolveFileByPath:a}=await Promise.resolve().then(()=>(Jh(),NUt)),l=await t.vault.adapter.list(e);for(let c of l.folders){if((c.split("/").pop()??"")===ff)continue;let d=`${c}/${Xh}`;if(await t.vault.adapter.exists(d)){let f=await a(t,d);f&&r.push(f)}}}r.sort((a,l)=>a.path.localeCompare(l.path));let o={},i=[],s=[];for(let a of r){let l;try{l=await P$(t,a)}catch(u){H(`[Projects] Failed to parse project file, skipping: ${a.path}`,u),i.push(a.path);continue}if(!l){i.push(a.path);continue}let c=l.project.id;if(o[c]||(o[c]=[]),o[c].push(a.path),o[c].length>1){W(`[Projects] Duplicate project id="${c}": ${o[c].join(", ")}; keeping first: ${o[c][0]}`);continue}s.push(l)}return{records:s,diagnostics:{duplicateIdIndex:o,ignoredFiles:i}}}async function BI(t){let{records:e}=await Cbe(t);return LQ(e),e}async function lQt(t){let{records:e}=await Cbe(t);return e}async function ZQ(t,e,n){let r=qb(e.path),o=Date.now(),i=Number.isFinite(n.project.created)&&n.project.created>0?n.project.created:o,s=Number.isFinite(n.project.UsageTimestamps)&&n.project.UsageTimestamps>0?n.project.UsageTimestamps:0,a=$I(n.project.contextSource?.webUrls||""),l=$I(n.project.contextSource?.youtubeUrls||"");try{r||Nf(e.path),await t.fileManager.processFrontMatter(e,c=>{c[Tm]==null&&n.project.id&&(c[Tm]=n.project.id),c[GR]==null&&(c[GR]=n.project.name||n.folderName),c[ZR]==null&&n.project.description&&(c[ZR]=n.project.description),c[YR]==null&&n.project.projectModelKey&&(c[YR]=n.project.projectModelKey),c[oA]==null&&n.project.modelConfigs?.temperature!=null&&(c[oA]=n.project.modelConfigs.temperature),c[iA]==null&&n.project.modelConfigs?.maxTokens!=null&&(c[iA]=n.project.modelConfigs.maxTokens),c[XR]==null&&n.project.contextSource?.inclusions&&(c[XR]=n.project.contextSource.inclusions),c[QR]==null&&n.project.contextSource?.exclusions&&(c[QR]=n.project.contextSource.exclusions),c[eL]==null&&a.length>0&&(c[eL]=a),c[tL]==null&&l.length>0&&(c[tL]=l),c[JR]==null&&(c[JR]=i),c[fb]==null&&(c[fb]=s)})}finally{r||Ed(e.path)}}var jI,YQ=b(()=>{sA();Mv();ut();pe();jI=require("obsidian");Md();Mv()});async function uQt(t){let e=Od(),n;try{n=await vSr(t,e)}catch(r){H("[Projects] Failed to scan for PR2b-1 AGENTS.md residue",r);return}for(let r of n){if((r.split("/").pop()??"")===ff)continue;let i=(0,Vm.normalizePath)(`${r}/${df}`),s=(0,Vm.normalizePath)(`${r}/${Xh}`);try{if(!await cQt(t,i)||await cQt(t,s))continue;let a=await wSr(t,i);if(a===null||!ySr(a))continue;Nf(s);try{await _Sr(t,s,a)}finally{Ed(s)}let l=fy(a,{trimStart:!1});if(l!==a){Nf(i);try{await bSr(t,i,l)}finally{Ed(i)}}j(`[Projects] Reconciled PR2b-1 AGENTS.md residue \u2192 project.md in ${r}`)}catch(a){H(`[Projects] Failed to reconcile AGENTS.md residue in ${r}`,a)}}}function ySr(t){let e=t.replace(/^\uFEFF/,"").match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!e)return!1;try{let n=(0,Vm.parseYaml)(e[1]);if(!n||typeof n!="object")return!1;let r=n[Tm];return typeof r=="string"?r.trim().length>0:typeof r=="number"}catch{return!1}}async function vSr(t,e){let n=t.vault.getAbstractFileByPath(e);return n instanceof Vm.TFolder?n.children.filter(r=>r instanceof Vm.TFolder).map(r=>r.path):await t.vault.adapter.exists(e)?(await t.vault.adapter.list(e)).folders:[]}async function cQt(t,e){return t.vault.getAbstractFileByPath(e)instanceof Vm.TFile?!0:t.vault.adapter.exists(e)}async function wSr(t,e){let n=t.vault.getAbstractFileByPath(e);return n instanceof Vm.TFile?t.vault.read(n):await t.vault.adapter.exists(e)?t.vault.adapter.read(e):null}async function bSr(t,e,n){let r=t.vault.getAbstractFileByPath(e);if(r instanceof Vm.TFile){await t.vault.modify(r,n);return}await t.vault.adapter.write(e,n)}async function _Sr(t,e,n){let r=(0,Vm.normalizePath)(e.split("/").slice(0,-1).join("/"));t.vault.getAbstractFileByPath(r)instanceof Vm.TFolder?await t.vault.create(e,n):await t.vault.adapter.write(e,n)}var Vm,dQt=b(()=>{db();pe();sA();Mv();Md();ut();Vm=require("obsidian")});function fQt(t){return t.replace(/\r\n/g,`
`).replace(/\r/g,`
`)}async function A$(t,e,n,r){try{let o=(0,qm.normalizePath)(`${r}/${ff}`);await ao(t,o);let i=xS(e.id||"unknown")||"unknown",s=`Project Migration Failed - ${i}`,a=`${o}/${s}.md`,l=2;for(;await t.adapter.exists(a);){if(l===2)try{let d=(await t.adapter.read(a)).match(/```json\s*\n([\s\S]*?)\n```/);if(d){let f=JSON.parse(d[1]);if(JSON.stringify(f)===JSON.stringify(e))return!1}}catch{}if(a=`${o}/${s} - ${l}.md`,l++,l>20)return W(`[Projects] Too many backup collisions for safeId="${i}", giving up`),!1}let c=[`> Projects migration failed: ${n}`,">","> This file is an automatic backup (unsupported/), for manual recovery.","> You can recreate the project from the JSON below, or fix and re-migrate.","","```json",JSON.stringify(e,null,2),"```",""].join(`
`);return await t.create(a,c),!0}catch(o){return H(`[Projects] Failed to save unsupported backup for project id=${e.id||"unknown"}`,o),!1}}async function hQt(t,e,n){let r=t.vault;try{let o=r.getAbstractFileByPath(e);o instanceof qm.TFile?await Bc(t,o):await r.adapter.exists(e)&&await r.adapter.remove(e);let i=r.getAbstractFileByPath(n);if(i instanceof qm.TFolder&&i.children.length===0)await Bc(t,i);else if(await r.adapter.exists(n)){let s=await r.adapter.list(n);s.files.length===0&&s.folders.length===0&&await r.adapter.rmdir(n,!1)}}catch(o){H(`[Projects] Migration rollback failed for ${e}`,o)}}async function xSr(t,e,n,r){let o=t.vault;await ao(o,r),await ao(o,`${r}/${n}`);let i=BE(n,r),s=`${r}/${n}`;Nf(i);try{let a=await o.create(i,e.systemPrompt||""),l=Date.now(),c=Number.isFinite(e.created)&&e.created>0?e.created:l,u=Number.isFinite(e.UsageTimestamps)&&e.UsageTimestamps>0?e.UsageTimestamps:0;try{await GQ(t,a,e,n,{createdMs:c,lastUsedMs:u})}catch(d){throw await hQt(t,i,s),d}return a}finally{Ed(i)}}async function pQt(t,e,n){try{let r=e instanceof qm.TFile?await t.read(e):await t.adapter.read(e),o=fy(r,{trimStart:!1}),i=fQt(o).replace(/^\n+/,""),s=fQt(n||"").replace(/^\n+/,"");return i!==s?(W(`[Projects] Migration verify failed: content mismatch. Expected ${s.length} chars, got ${i.length} chars`),!1):!0}catch(r){return H("[Projects] Migration verify failed: unable to read back file",r),!1}}function mQt(t,e){return bJt(t,e)}async function SSr(t){let e=Od(),n=t.vault,o=Y().projectList||[];if(o.length===0)return j("[Projects] No legacy projects to migrate"),null;j(`[Projects] Migrating ${o.length} legacy projects to vault files...`);let i=[],s=new Set,a=new Map;for(let f of o){let p=(f.id||"").trim();if(!p){W("[Projects] Skip migrating project with empty id"),await A$(n,f,"empty project id",e);continue}if(s.has(p)){W(`[Projects] Skip migrating duplicate project id: ${p}`),await A$(n,f,`duplicate project id: ${p}`,e);continue}s.add(p);let m=mQt(p,f.name),h=m.toLowerCase(),g=a.get(h);if(g){W(`[Projects] Skip migrating project id="${p}": folder name "${m}" collides with id="${g}"`),await A$(n,f,`folder name collision: "${m}" already used by id="${g}"`,e);continue}a.set(h,p);let v=BE(m,e),y=n.getAbstractFileByPath(v);if(y instanceof qm.TFile||await n.adapter.exists(v)){let _="";if(y instanceof qm.TFile){let S=t.metadataCache.getFileCache(y);_=String(S?.frontmatter?.[Tm]??"").trim(),_||(_=await eYe(n,y,Tm))}else try{let I=(await n.adapter.read(v)).replace(/^\uFEFF/,"").match(/^---\r?\n([\s\S]*?)\r?\n---/);if(I){let C=(0,qm.parseYaml)(I[1]);if(C&&typeof C=="object"){let k=C[Tm];_=(typeof k=="string"?k:"").trim()}}}catch{_=""}if(_===p){if(await pQt(n,y instanceof qm.TFile?y:v,f.systemPrompt||"")){if(y instanceof qm.TFile)try{let I=mQt(p,f.name);await ZQ(t,y,{project:f,filePath:v,folderName:I})}catch(I){W(`[Projects] Failed to repair frontmatter for id=${p}, continuing`,I)}j(`[Projects] Migration skip: target file already exists for id=${p} at ${v}`),i.push(f);continue}W(`[Projects] Migration verify failed on existing file for id=${p} at ${v}`),await A$(n,f,`existing file content mismatch at ${v} (delete/rename the file and re-run migration)`,e);continue}W(`[Projects] Migration conflict: ${v} exists with id="${_}" but expected "${p}"`),await A$(n,f,`target file exists at ${v} with mismatched id="${_}"`,e);continue}try{let _=await xSr(t,f,m,e);if(await pQt(n,_,f.systemPrompt||""))i.push(f);else{let I=`${e}/${m}`;await hQt(t,_.path,I),await A$(n,f,"content verification mismatch",e)}}catch(_){let S=_ instanceof Error?_.message:String(_);H(`[Projects] Failed to migrate project id=${p}`,_),await A$(n,f,S,e)}}At("projectList",[]);let l=i.length,c=o.length-l,u=Od(),d=Q7e();return c===0?(j(`[Projects] Migration succeeded: all ${l} project(s) migrated to vault files`),{id:"projects",title:"Projects",status:"success",summary:`All ${l} project${l===1?" was":"s were"} migrated to note files.`,details:[`Stored in ${u}.`]}):l>0?(W(`[Projects] Migration partially succeeded: ${l} migrated, ${c} failed`),{id:"projects",title:"Projects",status:"action-required",summary:`${l} project${l===1?" was":"s were"} migrated; ${c} could not be migrated.`,details:[`Migrated projects are in ${u}.`,`Recover the remaining projects from ${d}.`]}):(W("[Projects] Migration failed: no projects were migrated"),{id:"projects",title:"Projects",status:"error",summary:"No projects could be migrated, but recovery copies were created.",details:[`Recover the projects from ${d}.`]})}async function CSr(t){let e=t.vault,{records:n}=await Cbe(t);if(n.length===0)return;let r=0,o=new Map;for(let i of n)o.set(i.folderName.toLowerCase(),i.project.id);for(let i of n){let s=(i.project.name||"").trim();if(!s)continue;let a=xS(s),l=a.toLowerCase()===ff?`_${a}`:a;if(l===i.folderName)continue;let{projectsRoot:c,projectFolderPath:u}=Nd(i.filePath),d=`${c}/${l}`,f=i.filePath,p=BE(l,c),m=l.toLowerCase(),h=o.get(m);if(h&&h!==i.project.id){W(`[Projects] Naming migration skip: folder "${l}" collides (case-insensitive) with project id="${h}" for project id="${i.project.id}"`);continue}if(!(d.toLowerCase()===u.toLowerCase())&&await e.adapter.exists(d)){W(`[Projects] Naming migration skip: target folder "${d}" already exists for project id="${i.project.id}"`);continue}try{Nf(f),Nf(p);let v=e.getAbstractFileByPath(u);v instanceof qm.TFolder?await e.rename(v,d):await e.adapter.rename(u,d),r++,o.delete(i.folderName.toLowerCase()),o.set(m,i.project.id),j(`[Projects] Naming migration: renamed folder "${i.folderName}" \u2192 "${l}" for project "${s}" (id=${i.project.id})`)}catch(v){H(`[Projects] Naming migration failed for project id="${i.project.id}"`,v)}finally{Ed(f),Ed(p)}}r>0&&j(`[Projects] Naming migration complete: ${r} folder(s) renamed`)}async function gQt(t){let e=Y().projectList||[],n=null;return e.length>0&&(n=await SSr(t)),await uQt(t),await CSr(t),n}var qm,yQt=b(()=>{pe();sA();dQt();Mv();YQ();Md();Se();ut();qm=require("obsidian");Jh()});var vQt={};sr(vQt,{clearProjectMarkers:()=>kSr});async function kSr(t,e){let n=(e||"").trim();n&&await t6(YW(t,n)).clear()}var wQt=b(()=>{n6();_$()});var Ig,nl,zI=b(()=>{db();pe();sA();YQ();Md();ut();$n();wC();Jh();Ig=require("obsidian");yQt();nl=class t{constructor(e){this.projectLastUsedManager=new t2;this.app=e,this.vault=e.vault}static getInstance(e){if(!t.instance){if(!e)throw new Error("App is required for first initialization");t.instance=new t(e)}return t.instance}async initialize(){j("[Projects] Initializing ProjectFileManager");let e=await gQt(this.app);return await BI(this.app),e}getProjects(){return $p().map(e=>e.project)}getProjectRecords(){return $p()}async reloadProjects(){return await BI(this.app)}async fetchProjects(){return await lQt(this.app)}getProjectUsageTimestampsManager(){return this.projectLastUsedManager}sanitizeFolderName(e){let n=xS(e);return n.toLowerCase()===ff?`_${n}`:n}async rollbackCreatedFile(e,n){try{let r=this.vault.getAbstractFileByPath(e);r instanceof Ig.TFile?await Bc(this.app,r):await this.vault.adapter.exists(e)&&await this.vault.adapter.remove(e);let o=this.vault.getAbstractFileByPath(n);if(o instanceof Ig.TFolder&&o.children.length===0)await Bc(this.app,o);else if(await this.vault.adapter.exists(n)){let i=await this.vault.adapter.list(n);i.files.length===0&&i.folders.length===0&&await this.vault.adapter.rmdir(n,!1)}}catch(r){H(`[Projects] Rollback failed for ${e}`,r)}}getLeadingFrontmatterBlock(e){let r=e.replace(/^\uFEFF/,"").match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return r?r[0]:null}buildProjectFileContent(e,n,r){let o=$I(e.contextSource?.webUrls||""),i=$I(e.contextSource?.youtubeUrls||""),s={[Tm]:e.id.trim(),[GR]:(e.name||n).trim(),[ZR]:(e.description||"").trim(),[YR]:(e.projectModelKey||"").trim(),[XR]:e.contextSource?.inclusions||"",[QR]:e.contextSource?.exclusions||"",[eL]:o,[tL]:i,[JR]:r.createdMs,[fb]:r.lastUsedMs};return e.modelConfigs?.temperature!=null&&(s[oA]=e.modelConfigs.temperature),e.modelConfigs?.maxTokens!=null&&(s[iA]=e.modelConfigs.maxTokens),`---
${(0,Ig.stringifyYaml)(s)}---
${e.systemPrompt||""}`}async createProject(e){let n=(e.id||"").trim();if(!n)throw new Error("Project id cannot be empty");if(mo(n))throw new Error(`Project id already exists: ${n}`);let r=(e.name||"").trim();if(r&&$p().some(d=>d.project.name.trim().toLowerCase()===r.toLowerCase()))throw new Error(`A project with the name "${r}" already exists`);let o=this.sanitizeFolderName(r||n),i=$Q(o),s=BE(o),a=o.toLowerCase(),c=$p().find(u=>u.folderName.toLowerCase()===a&&u.project.id!==n);if(c)throw new Error(`Folder name collision: project id "${n}" sanitizes to folder "${o}" which conflicts with existing project "${c.project.id}"`);try{if(Nf(s),await ao(this.vault,Od()),await ao(this.vault,i),await this.vault.adapter.exists(s))throw new Error(`Project file already exists at "${s}". This may be a folder name collision \u2014 project id "${n}" sanitizes to folder "${o}"`);let u=Date.now(),d=Number.isFinite(e.created)&&e.created>0?e.created:u,f=Number.isFinite(e.UsageTimestamps)&&e.UsageTimestamps>0?e.UsageTimestamps:0,p=await this.vault.create(s,e.systemPrompt||"");try{await GQ(this.app,p,e,o,{createdMs:d,lastUsedMs:f})}catch(h){throw await this.rollbackCreatedFile(s,i),h}let m={project:{...e,id:n,created:d,UsageTimestamps:f},filePath:s,folderName:o};return S$(m),j(`[Projects] Created project: ${n} -> ${s}`),m}finally{Ed(s)}}async updateProject(e,n){let r=(e||"").trim();if(!r)throw new Error("Project id cannot be empty");if((n.id||"").trim()!==r)throw new Error("Project id mismatch: cannot change id via update");let o=mo(r);if(!o)throw new Error(`Project not found: ${r}`);let i=(n.name||"").trim();if(i&&$p().some(p=>p.project.id!==r&&p.project.name.trim().toLowerCase()===i.toLowerCase()))throw new Error(`A project with the name "${i}" already exists`);let s=o.filePath,a=o.folderName,{projectsRoot:l}=Nd(o.filePath),c=f=>(0,Ig.normalizePath)(`${l}/${f}`),u=this.sanitizeFolderName(i||r),d=null;if(u!==o.folderName){let f=c(u),p=BE(u,l),m=u.toLowerCase(),h=$p().find(v=>v.project.id!==r&&v.folderName.toLowerCase()===m);if(h)throw new Error(`Cannot rename project folder: "${u}" conflicts with project "${h.project.name}"`);if(!(f.toLowerCase()===c(o.folderName).toLowerCase())&&await this.vault.adapter.exists(f))throw new Error(`Cannot rename project folder: "${f}" already exists on disk`);d=s,Nf(d),Nf(p);try{let v=c(o.folderName),y=this.vault.getAbstractFileByPath(v);y instanceof Ig.TFolder?await this.vault.rename(y,f):await this.vault.adapter.rename(v,f)}catch(v){throw Ed(d),Ed(p),v}s=p,a=u,j(`[Projects] Renamed project folder: "${o.folderName}" \u2192 "${u}" for project ${r}`)}try{d||Nf(s);let f=await Dk(this.app,s),p=!1;if(!f){j(`[Projects] Materializing missing vault file for project: ${r}`);let _=c(a);await ao(this.vault,l),await ao(this.vault,_),f=await this.vault.create(s,n.systemPrompt||""),p=!0}let m=Number.isFinite(o.project.created)&&o.project.created>0?o.project.created:Date.now(),h=Number.isFinite(o.project.UsageTimestamps)&&o.project.UsageTimestamps>0?o.project.UsageTimestamps:0,g=this.projectLastUsedManager.getLastTouchedAt(r)??0,v=Math.max(h,g),y={...n,created:m,UsageTimestamps:v};if(xp(this.app,s)){try{await GQ(this.app,f,y,a,{createdMs:m,lastUsedMs:v})}catch(C){throw p&&await this.rollbackCreatedFile(s,c(a)),C}let _=await this.vault.read(f),S=this.getLeadingFrontmatterBlock(_);if(!S)throw new Error(`Expected frontmatter block after update: ${f.path}`);let I=S.endsWith(`
`)?"":`
`;await this.vault.modify(f,S+I+(n.systemPrompt||""))}else{let _=this.buildProjectFileContent(y,a,{createdMs:m,lastUsedMs:v});await this.vault.adapter.write(s,_)}let w={project:{...n,created:m,UsageTimestamps:v},filePath:s,folderName:a};return S$(w),j(`[Projects] Updated project: ${r} -> ${s}`),w}catch(f){if(d&&a!==o.folderName)try{let p=c(o.folderName),m=c(a),h=this.vault.getAbstractFileByPath(m);h instanceof Ig.TFolder?await this.vault.rename(h,p):await this.vault.adapter.rename(m,p),W(`[Projects] Rolled back folder rename "${a}" \u2192 "${o.folderName}" after write failure`)}catch(p){H(`[Projects] Failed to rollback folder rename for ${r}`,p)}throw f}finally{Ed(s),d&&Ed(d)}}async deleteProject(e){let n=(e||"").trim(),r=mo(n);if(!r){W(`[Projects] deleteProject: not found: ${n}`);return}let{projectFolderPath:o}=Nd(r.filePath);try{Nf(r.filePath);let i=this.vault.getAbstractFileByPath(r.filePath);i instanceof Ig.TFile?await Bc(this.app,i):await this.vault.adapter.exists(r.filePath)&&await this.vault.adapter.remove(r.filePath),yJt(n),await UUt(this.app,o);try{let s=this.vault.getAbstractFileByPath(o);if(s instanceof Ig.TFolder&&s.children.length===0)await Bc(this.app,s);else if(await this.vault.adapter.exists(o)){let a=await this.vault.adapter.list(o);a.files.length===0&&a.folders.length===0&&await this.vault.adapter.rmdir(o,!1)}}catch(s){W(`[Projects] Failed to clean up empty project folder: ${o}`,s)}if(Ln()){let{clearProjectMarkers:s}=await Promise.resolve().then(()=>(wQt(),vQt));await s(this.app,n).catch(a=>H("[Projects] Failed to clear off-vault failure markers on delete",a))}j(`[Projects] Deleted project: ${n} -> ${o}`),BI(this.app).catch(s=>H("[Projects] Rescan after delete failed",s))}finally{Ed(r.filePath)}}async touchProjectLastUsed(e){let n=(e||"").trim(),r=mo(n);if(r)try{this.projectLastUsedManager.touch(n);let o=this.projectLastUsedManager.shouldPersist(n,r.project.UsageTimestamps);if(o===null)return;let i=(0,Ig.normalizePath)(r.filePath),s=await Dk(this.app,i);if(!s)return;let a=qb(i),l=o;try{if(a||Nf(i),xp(this.app,i))await this.app.fileManager.processFrontMatter(s,u=>{let d=Number(u[fb]),f=Number.isFinite(d)&&d>0?d:0;l=Math.max(f,o),f!==l&&(u[fb]=l)});else{let u=await uf(this.app,i),d=Number(u?.[fb]),f=Number.isFinite(d)&&d>0?d:0;l=Math.max(f,o),f!==l&&await kx(this.app,i,{[fb]:l})}}finally{a||Ed(i)}this.projectLastUsedManager.markPersisted(n,l);let c=mo(n);c&&S$({...c,project:{...c.project,UsageTimestamps:l}})}catch(o){H(`[Projects] Failed to touch last-used for projectId=${e}`,o)}}}});async function kbe(t,e){let n=e.project.systemPrompt??"";if(n.trim())try{let r=Nd(e.filePath).projectFolderPath;if(!await pme(t,r))return;await uY(t,r,n),await nl.getInstance(t).updateProject(e.project.id,{...e.project,systemPrompt:""}),j(`[Projects] Moved project instructions into ${r}/AGENTS.md`)}catch(r){W(`[Projects] Failed to move project instructions for "${e.folderName}"`,r)}}var DYe=b(()=>{db();pe();zI();Mv()});function TSr(t,e,n){return new Promise(r=>{let o=window.setTimeout(()=>r(n),e);t.then(i=>{window.clearTimeout(o),r(i)},()=>{window.clearTimeout(o),r(n)})})}function PSr(t,e){let n=r=>r.replace(/[/\\]+$/,"");return n(t)===n(e)}function UYe(t){return{path:t.source,type:t.kind==="file"?"nonMd":t.kind,error:t.error,usedStaleSnapshot:t.usedStaleSnapshot}}function MSr(t,e){return t.path!==e.source?!1:e.kind==="file"?t.type==="nonMd":t.type===e.kind}function OSr(t,e){return t.some(n=>n.kind===e.kind&&n.source===e.source)?t:[...t,{kind:e.kind,source:e.source}]}function xQt(t,e){return t.filter(n=>!(n.kind===e.kind&&n.source===e.source))}function NSr(t,e){return[...t.filter(n=>!(n.path===e.path&&n.type===e.type)),e]}var Km,bQt,ISr,ASr,FYe,_Qt,ESr,Ibe,SQt=b(()=>{pe();gJt();es();Se();ZJt();ut();zQ();Jh();Km=require("obsidian");Gf();KXt();H5();mYe();ok();YXt();JXt();XB();_S();eQt();Md();Jwe();nQt();oQt();db();DYe();Mv();zI();bQt=500,ISr=1500;ASr=Object.freeze([]),FYe=Object.freeze([]),_Qt=new Set,ESr=-1;Ibe=class{constructor(e,n,r){this.app=e;this.plugin=n;this.opts=r;this.backends=new Map;this.starting=new Map;this.sessions=new Map;this.chatUIStates=new Map;this.activeSessionId=null;this.activeProjectId=tr;this.lastActiveByScope=new Map;this.detachedFromTabIds=new Set;this.contextDirtySignatures=new Map;this.landingCaptureSignatures=new Map;this.lastSeenProjectContentEpochBySession=new Map;this.previousProjectRecords=[];this.firstSessionPromiseByScope=new Map;this.replacementCursorByChatInputId=new Map;this.resumedSessionPromiseById=new Map;this.latestHistoryLoadRequestId=0;this.pendingCreates=0;this.listeners=new Set;this.disposed=!1;this.startingBackendId=null;this.lastError=null;this.lastErrorSeq=0;this.pendingBackendRestarts=new Map;this.restartingBackends=new Set;this.preloadStatus=new Map;this.sessionState=new Map;this.readOnlyFanoutSessions=new Set;this.defaultApplyChains=new Map;if(Km.Platform.isMobile)throw new Error("AgentSessionManager is desktop only");this.preloader=r.modelPreloader,this.fanoutOrchestrator=new _be(this.createFanoutHost()),this.settingsUnsub=zr((o,i)=>this.onDefaultSelectionsChanged(o,i)),this.contentTracker=new xbe(this.app),this.contentTrackerUnsubscribe=this.contentTracker.onContentChanged(o=>this.markProjectContextDirty(o)),this.setupProjectRecordChangeMonitor()}getSessionState(e){let n=this.sessionState.get(e);return n||(n={},this.sessionState.set(e,n)),n}onDefaultSelectionsChanged(e,n){let r=e.agentMode?.backends,o=n.agentMode?.backends;for(let i of this.sessions.values()){if(i.getStatus()==="closed")continue;let s=i.backendId,a=r?.[s]?.defaultModel??null,l=o?.[s]?.defaultModel??null;if(a?.baseModelId===l?.baseModelId&&a?.effort===l?.effort)continue;let c=this.opts.resolveDescriptor(s);c&&this.enqueueDefaultApply(i,c)}}enqueueDefaultApply(e,n){let r=e.backendId,i=(this.defaultApplyChains.get(e.internalId)??Promise.resolve()).then(()=>e.ready).then(()=>{if(e.getStatus()==="closed")return;let s=this.getDefaultSelection(r);if(s)return n.applySelection(e,s)}).catch(s=>W(`[AgentMode] re-applying default model for ${r} failed`,s)).finally(()=>{this.defaultApplyChains.get(e.internalId)===i&&this.defaultApplyChains.delete(e.internalId)});this.defaultApplyChains.set(e.internalId,i)}isReadOnlyFanoutSession(e){return this.readOnlyFanoutSessions.has(e)}runFanoutTurn(e){return this.fanoutOrchestrator.run(e)}createFanoutHost(){return{ensureBackendForFanout:async e=>{let n=this.resolveDescriptor(e);return{proc:await this.ensureBackend(e,n),descriptor:n}},getDefaultSelection:e=>this.getDefaultSelection(e),getDisplayName:e=>this.resolveDescriptor(e).displayName,getCwd:()=>{let e=this.app.vault.adapter;return e instanceof Km.FileSystemAdapter?e.getBasePath():null},registerReadOnlySession:e=>(this.readOnlyFanoutSessions.add(e),()=>this.readOnlyFanoutSessions.delete(e)),excludeSubSessionFromHistory:(e,n)=>{this.opts.sessionIndex?.deleteSession(e,n)}}}setupProjectRecordChangeMonitor(){this.previousProjectRecords=$p(),this.projectRecordsUnsubscriber?.(),this.projectRecordsUnsubscriber=vJt(e=>{this.handleProjectRecordsChanged(e)})}handleProjectRecordsChanged(e){if(this.disposed)return;let n=this.previousProjectRecords;this.previousProjectRecords=e;let r=new Set(e.map(o=>o.project.id));for(let o of this.contextDirtySignatures.keys())r.has(o)||this.contextDirtySignatures.delete(o);for(let o of e){let i=n.find(l=>l.project.id===o.project.id);if(!i)continue;let s=DI(o);if(DI(i)===s)continue;let a=o.project.id;this.contentTracker.bumpEpoch(a),this.markProjectContextDirty(a,o),a===this.activeProjectId&&this.warmProjectContext(a)}}markProjectContextDirty(e,n=mo(e)){if(this.disposed||e===tr||!n)return;let r=tYe(DI(n),this.contentTracker.getEpoch(e));this.contextDirtySignatures.set(e,r)}warmProjectContext(e){if(this.disposed||e===tr)return;let n;try{n=this.resolveSessionCwd(e)}catch{return}cYe(this.app,e,n,void 0,void 0,this.currentContextRevisionKey(e)).catch(r=>W(`[AgentMode] background context warm failed for ${e}`,r))}currentContextRevisionKey(e){let n=mo(e);if(n)return tYe(DI(n),this.contentTracker.getEpoch(e))}isProjectContextDirty(e){return this.contextDirtySignatures.has(e)}clearContextDirtyIfCaptured(e,n,r){n===void 0||r===void 0||this.contextDirtySignatures.get(e)===n&&CJt(n,r)&&this.contextDirtySignatures.delete(e)}getProjectContextUpdates(e,n){if(n===tr)return null;this.contentTracker.flushNow();let r=this.contentTracker.getEpoch(n),o=this.lastSeenProjectContentEpochBySession.get(e)??0;return r<=o?null:{epoch:r,block:rQt()}}markProjectContextUpdatesDelivered(e,n){let r=this.lastSeenProjectContentEpochBySession.get(e)??0;n>r&&this.lastSeenProjectContentEpochBySession.set(e,n)}async getChatHistoryItems(e){let n=this.opts.persistenceManager,r=this.opts.sessionIndex;if(!n&&!r)return FYe;let o=this.collectLiveAttentionPaths(),i=[],s=[];if(n){i=await n.getAgentChatHistoryFiles();let l=this.plugin.getChatHistoryLastAccessedAtManager();s=await Promise.all(i.map(async c=>{let u=await this.readSessionRefFromFile(c.path),d=sbe(this.app,c,l);return{item:o.has(d.id)?{...d,needsAttention:!0}:d,backendId:u?.backendId,sessionId:u?.sessionId}}))}if(e&&e!==tr){let l=await Promise.all(i.map(async(f,p)=>((await dYe(this.app,f.path))?.trim()||tr)===e?s[p]:null)),c=await this.dropNonLocalMarkdownEntries(l.filter(f=>f!==null));if(!r){let f=c.map(p=>p.item);return f.length===0?FYe:f}await this.refreshNativeSessionsFromBackends();let u=(await r.getEntries()).filter(f=>f.projectId===e),d=pYe(c,u);return d.length===0?FYe:d}if(s=await this.dropNonLocalMarkdownEntries(s),!r)return s.map(l=>l.item);await this.refreshNativeSessionsFromBackends();let a=await r.getEntries();return pYe(s,a)}collectLiveAttentionPaths(){let e=new Set;for(let[n,r]of this.sessions){if(!r.getNeedsAttention())continue;let o=this.sessionState.get(n)?.path;o&&e.add(o)}return e}recentChatIdsForSession(e,n){let r=[],o=this.sessionState.get(e)?.path;o&&r.push(o);let i=n.getBackendSessionId();return i&&r.push(B5(n.backendId,i)),r}getRunningChatIds(){let e=new Set;for(let[n,r]of this.sessions)if(r.getStatus()==="running")for(let o of this.recentChatIdsForSession(n,r))e.add(o);return e.size===0?_Qt:e}getAttentionChatIds(){let e=new Set;for(let[n,r]of this.sessions)if(r.getNeedsAttention())for(let o of this.recentChatIdsForSession(n,r))e.add(o);return e.size===0?_Qt:e}async updateChatTitle(e,n){let r=z5(e);if(r){let i=this.opts.sessionIndex;if(!i)throw new Error("Agent session index is not configured.");await i.setTitle(r.backendId,r.sessionId,n),this.findLiveSession(r.backendId,r.sessionId)?.setLabel(n);return}let o=this.opts.persistenceManager;if(!o)throw new Error("Agent chat persistence is not configured.");await o.updateTopic(e,n)}async deleteChatHistory(e){let n=this.opts.sessionIndex,r=z5(e);if(r){if(!n)throw new Error("Agent session index is not configured.");this.cancelPendingIndexTouch(r.backendId,r.sessionId),await n.deleteSession(r.backendId,r.sessionId);return}let o=this.opts.persistenceManager;if(!o)throw new Error("Agent chat persistence is not configured.");if(n){let i=await this.readSessionRefFromFile(e);i&&(this.cancelPendingIndexTouch(i.backendId,i.sessionId),await n.deleteSession(i.backendId,i.sessionId))}await o.deleteFile(e)}cancelPendingIndexTouch(e,n){for(let r of this.sessions.values()){if(r.backendId!==e||r.getBackendSessionId()!==n)continue;let o=this.sessionState.get(r.internalId);o?.indexTimer&&(window.clearTimeout(o.indexTimer),o.indexTimer=void 0)}}async readSessionRefFromFile(e){let n,r=this.app.vault.getAbstractFileByPath(e);if(r instanceof Km.TFile&&(n=this.app.metadataCache.getFileCache(r)?.frontmatter),!n)try{n=await uf(this.app,e)??void 0}catch{return null}let o=typeof n?.backendId=="string"?n.backendId.trim():"",i=typeof n?.sessionId=="string"?n.sessionId.trim():"";return!o||!i?null:{backendId:o,sessionId:i}}async refreshNativeSessionsFromBackends(){if(!this.opts.sessionIndex)return;let n=this.app.vault.adapter;if(!(n instanceof Km.FileSystemAdapter))return;let r=n.getBasePath(),o=this.getRunningProcsByBackend();if(o.size===0)return;let i=Array.from(o,([s,a])=>this.sweepNativeSessions(s,a,r));await TSr(Promise.allSettled(i).then(()=>{}),ISr,void 0)}getRunningProcsByBackend(){let e=new Map;for(let{backendId:n,proc:r}of this.preloader.getWarmProcs())r.isRunning()&&e.set(n,r);for(let[n,r]of this.backends)r.isRunning()&&e.set(n,r);return e}async dropNonLocalMarkdownEntries(e){let n=this.app.vault.adapter;if(!(n instanceof Km.FileSystemAdapter))return e;let r=n.getBasePath(),o=this.getRunningProcsByBackend(),i=await Promise.all(e.map(async a=>{if(!a.backendId||!a.sessionId)return!0;let l=o.get(a.backendId);if(!l?.sessionExistsLocally)return!0;let c;try{let u=(await dYe(this.app,a.item.id))?.trim()||tr;c=LYe(r,u)}catch{return!0}try{return await l.sessionExistsLocally({sessionId:a.sessionId,cwd:c})}catch{return!0}})),s=this.opts.sessionIndex;return s&&await Promise.all(e.map(async(a,l)=>{i[l]||!a.backendId||!a.sessionId||(this.cancelPendingIndexTouch(a.backendId,a.sessionId),await s.deleteSession(a.backendId,a.sessionId))})),e.filter((a,l)=>i[l])}async sweepNativeSessions(e,n,r){let o=this.opts.sessionIndex;if(!o)return;let i=this.opts.resolveDescriptor(e);if(!i?.summarizesSessionTitle)return;let s;try{({sessions:s}=await n.listSessions({cwd:r}))}catch(u){u instanceof da||W(`[AgentMode] listSessions sweep failed for ${e}`,u);return}let a=i.getProbeSessionId?.(Y()),l=Date.now(),c=[];for(let u of s){let d=PSr(u.cwd,r),f=d?void 0:XXt(r,u.cwd);if(!d&&!f||a&&u.sessionId===a||this.readOnlyFanoutSessions.has(u.sessionId))continue;let p=u.title?.trim();if(!p||p.startsWith(NYe))continue;let m=u.updatedAt?Date.parse(u.updatedAt):NaN,h=Number.isFinite(m)&&m>0?m:l;c.push({backendId:e,sessionId:u.sessionId,title:p,createdAtMs:h,lastAccessedAtMs:h,projectId:f})}c.length>0&&await o.mergeDiscoveredSessions(c)}async getOrCreateActiveSession(){if(this.disposed)throw new Error("AgentSessionManager has been shut down");let e=this.getActiveSession();if(e&&e.projectId===this.activeProjectId&&e.getStatus()!=="closed")return e;let n=this.activeProjectId,r=this.firstSessionPromiseByScope.get(n);if(r)return r;let o=this.createSession(void 0,n);this.firstSessionPromiseByScope.set(n,o);try{return await o}finally{this.firstSessionPromiseByScope.delete(n)}}async createSession(e,n=this.activeProjectId,r,o){if(this.disposed)throw new Error("AgentSessionManager has been shut down");let i=e??Y().agentMode?.activeBackend??"opencode",s=this.opts.resolveDescriptor(i)?i:"opencode",a=this.lastErrorSeq,l=n===tr?void 0:mo(n);await this.ensureScopeInstructions(n,l);let c=l?DQ(this.app,l):void 0,u=this.resolveSessionCwd(n);n!==tr&&this.contentTracker.flushNow();let d=n===tr?0:this.contentTracker.getEpoch(n),f=n===tr?void 0:this.contextDirtySignatures.get(n),p=n===tr?void 0:this.beginContextMaterialization(n,u,void 0,this.currentContextRevisionKey(n)),m=this.resolveDescriptor(s);this.pendingCreates++,this.startingBackendId=s,this.notify();let h;try{h=await this.ensureBackend(s,m)}catch(_){throw this.setLastError(kt(_)),this.finishPendingCreate(),_}if(this.disposed)throw this.finishPendingCreate(),new Error("AgentSessionManager was shut down during session creation");let g=r??this.getDefaultSelection(s)??void 0,v=Co(),y=o??Co(),w=KQ.start({backend:h,cwd:u,internalId:v,chatInputId:y,backendId:s,projectId:n,defaultModelSelection:g,getDescriptor:()=>this.opts.resolveDescriptor(s),runFanoutTurn:_=>this.runFanoutTurn(_),getDisplayName:_=>this.resolveDescriptor(_).displayName,getApp:()=>this.app,contextReady:p,...n!==tr?{getProjectContextUpdates:()=>this.getProjectContextUpdates(v,n),markProjectContextUpdatesDelivered:_=>this.markProjectContextUpdatesDelivered(v,_)}:{}});return this.sessions.set(w.internalId,w),this.chatUIStates.set(w.internalId,new NQ(w)),c?this.landingCaptureSignatures.set(w.internalId,c):this.landingCaptureSignatures.delete(w.internalId),this.detachedFromTabIds.delete(w.internalId),this.lastActiveByScope.set(n,w.internalId),n===this.activeProjectId&&(this.activeSessionId=w.internalId),this.attachAutoSave(w),this.attachAttentionTracking(w),this.notify(),p&&p.then(_=>{if(this.disposed||this.sessions.get(v)!==w||_.contextSignature===void 0)return;let S=this.lastSeenProjectContentEpochBySession.get(v);(S===void 0||d>S)&&this.lastSeenProjectContentEpochBySession.set(v,d)}).catch(()=>{}),w.ready.then(async()=>{if(p){let _=await p;!this.disposed&&this.sessions.get(v)===w&&_.contextSignature!==void 0&&this.clearContextDirtyIfCaptured(n,f,_.contextSignature)}if(m.applyInitialSessionConfig)try{await m.applyInitialSessionConfig(w,Y(),g)}catch(_){W(`[AgentMode] applyInitialSessionConfig failed for ${s}; continuing`,_)}this.lastErrorSeq===a&&(this.lastError=null),j(`[AgentMode] session ready (internal=${w.internalId} backend-id=${w.getBackendSessionId()} backend=${s}); pool size=${this.sessions.size}`),await RYe(w,this.getDefaultMode(s))}).catch(_=>{this.setLastError(kt(_))}).finally(()=>this.finishPendingCreate()),w}setLastError(e){this.lastError=e,this.lastErrorSeq++}finishPendingCreate(){this.pendingCreates--,this.pendingCreates===0&&(this.startingBackendId=null),this.notify()}resolveDescriptor(e){let n=this.opts.resolveDescriptor(e);if(!n)throw new Error(`Unknown backend "${e}". Did you forget to register it?`);return n}resolveSessionCwd(e){let n=this.app.vault.adapter;if(!(n instanceof Km.FileSystemAdapter))throw new Error("Agent Mode requires desktop Obsidian (FileSystemAdapter).");return LYe(n.getBasePath(),e)}beginContextMaterialization(e,n,r,o){let i={},s=[],a=[],l="resolve",u=!on.get(my)[e]?.blocking;u&&this.setContextLoadState(e,{phase:"resolve",blocking:!0});let d=()=>{this.setContextLoadState(e,{phase:l,blocking:!0,...i,failedSources:s,processingSources:a.length>0?a:void 0})},f=u?p=>{switch(p.phase){case"failures":s=p.failures.map(UYe);return;case"itemStart":a=OSr(a,p.item),s=s.filter(m=>!MSr(m,p.item)),d();return;case"itemFailed":a=xQt(a,p.item),s=NSr(s,UYe(p.failure)),d();return;case"itemSettled":a=xQt(a,p.item),d();return;case"resolve":i.resolved=p.resolved,l="resolve",d();return;case"prefetch":i.prefetch={done:p.done,total:p.total},l="prefetch",d();return;case"parse":i.parsed={done:p.done,total:p.total},l="parse",d();return}}:void 0;return cYe(this.app,e,n,f,r,o).then(p=>(u&&this.setContextLoadState(e,{phase:"done",blocking:!1,...i,failedSources:s}),p)).catch(p=>(W(`[AgentMode] project context materialize failed for ${e}; continuing`,p),u&&this.setContextLoadState(e,{phase:"done",blocking:!1,failedSources:[{path:"Project context",type:"nonMd",error:kt(p)}]}),lYe))}setContextLoadState(e,n){on.set(my,r=>({...r,[e]:n}))}rematerializeContext(e){if(e===tr||on.get(my)[e]?.blocking)return!1;let n;try{n=this.resolveSessionCwd(e)}catch(r){return this.setContextLoadState(e,{phase:"done",blocking:!1,failedSources:[{path:"Project context",type:"nonMd",error:kt(r)}]}),!1}return this.beginContextMaterialization(e,n,!0,this.currentContextRevisionKey(e)),!0}async rematerializeSource(e,n){if(e===tr)return!1;let r=on.get(my)[e];if(r?.blocking)return!1;let o=d=>d.path===n.source&&(n.kind==="file"?d.type==="nonMd":d.type===n.kind),i=d=>d.kind===n.kind&&d.source===n.source,s=r?.retryingSources??[];if(s.some(i))return!1;this.setContextLoadState(e,{...r??{phase:"done"},blocking:!1,failedSources:(r?.failedSources??[]).filter(d=>!o(d)),retryingSources:[...s,n]});let a=await GJt(this.app,e,n),l=on.get(my)[e];if(l?.blocking)return!1;let c=(l?.failedSources??[]).filter(d=>!o(d)),u=(l?.retryingSources??[]).filter(d=>!i(d));return this.setContextLoadState(e,{...l??{phase:"done"},blocking:!1,retryingSources:u.length>0?u:void 0,failedSources:[...c,...a.map(UYe)]}),!0}getActiveProjectId(){return this.activeProjectId}getSessionsForScope(e){let n=[];for(let r of this.sessions.values())r.projectId===e&&(this.detachedFromTabIds.has(r.internalId)||n.push(r));return n.length===0?ASr:n}getSessionIdsForScope(e){let n=[];for(let r of this.sessions.values())r.projectId===e&&(this.detachedFromTabIds.has(r.internalId)||n.push(r.internalId));return n}async enterProject(e){if(this.disposed)return;if(e!==tr&&!mo(e)){new Km.Notice("This project no longer exists. Restore it to open its chats.");return}let n=this.getActiveSession();if(e===this.activeProjectId&&n&&n.projectId===e&&n.getStatus()!=="closed")return;let r=this.activeProjectId,o=this.activeSessionId;if(this.parkActiveScope(),this.activeProjectId=e,e!==tr){this.contentTracker.flushNow();let a=this.isProjectContextDirty(e)?null:this.pickReusableLandingSession(e);if(this.detachSessionsForProjectEntry(e,{includeEmpty:!a}),a){this.detachedFromTabIds.delete(a.internalId),this.activeSessionId=a.internalId,this.lastActiveByScope.set(e,a.internalId),a.clearNeedsAttention(),this.notify(),this.touchProjectUsage(e);return}this.activeSessionId=null,this.notify(),await this.spawnEnteredScopeOrRollback(e,r,o),this.touchProjectUsage(e);return}let i=this.restoreScopeActiveSession(e);if(i){this.activeSessionId=i.internalId,this.lastActiveByScope.set(e,i.internalId),i.clearNeedsAttention(),this.notify(),this.touchProjectUsage(e);return}this.activeSessionId=null,this.notify(),await this.getOrCreateActiveSession(),this.touchProjectUsage(e)}detachSessionsForProjectEntry(e,n){for(let r of this.sessions.values())r.projectId===e&&r.getStatus()!=="closed"&&(!n.includeEmpty&&!r.hasUserVisibleMessages()||this.detachedFromTabIds.add(r.internalId))}pickReusableLandingSession(e){let n=this.currentLandingCaptureSignature(e);if(!n||!SJt(n))return null;let r=a=>this.isReusableLandingShell(a,e)&&!this.detachedFromTabIds.has(a.internalId)&&this.landingCaptureSignatures.get(a.internalId)===n,o=this.lastActiveByScope.get(e),i=o?this.sessions.get(o):void 0;if(i&&r(i))return i;let s=null;for(let a of this.sessions.values())r(a)&&(s=a);return s}isReusableLandingShell(e,n){return e.projectId===n&&(e.getStatus()==="idle"||e.getStatus()==="starting")&&!e.hasUserVisibleMessages()}currentLandingCaptureSignature(e){if(e===tr)return null;let n=mo(e);return n?DQ(this.app,n):null}async ensureScopeInstructions(e,n){if(e===tr){await gme(this.app,"","");return}n&&(await gme(this.app,"",""),await kbe(this.app,n),await gme(this.app,Nd(n.filePath).projectFolderPath,""))}touchProjectUsage(e){this.disposed||e===tr||this.activeProjectId!==e||nl.getInstance(this.app).touchProjectLastUsed(e)}async exitProject(){await this.enterProject(tr)}parkActiveScope(){let e=this.getActiveSession();e&&e.getStatus()!=="closed"&&this.lastActiveByScope.set(e.projectId,e.internalId)}restoreScopeActiveSession(e){let n=this.lastActiveByScope.get(e);if(n){let o=this.sessions.get(n);if(o&&o.getStatus()!=="closed")return o}let r=this.getSessionsForScope(e);return r.length>0?r[r.length-1]:null}setActiveScope(e){e!==this.activeProjectId&&(this.parkActiveScope(),this.activeProjectId=e)}rollbackHistoryLoadScope(e,n){this.activeProjectId===e&&(this.activeProjectId=n)}async spawnEnteredScopeOrRollback(e,n,r){try{await this.getOrCreateActiveSession()}catch(o){throw this.activeProjectId===e&&(this.activeProjectId=n,this.activeSessionId=r,this.notify()),o}}setDefaultBackend(e){Y().agentMode?.activeBackend!==e&&(En(n=>({agentMode:{...n.agentMode,activeBackend:e}})),this.notify())}getDefaultSelection(e){return Y().agentMode?.backends?.[e]?.defaultModel??null}async persistDefaultSelection(e,n){En(r=>{let o=r.agentMode.backends?.[e];return{agentMode:{...r.agentMode,backends:{...r.agentMode.backends,[e]:{...o??{},defaultModel:n}}}}})}async applySelection(e,n){let r=this.getActiveSession();if(!r||n?.expectBackendId&&r.backendId!==n.expectBackendId)return;let o=r.getState()?.model?.current;if(!o)return;let i=this.resolveDescriptor(r.backendId),s={baseModelId:e.baseModelId??o.baseModelId,effort:e.effort!==void 0?e.effort:o.effort};await i.applySelection(r,s)}async applyMode(e,n,r){let o=this.getActiveSession();if(!o||o.backendId!==e)return;let i=this.resolveDescriptor(e).getModeMapping?.(null,null),s=i?.kind==="setMode"?i.canonical[n]:void 0,a=s?{kind:"setMode",nativeId:s}:r;a.kind==="setMode"?await o.setMode(a.nativeId):await o.setConfigOption(a.configId,a.value),await this.persistDefaultMode(e,n)}getDefaultMode(e){return Y().agentMode?.backends?.[e]?.defaultMode??null}async persistDefaultMode(e,n){En(r=>{let o=r.agentMode.backends?.[e];return{agentMode:{...r.agentMode,backends:{...r.agentMode.backends,[e]:{...o??{},defaultMode:n}}}}})}getBackendProcess(e){return this.backends.get(e)??null}async restartBackend(e,n){if(this.disposed)return!1;let r=this.starting.get(e);if(r&&await r.catch(()=>{}),!this.backends.get(e))return this.refreshWarmProbe(e,n);if(this.hasBusySession(e)){let i=this.pendingBackendRestarts.get(e);return this.pendingBackendRestarts.set(e,i?`${i}; ${n}`:n),j(`[AgentMode] deferred ${e} backend restart: ${n}`),!0}return await this.restartBackendNow(e,n),!0}async onInstallStateChanged(e){if(this.disposed)return;let n=this.opts.resolveDescriptor(e)?.getInstallState(Y());if(n?.kind==="checking")return;if(n?.kind!=="ready"){await this.restartBackend(e,"binary no longer available"),this.preloader.clearCached(e),(!n||n.kind==="absent")&&this.preloadStatus.delete(e)&&this.notify();return}await this.restartBackend(e,"binary path changed")||this.registerPreload(e,this.preloader.preload(e))}refreshWarmProbe(e,n){if(this.disposed||!this.isBackendInstalled(e))return!1;let r=this.preloader.refresh(e);return r?(j(`[AgentMode] refreshing warm ${e} probe: ${n}`),this.registerPreload(e,r),!0):!1}isBackendInstalled(e){return this.opts.resolveDescriptor(e)?.getInstallState(Y())?.kind==="ready"}getCachedModelCatalog(e){return this.preloader.getCachedModelCatalog(e)}getEffortCatalog(e){return this.preloader.getEffortCatalog(e)}subscribeModelCache(e){return this.preloader.subscribe(e)}getModelCacheSignature(e){let n=this.getPreloadStatus(e),r=_2t(this.getCachedModelCatalog(e)),o=this.getEffortCatalog(e),i=o?Object.keys(o).sort().map(s=>`${s}:${o[s].map(a=>a.value??"").join(",")}`).join("|"):"";return`${n}#${r}#${i}`}preloadModels(e){return this.preloader.preload(e)}registerPreload(e,n){this.preloadStatus.set(e,"pending"),this.notify(),n.then(()=>{this.disposed||(this.preloadStatus.set(e,"ready"),this.notify())},()=>{this.disposed||(this.preloadStatus.set(e,"error"),this.notify())})}isPreloadReady(e){let n=e??Y().agentMode?.activeBackend;if(!n)return!0;let r=this.preloadStatus.get(n);return r===void 0||r==="ready"||r==="error"}getPreloadStatus(e){return this.preloadStatus.get(e)??"absent"}async closeSession(e){let n=this.sessions.get(e);if(!n)return;let r=n.projectId,i=this.getSessionIdsForScope(r).indexOf(e);try{await n.cancel()}catch(s){W("[AgentMode] cancel during closeSession failed",s)}await this.drainAutoSave(n);try{await n.dispose()}catch(s){W("[AgentMode] dispose during closeSession failed",s)}if(this.detachAutoSave(e),this.sessions.delete(e),this.chatUIStates.delete(e),this.landingCaptureSignatures.delete(e),this.lastSeenProjectContentEpochBySession.delete(e),this.detachedFromTabIds.delete(e),this.lastActiveByScope.get(r)===e&&this.lastActiveByScope.delete(r),this.activeSessionId===e){let s=this.getSessionIdsForScope(r),a=QXt(s,i,this.lastActiveByScope.get(r));this.activeSessionId=a,a&&this.lastActiveByScope.set(r,a)}this.notify()}setActiveSession(e){let n=this.sessions.get(e);n&&this.activeSessionId!==e&&(n.projectId!==this.activeProjectId&&(this.parkActiveScope(),this.activeProjectId=n.projectId),this.detachedFromTabIds.delete(e),this.activeSessionId=e,this.lastActiveByScope.set(n.projectId,e),n.clearNeedsAttention(),this.notify())}async replaceSessionInPlace(e,n,r={}){let o=this.sessions.get(e)?.chatInputId??e,i=this.replacementCursorByChatInputId.get(o)??Promise.resolve(e),s=i.then(l=>this.replaceSessionInPlaceOnce(l,n,r)),a=s.then(l=>l.internalId,()=>i);this.replacementCursorByChatInputId.set(o,a);try{return await s}finally{this.replacementCursorByChatInputId.get(o)===a&&this.replacementCursorByChatInputId.delete(o)}}async replaceSessionInPlaceOnce(e,n,r={}){let o=Array.from(this.sessions.keys()).indexOf(e),i=this.sessions.get(e),s=i?.projectId??this.activeProjectId,a=r.preserveChatInput?i?.chatInputId:void 0,l=await this.createSession(n,s,r.seedSelection,a);return o>=0&&(this.moveMapEntry(this.sessions,l.internalId,o),this.moveMapEntry(this.chatUIStates,l.internalId,o),this.notify()),this.closeSession(e).catch(c=>W("[AgentMode] closeSession during replaceSessionInPlace failed",c)),l}moveMapEntry(e,n,r){if(!e.has(n))return;let o=Array.from(e.entries()),i=o.findIndex(([a])=>a===n);if(i===-1||i===r)return;let[s]=o.splice(i,1);o.splice(r,0,s),e.clear();for(let[a,l]of o)e.set(a,l)}renameSession(e,n){let r=this.sessions.get(e);r&&(r.setLabel(n),this.notify())}getIsStarting(){return this.startingBackendId!==null}getStartingBackendId(){return this.startingBackendId}getLastError(){return this.lastError}getSession(e){return this.sessions.get(e)??null}getSessionByBackendId(e){for(let n of this.sessions.values())if(n.getBackendSessionId()===e)return n;return null}findLiveSession(e,n){for(let r of this.sessions.values())if(r.backendId===e&&r.getBackendSessionId()===n&&r.getStatus()!=="closed")return r;return null}getChatUIState(e){return this.chatUIStates.get(e)??null}getActiveSession(){return this.activeSessionId?this.sessions.get(this.activeSessionId)??null:null}getActiveChatUIState(){return this.activeSessionId?this.chatUIStates.get(this.activeSessionId)??null:null}getSessions(){return Array.from(this.sessions.values())}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(){for(let e of this.listeners)try{e()}catch(n){H("[AgentMode] manager listener threw",n)}}async cancel(){await this.getActiveSession()?.cancel()}async shutdown(){if(this.disposed)return;this.disposed=!0,this.settingsUnsub(),this.projectRecordsUnsubscriber?.(),this.projectRecordsUnsubscriber=void 0,this.contentTrackerUnsubscribe?.(),this.contentTrackerUnsubscribe=void 0,this.contentTracker.dispose(),j(`[AgentMode] shutdown (pool size=${this.sessions.size}, backends=${this.backends.size})`);let e=Array.from(this.sessions.values());await Promise.allSettled(e.map(r=>this.drainAutoSave(r)));for(let r of Array.from(this.sessionState.keys()))this.detachAutoSave(r);await Promise.allSettled(e.map(async r=>{try{await r.cancel()}catch(o){H("[AgentMode] cancel during shutdown failed",o)}try{await r.dispose()}catch(o){H("[AgentMode] dispose during shutdown failed",o)}})),this.sessions.clear(),this.chatUIStates.clear(),this.landingCaptureSignatures.clear(),this.lastSeenProjectContentEpochBySession.clear(),this.activeSessionId=null,this.activeProjectId=tr,this.lastActiveByScope.clear(),this.detachedFromTabIds.clear(),this.contextDirtySignatures.clear(),this.firstSessionPromiseByScope.clear();let n=Array.from(this.backends.values());await Promise.allSettled(n.map(async r=>{try{await r.shutdown()}catch(o){H("[AgentMode] backend shutdown failed",o)}})),this.backends.clear(),this.starting.clear(),this.startingBackendId=null,this.listeners.clear(),this.preloadStatus.clear(),this.preloader.shutdown(),await this.opts.sessionIndex?.flush()}async loadSessionFromHistory(e){if(!this.opts.persistenceManager)throw new Error("Agent chat persistence is not configured.");if(this.disposed)throw new Error("AgentSessionManager has been shut down");let n=++this.latestHistoryLoadRequestId;for(let[l,c]of this.sessionState.entries()){if(c.path!==e.path)continue;let u=this.sessions.get(l);if(u&&u.getStatus()!=="closed")return this.setActiveSession(l),u;c.path=void 0}let r=this.activeSessionId,o=await this.opts.persistenceManager.loadFile(e),i=o.projectId;if(i!==tr&&!mo(i))throw new Km.Notice("This chat belongs to a project that no longer exists."),new m6(i);let s=this.activeProjectId;this.setActiveScope(i);let a;try{a=(o.sessionId?await this.tryResumeSessionFromHistory(o.backendId,o.sessionId,i):null)??await this.createSession(o.backendId,i)}catch(l){throw this.rollbackHistoryLoadScope(i,s),l}return a.loadDisplayMessages(o.messages),a.seedSessionUsage(o.usage),o.label&&a.setLabel(o.label),this.getSessionState(a.internalId).path=e.path,o.sessionId&&this.opts.sessionIndex?.touch(o.backendId,o.sessionId),n===this.latestHistoryLoadRequestId&&(this.setActiveSession(a.internalId),this.absorbIntoEmptyActiveTab(a,r),this.notify()),a}absorbIntoEmptyActiveTab(e,n){if(!n||n===e.internalId)return;let r=this.sessions.get(n);if(!r||r.hasUserVisibleMessages())return;let o=Array.from(this.sessions.keys()).indexOf(n);o>=0&&(this.moveMapEntry(this.sessions,e.internalId,o),this.moveMapEntry(this.chatUIStates,e.internalId,o)),this.closeSession(n).catch(i=>W("[AgentMode] closing empty tab during history load failed",i))}async loadNativeSessionFromHistory(e,n){if(this.disposed)throw new Error("AgentSessionManager has been shut down");let r=++this.latestHistoryLoadRequestId,o=this.findLiveSession(e,n);if(o)return this.setActiveSession(o.internalId),o;let i=this.activeSessionId,s=this.opts.sessionIndex,a=s?await s.getEntry(e,n):null,l=a?.projectId??tr;if(l!==tr&&!mo(l))throw new Km.Notice("This chat belongs to a project that no longer exists."),new m6(l);let c=this.activeProjectId;this.setActiveScope(l);let u;try{let d=await this.tryResumeSessionFromHistory(e,n,l);if(!d)throw new Error(`Could not resume session ${n} from the ${e} session store.`);u=d}catch(d){throw this.rollbackHistoryLoadScope(l,c),d}return await this.hydrateResumedTranscript(u,e,n),a?.title&&u.restoreLabel(a.title,a.titleSource==="user"?"user":"agent"),s&&await s.touch(e,n),r===this.latestHistoryLoadRequestId&&(this.setActiveSession(u.internalId),this.absorbIntoEmptyActiveTab(u,i),this.notify()),u}async hydrateResumedTranscript(e,n,r){let o=this.backends.get(n);if(o?.readPersistedTranscript&&!(e.store.getDisplayMessages().length>0))try{let i=await o.readPersistedTranscript({sessionId:r,cwd:this.resolveSessionCwd(e.projectId)});i.length>0&&e.loadDisplayMessages(i)}catch(i){W(`[AgentMode] could not hydrate transcript for ${r}`,i)}}async tryResumeSessionFromHistory(e,n,r){let o=this.findLiveSession(e,n);if(o)return o;let i=B5(e,n),s=this.resumedSessionPromiseById.get(i);if(s)return s;let a=this.resumeSessionFromHistory(e,n,r).finally(()=>{this.resumedSessionPromiseById.get(i)===a&&this.resumedSessionPromiseById.delete(i)});return this.resumedSessionPromiseById.set(i,a),a}async resumeSessionFromHistory(e,n,r){await this.ensureScopeInstructions(r,r===tr?void 0:mo(r));let o=this.resolveSessionCwd(r);r!==tr&&this.contentTracker.flushNow();let i=r===tr?void 0:this.beginContextMaterialization(r,o,void 0,this.currentContextRevisionKey(r)),s=this.resolveDescriptor(e);this.pendingCreates++,this.startingBackendId=e,this.notify();let a;try{a=await this.ensureBackend(e,s)}catch(f){return this.setLastError(kt(f)),this.finishPendingCreate(),null}if(this.disposed)return this.finishPendingCreate(),null;let l=i?(await i).additionalDirectories:void 0;if(this.disposed)return this.finishPendingCreate(),null;let c=null;try{c=await a.loadSession({sessionId:n,cwd:o,projectId:r,additionalDirectories:l})}catch(f){if(!(f instanceof da))return W(`[AgentMode] loadSession failed for ${n}`,f),this.finishPendingCreate(),null}if(!c)try{c=await a.resumeSession({sessionId:n,cwd:o,projectId:r,additionalDirectories:l})}catch(f){return f instanceof da?j(`[AgentMode] backend ${e} does not support session resume; falling back to fresh session`):W(`[AgentMode] resumeSession failed for ${n}`,f),this.finishPendingCreate(),null}if(this.disposed)return this.finishPendingCreate(),null;let u=Co(),d=new KQ({backend:a,backendSessionId:c.sessionId,internalId:u,backendId:e,projectId:r,initialState:c.state,cwd:o,getDescriptor:()=>this.opts.resolveDescriptor(e),runFanoutTurn:f=>this.runFanoutTurn(f),getDisplayName:f=>this.resolveDescriptor(f).displayName,getApp:()=>this.app,...r!==tr?{getProjectContextUpdates:()=>this.getProjectContextUpdates(u,r),markProjectContextUpdatesDelivered:f=>this.markProjectContextUpdatesDelivered(u,f)}:{}});if(c.transcript?.length&&d.loadDisplayMessages(c.transcript),s.applyInitialSessionConfig)try{await s.applyInitialSessionConfig(d,Y())}catch(f){W(`[AgentMode] applyInitialSessionConfig failed for resumed ${e} session; continuing`,f)}return await RYe(d,this.getDefaultMode(e)),this.disposed?(await d.dispose(),this.finishPendingCreate(),null):(r!==tr&&this.lastSeenProjectContentEpochBySession.set(u,ESr),this.sessions.set(d.internalId,d),this.chatUIStates.set(d.internalId,new NQ(d)),this.detachedFromTabIds.delete(d.internalId),this.attachAutoSave(d),this.attachAttentionTracking(d),this.lastError=null,this.finishPendingCreate(),j(`[AgentMode] resumed session (internal=${d.internalId} backend-id=${n} backend=${e})`),d)}attachAutoSave(e){let n=this.opts.persistenceManager,r=this.opts.sessionIndex;if(!n&&!r)return;let o=()=>{this.scheduleAutoSave(e),this.scheduleIndexTouch(e)},i=e.subscribe({onMessagesChanged:o,onStatusChanged:()=>{},onLabelChanged:o});this.getSessionState(e.internalId).unsub=i}scheduleAutoSave(e){if(!Y().autosaveChat)return;let n=this.getSessionState(e.internalId);n.timer&&window.clearTimeout(n.timer),n.timer=window.setTimeout(()=>{n.timer=void 0,this.flushAutoSave(e).catch(r=>W(`[AgentMode] auto-save failed for ${e.internalId}`,r))},bQt)}scheduleIndexTouch(e){if(!this.opts.sessionIndex)return;let n=this.getSessionState(e.internalId);n.indexTimer&&window.clearTimeout(n.indexTimer),n.indexTimer=window.setTimeout(()=>{n.indexTimer=void 0,this.flushIndexTouch(e).catch(r=>W(`[AgentMode] session-index update failed for ${e.internalId}`,r))},bQt)}async flushIndexTouch(e){let n=this.opts.sessionIndex;if(!n||!this.sessions.has(e.internalId))return;let r=e.getBackendSessionId();if(!r)return;let o=e.store.getDisplayMessages();if(o.length===0)return;let i=Date.now(),s=e.getLabel(),a=s??lbe(o),l=a?s&&e.getLabelSource()==="user"?"user":"agent":void 0;await n.recordSession({backendId:e.backendId,sessionId:r,title:a,titleSource:l,createdAtMs:o[0]?.timestamp?.epoch??i,lastAccessedAtMs:i,projectId:e.projectId===tr?void 0:e.projectId})}async saveActiveSession(){let e=this.getActiveSession();if(!e)return null;let n=this.sessionState.get(e.internalId);return n?.timer&&(window.clearTimeout(n.timer),n.timer=void 0),this.flushAutoSave(e)}async flushAutoSave(e){let n=this.opts.persistenceManager;if(!n||!this.sessions.has(e.internalId))return null;let r=e.store.getDisplayMessages();if(r.length===0)return null;let o=e.getLabel(),i=e.getBackendSessionId(),s=e.getSessionUsage(),a=r[r.length-1],l=a?.fanout?Object.values(a.fanout.answers).map(f=>`${f.status}:${f.text.length}`).join(",")+`|${a.fanout.summary.status}:${a.fanout.summary.text.length}`:"",c=`${o??""}-${i??""}-${r.length}-${a?.message??""}-${l}-${s?.updatedAt??""}`,u=this.getSessionState(e.internalId);if(u.signature===c)return u.path?{path:u.path}:null;let d=await n.saveSession(r,e.backendId,{label:o,existingPath:u.path,sessionId:i,projectId:e.projectId,usage:s??void 0});return d&&(u.path=d.path,u.signature=c),d}async drainAutoSave(e){let n=this.sessionState.get(e.internalId);if(n?.indexTimer){window.clearTimeout(n.indexTimer),n.indexTimer=void 0;try{await this.flushIndexTouch(e)}catch(r){W(`[AgentMode] drain session-index update failed for ${e.internalId}`,r)}}if(n?.timer){window.clearTimeout(n.timer),n.timer=void 0;try{await this.flushAutoSave(e)}catch(r){W(`[AgentMode] drain auto-save failed for ${e.internalId}`,r)}}}detachAutoSave(e){let n=this.sessionState.get(e);n&&(n.timer&&window.clearTimeout(n.timer),n.indexTimer&&window.clearTimeout(n.indexTimer),n.unsub?.(),n.attentionUnsub?.(),this.sessionState.delete(e))}attachAttentionTracking(e){let n=e.getStatus(),r=e.subscribe({onMessagesChanged:()=>{},onStatusChanged:o=>{let i=n==="running",s=o==="running";n=o,this.flushDeferredBackendRestartIfReady(e.backendId),i&&VXt.has(o)&&this.activeSessionId!==e.internalId&&e.markNeedsAttention(),i!==s&&this.notify()}});this.getSessionState(e.internalId).attentionUnsub=r}wirePrompters(e){e.setPermissionPrompter(this.opts.permissionPrompter),this.opts.askUserQuestionPrompter&&e.setAskUserQuestionPrompter?.(this.opts.askUserQuestionPrompter),e.setReadOnlySessionPredicate?.(n=>this.isReadOnlyFanoutSession(n))}async ensureBackend(e,n){let r=this.backends.get(e);if(r&&r.isRunning())return r;let o=this.starting.get(e);if(o)return o;let i=(async()=>{this.isPreloadReady(e)||await this.preloader.preload(e);let s=this.preloader.takeWarm(e);if(s)return this.wirePrompters(s.proc),this.installBackendExitHandler(e,s.proc,n),this.backends.set(e,s.proc),s.proc;let a=n.createBackendProcess({plugin:this.plugin,app:this.app,clientVersion:this.plugin.manifest.version,descriptor:n});return a.start&&await a.start(),this.wirePrompters(a),this.installBackendExitHandler(e,a,n),this.backends.set(e,a),a})();this.starting.set(e,i);try{return await i}finally{this.starting.delete(e)}}installBackendExitHandler(e,n,r){n.onExit(()=>{this.backends.get(e)===n&&this.backends.delete(e);let o=Array.from(this.sessions.values()).filter(i=>i.backendId===e);if(o.length!==0){for(let i of o)this.detachAutoSave(i.internalId),this.sessions.delete(i.internalId),this.chatUIStates.delete(i.internalId),this.landingCaptureSignatures.delete(i.internalId),this.lastSeenProjectContentEpochBySession.delete(i.internalId),this.detachedFromTabIds.delete(i.internalId),this.lastActiveByScope.get(i.projectId)===i.internalId&&this.lastActiveByScope.delete(i.projectId),i.cancel().catch(()=>{}),i.dispose().catch(()=>{});if(this.activeSessionId&&!this.sessions.has(this.activeSessionId)){let i;for(let s of this.sessions.values())if(!this.detachedFromTabIds.has(s.internalId)){i=s;break}this.activeSessionId=i?.internalId??null,i&&(this.activeProjectId=i.projectId)}this.setLastError(`${r.displayName} backend exited unexpectedly.`),this.notify()}})}hasBusySession(e){return Array.from(this.sessions.values()).some(n=>{if(n.backendId!==e)return!1;let r=n.getStatus();return r==="starting"||r==="running"||r==="awaiting_permission"})}async flushDeferredBackendRestartIfReady(e){let n=this.pendingBackendRestarts.get(e);if(n&&!this.hasBusySession(e)){this.pendingBackendRestarts.delete(e);try{await this.restartBackendNow(e,n)}catch(r){this.setLastError(kt(r)),H(`[AgentMode] deferred ${e} backend restart failed`,r),this.notify()}}}async restartBackendNow(e,n){if(this.restartingBackends.has(e)){let i=this.pendingBackendRestarts.get(e);this.pendingBackendRestarts.set(e,i?`${i}; ${n}`:n);return}let r=this.backends.get(e);if(!r)return;this.restartingBackends.add(e),j(`[AgentMode] restarting ${e} backend: ${n}`);try{let i=Array.from(this.sessions.values()).filter(c=>c.backendId===e),s=i.find(c=>c.internalId===this.activeSessionId),a=this.isBackendInstalled(e)&&i.length>0&&s!==void 0,l=s?.projectId??this.activeProjectId;for(let c of i)await this.closeSession(c.internalId);if(await r.shutdown(),this.backends.get(e)===r&&this.backends.delete(e),this.preloader.clearCached(e),new Km.Notice(`${this.resolveDescriptor(e).displayName} refreshed.`),!this.disposed&&this.isBackendInstalled(e)){let c=this.preloader.preload(e);this.registerPreload(e,c),a&&!this.disposed&&(await c,await this.createSession(e,l))}this.notify()}finally{this.restartingBackends.delete(e)}let o=this.pendingBackendRestarts.get(e);if(o!==void 0&&!this.disposed){if(this.pendingBackendRestarts.delete(e),this.hasBusySession(e)){this.pendingBackendRestarts.set(e,o);return}try{await this.restartBackendNow(e,o)}catch(i){this.setLastError(kt(i)),H(`[AgentMode] queued ${e} backend restart failed`,i),this.notify()}}}}});function CQt(t,e){let n=Y(),r=new Map;for(let o of t){let i=o.getWireBaseId?.(e,n)??null;i&&r.set(o.id,i)}return r.size===0?[]:(En(o=>{let i={...o.agentMode.backends};for(let[s,a]of r)i[s]={...i[s]??{},defaultModel:{baseModelId:a,effort:null}};return{agentMode:{...o.agentMode,backends:i}}}),[...r.keys()])}var kQt=b(()=>{Se()});function BYe(t){let e=t.match(RSr);return e?Number.parseInt(e[1],10):null}async function zYe(t,e,n,r){let o=Fr(Fr(t,e),"SKILL.md");try{if(!await n.exists(o))return"absent";let i=BYe(await n.read(o));return i===null?"collision":r!==void 0&&i<r?"stale":"seeded"}catch{return"failed"}}function LSr(t,e){let n=t.match(IQt);return n?e.replace(IQt,`$1${n[2]}`):e}async function jYe(t,e){let n=e.replace(/^\/+|\/+$/g,"").split("/").filter(Boolean),r="";for(let o of n)r=r?`${r}/${o}`:o,await t.exists(r)||await t.mkdir(r)}async function Tbe(t){let{skillsFolderRelPath:e,fs:n}=t,r=t.skills??tW,o=[];await jYe(n,e);for(let i of r){let s=Fr(e,i.name),a=Fr(s,"SKILL.md"),l=null;if(await n.exists(a))try{l=await n.read(a);let c=BYe(l);if(c===null||c>=i.version&&await Promise.all(i.files.map(d=>n.exists(Fr(s,d.path)))).then(d=>d.every(Boolean)))continue}catch(c){H(`[Skills] could not read builtin skill ${i.name} for version check`,c)}try{await jYe(n,s);let c=l?LSr(l,i.skillMd):i.skillMd;for(let u of i.files){let d=Fr(s,u.path);await jYe(n,PU(d)),await n.write(d,u.content)}await n.write(a,c),o.push(i.name)}catch(c){H(`[Skills] failed to seed builtin skill ${i.name}`,c)}}return o.length>0&&j(`[Skills] seeded builtin skills: ${o.join(", ")}`),{seeded:o}}async function Pbe(t,e,n){let r=Fr(t,e),o=Fr(r,"SKILL.md");try{return!await n.exists(o)||BYe(await n.read(o))===null?!1:(await n.rmRecursive(r),j(`[Skills] removed de-gated builtin skill: ${e}`),!0)}catch(i){return H(`[Skills] failed to remove de-gated builtin skill ${e}`,i),!1}}var RSr,IQt,HYe=b(()=>{pe();rp();wX();RSr=/copilot-builtin-version:\s*"?(\d+)"?/;IQt=/^([ \t]*copilot-enabled-agents:[ \t]*)(.*)$/m});function Abe(t){let e=t.vault.adapter;return{exists:n=>e.exists(n),read:n=>e.read(n),write:(n,r)=>e.write(n,r),mkdir:n=>e.mkdir(n),rmRecursive:n=>e.rmdir(n,!0)}}async function TQt(t,e){let n=Abe(t);try{await Tbe({skillsFolderRelPath:e,fs:n,skills:[uS]})}catch{return"failed"}let r=await zYe(e,uS.name,n,uS.version);if(r==="collision")return"collision";if(r!=="seeded")return"failed";let o=Fr(e,uS.name);try{return(await Promise.all(uS.files.map(s=>n.exists(Fr(o,s.path))))).every(Boolean)?"installed":"failed"}catch{return"failed"}}async function PQt(t,e){let n=Abe(t);if(await Pbe(e,uS.name,n))return"removed";switch(await zYe(e,uS.name,n)){case"absent":return"removed";case"collision":return"collision";default:return"failed"}}var WYe=b(()=>{rp();wX();HYe()});function $Sr(t){let e=t.toolCall.kind,n=qpe(e)||e==="other",r=n?tY:Wpe,o=t.options.find(s=>r.includes(s.kind));if(!o)return{outcome:{outcome:"cancelled"}};let i={outcome:{outcome:"selected",optionId:o.optionId}};return n?{...i,denyMessage:"Read-only QA turn: vault-write tools are disabled."}:i}function AQt(t,e){return n=>{if(e?.(n.sessionId))return Promise.resolve($Sr(n));let r=t(n.sessionId);return r?n.toolCall.isPlanProposal?r.handlePlanProposalPermission(n):r.handleToolPermission(n):Promise.resolve({outcome:{outcome:"cancelled"}})}}function EQt(t){return e=>{let n=t(e.sessionId);return n?n.handleAskUserQuestion(e):Promise.resolve({})}}var MQt=b(()=>{tA();rz()});function v6(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var Npi,OQt=b(()=>{Npi=!!(typeof window<"u"&&window.document&&window.document.createElement)});function NQt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function VYe(...t){return e=>{let n=!1,r=t.map(o=>{let i=NQt(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():NQt(t[o],null)}}}}function JQ(...t){return RQt.useCallback(VYe(...t),t)}var RQt,Ebe=b(()=>{RQt=L(B(),1)});function $Qt(t,e=[]){let n=[];function r(i,s){let a=HI.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=HI.useMemo(()=>m,Object.values(m));return(0,LQt.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=HI.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>HI.createContext(s));return function(a){let l=a?.[t]||i;return HI.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,DSr(o,...e)]}function DSr(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return HI.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var HI,LQt,DQt=b(()=>{HI=L(B(),1),LQt=L(Mt(),1)});var FQt,E$,Mbe=b(()=>{FQt=L(B(),1),E$=globalThis?.document?FQt.useLayoutEffect:()=>{}});function UQt(t){let[e,n]=qYe.useState(FSr());return E$(()=>{t||n(r=>r??String(USr++))},[t]),t||(e?`radix-${e}`:"")}var qYe,FSr,USr,jQt=b(()=>{qYe=L(B(),1);Mbe();FSr=qYe[" useId ".trim().toString()]||(()=>{}),USr=0});function jSr(t,e){return BQt.useReducer((n,r)=>e[n][r]??n,t)}function BSr(t){let[e,n]=Gm.useState(),r=Gm.useRef(null),o=Gm.useRef(t),i=Gm.useRef("none"),s=t?"mounted":"unmounted",[a,l]=jSr(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return Gm.useEffect(()=>{let c=Obe(r.current);i.current=a==="mounted"?c:"none"},[a]),E$(()=>{let c=r.current,u=o.current;if(u!==t){let f=i.current,p=Obe(c);t?l("MOUNT"):p==="none"||c?.display==="none"?l("UNMOUNT"):l(u&&f!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,l]),E$(()=>{if(e){let c,u=e.ownerDocument.defaultView??window,d=p=>{let h=Obe(r.current).includes(CSS.escape(p.animationName));if(p.target===e&&h&&(l("ANIMATION_END"),!o.current)){let g=e.style.animationFillMode;e.style.animationFillMode="forwards",c=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=g)})}},f=p=>{p.target===e&&(i.current=Obe(r.current))};return e.addEventListener("animationstart",f),e.addEventListener("animationcancel",d),e.addEventListener("animationend",d),()=>{u.clearTimeout(c),e.removeEventListener("animationstart",f),e.removeEventListener("animationcancel",d),e.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:Gm.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function Obe(t){return t?.animationName||"none"}function zSr(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Gm,BQt,Nbe,zQt=b(()=>{"use client";Gm=L(B(),1);Ebe();Mbe();BQt=L(B(),1);Nbe=t=>{let{present:e,children:n}=t,r=BSr(e),o=typeof n=="function"?n({present:r.isPresent}):Gm.Children.only(n),i=JQ(r.ref,zSr(o));return typeof n=="function"||r.isPresent?Gm.cloneElement(o,{ref:i}):null};Nbe.displayName="Presence"});function Lbe(t){let e=HSr(t),n=tu.forwardRef((r,o)=>{let{children:i,...s}=r,a=tu.Children.toArray(i),l=a.find(VSr);if(l){let c=l.props.children,u=a.map(d=>d===l?tu.Children.count(c)>1?tu.Children.only(null):tu.isValidElement(c)?c.props.children:null:d);return(0,Rbe.jsx)(e,{...s,ref:o,children:tu.isValidElement(c)?tu.cloneElement(c,void 0,u):null})}return(0,Rbe.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function HSr(t){let e=tu.forwardRef((n,r)=>{let{children:o,...i}=n;if(tu.isValidElement(o)){let s=KSr(o),a=qSr(i,o.props);return o.type!==tu.Fragment&&(a.ref=r?VYe(r,s):s),tu.cloneElement(o,a)}return tu.Children.count(o)>1?tu.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}function VSr(t){return tu.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===WSr}function qSr(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function KSr(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var tu,Rbe,WSr,KYe=b(()=>{tu=L(B(),1);Ebe();Rbe=L(Mt(),1);WSr=Symbol("radix.slottable")});var HQt,GSr,WQt,ZSr,GYe,VQt=b(()=>{HQt=L(B(),1),GSr=L(Es(),1);KYe();WQt=L(Mt(),1),ZSr=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],GYe=ZSr.reduce((t,e)=>{let n=Lbe(`Primitive.${e}`),r=HQt.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,WQt.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{})});function qQt({prop:t,defaultProp:e,onChange:n=()=>{},caller:r}){let[o,i,s]=JSr({defaultProp:e,onChange:n}),a=t!==void 0,l=a?t:o;{let u=Ov.useRef(t!==void 0);Ov.useEffect(()=>{let d=u.current;d!==a&&console.warn(`${r} is changing from ${d?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=a},[a,r])}let c=Ov.useCallback(u=>{if(a){let d=XSr(u)?u(t):u;d!==t&&s.current?.(d)}else i(u)},[a,t,i,s]);return[l,c]}function JSr({defaultProp:t,onChange:e}){let[n,r]=Ov.useState(t),o=Ov.useRef(n),i=Ov.useRef(e);return YSr(()=>{i.current=e},[e]),Ov.useEffect(()=>{o.current!==n&&(i.current?.(n),o.current=n)},[n,o]),[n,r,i]}function XSr(t){return typeof t=="function"}var Ov,$be,YSr,Gpi,KQt=b(()=>{Ov=L(B(),1);Mbe();$be=L(B(),1),YSr=Ov[" useInsertionEffect ".trim().toString()]||E$;Gpi=Symbol("RADIX:SYNC_STATE")});function oen(t){return t?"open":"closed"}var ga,tc,Dbe,GQt,dmi,XQ,QSr,VE,ZQt,YQt,JQt,XQt,QQt,ZYe,eCr,tCr,een,w6,ten,nCr,rCr,oCr,nen,ren,iCr,sCr,aCr,ien,sen,aen,len,YYe,cen=b(()=>{"use client";ga=L(B(),1);OQt();Ebe();DQt();aue();$Fe();zFe();jQt();lR();lR();Tue();zQt();VQt();KYe();KQt();b2e();j2e();tc=L(Mt(),1),Dbe="Popover",[GQt,dmi]=$Qt(Dbe,[bk]),XQ=bk(),[QSr,VE]=GQt(Dbe),ZQt=t=>{let{__scopePopover:e,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=t,a=XQ(e),l=ga.useRef(null),[c,u]=ga.useState(!1),[d,f]=qQt({prop:r,defaultProp:o??!1,onChange:i,caller:Dbe});return(0,tc.jsx)(sR,{...a,children:(0,tc.jsx)(QSr,{scope:e,contentId:UQt(),triggerRef:l,open:d,onOpenChange:f,onOpenToggle:ga.useCallback(()=>f(p=>!p),[f]),hasCustomAnchor:c,onCustomAnchorAdd:ga.useCallback(()=>u(!0),[]),onCustomAnchorRemove:ga.useCallback(()=>u(!1),[]),modal:s,children:n})})};ZQt.displayName=Dbe;YQt="PopoverAnchor",JQt=ga.forwardRef((t,e)=>{let{__scopePopover:n,...r}=t,o=VE(YQt,n),i=XQ(n),{onCustomAnchorAdd:s,onCustomAnchorRemove:a}=o;return ga.useEffect(()=>(s(),()=>a()),[s,a]),(0,tc.jsx)(aR,{...i,...r,ref:e})});JQt.displayName=YQt;XQt="PopoverTrigger",QQt=ga.forwardRef((t,e)=>{let{__scopePopover:n,...r}=t,o=VE(XQt,n),i=XQ(n),s=JQ(e,o.triggerRef),a=(0,tc.jsx)(GYe.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":oen(o.open),...r,ref:s,onClick:v6(t.onClick,o.onOpenToggle)});return o.hasCustomAnchor?a:(0,tc.jsx)(aR,{asChild:!0,...i,children:a})});QQt.displayName=XQt;ZYe="PopoverPortal",[eCr,tCr]=GQt(ZYe,{forceMount:void 0}),een=t=>{let{__scopePopover:e,forceMount:n,children:r,container:o}=t,i=VE(ZYe,e);return(0,tc.jsx)(eCr,{scope:e,forceMount:n,children:(0,tc.jsx)(Nbe,{present:n||i.open,children:(0,tc.jsx)(cR,{asChild:!0,container:o,children:r})})})};een.displayName=ZYe;w6="PopoverContent",ten=ga.forwardRef((t,e)=>{let n=tCr(w6,t.__scopePopover),{forceMount:r=n.forceMount,...o}=t,i=VE(w6,t.__scopePopover);return(0,tc.jsx)(Nbe,{present:r||i.open,children:i.modal?(0,tc.jsx)(rCr,{...o,ref:e}):(0,tc.jsx)(oCr,{...o,ref:e})})});ten.displayName=w6;nCr=Lbe("PopoverContent.RemoveScroll"),rCr=ga.forwardRef((t,e)=>{let n=VE(w6,t.__scopePopover),r=ga.useRef(null),o=JQ(e,r),i=ga.useRef(!1);return ga.useEffect(()=>{let s=r.current;if(s)return Fue(s)},[]),(0,tc.jsx)(pZ,{as:nCr,allowPinchZoom:!0,children:(0,tc.jsx)(nen,{...t,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:v6(t.onCloseAutoFocus,s=>{s.preventDefault(),i.current||n.triggerRef.current?.focus()}),onPointerDownOutside:v6(t.onPointerDownOutside,s=>{let a=s.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0,c=a.button===2||l;i.current=c},{checkForDefaultPrevented:!1}),onFocusOutside:v6(t.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})})}),oCr=ga.forwardRef((t,e)=>{let n=VE(w6,t.__scopePopover),r=ga.useRef(!1),o=ga.useRef(!1);return(0,tc.jsx)(nen,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{t.onCloseAutoFocus?.(i),i.defaultPrevented||(r.current||n.triggerRef.current?.focus(),i.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:i=>{t.onInteractOutside?.(i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));let s=i.target;n.triggerRef.current?.contains(s)&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}})}),nen=ga.forwardRef((t,e)=>{let{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:c,onInteractOutside:u,...d}=t,f=VE(w6,n),p=XQ(n);return lue(),(0,tc.jsx)(tZ,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i,children:(0,tc.jsx)(QN,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:u,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:c,onDismiss:()=>f.onOpenChange(!1),children:(0,tc.jsx)(Oj,{"data-state":oen(f.open),role:"dialog",id:f.contentId,...p,...d,ref:e,style:{...d.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),ren="PopoverClose",iCr=ga.forwardRef((t,e)=>{let{__scopePopover:n,...r}=t,o=VE(ren,n);return(0,tc.jsx)(GYe.button,{type:"button",...r,ref:e,onClick:v6(t.onClick,()=>o.onOpenChange(!1))})});iCr.displayName=ren;sCr="PopoverArrow",aCr=ga.forwardRef((t,e)=>{let{__scopePopover:n,...r}=t,o=XQ(n);return(0,tc.jsx)(Nj,{...o,...r,ref:e})});aCr.displayName=sCr;ien=ZQt,sen=JQt,aen=QQt,len=een,YYe=ten});var QQ,uen,nc,Ku,den,Cl,Gb=b(()=>{QQ=L(B());cen();uen=require("obsidian");De();nc=ien,Ku=aen,den=sen,Cl=QQ.forwardRef(({className:t,align:e="center",sideOffset:n=4,container:r,...o},i)=>QQ.createElement(len,{container:r??activeDocument.body},QQ.createElement(YYe,{ref:i,align:e,sideOffset:n,hideWhenDetached:uen.Platform.isMobile,className:J("tw-z-popover tw-w-72 tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-4 tw-text-normal tw-shadow-md tw-outline-none data-[state=open]:tw-animate-in data-[state=closed]:tw-animate-out data-[state=closed]:tw-fade-out-0 data-[state=open]:tw-fade-in-0 data-[state=closed]:tw-zoom-out-95 data-[state=open]:tw-zoom-in-95 data-[side=bottom]:tw-slide-in-from-top-2 data-[side=left]:tw-slide-in-from-right-2 data-[side=right]:tw-slide-in-from-left-2 data-[side=top]:tw-slide-in-from-bottom-2",t),...o})));Cl.displayName=YYe.displayName});function fen(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function JYe(...t){return e=>{let n=!1,r=t.map(o=>{let i=fen(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():fen(t[o],null)}}}}function WI(...t){return pen.useCallback(JYe(...t),t)}var pen,Fbe=b(()=>{pen=L(B(),1)});function men(t){let e=cCr(t),n=nu.forwardRef((r,o)=>{let{children:i,...s}=r,a=nu.Children.toArray(i),l=a.find(dCr);if(l){let c=l.props.children,u=a.map(d=>d===l?nu.Children.count(c)>1?nu.Children.only(null):nu.isValidElement(c)?c.props.children:null:d);return(0,Ube.jsx)(e,{...s,ref:o,children:nu.isValidElement(c)?nu.cloneElement(c,void 0,u):null})}return(0,Ube.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function cCr(t){let e=nu.forwardRef((n,r)=>{let{children:o,...i}=n;if(nu.isValidElement(o)){let s=pCr(o),a=fCr(i,o.props);return o.type!==nu.Fragment&&(a.ref=r?JYe(r,s):s),nu.cloneElement(o,a)}return nu.Children.count(o)>1?nu.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}function dCr(t){return nu.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===uCr}function fCr(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function pCr(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var nu,Ube,uCr,hen=b(()=>{nu=L(B(),1);Fbe();Ube=L(Mt(),1);uCr=Symbol("radix.slottable")});var gen,mCr,yen,hCr,b6,ven=b(()=>{gen=L(B(),1),mCr=L(Es(),1);hen();yen=L(Mt(),1),hCr=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],b6=hCr.reduce((t,e)=>{let n=men(`Primitive.${e}`),r=gen.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,yen.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{})});var wen,eee,XYe=b(()=>{wen=L(B(),1),eee=globalThis?.document?wen.useLayoutEffect:()=>{}});function gCr(t,e){return ben.useReducer((n,r)=>e[n][r]??n,t)}function yCr(t){let[e,n]=Zm.useState(),r=Zm.useRef(null),o=Zm.useRef(t),i=Zm.useRef("none"),s=t?"mounted":"unmounted",[a,l]=gCr(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return Zm.useEffect(()=>{let c=jbe(r.current);i.current=a==="mounted"?c:"none"},[a]),eee(()=>{let c=r.current,u=o.current;if(u!==t){let f=i.current,p=jbe(c);t?l("MOUNT"):p==="none"||c?.display==="none"?l("UNMOUNT"):l(u&&f!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,l]),eee(()=>{if(e){let c,u=e.ownerDocument.defaultView??window,d=p=>{let h=jbe(r.current).includes(CSS.escape(p.animationName));if(p.target===e&&h&&(l("ANIMATION_END"),!o.current)){let g=e.style.animationFillMode;e.style.animationFillMode="forwards",c=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=g)})}},f=p=>{p.target===e&&(i.current=jbe(r.current))};return e.addEventListener("animationstart",f),e.addEventListener("animationcancel",d),e.addEventListener("animationend",d),()=>{u.clearTimeout(c),e.removeEventListener("animationstart",f),e.removeEventListener("animationcancel",d),e.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:Zm.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function jbe(t){return t?.animationName||"none"}function vCr(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Zm,ben,_6,_en=b(()=>{"use client";Zm=L(B(),1);Fbe();XYe();ben=L(B(),1);_6=t=>{let{present:e,children:n}=t,r=yCr(e),o=typeof n=="function"?n({present:r.isPresent}):Zm.Children.only(n),i=WI(r.ref,vCr(o));return typeof n=="function"||r.isPresent?Zm.cloneElement(o,{ref:i}):null};_6.displayName="Presence"});function Sen(t,e=[]){let n=[];function r(i,s){let a=VI.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=VI.useMemo(()=>m,Object.values(m));return(0,xen.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=VI.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>VI.createContext(s));return function(a){let l=a?.[t]||i;return VI.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,wCr(o,...e)]}function wCr(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return VI.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var VI,xen,Cen=b(()=>{VI=L(B(),1),xen=L(Mt(),1)});function qE(t){let e=x6.useRef(t);return x6.useEffect(()=>{e.current=t}),x6.useMemo(()=>(...n)=>e.current?.(...n),[])}var x6,ken=b(()=>{x6=L(B(),1)});function Ien(t){let e=Bbe.useContext(_Cr);return t||e||"ltr"}var Bbe,bCr,_Cr,Ten=b(()=>{Bbe=L(B(),1),bCr=L(Mt(),1),_Cr=Bbe.createContext(void 0)});function KE(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var Tmi,Pen=b(()=>{Tmi=!!(typeof window<"u"&&window.document&&window.document.createElement)});function xCr(t,e){return Een.useReducer((n,r)=>e[n][r]??n,t)}function Hbe(t){return t?parseInt(t,10):0}function Uen(t,e){let n=t/e;return isNaN(n)?0:n}function Vbe(t){let e=Uen(t.viewport,t.content),n=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,r=(t.scrollbar.size-n)*e;return Math.max(r,18)}function MCr(t,e,n,r="ltr"){let o=Vbe(n),i=o/2,s=e||i,a=o-s,l=n.scrollbar.paddingStart+s,c=n.scrollbar.size-n.scrollbar.paddingEnd-a,u=n.content-n.viewport,d=r==="ltr"?[0,u]:[u*-1,0];return jen([l,c],d)(t)}function Aen(t,e,n="ltr"){let r=Vbe(e),o=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,i=e.scrollbar.size-o,s=e.content-e.viewport,a=i-r,l=n==="ltr"?[0,s]:[s*-1,0],c=CX(t,l);return jen([0,s],[0,a])(c)}function jen(t,e){return n=>{if(t[0]===t[1]||e[0]===e[1])return e[0];let r=(e[1]-e[0])/(t[1]-t[0]);return e[0]+r*(n-t[0])}}function Ben(t,e){return t>0&&t<e}function qbe(t,e){let n=qE(t),r=Dn.useRef(0);return Dn.useEffect(()=>()=>window.clearTimeout(r.current),[]),Dn.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,e)},[n,e])}function S6(t,e){let n=qE(e);eee(()=>{let r=0;if(t){let o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(t),()=>{window.cancelAnimationFrame(r),o.unobserve(t)}}},[t,n])}var Dn,Een,Pi,QYe,Men,Fmi,SCr,Nv,Oen,Nen,Ren,SS,Wbe,CCr,kCr,Len,eJe,ICr,TCr,PCr,$en,Den,zbe,tJe,ACr,nJe,Fen,ECr,OCr,rJe,zen,Hen,Wen=b(()=>{"use client";Dn=L(B(),1);ven();_en();Cen();Fbe();ken();Ten();XYe();W9e();Pen();Een=L(B(),1),Pi=L(Mt(),1);QYe="ScrollArea",[Men,Fmi]=Sen(QYe),[SCr,Nv]=Men(QYe),Oen=Dn.forwardRef((t,e)=>{let{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=t,[a,l]=Dn.useState(null),[c,u]=Dn.useState(null),[d,f]=Dn.useState(null),[p,m]=Dn.useState(null),[h,g]=Dn.useState(null),[v,y]=Dn.useState(0),[w,_]=Dn.useState(0),[S,I]=Dn.useState(!1),[C,k]=Dn.useState(!1),T=WI(e,E=>l(E)),P=Ien(o);return(0,Pi.jsx)(SCr,{scope:n,type:r,dir:P,scrollHideDelay:i,scrollArea:a,viewport:c,onViewportChange:u,content:d,onContentChange:f,scrollbarX:p,onScrollbarXChange:m,scrollbarXEnabled:S,onScrollbarXEnabledChange:I,scrollbarY:h,onScrollbarYChange:g,scrollbarYEnabled:C,onScrollbarYEnabledChange:k,onCornerWidthChange:y,onCornerHeightChange:_,children:(0,Pi.jsx)(b6.div,{dir:P,...s,ref:T,style:{position:"relative","--radix-scroll-area-corner-width":v+"px","--radix-scroll-area-corner-height":w+"px",...t.style}})})});Oen.displayName=QYe;Nen="ScrollAreaViewport",Ren=Dn.forwardRef((t,e)=>{let{__scopeScrollArea:n,children:r,nonce:o,...i}=t,s=Nv(Nen,n),a=Dn.useRef(null),l=WI(e,a,s.onViewportChange);return(0,Pi.jsxs)(Pi.Fragment,{children:[(0,Pi.jsx)("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:o}),(0,Pi.jsx)(b6.div,{"data-radix-scroll-area-viewport":"",...i,ref:l,style:{overflowX:s.scrollbarXEnabled?"scroll":"hidden",overflowY:s.scrollbarYEnabled?"scroll":"hidden",...t.style},children:(0,Pi.jsx)("div",{ref:s.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});Ren.displayName=Nen;SS="ScrollAreaScrollbar",Wbe=Dn.forwardRef((t,e)=>{let{forceMount:n,...r}=t,o=Nv(SS,t.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,a=t.orientation==="horizontal";return Dn.useEffect(()=>(a?i(!0):s(!0),()=>{a?i(!1):s(!1)}),[a,i,s]),o.type==="hover"?(0,Pi.jsx)(CCr,{...r,ref:e,forceMount:n}):o.type==="scroll"?(0,Pi.jsx)(kCr,{...r,ref:e,forceMount:n}):o.type==="auto"?(0,Pi.jsx)(Len,{...r,ref:e,forceMount:n}):o.type==="always"?(0,Pi.jsx)(eJe,{...r,ref:e}):null});Wbe.displayName=SS;CCr=Dn.forwardRef((t,e)=>{let{forceMount:n,...r}=t,o=Nv(SS,t.__scopeScrollArea),[i,s]=Dn.useState(!1);return Dn.useEffect(()=>{let a=o.scrollArea,l=0;if(a){let c=()=>{window.clearTimeout(l),s(!0)},u=()=>{l=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",c),a.addEventListener("pointerleave",u),()=>{window.clearTimeout(l),a.removeEventListener("pointerenter",c),a.removeEventListener("pointerleave",u)}}},[o.scrollArea,o.scrollHideDelay]),(0,Pi.jsx)(_6,{present:n||i,children:(0,Pi.jsx)(Len,{"data-state":i?"visible":"hidden",...r,ref:e})})}),kCr=Dn.forwardRef((t,e)=>{let{forceMount:n,...r}=t,o=Nv(SS,t.__scopeScrollArea),i=t.orientation==="horizontal",s=qbe(()=>l("SCROLL_END"),100),[a,l]=xCr("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return Dn.useEffect(()=>{if(a==="idle"){let c=window.setTimeout(()=>l("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(c)}},[a,o.scrollHideDelay,l]),Dn.useEffect(()=>{let c=o.viewport,u=i?"scrollLeft":"scrollTop";if(c){let d=c[u],f=()=>{let p=c[u];d!==p&&(l("SCROLL"),s()),d=p};return c.addEventListener("scroll",f),()=>c.removeEventListener("scroll",f)}},[o.viewport,i,l,s]),(0,Pi.jsx)(_6,{present:n||a!=="hidden",children:(0,Pi.jsx)(eJe,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:e,onPointerEnter:KE(t.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:KE(t.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),Len=Dn.forwardRef((t,e)=>{let n=Nv(SS,t.__scopeScrollArea),{forceMount:r,...o}=t,[i,s]=Dn.useState(!1),a=t.orientation==="horizontal",l=qbe(()=>{if(n.viewport){let c=n.viewport.offsetWidth<n.viewport.scrollWidth,u=n.viewport.offsetHeight<n.viewport.scrollHeight;s(a?c:u)}},10);return S6(n.viewport,l),S6(n.content,l),(0,Pi.jsx)(_6,{present:r||i,children:(0,Pi.jsx)(eJe,{"data-state":i?"visible":"hidden",...o,ref:e})})}),eJe=Dn.forwardRef((t,e)=>{let{orientation:n="vertical",...r}=t,o=Nv(SS,t.__scopeScrollArea),i=Dn.useRef(null),s=Dn.useRef(0),[a,l]=Dn.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),c=Uen(a.viewport,a.content),u={...r,sizes:a,onSizesChange:l,hasThumb:c>0&&c<1,onThumbChange:f=>i.current=f,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:f=>s.current=f};function d(f,p){return MCr(f,s.current,a,p)}return n==="horizontal"?(0,Pi.jsx)(ICr,{...u,ref:e,onThumbPositionChange:()=>{if(o.viewport&&i.current){let f=o.viewport.scrollLeft,p=Aen(f,a,o.dir);i.current.style.transform=`translate3d(${p}px, 0, 0)`}},onWheelScroll:f=>{o.viewport&&(o.viewport.scrollLeft=f)},onDragScroll:f=>{o.viewport&&(o.viewport.scrollLeft=d(f,o.dir))}}):n==="vertical"?(0,Pi.jsx)(TCr,{...u,ref:e,onThumbPositionChange:()=>{if(o.viewport&&i.current){let f=o.viewport.scrollTop,p=Aen(f,a);i.current.style.transform=`translate3d(0, ${p}px, 0)`}},onWheelScroll:f=>{o.viewport&&(o.viewport.scrollTop=f)},onDragScroll:f=>{o.viewport&&(o.viewport.scrollTop=d(f))}}):null}),ICr=Dn.forwardRef((t,e)=>{let{sizes:n,onSizesChange:r,...o}=t,i=Nv(SS,t.__scopeScrollArea),[s,a]=Dn.useState(),l=Dn.useRef(null),c=WI(e,l,i.onScrollbarXChange);return Dn.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),(0,Pi.jsx)(Den,{"data-orientation":"horizontal",...o,ref:c,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Vbe(n)+"px",...t.style},onThumbPointerDown:u=>t.onThumbPointerDown(u.x),onDragScroll:u=>t.onDragScroll(u.x),onWheelScroll:(u,d)=>{if(i.viewport){let f=i.viewport.scrollLeft+u.deltaX;t.onWheelScroll(f),Ben(f,d)&&u.preventDefault()}},onResize:()=>{l.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:Hbe(s.paddingLeft),paddingEnd:Hbe(s.paddingRight)}})}})}),TCr=Dn.forwardRef((t,e)=>{let{sizes:n,onSizesChange:r,...o}=t,i=Nv(SS,t.__scopeScrollArea),[s,a]=Dn.useState(),l=Dn.useRef(null),c=WI(e,l,i.onScrollbarYChange);return Dn.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),(0,Pi.jsx)(Den,{"data-orientation":"vertical",...o,ref:c,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Vbe(n)+"px",...t.style},onThumbPointerDown:u=>t.onThumbPointerDown(u.y),onDragScroll:u=>t.onDragScroll(u.y),onWheelScroll:(u,d)=>{if(i.viewport){let f=i.viewport.scrollTop+u.deltaY;t.onWheelScroll(f),Ben(f,d)&&u.preventDefault()}},onResize:()=>{l.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:Hbe(s.paddingTop),paddingEnd:Hbe(s.paddingBottom)}})}})}),[PCr,$en]=Men(SS),Den=Dn.forwardRef((t,e)=>{let{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:c,onWheelScroll:u,onResize:d,...f}=t,p=Nv(SS,n),[m,h]=Dn.useState(null),g=WI(e,T=>h(T)),v=Dn.useRef(null),y=Dn.useRef(""),w=p.viewport,_=r.content-r.viewport,S=qE(u),I=qE(l),C=qbe(d,10);function k(T){if(v.current){let P=T.clientX-v.current.left,E=T.clientY-v.current.top;c({x:P,y:E})}}return Dn.useEffect(()=>{let T=P=>{let E=P.target;m?.contains(E)&&S(P,_)};return document.addEventListener("wheel",T,{passive:!1}),()=>document.removeEventListener("wheel",T,{passive:!1})},[w,m,_,S]),Dn.useEffect(I,[r,I]),S6(m,C),S6(p.content,C),(0,Pi.jsx)(PCr,{scope:n,scrollbar:m,hasThumb:o,onThumbChange:qE(i),onThumbPointerUp:qE(s),onThumbPositionChange:I,onThumbPointerDown:qE(a),children:(0,Pi.jsx)(b6.div,{...f,ref:g,style:{position:"absolute",...f.style},onPointerDown:KE(t.onPointerDown,T=>{T.button===0&&(T.target.setPointerCapture(T.pointerId),v.current=m.getBoundingClientRect(),y.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",p.viewport&&(p.viewport.style.scrollBehavior="auto"),k(T))}),onPointerMove:KE(t.onPointerMove,k),onPointerUp:KE(t.onPointerUp,T=>{let P=T.target;P.hasPointerCapture(T.pointerId)&&P.releasePointerCapture(T.pointerId),document.body.style.webkitUserSelect=y.current,p.viewport&&(p.viewport.style.scrollBehavior=""),v.current=null})})})}),zbe="ScrollAreaThumb",tJe=Dn.forwardRef((t,e)=>{let{forceMount:n,...r}=t,o=$en(zbe,t.__scopeScrollArea);return(0,Pi.jsx)(_6,{present:n||o.hasThumb,children:(0,Pi.jsx)(ACr,{ref:e,...r})})}),ACr=Dn.forwardRef((t,e)=>{let{__scopeScrollArea:n,style:r,...o}=t,i=Nv(zbe,n),s=$en(zbe,n),{onThumbPositionChange:a}=s,l=WI(e,d=>s.onThumbChange(d)),c=Dn.useRef(void 0),u=qbe(()=>{c.current&&(c.current(),c.current=void 0)},100);return Dn.useEffect(()=>{let d=i.viewport;if(d){let f=()=>{if(u(),!c.current){let p=OCr(d,a);c.current=p,a()}};return a(),d.addEventListener("scroll",f),()=>d.removeEventListener("scroll",f)}},[i.viewport,u,a]),(0,Pi.jsx)(b6.div,{"data-state":s.hasThumb?"visible":"hidden",...o,ref:l,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:KE(t.onPointerDownCapture,d=>{let p=d.target.getBoundingClientRect(),m=d.clientX-p.left,h=d.clientY-p.top;s.onThumbPointerDown({x:m,y:h})}),onPointerUp:KE(t.onPointerUp,s.onThumbPointerUp)})});tJe.displayName=zbe;nJe="ScrollAreaCorner",Fen=Dn.forwardRef((t,e)=>{let n=Nv(nJe,t.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?(0,Pi.jsx)(ECr,{...t,ref:e}):null});Fen.displayName=nJe;ECr=Dn.forwardRef((t,e)=>{let{__scopeScrollArea:n,...r}=t,o=Nv(nJe,n),[i,s]=Dn.useState(0),[a,l]=Dn.useState(0),c=!!(i&&a);return S6(o.scrollbarX,()=>{let u=o.scrollbarX?.offsetHeight||0;o.onCornerHeightChange(u),l(u)}),S6(o.scrollbarY,()=>{let u=o.scrollbarY?.offsetWidth||0;o.onCornerWidthChange(u),s(u)}),c?(0,Pi.jsx)(b6.div,{...r,ref:e,style:{width:i,height:a,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...t.style}}):null});OCr=(t,e=()=>{})=>{let n={left:t.scrollLeft,top:t.scrollTop},r=0;return function o(){let i={left:t.scrollLeft,top:t.scrollTop},s=n.left!==i.left,a=n.top!==i.top;(s||a)&&e(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};rJe=Oen,zen=Ren,Hen=Fen});var CS,Ym,Ven,M$=b(()=>{CS=L(B());Wen();De();Ym=CS.forwardRef(({className:t,children:e,...n},r)=>CS.createElement(rJe,{ref:r,className:J("tw-relative tw-overflow-hidden",t),...n},CS.createElement(zen,{className:"tw-size-full tw-rounded-[inherit] [&>div:first-child]:!tw-block"},e),CS.createElement(Ven,null),CS.createElement(Hen,null)));Ym.displayName=rJe.displayName;Ven=CS.forwardRef(({className:t,orientation:e="vertical",...n},r)=>CS.createElement(Wbe,{ref:r,orientation:e,className:J("tw-flex tw-touch-none tw-select-none tw-transition-colors",e==="vertical"&&"tw-h-full tw-w-2.5 tw-border-l tw-border-l-transparent tw-p-px",e==="horizontal"&&"tw-h-2.5 tw-flex-col tw-border-t tw-border-t-transparent tw-p-px",t),...n},CS.createElement(tJe,{className:"tw-relative tw-flex-1 tw-rounded-full tw-bg-[var(--background-modifier-border)]"})));Ven.displayName=Wbe.displayName});var Kbe,tee,oJe=b(()=>{Kbe=L(B());De();tee=({icon:t,needsAttention:e,iconClassName:n})=>Kbe.default.createElement("span",{className:"tw-relative tw-inline-flex tw-shrink-0 tw-items-center tw-justify-center"},Kbe.default.createElement(t,{className:n}),e&&Kbe.default.createElement("span",{"aria-hidden":!0,className:J("tw-absolute -tw-right-0.5 -tw-top-0.5 tw-size-1.5 tw-rounded-full tw-ring-1 tw-ring-[var(--background-primary)]","tw-bg-interactive-accent")}))});function C6({children:t,chatHistory:e,onUpdateTitle:n,onDeleteChat:r,onLoadChat:o,onOpenSourceFile:i,getIcon:s,getBadge:a,side:l="top",align:c="end"}){let[u,d]=(0,tn.useState)(""),[f,p]=(0,tn.useState)(null),[m,h]=(0,tn.useState)(""),[g,v]=(0,tn.useState)(!1),[y,w]=(0,tn.useState)(null),[_,S]=(0,tn.useState)(Gbe),I=(0,tn.useRef)(null),C=(0,tn.useRef)(null),k=qen.Platform.isMobile,T=xt(),P=(0,tn.useMemo)(()=>u.trim()?e.filter(ae=>ae.title.toLowerCase().includes(u.toLowerCase())):e,[e,u]),E=(0,tn.useMemo)(()=>ay(P,T.chatHistorySortStrategy,{getName:ae=>ae.title,getCreatedAtMs:ae=>ae.createdAt.getTime(),getLastUsedAtMs:ae=>ae.lastAccessedAt.getTime()}),[P,T.chatHistorySortStrategy]);(0,tn.useLayoutEffect)(()=>{g&&S(Gbe)},[g,u]);let O=(0,tn.useMemo)(()=>E.slice(0,_),[E,_]),$=(0,tn.useRef)({displayCount:Gbe,totalCount:0});(0,tn.useEffect)(()=>{$.current={displayCount:_,totalCount:E.length}},[_,E.length]);let U=(0,tn.useCallback)(ae=>{if(I.current&&(I.current.disconnect(),I.current=null),!ae)return;let q=new IntersectionObserver(F=>{if(F[0].isIntersecting){let{displayCount:z,totalCount:N}=$.current;z<N&&S(R=>Math.min(R+Gbe,N))}},{threshold:.1});q.observe(ae),I.current=q},[]),V=(0,tn.useMemo)(()=>{let ae=T.chatHistorySortStrategy;if(ae==="name")return[{key:"All",label:"All",chats:O,priority:0}];let q=[],F=new Map,z=new Date;return O.forEach(N=>{let R=ae==="recent"?N.lastAccessedAt:N.createdAt,X=z.getTime()-R.getTime(),D=Math.floor(X/(1e3*60*60*24)),G,ce;if(D===0)G="Today",ce=0;else if(D===1)G="Yesterday",ce=1;else if(D<7)G=`${D}d ago`,ce=2+D;else if(D<30){let Z=Math.floor(D/7);G=Z===1?"1w ago":`${Z}w ago`,ce=10+Z}else{let Z=Math.floor(D/30);G=Z===1?"1m ago":`${Z}m ago`,ce=50+Z}F.has(G)||(F.set(G,[]),q.push({key:G,label:G,chats:F.get(G),priority:ce})),F.get(G).push(N)}),q.sort((N,R)=>N.priority-R.priority)},[T.chatHistorySortStrategy,O]),K=(ae,q)=>{p(ae),h(q)},se=async()=>{if(f&&m.trim())try{await n(f,m.trim()),p(null),h("")}catch(ae){H("Error updating title:",ae);return}else p(null),h("")},le=()=>{p(null),h("")};(0,tn.useEffect)(()=>()=>{C.current&&window.clearTimeout(C.current)},[]);let Q=async ae=>{if(y===ae)try{await r(ae),w(null)}catch(q){H("Error deleting chat:",q),w(null)}else C.current&&window.clearTimeout(C.current),w(ae),C.current=window.setTimeout(()=>{w(null),C.current=null},3e3)},ne=()=>{w(null)},ee=async ae=>{o&&await o(ae),v(!1)};return tn.default.createElement(nc,{open:g,onOpenChange:v},tn.default.createElement(Ku,{asChild:!0},t),tn.default.createElement(Cl,{className:"tw-w-80 tw-max-w-[calc(100vw-2rem)] tw-p-0",align:c,side:l,collisionPadding:16},tn.default.createElement("div",{className:"tw-flex tw-max-h-[400px] tw-flex-col"},tn.default.createElement("div",{className:"tw-shrink-0 tw-border-b tw-p-1"},tn.default.createElement(rf,{value:u,onChange:d})),tn.default.createElement(Ym,{className:"tw-min-h-[150px] tw-flex-1 tw-overflow-y-auto"},tn.default.createElement("div",{className:"tw-p-2"},V.length===0?tn.default.createElement("div",{className:"tw-py-8 tw-text-center tw-text-muted"},u?"No matching chat history found.":"No chat history"):tn.default.createElement(tn.default.Fragment,null,V.map(ae=>tn.default.createElement("div",{key:ae.key,className:"tw-mb-3 tw-border-x-[0px] tw-border-b tw-border-t-[0px] tw-border-border tw-pb-2",style:{borderBottomStyle:"solid"}},tn.default.createElement("div",{className:"tw-mb-2 tw-px-2 tw-text-xs tw-font-medium tw-tracking-wider tw-text-muted"},ae.label),tn.default.createElement("div",{className:"tw-space-y-1"},ae.chats.map(q=>tn.default.createElement(RCr,{key:q.id,chat:q,isEditing:f===q.id,editingTitle:m,onEditingTitleChange:h,onStartEdit:K,onSaveEdit:xn(se),onCancelEdit:le,onDelete:xn(Q),onCancelDelete:ne,onLoadChat:xn(ee),onOpenSourceFile:i?xn(i):void 0,isMobile:k,confirmDeleteId:y,getIcon:s,getBadge:a}))))),tn.default.createElement("div",{ref:U,className:"tw-h-1"}),_<E.length?tn.default.createElement("div",{className:"tw-py-2 tw-text-center tw-text-xs tw-text-muted"},"Showing ",_," of ",E.length," \u2014 scroll for more"):null))))))}function RCr({chat:t,isEditing:e,editingTitle:n,onEditingTitleChange:r,onStartEdit:o,onSaveEdit:i,onCancelEdit:s,onDelete:a,onCancelDelete:l,onLoadChat:c,onOpenSourceFile:u,isMobile:d,confirmDeleteId:f,getIcon:p,getBadge:m}){let h=p?.(t)??BC;return e?tn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2 tw-rounded-md tw-p-2"},tn.default.createElement(tee,{icon:h,needsAttention:t.needsAttention,iconClassName:"tw-size-3 tw-text-muted"}),tn.default.createElement(Ir,{value:n,onChange:g=>r(g.target.value),className:"!tw-h-6 tw-flex-1",autoFocus:!0,onKeyDown:g=>{g.key==="Enter"?i():g.key==="Escape"&&s()}}),tn.default.createElement(oe,{size:"sm",variant:"ghost",onClick:i,className:"tw-size-5 tw-p-0"},tn.default.createElement(Hr,{className:"tw-size-3"})),tn.default.createElement(oe,{size:"sm",variant:"ghost",onClick:s,className:"tw-size-5 tw-p-0"},tn.default.createElement(pn,{className:"tw-size-3"}))):tn.default.createElement("div",{className:J("tw-group tw-flex tw-cursor-pointer tw-items-center tw-gap-2 tw-rounded-md tw-p-1 tw-transition-colors hover:tw-bg-modifier-hover"),onClick:()=>c(t.id)},tn.default.createElement(tee,{icon:h,needsAttention:t.needsAttention,iconClassName:"tw-size-3 tw-text-muted"}),tn.default.createElement("span",{className:"tw-block tw-min-w-0 tw-flex-1 tw-truncate tw-text-sm tw-font-medium tw-text-normal",title:t.title},t.title),m?.(t),tn.default.createElement("div",{className:J("tw-flex tw-shrink-0 tw-items-center tw-gap-1.5 tw-transition-opacity",d?"tw-flex":"tw-hidden group-hover:tw-flex")},f===t.id?tn.default.createElement(tn.default.Fragment,null,tn.default.createElement(oe,{size:"sm",variant:"ghost",onClick:g=>{g.stopPropagation(),a(t.id)},className:"tw-size-5 tw-p-0 tw-text-error hover:tw-text-error",title:"Confirm Delete"},tn.default.createElement(Hr,{className:"tw-size-3"})),tn.default.createElement(oe,{size:"sm",variant:"ghost",onClick:g=>{g.stopPropagation(),l()},className:"tw-size-5 tw-p-0",title:"Cancel deletion"},tn.default.createElement(pn,{className:"tw-size-3"}))):tn.default.createElement(tn.default.Fragment,null,tn.default.createElement(oe,{size:"sm",variant:"ghost",onClick:g=>{g.stopPropagation(),u&&u(t.id)},className:"tw-size-5 tw-p-0",title:"Open the source file"},tn.default.createElement(us,{className:"tw-size-4"})),tn.default.createElement(oe,{size:"sm",variant:"ghost",onClick:g=>{g.stopPropagation(),o(t.id,t.title)},className:"tw-size-5 tw-p-0"},tn.default.createElement(rm,{className:"tw-size-3"})),tn.default.createElement(oe,{size:"sm",variant:"ghost",onClick:g=>{g.stopPropagation(),a(t.id)},className:"tw-size-5 tw-p-0 tw-text-error hover:tw-text-error",title:"delete file"},tn.default.createElement(Ts,{className:"tw-size-3"})))))}var tn,qen,Gbe,Zbe=b(()=>{tn=L(B());Re();yt();hl();pk();Gb();M$();De();oJe();pe();Se();wC();qen=require("obsidian");Hl();Gbe=50});var Da,LCr,nee,iJe=b(()=>{Wm();Zbe();yt();Oc();gt();De();vc();Se();Re();Da=L(B()),LCr=t=>t.backendId?$a[t.backendId]?.Icon:void 0,nee=({onNewChat:t,onSaveAsNote:e,chatHistoryItems:n,onLoadHistory:r,onLoadChat:o,onUpdateChatTitle:i,onDeleteChat:s,onOpenSourceFile:a,usageMeter:l,showMultiAgentUpsell:c=!1})=>{let u=xt(),d=Ybe(),f=!!(n&&o&&i&&s);return Da.default.createElement("div",{className:"tw-flex tw-w-full tw-items-center tw-justify-between tw-p-1"},Da.default.createElement("div",{className:"tw-ml-1 tw-flex tw-min-w-0 tw-flex-1 tw-items-center tw-gap-1"},c&&!d&&Da.default.createElement(oe,{variant:"ghost2",size:"fit",className:J("tw-flex tw-min-w-0 tw-items-center tw-gap-1 tw-text-ui-smaller tw-text-muted","hover:tw-text-normal"),onClick:()=>ek(hw.MULTI_AGENT)},Da.default.createElement(hc,{className:"tw-size-3 tw-shrink-0"}),Da.default.createElement("span",{className:"tw-truncate"},"Mention multiple agents with @ (needs Plus tier or above)"))),Da.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},l,t&&Da.default.createElement(hr,null,Da.default.createElement(gr,{asChild:!0},Da.default.createElement(oe,{variant:"ghost2",size:"icon",title:"New Chat",onClick:t},Da.default.createElement(lN,{className:"tw-size-4"}))),Da.default.createElement(fr,null,"New Chat")),!u.autosaveChat&&e&&Da.default.createElement(hr,null,Da.default.createElement(gr,{asChild:!0},Da.default.createElement(oe,{variant:"ghost2",size:"icon",title:"Save Chat as Note",onClick:()=>void e()},Da.default.createElement(LC,{className:"tw-size-4"}))),Da.default.createElement(fr,null,"Save Chat as Note")),f&&Da.default.createElement(hr,null,Da.default.createElement(C6,{chatHistory:n,onUpdateTitle:i,onDeleteChat:s,onLoadChat:o,onOpenSourceFile:a,getIcon:LCr},Da.default.createElement(gr,{asChild:!0},Da.default.createElement(oe,{variant:"ghost2",size:"icon",title:"Chat History",onClick:()=>{r?.()}},Da.default.createElement(aN,{className:"tw-size-4"})))),Da.default.createElement(fr,null,"Chat History"))))}});function Ken(t){let e=t.filter(n=>n.kind==="text"&&n.text.trim().length>0).map(n=>n.text).join(`
`);return _h(e)}function $Cr(t){return t.kind==="tool_call"&&t.vendorToolName==="ToolSearch"}function DCr(t){return!t.mcpServer&&(t.vendorToolName==="Agent"||t.vendorToolName==="Task")?!0:t.vendorToolName||t.mcpServer||t.toolKind&&t.toolKind!=="other"?!1:typeof t.input?.subagent_type=="string"}function Gen(t,e={}){let n=e.maxDepth??3;t=t.filter(s=>!$Cr(s));let r=new Map;for(let s of t)s.kind==="tool_call"&&r.set(s.id,s);let o=new Map;for(let s of t){if(s.kind!=="tool_call")continue;let a=s.parentToolCallId;if(a&&r.has(a)){let l=o.get(a)??[];l.push(s),o.set(a,l)}}let i=t.filter(s=>{if(s.kind!=="tool_call")return!0;let a=s.parentToolCallId;return!(a&&r.has(a))});return Zen(i,o,n,0)}function Zen(t,e,n,r){let o=[];for(let i of t){if(i.kind==="thought"){o.push({type:"reasoning",part:i});continue}if(i.kind==="text"){if(i.text.trim().length===0)continue;o.push({type:"text",part:i});continue}if(i.kind==="plan"){o.push({type:"plan",part:i});continue}let s=e.get(i.id);if(s&&s.length>0||DCr(i)){let a=r+1>=n?[]:Zen(s??[],e,n,r+1);o.push({type:"subagent",parent:i,children:a,truncated:r+1>=n});continue}o.push({type:"action",part:i})}return o}var Yen=b(()=>{ut()});function kl(t){return t.vendorToolName&&Jen[t.vendorToolName]?Jen[t.vendorToolName]:t.toolKind&&Xen[t.toolKind]?Xen[t.toolKind]:V2}var Jen,Xen,sJe=b(()=>{Re();Jen={Read:Jo,Edit:wy,MultiEdit:wy,Write:wy,Bash:Z2,Glob:Iw,Grep:Iw,LS:wG,WebSearch:Xo,WebFetch:Xo,Task:gy,Agent:gy,TodoWrite:kG,ExitPlanMode:AT,Skill:hc},Xen={read:Jo,edit:wy,delete:Ts,move:tG,search:Iw,execute:Z2,fetch:Xo,switch_mode:AT,think:H_,other:V2}});function k6(t){if(!Number.isFinite(t)||t<=0||t<1e3)return"< 1s";let e=Math.floor(t/1e3);if(e<60)return`${e}s`;let n=Math.floor(e/60),r=e%60;if(n<60)return r===0?`${n}m`:`${n}m ${r}s`;let o=Math.floor(n/60),i=n%60;return i===0?`${o}h`:`${o}h ${i}m`}var Jbe=b(()=>{});function I6(t){let e=FCr(t);if(!t.mcpServer)return e;let n=t.mcpServer;return{...e,collapsedLine:(r,o)=>`${n} \xB7 ${e.collapsedLine(r,o)}`}}function FCr(t){if(UCr(t))return lJe;if(t.vendorToolName){let e=JCr[t.vendorToolName];if(e)return e}if(t.toolKind){let e=ikr[t.toolKind];if(e)return e}return skr}function UCr(t){return t.vendorToolName||t.toolKind&&t.toolKind!=="other"?!1:typeof t.input?.subagent_type=="string"}function O$(t,e,n){return`${t} ${t===1?e:n??`${e}s`}`}function qI(t){let e=t.title;return!e||t.vendorToolName&&e.toLowerCase()===t.vendorToolName.toLowerCase()?"\u2026":e}function jCr(t){let e=t.replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").trim().toLowerCase();return e?e.charAt(0).toUpperCase()+e.slice(1):""}function BCr(t){if(!t.vendorToolName&&/\s/.test(t.title))return t.title;let e=t.vendorToolName??t.title;return jCr(e)||"Tool call"}function zCr(t){let n=t.input?.questions?.[0];if(!n)return null;let r=typeof n.header=="string"?n.header.trim():"";return r||(typeof n.question=="string"?n.question.trim():"")||null}function Dp(t,e,n){return t.status==="completed"||t.status==="failed"?n:e}function aJe(t){let e=new Set;for(let n of t.output??[])n.type==="diff"&&n.path.length>0&&e.add(n.path);return[...e]}function cJe(t,e){let n=t.locations?.[0]?.path;if(typeof n=="string"&&n.length>0)return Sv(n,e);let r=t.input;if(typeof r?.file_path=="string")return Sv(r.file_path,e);if(typeof r?.filePath=="string")return Sv(r.filePath,e);if(typeof r?.path=="string")return Sv(r.path,e);let o=aJe(t);return o.length===1?Sv(o[0],e):null}function ree(t,e){let n=cJe(t,e);if(!n||!_X(n))return n;let r=n.replace(/\\/g,"/").replace(/\/+$/,"").split("/").pop();return r?`\u2026/${r}`:"\u2026"}function HCr(t){let n=t.input?.skill;if(typeof n!="string")return null;let r=n.trim();return r.length>0?r:null}function uJe(t){let e=t.input;for(let n of["query","pattern","q"]){let r=e?.[n];if(typeof r=="string"&&r.length>0)return r}return null}function WCr(t){let e=0,n=0;for(let r of t.output??[])r.type==="diff"&&(r.oldText!==null&&(n+=r.oldText.split(`
`).length),e+=r.newText.split(`
`).length);return{added:e,removed:n}}function VCr(t){let e=0;for(let n of t.output??[])n.type==="text"&&(e+=n.text.length);return Math.round(e/4)}function akr(t){return t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function dJe(t){let n=t.input?.prompt;if(typeof n!="string")return null;let r=n.trim();return r.length>0?r:null}function otn(t){if(!t.output)return null;let e=t.output.filter(s=>s.type==="text");if(e.length===0)return null;let n=e.map(s=>s.text).join(`
`),r=n.match(/<task_result>([\s\S]*?)<\/task_result>/),o=r?r[1].trim():n.trim();if(!o)return null;let i=dJe(t);return i&&i===o?null:o}var etn,qCr,Xbe,ttn,Qen,KCr,ntn,lJe,GCr,rtn,ZCr,YCr,JCr,XCr,QCr,ekr,tkr,nkr,rkr,okr,ikr,skr,oee=b(()=>{Re();sJe();Jbe();_I();etn={icon:kl({vendorToolName:"Read"}),collapsedLine:(t,e)=>`${Dp(t,"Reading","Read")} ${ree(t,e?.vaultBase??null)??qI(t)}`,outcome:t=>{let e=VCr(t);return e>0?`~${akr(e)} tokens`:null},targetPath:(t,e)=>cJe(t,e?.vaultBase??null)},qCr={icon:kl({vendorToolName:"LS"}),collapsedLine:(t,e)=>{let n=Dp(t,"Listing","Listed"),r=ree(t,e?.vaultBase??null);return r?`${n} ${r}`:`${n} vault root`},outcome:()=>null},Xbe={icon:kl({vendorToolName:"Edit"}),collapsedLine:(t,e)=>{let n=aJe(t).length;return`${Dp(t,"Editing","Edited")} ${n>1?O$(n,"file"):ree(t,e?.vaultBase??null)??"files"}`},outcome:t=>{let{added:e,removed:n}=WCr(t);return e===0&&n===0?null:`+${e} / \u2212${n} lines`},targetPath:(t,e)=>aJe(t).length>1?null:cJe(t,e?.vaultBase??null)},ttn={icon:kl({vendorToolName:"Bash"}),collapsedLine:t=>{let e=Dp(t,"Running","Ran"),n=t.input;if(typeof n?.description=="string"&&n.description.length>0)return`${e} ${n.description}`;if(typeof n?.command=="string"){let r=n.command.length>60?n.command.slice(0,60)+"\u2026":n.command;return`${e} \`${r}\``}return`${e} ${qI(t)}`},outcome:()=>null,expandedDetails:t=>{let e=t.input;return typeof e?.command!="string"||e.command.length===0?null:typeof e.description=="string"&&e.description.length>0?`# ${e.description}
${e.command}`:e.command}},Qen={icon:kl({vendorToolName:"Grep"}),collapsedLine:t=>{let e=Dp(t,"Searching vault","Searched vault"),n=uJe(t);return n?`${e} \xB7 "${n}"`:`${e} \xB7 ${qI(t)}`},outcome:()=>null},KCr={icon:kl({vendorToolName:"WebSearch"}),collapsedLine:t=>{let e=Dp(t,"Searching web","Searched web"),n=uJe(t);return n?`${e} \xB7 "${n}"`:`${e} \xB7 ${qI(t)}`},outcome:()=>null},ntn={icon:kl({vendorToolName:"WebFetch"}),collapsedLine:t=>{let e=Dp(t,"Fetching","Fetched"),n=t.input;return typeof n?.url=="string"?`${e} ${n.url}`:`${e} ${qI(t)}`},outcome:()=>null},lJe={icon:gy,collapsedLine:t=>{let e=t.input,n=typeof e?.subagent_type=="string"?e.subagent_type:null,r=typeof e?.description=="string"&&e.description.length>0?e.description:typeof e?.prompt=="string"?e.prompt.slice(0,60):qI(t);return n?`${n} \xB7 "${r}"`:`Sub-agent \xB7 "${r}"`},outcome:t=>{let e=t.progress;if(!e)return null;let n=[];return(t.status==="pending"||t.status==="in_progress")&&e.description?.trim()&&n.push(e.description.trim()),e.toolUses!==void 0&&n.push(O$(e.toolUses,"tool")),e.durationMs!==void 0&&n.push(k6(e.durationMs)),n.length>0?n.join(" \xB7 "):null}},GCr={icon:kl({vendorToolName:"TodoWrite"}),collapsedLine:t=>`${Dp(t,"Updating","Updated")} task list`,outcome:t=>{let e=t.input,n=Array.isArray(e?.todos)?e.todos.length:0;return n>0?O$(n,"task"):null}},rtn={icon:kl({vendorToolName:"ExitPlanMode"}),collapsedLine:t=>`${Dp(t,"Proposing","Proposed")} plan`,outcome:()=>null},ZCr={icon:cN,collapsedLine:t=>{let e=Dp(t,"Asking","Asked"),n=zCr(t);return n?`${e}: "${n}"`:`${e} a question`},outcome:()=>null},YCr={icon:kl({vendorToolName:"Skill"}),collapsedLine:t=>{let e=Dp(t,"Running","Ran"),n=HCr(t);return n?`${e} skill ${n}`:`${e} a skill`},outcome:()=>null,expandedDetails:t=>{let e=t.input;return typeof e?.args=="string"&&e.args.length>0?e.args:null}},JCr={Read:etn,Edit:Xbe,MultiEdit:Xbe,Write:Xbe,Bash:ttn,Glob:Qen,Grep:Qen,WebSearch:KCr,WebFetch:ntn,Task:lJe,Agent:lJe,TodoWrite:GCr,ExitPlanMode:rtn,AskUserQuestion:ZCr,LS:qCr,Skill:YCr},XCr={icon:kl({toolKind:"search"}),collapsedLine:t=>{let e=Dp(t,"Searching","Searched"),n=uJe(t);return n?`${e} \xB7 "${n}"`:`${e} \xB7 ${qI(t)}`},outcome:()=>null},QCr={...ttn,icon:kl({toolKind:"execute"})},ekr={...ntn,icon:kl({toolKind:"fetch"})},tkr={icon:kl({toolKind:"delete"}),collapsedLine:(t,e)=>`${Dp(t,"Deleting","Deleted")} ${ree(t,e?.vaultBase??null)??qI(t)}`,outcome:()=>null},nkr={icon:kl({toolKind:"move"}),collapsedLine:(t,e)=>`${Dp(t,"Moving","Moved")} ${ree(t,e?.vaultBase??null)??qI(t)}`,outcome:()=>null},rkr={...rtn,icon:kl({toolKind:"switch_mode"})},okr={icon:kl({toolKind:"think"}),collapsedLine:t=>Dp(t,"Thinking","Thought"),outcome:()=>null},ikr={read:etn,edit:Xbe,search:XCr,execute:QCr,fetch:ekr,delete:tkr,move:nkr,switch_mode:rkr,think:okr},skr={icon:kl({}),collapsedLine:t=>BCr(t),outcome:()=>null}});function Qbe(t,e){let n=[];if(t!==null)for(let r of t.split(`
`))n.push(`- ${r}`);for(let r of e.split(`
`))n.push(`+ ${r}`);return n.join(`
`)}function itn(t){if(t==null)return null;try{return JSON.stringify(t,null,2)}catch{return String(typeof t=="string"||typeof t=="number"||typeof t=="boolean"?t:Object.prototype.toString.call(t))}}function stn(t=null){if(!t)return[];let e=[];for(let n of t)n.type==="diff"&&typeof n.path=="string"&&typeof n.newText=="string"&&e.push({path:n.path,oldText:n.oldText??null,newText:n.newText});return e}var fJe=b(()=>{});function e_e(t,e,n={}){let r=lkr(t,e)??e;if(_X(r)){let s=Sv(r,Hu(t));if(s===r){w$(r);return}r=s}let{filePath:o,anchor:i}=ltn(r);if(o&&!t.vault.getAbstractFileByPath(o)){let s=atn(t,o);if(s){s.indexedPath?t.workspace.openLinkText(s.indexedPath+i,n.sourcePath??"",n.newLeaf??!1):w$(s.absolutePath);return}}t.workspace.openLinkText(r,n.sourcePath??"",n.newLeaf??!1)}function atn(t,e){let n=Hu(t);if(!n)return null;try{let r=Pe("fs"),o=r.realpathSync(`${n}/${e}`),i=r.realpathSync(n),s=Sv(o,i);return s===o?{absolutePath:o,indexedPath:null}:{absolutePath:o,indexedPath:t.vault.getAbstractFileByPath(s)?s:null}}catch{return null}}function ltn(t){let e=t.indexOf("#");return e===-1?{filePath:t,anchor:""}:{filePath:t.slice(0,e),anchor:t.slice(e)}}function lkr(t,e){if(!e.startsWith("/")||e.startsWith("//"))return null;let n=e.replace(/^\/+/,"");if(!n)return null;let{filePath:r}=ltn(n);return r&&(t.vault.getAbstractFileByPath(r)||atn(t,r))?n:null}var pJe=b(()=>{$we();$n();_I()});var Zb,GE,iee=b(()=>{De();Re();Zb=L(B()),GE=({icon:t,label:e,trailing:n,secondary:r,expandable:o=!1,open:i=!1,onToggle:s,children:a})=>{let l=(0,Zb.useId)(),c=o&&s!==void 0;return Zb.default.createElement("div",{className:"tw-my-1 tw-flex tw-w-full tw-flex-col tw-gap-0.5"},Zb.default.createElement("div",{"data-agent-activity-card-header":!0,className:J("tw-flex tw-w-full tw-items-center tw-gap-1.5 tw-pl-1 tw-text-left tw-text-sm tw-text-muted",c?"tw-cursor-pointer hover:tw-text-normal":"tw-cursor-default"),role:c?"button":void 0,tabIndex:c?0:void 0,"aria-expanded":c?i:void 0,"aria-controls":c?l:void 0,onClick:c?s:void 0,onKeyDown:c?u=>{u.key!=="Enter"&&u.key!==" "||(u.preventDefault(),s())}:void 0},Zb.default.createElement("span",{className:"tw-flex tw-size-3.5 tw-shrink-0 tw-items-center tw-justify-center"},Zb.default.createElement(t,{className:"tw-size-3.5 tw-text-muted"})),Zb.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-items-center tw-gap-1 tw-truncate tw-font-medium"},e),n,c?Zb.default.createElement(Vi,{className:J("tw-size-3 tw-shrink-0 tw-text-muted tw-transition-transform",i&&"tw-rotate-90")}):null),r?Zb.default.createElement("div",{className:"tw-truncate tw-pl-6 tw-text-xs tw-text-muted"},r):null,c&&i?Zb.default.createElement("div",{id:l,className:"tw-ml-1 tw-mt-1 tw-flex tw-flex-col tw-gap-1 tw-border-l tw-border-border tw-pl-3"},a):null)}});var $f,ctn,mJe,hJe=b(()=>{$f=L(B());Re();oee();fJe();_I();pJe();ko();iee();ctn=({part:t,open:e,onToggle:n})=>{let r=vn(),o=I6(t),i=(0,$f.useMemo)(()=>({vaultBase:Hu(r)}),[r]),s=o.icon,a=o.collapsedLine(t,i),l=o.outcome(t),c=t.output??[],u=o.expandedDetails?.(t)??null,d=c.length>0||u!==null,f=t.status==="completed"?o.targetPath?.(t,i)??null:null;return $f.default.createElement(GE,{icon:s,label:f?$f.default.createElement("a",{href:"#",className:"tw-min-w-0 tw-truncate tw-text-inherit hover:tw-text-accent hover:tw-underline",onClick:p=>{p.preventDefault(),p.stopPropagation(),e_e(r,f,{newLeaf:!0})}},a):$f.default.createElement("span",{className:"tw-truncate"},a),trailing:$f.default.createElement(mJe,{status:t.status}),expandable:d,open:e,onToggle:n},u?$f.default.createElement("pre",{className:"tw-max-h-40 tw-overflow-auto tw-whitespace-pre-wrap tw-rounded tw-bg-secondary-alt tw-p-1 tw-text-xs"},u):null,l?$f.default.createElement("div",{className:"tw-text-xs tw-text-muted"},l):null,c.map((p,m)=>p.type==="text"?$f.default.createElement("pre",{key:`text-${m}`,className:"tw-max-h-40 tw-overflow-auto tw-whitespace-pre-wrap tw-rounded tw-bg-secondary-alt tw-p-1 tw-text-xs"},p.text):$f.default.createElement("div",{key:`diff-${m}-${p.path}`,className:"tw-rounded tw-bg-secondary-alt tw-p-1"},$f.default.createElement("p",{className:"tw-font-mono tw-text-xs tw-text-muted"},p.path),$f.default.createElement("pre",{className:"tw-max-h-40 tw-overflow-auto tw-whitespace-pre-wrap tw-text-xs"},Qbe(p.oldText,p.newText)))))},mJe=({status:t})=>t==="in_progress"||t==="pending"?$f.default.createElement(Dr,{className:"tw-size-3 tw-shrink-0 tw-animate-spin tw-text-loading"}):t==="failed"?$f.default.createElement(pn,{className:"tw-size-3 tw-shrink-0 tw-text-error"}):$f.default.createElement(Hr,{className:"tw-size-3 tw-shrink-0 tw-text-success"})});function ckr(t){if(t.mcpServer)return!1;let e=t.vendorToolName;return t.toolKind==="switch_mode"||e==="AskUserQuestion"||e==="ExitPlanMode"||e==="EnterPlanMode"}function gJe(t){if(t.length===0)return ukr;let e=[],n=[],r=0,o=()=>{n.length!==0&&(n.length===1?e.push(n[0]):e.push({type:"activityGroup",id:`activity-${r++}`,members:n}),n=[])};for(let i of t)switch(i.type){case"reasoning":n.push(i);break;case"action":ckr(i.part)?(o(),e.push(i)):n.push(i);break;default:o(),e.push(i)}return o(),e}function dkr(t){if(!t.mcpServer)switch(t.vendorToolName){case"Read":case"NotebookRead":return"read";case"Edit":case"MultiEdit":case"Write":case"NotebookEdit":return"edit"}switch(t.toolKind){case"read":return"read";case"edit":return"edit";default:return"command"}}function fkr(t,e){switch(t){case"read":return`read ${O$(e,"file")}`;case"edit":return`edited ${O$(e,"file")}`;case"command":return`ran ${O$(e,"command")}`}}function utn(t,e={}){let n=[],r=new Map,o=0,i=0;for(let c of t){if(c.type==="reasoning"){o++;continue}c.part.status==="failed"&&i++;let u=dkr(c.part);r.has(u)||n.push(u),r.set(u,(r.get(u)??0)+1)}let s=n.map(c=>fkr(c,r.get(c)??0)),a=e.thinkingMs??0;o>0&&(a>=1e3?s.push(`thought for ${k6(a)}`):s.length===0&&s.push("thought"));let l=s.join(", ");return{line:l.length>0?l.charAt(0).toUpperCase()+l.slice(1):"Worked",failed:i}}var ukr,yJe=b(()=>{oee();Jbe();ukr=Object.freeze([])});function pkr(t){let e=new Set;for(let n of t)n.type==="action"&&e.add(kl({vendorToolName:n.part.vendorToolName,toolKind:n.part.toolKind}));return e.size===1?[...e][0]:xG}var T6,dtn,ftn=b(()=>{T6=L(B());Re();yJe();sJe();iee();dtn=({group:t,thinkingMs:e,open:n,onToggle:r,renderMember:o,liveStep:i})=>{let s=utn(t.members,{thinkingMs:e}),a=pkr(t.members),l=t.members.some(c=>c.type==="action"&&(c.part.status==="pending"||c.part.status==="in_progress"));return T6.default.createElement(GE,{icon:a,label:s.line,trailing:T6.default.createElement(T6.default.Fragment,null,s.failed>0?T6.default.createElement("span",{className:"tw-shrink-0 tw-text-xs tw-text-muted"},s.failed," failed"):null,l?T6.default.createElement(Dr,{className:"tw-size-3 tw-shrink-0 tw-animate-spin tw-text-loading"}):null),secondary:n?void 0:i,expandable:!0,open:n,onToggle:r},t.members.map((c,u)=>o(c,u)))}});function vJe(t,e){return e&&t[t.length-1]?.type==="reasoning"}function ptn(t,e,n){if(!e)return null;if(vJe(t,e))return mkr;for(let r=t.length-1;r>=0;r--){let o=t[r];if(o.type!=="action")continue;let i=o.part.status;if(i==="pending"||i==="in_progress")return I6(o.part).collapsedLine(o.part,n)}return null}var mkr,mtn=b(()=>{oee();mkr="Reasoning"});var wJe,hkr,P6,bJe,t_e,A6,n_e=b(()=>{De();wJe=L(B()),hkr=[{row:0,col:0,animIndex:2},{row:0,col:1,animIndex:1},{row:0,col:2,animIndex:0},{row:1,col:1,animIndex:3},{row:2,col:0,animIndex:4},{row:2,col:1,animIndex:5},{row:2,col:2,animIndex:6}],P6=2.5,bJe=3,t_e=P6*3+bJe*2,A6=({animated:t=!0})=>wJe.default.createElement("svg",{width:t_e,height:t_e,viewBox:`0 0 ${t_e} ${t_e}`,className:"copilot-spinner"},hkr.map(e=>{let n=e.col*(P6+bJe)+P6/2,r=e.row*(P6+bJe)+P6/2;return wJe.default.createElement("circle",{key:e.animIndex,cx:n,cy:r,r:P6/2,className:J("copilot-spinner-dot",t&&`copilot-spinner-dot-${e.animIndex}`)})}))});function gkr(t){let e=Number.isFinite(t)?Math.max(0,t):0,n=Math.floor(e/1e3),r=Math.floor(n/3600),o=Math.floor(n%3600/60),i=n%60;return r>0?`${r}h ${o}m ${i}s`:o>0?`${o}m ${i}s`:`${i}s`}var Fp,ZE,r_e=b(()=>{n_e();De();Fp=L(B());ZE=t=>{let[e,n]=(0,Fp.useState)(()=>Date.now()),r=(0,Fp.useRef)(null),o=t.status==="running";(0,Fp.useEffect)(()=>{if(!o)return;let s=r.current?.win;if(!s)return;let a=s.setInterval(()=>n(Date.now()),1e3);return()=>s.clearInterval(a)},[o]);let i=o?Math.max(0,e-t.startedAtMs):t.durationMs;return Fp.default.createElement("div",{ref:r,className:J("tw-text-ui-medium",!t.inline&&"tw-mb-2 tw-mt-1 tw-w-full max-md:tw-mb-1.5 max-md:tw-mt-0.5")},Fp.default.createElement("div",{className:J("tw-flex tw-items-center tw-gap-1.5 tw-pl-1 tw-text-left tw-text-ui-small tw-text-muted",!t.inline&&"tw-w-full")},Fp.default.createElement("span",{className:"tw-flex tw-size-icon-xs tw-shrink-0 tw-items-center tw-justify-start"},Fp.default.createElement(A6,{animated:o})),Fp.default.createElement("span",null,Fp.default.createElement("span",{className:o?"copilot-shimmer-text tw-font-medium":"tw-font-medium"},"Worked for")," ",Fp.default.createElement("span",{className:"tw-tabular-nums"},gkr(i))),o?Fp.default.createElement("span",{className:"tw-sr-only",role:"status","aria-live":"polite"},"Agent is working"):null))}});var E6,Yb,o_e=b(()=>{yt();Oc();E6=L(B()),Yb=({label:t,icon:e,onClick:n})=>E6.default.createElement(hr,null,E6.default.createElement(gr,{asChild:!0},E6.default.createElement(oe,{onClick:n,variant:"ghost2",size:"fit",title:t},E6.default.createElement(e,{className:"tw-size-4"}))),E6.default.createElement(fr,null,t))});function gtn(){let[t,e]=(0,htn.useState)(!1);return{isCopied:t,copy:r=>{!navigator.clipboard||!navigator.clipboard.writeText||navigator.clipboard.writeText(r).then(()=>{e(!0),window.setTimeout(()=>e(!1),2e3)}).catch(o=>H("Clipboard writeText failed",o))}}}var htn,ytn=b(()=>{pe();htn=L(B())});var vtn,see,_Je=b(()=>{o_e();ytn();Re();vtn=L(B()),see=({text:t})=>{let{isCopied:e,copy:n}=gtn();return vtn.default.createElement(Yb,{label:"Copy",icon:e?Hr:rN,onClick:()=>n(t)})}});var M6,KI,aee=b(()=>{M6=L(B()),KI=({leading:t,timestamp:e,actions:n})=>{let r=t!=null&&t!==!1,o=!r&&e!==void 0&&e!==null&&e!==!1,i=n!=null&&n!==!1;return M6.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-items-center tw-justify-between tw-gap-2"},r||o?M6.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-2 tw-overflow-hidden"},r?M6.default.createElement("div",{"data-response-footer-leading":!0,className:"tw-shrink-0"},t):null,o?M6.default.createElement("div",{className:"tw-truncate tw-text-xs tw-text-faint"},e):null):null,i?M6.default.createElement("div",{"data-response-footer-actions":!0,className:"tw-ml-auto tw-shrink-0"},n):null)}});var wtn,O6,btn,_tn=b(()=>{r_e();_Je();o_e();aee();De();ut();Re();wtn=require("obsidian"),O6=L(B()),btn=({text:t,app:e,durationMs:n,timestamp:r})=>O6.default.createElement(KI,{leading:n!==void 0?O6.default.createElement(ZE,{status:"complete",durationMs:n,inline:!0}):void 0,timestamp:r,actions:O6.default.createElement("div",{className:J("tw-flex tw-items-center tw-gap-1",{"group-hover:opacity-100 opacity-0":!wtn.Platform.isMobile})},O6.default.createElement(Yb,{label:"Insert / Replace at cursor",icon:dN,onClick:()=>void I2(e,t)}),O6.default.createElement(see,{text:t}))})});async function YE(t,e,n,r,o){let i=xtn.MarkdownRenderer.render;await i(t,e,n,r,o),ykr(n,t,r,o)}function ykr(t,e,n,r){let o=i=>{let a=i.target?.closest?.("a.internal-link");if(!a||!t.contains(a)||i.button!==0&&i.button!==1)return;i.preventDefault();let l=a.getAttribute("data-href")||a.getAttribute("href");if(!l)return;let c=l;try{c=decodeURIComponent(l)}catch{}let u=i.button===1||i.ctrlKey||i.metaKey;e_e(e,c,{newLeaf:u,sourcePath:n})};t.addEventListener("click",o),t.addEventListener("auxclick",o),r.register(()=>{t.removeEventListener("click",o),t.removeEventListener("auxclick",o)})}var xtn,lee=b(()=>{pJe();xtn=require("obsidian")});var N6,Stn,JE,i_e=b(()=>{N6=L(B());pe();lee();Stn=require("obsidian"),JE=({text:t,app:e})=>{let n=(0,N6.useRef)(null);return(0,N6.useEffect)(()=>{let r=n.current;if(!r)return;r.classList.add("markdown-rendered"),r.empty();let o=new Stn.Component;o.load();let i=e.workspace.getActiveFile()?.path??"";return YE(e,t,r,i,o).catch(s=>{W("[AgentTrail] markdown render failed",s)}),()=>{o.unload(),r.empty()}},[e,t]),N6.default.createElement("div",{ref:n,className:"tw-p-1 tw-text-sm"})}});function vkr(t){let e=0,n=0;for(let r of t)if(r.type==="action"||r.type==="subagent")e+=1;else if(r.type==="reasoning")n+=1;else if(r.type==="activityGroup")for(let o of r.members)o.type==="action"?e+=1:n+=1;return{tools:e,reasoning:n}}function wkr(t,e){if(e)return"Nested";let n=[];return t.tools>0&&n.push(`${t.tools} ${t.tools===1?"tool":"tools"}`),t.reasoning>0&&n.push(`${t.reasoning} reasoning`),n.length>0?n.join(" \xB7 "):"No activity"}var Rd,Ctn,ktn=b(()=>{Rd=L(B());Re();hJe();i_e();oee();iee();Ctn=({parent:t,childNodes:e,truncated:n,app:r,renderNode:o})=>{let[i,s]=(0,Rd.useState)(!1),[a,l]=(0,Rd.useState)(!1),c=I6(t),u=c.icon,d=c.collapsedLine(t),f=c.outcome(t),p=vkr(e),m=dJe(t),h=otn(t);return Rd.default.createElement(GE,{icon:u,label:d,trailing:Rd.default.createElement(mJe,{status:t.status}),secondary:f,expandable:!0,open:i,onToggle:()=>s(g=>!g)},p.tools>0||p.reasoning>0||n?Rd.default.createElement("div",{className:"tw-text-xs tw-text-muted"},wkr(p,n)):null,m?Rd.default.createElement("div",{className:"tw-my-1"},Rd.default.createElement("div",{className:"tw-flex tw-cursor-pointer tw-items-center tw-gap-2 tw-text-xs tw-text-muted",onClick:()=>l(g=>!g),role:"button"},Rd.default.createElement("span",{className:"tw-flex-1 tw-truncate"},"Prompt"),a?Rd.default.createElement(Bs,{className:"tw-size-3"}):Rd.default.createElement(Vi,{className:"tw-size-3"})),a?Rd.default.createElement("div",{className:"tw-mt-1 tw-border-l-[2px] tw-border-border tw-pl-2"},Rd.default.createElement(JE,{text:m,app:r})):null):null,n?Rd.default.createElement("div",{className:"tw-text-xs tw-text-muted"},"Nested sub-agent \u2014 expand the parent to drill in."):e.map((g,v)=>o(g,v)),h?Rd.default.createElement("div",{className:"tw-my-1 tw-border-l-[2px] tw-border-border tw-pl-2"},Rd.default.createElement(JE,{text:h,app:r})):null)}});var Jm,s_e,xJe=b(()=>{iee();Jbe();Re();Jm=L(B()),s_e=({status:t,elapsedSeconds:e,steps:n,isStreaming:r})=>{let[o,i]=(0,Jm.useState)(!1),[s,a]=(0,Jm.useState)(t);if(t!==s&&(a(t),(t==="collapsed"||t==="complete")&&i(!1)),t==="idle")return null;let l=t==="reasoning",c=n.length>0;return Jm.default.createElement(GE,{icon:H_,label:Jm.default.createElement(Jm.default.Fragment,null,Jm.default.createElement("span",null,l?Jm.default.createElement(Jm.default.Fragment,null,"Reasoning",Jm.default.createElement("span",{className:"copilot-shimmer-text","aria-hidden":"true"},"...")):"Thought for"),l?null:Jm.default.createElement("span",{className:"tw-font-normal tw-text-muted"},k6(e*1e3))),expandable:c,open:o,onToggle:()=>i(u=>!u)},Jm.default.createElement("ul",{className:"tw-list-outside tw-list-disc tw-space-y-1.5 tw-pl-4 max-md:tw-space-y-1"},n.map((u,d)=>Jm.default.createElement("li",{key:d,className:"tw-text-xs tw-leading-[1.4] tw-text-muted"},u))))}});var Jb,Itn,Ttn=b(()=>{Jb=L(B());xJe();Itn=({part:t,isStreaming:e})=>{let n=(0,Jb.useRef)(null),r=(0,Jb.useRef)(null),o=(0,Jb.useRef)(e),[i,s]=(0,Jb.useState)(()=>Date.now());(0,Jb.useEffect)(()=>{n.current===null&&t.text.length>0&&(n.current=Date.now())},[t.text]),o.current!==e&&(!e&&n.current!==null?r.current=Date.now():e&&(r.current=null),o.current=e),(0,Jb.useEffect)(()=>{if(!e)return;let f=window.setInterval(()=>s(Date.now()),1e3);return()=>window.clearInterval(f)},[e]);let a=r.current,l=n.current??Date.now(),u=Math.max(0,Math.round(((a??(e?i:l))-l)/1e3)),d=t.text.split(/\n\n+/).map(f=>f.trim()).filter(f=>f.length>0);return Jb.default.createElement(s_e,{status:e?"reasoning":"complete",elapsedSeconds:u,steps:d.length>0?d:[t.text],isStreaming:e})}});function Ptn(t){return t==="completed"?"\u25CF":t==="in_progress"?"\u25D0":"\u25CB"}function Atn(t){return t==="completed"?"tw-text-muted tw-line-through":""}var Etn=b(()=>{});function Mtn(t){let e=(0,N$.useRef)(0),n=(0,N$.useRef)(null),[,r]=(0,N$.useState)(0);t&&n.current===null?n.current=Date.now():!t&&n.current!==null&&(e.current+=Date.now()-n.current,n.current=null),(0,N$.useEffect)(()=>{if(!t)return;let i=window.setInterval(()=>r(s=>s+1),1e3);return()=>window.clearInterval(i)},[t]);let o=n.current;return o===null?e.current:e.current+(Date.now()-o)}var N$,Otn=b(()=>{N$=L(B())});function Ntn(){let[t,e]=(0,cee.useState)(bkr),n=(0,cee.useCallback)(o=>{e(i=>{let s=new Set(i);return s.delete(o)||s.add(o),s})},[]);return{isOpen:(0,cee.useCallback)(o=>t.has(o),[t]),toggle:n}}var cee,bkr,Rtn=b(()=>{cee=L(B()),bkr=new Set});function SJe(t,e,n,r,o){switch(t.type){case"action":{let i=$tn(o,t.part.id);return ya.default.createElement(ctn,{key:e,part:t.part,open:n.expansion.isOpen(i),onToggle:()=>n.expansion.toggle(i)})}case"activityGroup":return ya.default.createElement(xkr,{key:e,group:t,ctx:n,atLiveEdge:r,trailId:o});case"subagent":{let i=gJe(t.children),s=i[i.length-1],a=`${o}/subagent:${t.parent.id}`;return ya.default.createElement(Ctn,{key:e,parent:t.parent,childNodes:i,truncated:t.truncated,app:n.app,renderNode:(l,c)=>SJe(l,c,n,r&&l===s,a)})}case"reasoning":{let i=r&&t.part===n.lastPart;return ya.default.createElement(Itn,{key:e,part:t.part,isStreaming:i})}case"text":return ya.default.createElement(JE,{key:e,text:t.part.text,app:n.app});case"plan":return ya.default.createElement(Skr,{key:e,entries:t.part.entries})}}function $tn(t,e){return`${t}/action:${e}`}var ya,Ltn,_kr,xkr,Skr,Dtn=b(()=>{ya=L(B());Yen();hJe();ftn();yJe();mtn();_tn();ktn();Ttn();i_e();Etn();Otn();Rtn();r_e();aee();_I();Ltn=({parts:t,isStreaming:e,turnStartedAtMs:n,turnDurationMs:r,timestamp:o,app:i,turnStopReason:s})=>{let a=Ken(t),l=e&&n!==void 0,c=!e&&s!=="cancelled"&&a.length>0?ya.default.createElement(btn,{text:a,app:i,durationMs:r,timestamp:o}):r!==void 0?ya.default.createElement(KI,{leading:ya.default.createElement(ZE,{status:"complete",durationMs:r,inline:!0})}):!l&&o?ya.default.createElement(KI,{timestamp:o}):null;return ya.default.createElement("div",{className:"tw-group tw-flex tw-flex-col tw-gap-1"},ya.default.createElement(_kr,{parts:t,isStreaming:e,app:i}),l?ya.default.createElement(ZE,{status:"running",startedAtMs:n}):null,c)},_kr=({parts:t,isStreaming:e,app:n})=>{let r=Ntn(),o=(0,ya.useMemo)(()=>({vaultBase:Hu(n)}),[n]),i=gJe(Gen(t)),s={app:n,lastPart:t.length>0?t[t.length-1]:void 0,expansion:r,summaryCtx:o};return ya.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1"},i.map((a,l)=>SJe(a,l,s,e&&l===i.length-1,"root")))};xkr=({group:t,atLiveEdge:e,ctx:n,trailId:r})=>{let o=Mtn(vJe(t.members,e)),i=`${r}/group:${t.id}`,s=t.members.flatMap(c=>c.type==="action"?[$tn(r,c.part.id)]:[]),a=n.expansion.isOpen(i)||s.some(c=>n.expansion.isOpen(c));return ya.default.createElement(dtn,{group:t,thinkingMs:o,open:a,onToggle:()=>{if(!a){n.expansion.toggle(i);return}n.expansion.isOpen(i)&&n.expansion.toggle(i);for(let c of s)n.expansion.isOpen(c)&&n.expansion.toggle(c)},renderMember:(c,u)=>SJe(c,c.type==="action"?c.part.id:`thought-${u}`,n,e,r),liveStep:ptn(t.members,e,n.summaryCtx)})};Skr=({entries:t})=>t.length===0?null:ya.default.createElement("div",{className:"tw-my-1 tw-rounded tw-border tw-border-border tw-bg-secondary tw-px-2 tw-py-1"},ya.default.createElement("p",{className:"tw-mb-1 tw-text-xs tw-text-muted"},"Plan"),ya.default.createElement("ul",{className:"tw-flex tw-flex-col tw-gap-0.5 tw-text-sm"},t.map((e,n)=>ya.default.createElement("li",{key:`plan-${n}`,className:"tw-flex tw-items-start tw-gap-2"},ya.default.createElement("span",{"aria-hidden":"true"},Ptn(e.status)),ya.default.createElement("span",{className:Atn(e.status)},e.content)))))});function Ckr(t,e,n,r){return n?r.trim().length>0:t.multiSelect?!0:typeof e=="string"&&e!==""}var Ko,Ftn,kkr,Utn=b(()=>{yt();De();Re();Ko=L(B());Ftn=({request:t,onResolve:e})=>{let{questions:n,requestId:r}=t,[o,i]=(0,Ko.useState)(!1),[s,a]=(0,Ko.useState)(0),[l,c]=(0,Ko.useState)({}),[u,d]=(0,Ko.useState)({}),[f,p]=(0,Ko.useState)({}),m=n.every((I,C)=>Ckr(I,l[C],u[C]??!1,f[C]??"")),h=()=>{if(o||!m)return;i(!0);let I={};for(let C=0;C<n.length;C++){let k=n[C],T=l[C],P=u[C]??!1,E=(f[C]??"").trim();if(k.multiSelect){let O=T instanceof Set?Array.from(T):[];P&&E&&O.push(E),I[k.question]=O.join(", ")}else I[k.question]=P?E:typeof T=="string"?T:""}e(r,I)},g=()=>{o||(i(!0),e(r,{}))},v=n.length>1,y=n[s]??n[0],w=n[s]?s:0,_=I=>{if(y.multiSelect){c(C=>{let k=C[w],T=new Set(k instanceof Set?k:[]);return T.has(I)?T.delete(I):T.add(I),{...C,[w]:T}});return}c(C=>({...C,[w]:I})),d(C=>({...C,[w]:!1}))},S=()=>{if(y.multiSelect){d(I=>({...I,[w]:!(I[w]??!1)}));return}d(I=>({...I,[w]:!0})),c(I=>({...I,[w]:""}))};return Ko.default.createElement("div",{className:"tw-mx-3 tw-my-2 tw-w-[calc(100%-1.5rem)] tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-secondary"},Ko.default.createElement("div",{className:"copilot-divider-b tw-flex tw-items-center tw-gap-2 tw-px-3 tw-py-2"},Ko.default.createElement(cN,{className:"tw-size-4 tw-shrink-0 tw-text-accent"}),Ko.default.createElement("div",{className:"tw-truncate tw-text-sm tw-font-medium"},"Question from agent")),Ko.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2 tw-px-3 tw-py-2"},v?Ko.default.createElement("div",{role:"tablist",className:"copilot-divider-b tw-flex tw-flex-wrap tw-gap-x-1"},n.map((I,C)=>{let k=C===w;return Ko.default.createElement("button",{key:I.question,type:"button",role:"tab","aria-selected":k,disabled:o,onClick:()=>a(C),className:J("tw--mb-px !tw-rounded-none !tw-border-none !tw-bg-transparent tw-p-1.5 tw-text-sm tw-transition-colors","disabled:tw-cursor-not-allowed disabled:tw-opacity-50",k?"tw-font-medium tw-text-normal !tw-shadow-[inset_0_-2px_0_0_var(--interactive-accent)]":"tw-text-muted !tw-shadow-none hover:tw-text-normal")},I.header||`Question ${C+1}`)})):null,Ko.default.createElement(kkr,{key:y.question,question:y,name:`askq-${r}-${w}`,selection:l[w],otherActive:u[w]??!1,customText:f[w]??"",disabled:o,onTogglePreset:_,onToggleOther:S,onCustomTextChange:I=>p(C=>({...C,[w]:I})),onSubmitShortcut:h})),Ko.default.createElement("div",{className:"copilot-divider-t tw-flex tw-flex-wrap tw-items-center tw-justify-end tw-gap-2 tw-px-3 tw-py-2"},Ko.default.createElement(oe,{variant:"secondary",size:"sm",disabled:o,onClick:g},"Cancel"),Ko.default.createElement(oe,{variant:"default",size:"sm",disabled:o||!m,onClick:h},"Submit")))},kkr=({question:t,name:e,selection:n,otherActive:r,customText:o,disabled:i,onTogglePreset:s,onToggleOther:a,onCustomTextChange:l,onSubmitShortcut:c})=>{let u=t.multiSelect?"checkbox":"radio";return Ko.default.createElement("div",{role:"tabpanel",className:"tw-flex tw-flex-col tw-gap-2"},Ko.default.createElement("div",{className:"tw-text-sm"},t.question),Ko.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1"},t.options.map(d=>{let f=t.multiSelect?n instanceof Set&&n.has(d.label):n===d.label;return Ko.default.createElement("label",{key:d.label,className:"tw-flex tw-cursor-pointer tw-items-start tw-gap-2 tw-rounded tw-px-2 tw-py-1.5 hover:tw-bg-modifier-hover"},Ko.default.createElement("span",{className:"tw-flex tw-h-5 tw-shrink-0 tw-items-center"},Ko.default.createElement("input",{type:u,name:e,checked:f,disabled:i,onChange:()=>s(d.label),className:"tw-m-0"})),Ko.default.createElement("div",{className:"tw-min-w-0"},Ko.default.createElement("div",{className:"tw-text-sm tw-leading-5"},d.label),d.description?Ko.default.createElement("div",{className:"tw-text-xs tw-text-muted"},d.description):null))}),Ko.default.createElement("label",{className:"tw-flex tw-cursor-pointer tw-items-start tw-gap-2 tw-rounded tw-px-2 tw-py-1.5 hover:tw-bg-modifier-hover"},Ko.default.createElement("span",{className:"tw-flex tw-h-5 tw-shrink-0 tw-items-center"},Ko.default.createElement("input",{type:u,name:e,checked:r,disabled:i,onChange:a,className:"tw-m-0"})),Ko.default.createElement("div",{className:"tw-min-w-0"},Ko.default.createElement("div",{className:"tw-text-sm tw-leading-5"},"Other"),Ko.default.createElement("div",{className:"tw-text-xs tw-text-muted"},"Type your own response")))),r?Ko.default.createElement("textarea",{className:"tw-min-h-9 tw-w-full tw-resize-y tw-rounded tw-border tw-border-solid tw-border-border tw-bg-primary tw-px-2 tw-py-1 tw-text-sm tw-text-normal tw-outline-none focus:tw-border-border-focus",placeholder:"Type your response\u2026",value:o,disabled:i,autoFocus:!0,onChange:d=>l(d.target.value),onKeyDown:d=>{d.key==="Enter"&&(d.metaKey||d.ctrlKey)&&(d.preventDefault(),c())},rows:2}):null)}});function Ikr(t){switch(t){case"running":return"streaming";case"error":return"error";case"cancelled":return"cancelled";case"done":return"answer"}}function Tkr(t){return t.status==="done"&&t.text.trim().length===0?"empty":Ikr(t.status)}function jtn(t){return t.summary.status==="streaming"?"writing":t.summary.status==="pending"?Object.values(t.answers).some(n=>n.status==="running")?"waiting":"cancelled":"unavailable"}function Btn(t){let e=$a[t];return e?{displayName:e.displayName,Icon:e.Icon}:{displayName:t}}function ztn(t){return Btn(t).displayName}function Htn(t){let e=[{value:GI,label:"Summary"}];for(let n of Object.keys(t.answers)){let r=t.answers[n],{displayName:o,Icon:i}=Btn(n);e.push({value:n,label:o,Icon:i,state:Tkr(r)})}return e}function Wtn(t){return GI}function Vtn(t,e){return e===GI?null:t.answers[e]??null}var GI,CJe=b(()=>{Wm();GI="__summary__"});var mr,a_e,Pkr,Akr,kJe,Ekr,qtn,Mkr,XE,Ktn=b(()=>{i_e();CJe();n_e();De();Re();mr=L(B()),a_e=()=>mr.default.createElement("span",{className:"tw-flex tw-size-4 tw-shrink-0 tw-items-center tw-justify-center"},mr.default.createElement(A6,null)),Pkr=({option:t,selected:e,onSelect:n})=>{let{value:r,Icon:o,label:i,state:s}=t,a=(0,mr.useCallback)(()=>n(r),[n,r]);return mr.default.createElement("button",{type:"button",role:"tab","aria-selected":e,onClick:a,className:J("tw-flex tw-items-center tw-gap-1.5 tw-rounded-md tw-border tw-border-solid tw-border-transparent tw-px-2 tw-py-1 tw-text-sm tw-transition-colors",e?"tw-border-interactive-accent tw-font-medium tw-text-normal tw-bg-interactive-accent/10":"tw-text-muted hover:tw-bg-interactive-hover hover:tw-text-normal")},o?mr.default.createElement(o,{className:"tw-size-4 tw-shrink-0"}):null,mr.default.createElement("span",{className:"tw-max-w-32 tw-truncate"},i),mr.default.createElement(Akr,{state:s}))},Akr=({state:t})=>t==="streaming"?mr.default.createElement(Dr,{className:"tw-size-3 tw-shrink-0 tw-animate-spin tw-text-loading"}):t==="answer"?mr.default.createElement(Hr,{className:"tw-size-3 tw-shrink-0 tw-text-success"}):t==="error"?mr.default.createElement(Wr,{className:"tw-size-3 tw-shrink-0 tw-text-error"}):t==="cancelled"||t==="empty"?mr.default.createElement(PT,{className:"tw-size-3 tw-shrink-0 tw-text-muted"}):null,kJe=(0,mr.memo)(({turn:t,app:e,value:n,onSelect:r})=>{let o=(0,mr.useMemo)(()=>Htn(t),[t]);return mr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},mr.default.createElement("div",{role:"tablist","aria-label":"Agent answers",className:"tw-flex tw-flex-wrap tw-gap-1"},o.map(i=>mr.default.createElement(Pkr,{key:i.value,option:i,selected:i.value===n,onSelect:r}))),mr.default.createElement(Ekr,{turn:t,value:n,app:e}))});kJe.displayName="FanoutTurnView";Ekr=({turn:t,value:e,app:n})=>{if(e===GI){if(t.summary.text)return mr.default.createElement(qtn,{text:t.summary.text,app:n});switch(jtn(t)){case"writing":return mr.default.createElement(XE,{icon:mr.default.createElement(a_e,null),text:"Writing summary\u2026",shimmer:!0});case"waiting":return mr.default.createElement(XE,{icon:mr.default.createElement(a_e,null),text:"Waiting for answers\u2026",shimmer:!0});case"cancelled":return mr.default.createElement(XE,{icon:mr.default.createElement(PT,{className:"tw-size-4 tw-text-muted"}),text:"Summary cancelled"});case"unavailable":return mr.default.createElement(XE,{icon:mr.default.createElement(Wr,{className:"tw-size-4 tw-text-error"}),text:"Summary unavailable",tone:"error"})}}let r=Vtn(t,e);if(!r)return null;if(r.status==="error"||r.status==="cancelled"){let o=r.status==="error";return mr.default.createElement(Mkr,{app:n,partialText:r.text},mr.default.createElement(XE,{icon:o?mr.default.createElement(Wr,{className:"tw-size-4 tw-text-error"}):mr.default.createElement(PT,{className:"tw-size-4 tw-text-muted"}),text:o?r.error?.trim()||"This agent failed to answer.":"Cancelled",tone:o?"error":void 0}))}return r.text?mr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1"},mr.default.createElement(qtn,{text:r.text,app:n}),r.status==="running"?mr.default.createElement(XE,{icon:mr.default.createElement(a_e,null),text:"Streaming\u2026",shimmer:!0}):null):r.status==="done"?mr.default.createElement(XE,{icon:mr.default.createElement(PT,{className:"tw-size-4 tw-text-muted"}),text:"This agent did not answer."}):mr.default.createElement(XE,{icon:mr.default.createElement(a_e,null),text:"Thinking\u2026",shimmer:!0})},qtn=({text:t,app:e})=>mr.default.createElement(JE,{text:t,app:e}),Mkr=({partialText:t,app:e,children:n})=>t.trim()?mr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1"},mr.default.createElement(JE,{text:t,app:e}),n):mr.default.createElement(mr.default.Fragment,null,n),XE=({icon:t,text:e,tone:n,shimmer:r})=>mr.default.createElement("div",{className:J("tw-flex tw-items-center tw-gap-2 tw-p-1 tw-text-sm",n==="error"?"tw-text-error":"tw-text-muted")},t,mr.default.createElement("span",{className:J(r&&"copilot-shimmer-text")},e))});var Gtn,Xm,l_e,IJe=b(()=>{_Je();o_e();gt();De();ut();Re();Gtn=require("obsidian"),Xm=L(B()),l_e=({message:t,onInsertIntoEditor:e,onRegenerate:n,onEdit:r,onDelete:o,onShowSources:i,hasSources:s})=>Xm.default.createElement("div",{className:J("tw-flex tw-gap-1",{"group-hover:opacity-100 opacity-0":!Gtn.Platform.isMobile})},t.sender===ar?Xm.default.createElement(Xm.default.Fragment,null,Xm.default.createElement(see,{text:_h(t.message)}),r&&Xm.default.createElement(Yb,{label:"Edit",icon:ld,onClick:r}),o&&Xm.default.createElement(Yb,{label:"Delete",icon:Ts,onClick:o})):Xm.default.createElement(Xm.default.Fragment,null,s&&Xm.default.createElement(Yb,{label:"Show Sources",icon:CG,onClick:i}),Xm.default.createElement(Yb,{label:"Insert / Replace at cursor",icon:dN,onClick:e}),Xm.default.createElement(see,{text:_h(t.message)}),n&&Xm.default.createElement(Yb,{label:"Regenerate",icon:NG,onClick:n}),o&&Xm.default.createElement(Yb,{label:"Delete",icon:Ts,onClick:o})))});var Ff,TJe,Ztn=b(()=>{Ktn();CJe();IJe();aee();tA();ut();Ff=L(B()),TJe=(0,Ff.memo)(({message:t,turn:e,app:n,footerStart:r})=>{let[o,i]=(0,Ff.useState)(()=>Wtn(e)),s=o!==GI&&!e.answers[o]?GI:o,a=(0,Ff.useMemo)(()=>s===GI?oY(e,ztn):e.answers[s]?.text??"",[e,s]),l=(0,Ff.useCallback)(()=>{I2(n,a)},[n,a]),c=(0,Ff.useMemo)(()=>({id:t.id,sender:t.sender,message:a,timestamp:t.timestamp,isVisible:t.isVisible}),[t.id,t.sender,t.timestamp,t.isVisible,a]);return Ff.default.createElement("div",{className:"tw-my-1 tw-flex tw-w-full tw-flex-col"},Ff.default.createElement("div",{className:"tw-group tw-mx-2 tw-rounded-md tw-p-2"},Ff.default.createElement("div",{className:"tw-flex tw-max-w-full tw-flex-col tw-gap-2 tw-overflow-hidden"},Ff.default.createElement(kJe,{turn:e,app:n,value:s,onSelect:i}),Ff.default.createElement(KI,{leading:r,timestamp:t.timestamp?.display,actions:Ff.default.createElement(l_e,{message:c,onInsertIntoEditor:l,hasSources:!1})}))))});TJe.displayName="FanoutMessageCard"});function PJe(t,e){for(let n of t.workspace.getLeavesOfType(R6))Jtn(n.view)===e&&n.detach()}async function Ytn(t,e){let n=t.workspace.getLeavesOfType(R6).find(o=>Jtn(o.view)===e.proposalId);if(n){await n.view.setState(e),t.workspace.revealLeaf(n);return}let r=t.workspace.getLeaf(!0);await r.setViewState({type:R6,active:!0,state:e}),t.workspace.revealLeaf(r)}function Jtn(t){let e=t;if(typeof e.getProposalId!="function")return;let n=e.getProposalId();return typeof n=="string"?n:void 0}var u_e,va,R6,c_e,Okr,AJe=b(()=>{yt();pe();Pa();Re();lee();u_e=require("obsidian"),va=L(B()),R6="copilot-plan-preview-view",c_e=class extends u_e.ItemView{constructor(n){super(n);this.root=null;this.state=null}getViewType(){return R6}getIcon(){return"clipboard-list"}getDisplayText(){return this.state?.title?.trim()||"Plan proposal"}getProposalId(){return this.state?.proposalId}async setState(n){!n||!n.planMarkdown||(this.state=n,this.render())}getState(){return{}}async onOpen(){this.render()}async onClose(){this.root&&(this.root.unmount(),this.root=null)}render(){if(!this.state)return;let n=this.containerEl.children[1];if(!this.root){n.empty();let r=n.createDiv();this.root=Er(r,this.app)}this.root.render(va.default.createElement(Okr,{app:this.app,state:this.state}))}},Okr=({app:t,state:e})=>{let n=(0,va.useRef)(null),[r,o]=(0,va.useState)(!1),[i,s]=(0,va.useState)(()=>e.chatBackend?.getCurrentPlan()??null);(0,va.useEffect)(()=>{let h=e.chatBackend;if(h)return s(h.getCurrentPlan()),h.subscribe(()=>{s(h.getCurrentPlan())})},[e.chatBackend]);let a=i?i.body:e.planMarkdown,l=i?.title?.trim()||e.title?.trim()||"Plan proposal",c=i?.id??e.proposalId,u=i?.revision??0,d=i?.decision==="pending";(0,va.useEffect)(()=>{o(!1)},[c,u]),(0,va.useEffect)(()=>{let h=n.current;if(!h)return;h.classList.add("markdown-rendered"),h.empty();let g=new u_e.Component;g.load();let v=t.workspace.getActiveFile()?.path??"";return YE(t,a,h,v,g).catch(y=>{W("[PlanPreviewView] markdown render failed",y)}),()=>{g.unload(),h.empty()}},[t,a]);let f=async h=>{if(r||(o(!0),!e.chatBackend||!i))return;let g=i.id;try{await e.chatBackend.resolvePlanProposal(g,h),h==="approve"&&PJe(t,g)}catch(v){W("[PlanPreviewView] resolvePlanProposal failed",v)}},p=!r&&e.chatBackend&&i&&d,m=e.chatBackend&&!i;return va.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-col"},va.default.createElement("div",{className:"copilot-divider-b tw-flex tw-items-center tw-justify-between tw-gap-2 tw-px-3 tw-py-2"},va.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-2"},va.default.createElement(Jo,{className:"tw-size-4 tw-shrink-0 tw-text-muted"}),va.default.createElement("div",{className:"tw-truncate tw-text-sm tw-font-medium"},l),va.default.createElement("span",{className:"tw-rounded tw-bg-secondary tw-px-2 tw-py-0.5 tw-text-xs tw-text-muted"},"Read-only")),p?va.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},va.default.createElement(oe,{variant:"destructive",size:"sm",onClick:()=>void f("reject")},va.default.createElement(pn,{className:"tw-size-4"}),"Reject"),va.default.createElement(oe,{variant:"success",size:"sm",onClick:()=>void f("approve")},va.default.createElement(Hr,{className:"tw-size-4"}),"Approve")):null),m?va.default.createElement("div",{className:"tw-flex tw-flex-1 tw-items-center tw-justify-center tw-px-6 tw-py-4 tw-text-sm tw-text-muted"},"Plan no longer pending. Switch back to plan mode to start a new review."):va.default.createElement("div",{ref:n,className:"tw-flex-1 tw-overflow-auto tw-px-6 tw-py-4"}))}});function Dkr(t){return t.split(`
`).filter((n,r)=>!(r===0&&n.trim()==="")).slice(0,4).join(`
`)}var Zi,Nkr,Xtn,Rkr,Lkr,$kr,Qtn=b(()=>{yt();pe();AJe();Re();Zi=L(B());Hl();Nkr="Give feedback to redirect the plan\u2026",Xtn=({plan:t,app:e,chatBackend:n})=>{let[r,o]=(0,Zi.useState)(""),[i,s]=(0,Zi.useState)(!1),a=t.decision==="pending";(0,Zi.useEffect)(()=>{o(""),s(!1)},[t.id]);let l=async()=>{try{await Ytn(e,{proposalId:t.id,planMarkdown:t.body,title:t.title,chatBackend:n})}catch(d){W("[PlanProposalCard] failed to open preview",d)}},c=async(d,f)=>{if(!i){s(!0);try{await n.resolvePlanProposal(t.id,d,f),d==="approve"&&PJe(e,t.id)}finally{s(!1)}}},u=async()=>{let d=r.trim();d&&(await c("feedback",d),o(""))};return Zi.default.createElement("div",{className:"tw-mx-3 tw-my-2 tw-w-[calc(100%-1.5rem)] tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-secondary"},Zi.default.createElement("div",{className:"copilot-divider-b tw-flex tw-items-center tw-justify-between tw-gap-2 tw-px-3 tw-py-2"},Zi.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-2"},Zi.default.createElement(AT,{className:"tw-size-4 tw-shrink-0 tw-text-accent"}),Zi.default.createElement("div",{className:"tw-truncate tw-text-sm tw-font-medium"},t.title||"Plan proposed")),Zi.default.createElement(Lkr,{decision:t.decision})),Zi.default.createElement("div",{className:"tw-px-3 tw-py-2"},Zi.default.createElement($kr,{plan:t})),Zi.default.createElement("div",{className:"tw-flex tw-flex-wrap tw-items-center tw-justify-end tw-gap-2 tw-border-t tw-border-solid tw-border-border tw-px-3 tw-py-2"},Zi.default.createElement(oe,{variant:"secondary",size:"sm",onClick:xn(l)},Zi.default.createElement(Jo,{className:"tw-size-4"}),"Open"),a?Zi.default.createElement(Zi.default.Fragment,null,Zi.default.createElement(oe,{variant:"destructive",size:"sm",disabled:i,onClick:xn(()=>c("reject"))},Zi.default.createElement(pn,{className:"tw-size-4"}),"Reject"),Zi.default.createElement(oe,{variant:"success",size:"sm",disabled:i,onClick:xn(()=>c("approve"))},Zi.default.createElement(Hr,{className:"tw-size-4"}),"Approve")):null),a?Zi.default.createElement("div",{className:"tw-flex tw-items-stretch tw-gap-2 tw-border-t tw-border-solid tw-border-border tw-px-3 tw-py-2"},Zi.default.createElement("textarea",{className:"tw-min-h-9 tw-flex-1 tw-resize-y tw-rounded tw-border tw-border-solid tw-border-border tw-bg-primary tw-px-2 tw-py-1 tw-text-sm tw-text-normal tw-outline-none focus:tw-border-border-focus",placeholder:Nkr,value:r,disabled:i,onChange:d=>o(d.target.value),onKeyDown:d=>{d.key==="Enter"&&(d.metaKey||d.ctrlKey)&&(d.preventDefault(),u())},rows:2}),Zi.default.createElement(oe,{variant:"default",size:"sm",disabled:i||r.trim().length===0,onClick:()=>void u()},Zi.default.createElement(zC,{className:"tw-size-4"}),"Send")):null)},Rkr={pending:{label:"Pending",cls:"tw-bg-modifier-message tw-text-muted"},approved:{label:"Approved",cls:"tw-bg-success tw-text-success"},rejected:{label:"Rejected",cls:"tw-bg-error tw-text-error"},rejected_with_feedback:{label:"Feedback sent",cls:"tw-bg-error tw-text-error"}},Lkr=({decision:t})=>{let{label:e,cls:n}=Rkr[t];return Zi.default.createElement("span",{className:`tw-rounded tw-px-2 tw-py-0.5 tw-text-xs ${n}`},e)},$kr=({plan:t})=>Zi.default.createElement("pre",{className:"tw-m-0 tw-whitespace-pre-wrap tw-break-words tw-text-xs tw-text-muted"},Dkr(t.body))});function Ukr(t){switch(t){case"allow_once":case"reject_once":return"secondary";case"allow_always":return"default";case"reject_always":return"destructive"}}function jkr(t){return[...t].sort((e,n)=>eA.indexOf(e.kind)-eA.indexOf(n.kind))}function Bkr(t){if(t.length===0)return Fkr;let e=new Map,n=new Map,r=new Set(t.map(o=>o.name));for(let o of t)e.set(o.name,(e.get(o.name)??0)+1);return t.map(o=>{if(e.get(o.name)===1)return o.name;let i=(n.get(o.name)??0)+1;for(;r.has(`${o.name} ${i}`);)i++;n.set(o.name,i);let s=`${o.name} ${i}`;return r.add(s),s})}var Ai,Fkr,enn,tnn=b(()=>{yt();Oc();fJe();rz();Re();Ai=L(B()),Fkr=Object.freeze([]),enn=({request:t,onResolve:e})=>{let{toolCall:n,options:r}=t,[o,i]=(0,Ai.useState)(!1),s=(0,Ai.useMemo)(()=>jkr(r),[r]),a=(0,Ai.useMemo)(()=>Bkr(s),[s]),l=(0,Ai.useMemo)(()=>stn(n.content),[n.content]),c=(0,Ai.useMemo)(()=>itn(n.rawInput),[n.rawInput]),u=n.title??"Tool call",d=f=>{o||(i(!0),e(n.toolCallId,f))};return Ai.default.createElement("div",{className:"tw-mx-3 tw-my-2 tw-w-[calc(100%-1.5rem)] tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-secondary"},Ai.default.createElement("div",{className:"copilot-divider-b tw-flex tw-items-center tw-gap-2 tw-px-3 tw-py-2"},Ai.default.createElement(LG,{className:"tw-size-4 tw-shrink-0 tw-text-accent"}),Ai.default.createElement("div",{className:"tw-truncate tw-text-sm tw-font-medium"},"Permission required")),Ai.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2 tw-px-3 tw-py-2"},Ai.default.createElement("p",{className:"tw-m-0 tw-text-sm"},"Agent Mode wants to run ",Ai.default.createElement("strong",null,u),"."),n.kind?Ai.default.createElement("p",{className:"tw-m-0 tw-text-xs tw-text-muted"},"Kind: ",Ai.default.createElement("code",null,n.kind)):null,l.length>0?Ai.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},l.map((f,p)=>Ai.default.createElement("div",{key:`diff-${p}-${f.path}`,className:"tw-rounded tw-border tw-border-solid tw-border-border tw-p-2"},Ai.default.createElement("p",{className:"tw-mb-1 tw-font-mono tw-text-xs tw-text-muted"},f.path),Ai.default.createElement("pre",{className:"tw-max-h-48 tw-overflow-auto tw-whitespace-pre-wrap tw-text-xs"},Qbe(f.oldText,f.newText))))):c?Ai.default.createElement("details",null,Ai.default.createElement("summary",{className:"tw-cursor-pointer tw-text-xs tw-text-muted"},"Show inputs"),Ai.default.createElement("pre",{className:"tw-mt-1 tw-max-h-48 tw-overflow-auto tw-rounded tw-bg-primary tw-p-2 tw-text-xs"},c)):null),Ai.default.createElement("div",{className:"tw-flex tw-flex-wrap tw-items-center tw-justify-end tw-gap-2 tw-border-t tw-border-solid tw-border-border tw-px-3 tw-py-2"},Ai.default.createElement(sf,{delayDuration:0},s.map((f,p)=>{let m=Ai.default.createElement(oe,{key:f.optionId,variant:Ukr(f.kind),size:"sm",className:"tw-h-auto tw-min-h-6 tw-min-w-0 tw-max-w-full tw-whitespace-normal",disabled:o,onClick:()=>d(f.optionId)},Ai.default.createElement("span",{className:"tw-min-w-0 tw-break-all"},a[p]));return f.description?Ai.default.createElement(hr,{key:f.optionId},Ai.default.createElement(gr,{asChild:!0},m),Ai.default.createElement(fr,{side:"top",className:"tw-max-w-sm tw-whitespace-pre-wrap tw-break-words"},f.description)):m}))))}});var L6,d_e,nnn=b(()=>{pe();L6=require("obsidian"),d_e=class extends L6.Modal{constructor(e,n){super(e),this.sources=n}onOpen(){let{contentEl:e}=this;e.empty(),new L6.Setting(e).setName("Sources").setHeading(),this.createSourceList(e,this.sources)}createSourceList(e,n){let r=e.createEl("ul");r.addClass("tw-list-none","tw-p-0"),n.forEach(o=>{let i=r.createEl("li");i.addClass("tw-mb-4");let s=i.createDiv();s.addClass("tw-cursor-pointer");let a=s.createSpan();a.addClass("tw-mr-2","tw-inline-block","tw-w-4","tw-transition-transform"),a.textContent=o.explanation?"\u25B6":"";let l=o.path&&o.path!==o.title?`${o.title} (${o.path})`:o.title,c=s.createEl("a",{href:`obsidian://open?vault=${encodeURIComponent(this.app.vault.getName())}&file=${encodeURIComponent(o.path||o.title)}`,text:l});c.title=`${l} - drag to insert wikilink`,c.draggable=!0,c.addEventListener("dragstart",d=>{let f=o.path||o.title,p=this.app.vault.getAbstractFileByPath(f);if(p instanceof L6.TFile){let m=this.app.dragManager;if(!m)return;let h=this.app.metadataCache.fileToLinktext(p,""),g=m.dragLink(d,h);m.onDragStart(d,g)}}),c.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),this.app.workspace.openLinkText(o.path||o.title,"").catch(H)}),typeof o.score=="number"&&s.appendChild(this.contentEl.doc.createTextNode(` - Relevance score: ${o.score.toFixed(4)}`));let u=null;o.explanation&&(u=this.addExplanation(i,o.explanation),u.addClass("tw-hidden"),s.addEventListener("click",d=>{if(d.target!==c&&u){let f=!u.hasClass("tw-hidden");u.toggleClass("tw-hidden",f),a.toggleClass("tw-rotate-90",!f)}}))})}addExplanation(e,n){let r=e.createDiv({cls:"search-explanation"});r.addClass("tw-ml-[2.5em]","tw-mt-2","tw-pl-2","tw-text-[0.9em]","tw-text-muted","tw-border-l","tw-border-l-border");let o=n,i=[];if(o.lexicalMatches&&o.lexicalMatches.length>0){let s=o.lexicalMatches,a=new Set(s.map(c=>c.field)),l=new Set(s.map(c=>c.query));i.push(`Lexical: matched "${Array.from(l).join('", "')}" in ${Array.from(a).join(", ")}`)}if(o.semanticScore!==void 0&&o.semanticScore>0&&i.push(`Semantic: ${(o.semanticScore*100).toFixed(1)}% similarity`),o.folderBoost){let s=o.folderBoost;i.push(`Folder boost: ${s.boostFactor.toFixed(2)}x (${s.documentCount} docs in ${s.folder||"root"})`)}if(o.graphConnections){let s=o.graphConnections,a=[];s.backlinks>0&&a.push(`${s.backlinks} backlinks`),s.coCitations>0&&a.push(`${s.coCitations} co-citations`),s.sharedTags>0&&a.push(`${s.sharedTags} shared tags`),a.length>0&&i.push(`Graph connections: ${s.score.toFixed(1)} score (${a.join(", ")})`)}if(o.graphBoost&&!o.graphConnections){let s=o.graphBoost;i.push(`Graph boost: ${s.boostFactor.toFixed(2)}x (${s.connections} connections)`)}return o.baseScore!==o.finalScore&&i.push(`Score: ${o.baseScore.toFixed(4)} \u2192 ${o.finalScore.toFixed(4)}`),i.length>0&&i.forEach(s=>{let a=r.createDiv();a.addClass("tw-mb-1"),a.textContent=`\u2022 ${s}`}),r}onClose(){let{contentEl:e}=this;e.empty()}}});function Hkr(t,e){return e&&e>1?t.current?t.current.offsetHeight<t.current.scrollHeight:!1:(t.current&&t.current?.offsetWidth+zkr<t.current?.scrollWidth)??!1}function Wkr(t){switch(t){case 2:return"tw-line-clamp-2";case 3:return"tw-line-clamp-3";default:return""}}var $6,f_e,zkr,si,rnn=b(()=>{$6=L(B());Oc();Oc();De();f_e=L(B()),zkr=2;si=({children:t,className:e,lineClamp:n,tooltipContent:r,alwaysShowTooltip:o=!1,...i})=>{let s=(0,f_e.useRef)(null),[a,l]=(0,f_e.useState)(!1);return $6.default.createElement(sf,{delayDuration:0},$6.default.createElement(hr,{open:a,onOpenChange:u=>{l(u&&(o||Hkr(s,n)))}},$6.default.createElement(gr,{asChild:!0},$6.default.createElement("div",{...i,ref:s,className:J("tw-max-w-full tw-text-normal",(!n||n<=1)&&"tw-truncate",n&&Wkr(n),e),"data-testid":"truncatedText"},t)),$6.default.createElement(fr,{className:"tw-max-w-64 tw-text-wrap tw-break-words"},r??t)))}});var kS=b(()=>{rnn()});function IS({children:t,icon:e,onRemove:n,className:r,isClickable:o=!1,...i}){return D6.default.createElement(ei,{variant:"default",tabIndex:n?0:void 0,className:J("tw-group/badge tw-items-center tw-gap-1 tw-border tw-border-solid tw-border-border tw-py-1 tw-pl-1.5 tw-pr-2 tw-text-xs",o&&"tw-cursor-pointer hover:tw-bg-interactive-hover",r),onKeyDown:n?s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),s.stopPropagation(),n())}:void 0,...i},D6.default.createElement("span",{className:"tw-relative tw-size-4 tw-shrink-0"},D6.default.createElement("span",{className:J("tw-flex tw-size-full tw-items-center tw-justify-center",n&&"context-badge-icon-removable group-focus-within/badge:tw-invisible group-hover/badge:tw-invisible")},e),n&&D6.default.createElement("div",{"aria-hidden":"true",className:"context-badge-close tw-invisible tw-absolute tw-inset-0 tw-flex tw-items-center tw-justify-center tw-text-muted group-focus-within/badge:tw-visible group-hover/badge:tw-visible",onClick:s=>{s.stopPropagation(),n()}},D6.default.createElement(pn,{className:"tw-size-3"}))),t)}var D6,onn=b(()=>{D6=L(B());Re();pm();De()});function Vkr({faviconUrl:t,className:e}){let[n,r]=xr.default.useState(!1);return n?xr.default.createElement(Xo,{className:e}):xr.default.createElement("img",{src:t,alt:"",referrerPolicy:"no-referrer",loading:"lazy",decoding:"async",className:J(e,"tw-rounded-sm"),onError:()=>r(!0)})}function EJe({faviconUrl:t,isLoaded:e=!0,className:n="tw-size-3"}){return e?t?xr.default.createElement(Vkr,{key:t,faviconUrl:t,className:n}):xr.default.createElement(Xo,{className:n}):xr.default.createElement(OC,{className:J(n,"tw-text-muted")})}function inn({currentActiveFile:t,onRemove:e,onClick:n}){if(!t)return null;let r=xr.default.createElement("div",{className:"tw-text-left"},t.path),o=t.extension==="pdf",i=t.extension==="canvas";return xr.default.createElement(IS,{icon:xr.default.createElement(Jo,{className:"tw-size-3"}),onRemove:e,isClickable:!!n,onClick:n},xr.default.createElement(si,{className:"tw-max-w-40",tooltipContent:r,alwaysShowTooltip:!0},t.basename),xr.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"Current"),o&&xr.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"pdf"),i&&xr.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"canvas"))}function snn({activeWebTab:t,onRemove:e,onClick:n}){if(!t)return null;let r=tN(t.url),o=t.title||r||t.url||"Untitled",i=xr.default.createElement("div",{className:"tw-text-left"},t.url);return xr.default.createElement(IS,{icon:xr.default.createElement(EJe,{faviconUrl:t.faviconUrl}),onRemove:e,isClickable:!!n,onClick:n},xr.default.createElement(si,{className:"tw-max-w-40",tooltipContent:i,alwaysShowTooltip:!0},o),xr.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"Current"))}function p_e({note:t,onRemove:e,onClick:n}){let r=xr.default.createElement("div",{className:"tw-text-left"},t.path),o=t.extension==="pdf",i=t.extension==="canvas";return xr.default.createElement(IS,{icon:xr.default.createElement(Jo,{className:"tw-size-3"}),onRemove:e,isClickable:!!n,onClick:n},xr.default.createElement(si,{className:"tw-max-w-40",tooltipContent:r,alwaysShowTooltip:!0},t.basename),o&&xr.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"pdf"),i&&xr.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"canvas"))}function m_e({url:t,onRemove:e}){return xr.default.createElement(IS,{icon:xr.default.createElement(Ch,{className:"tw-size-3"}),onRemove:e},xr.default.createElement(si,{className:"tw-max-w-40",tooltipContent:t},tN(t)))}function h_e({webTab:t,onRemove:e,onClick:n}){let r=t.isLoaded!==!1,o=tN(t.url),i=t.title||o||t.url||"Untitled",s=r?t.url:"Tab not loaded - switch to this tab to load content";return xr.default.createElement(IS,{icon:xr.default.createElement(EJe,{faviconUrl:t.faviconUrl,isLoaded:r}),onRemove:e,isClickable:!!n,onClick:n,className:J(!r&&"tw-opacity-60")},xr.default.createElement(si,{className:J("tw-max-w-40",!r&&"tw-italic"),tooltipContent:s},i),!r&&xr.default.createElement("span",{className:"tw-text-xs tw-text-muted"},"(not loaded)"))}function ann({tag:t,onRemove:e}){let n=t.startsWith("#")?t.slice(1):t;return xr.default.createElement(IS,{icon:xr.default.createElement(sN,{className:"tw-size-3"}),onRemove:e},xr.default.createElement(si,{className:"tw-max-w-40",tooltipContent:t},n))}function g_e({folder:t,onRemove:e}){return xr.default.createElement(IS,{icon:xr.default.createElement(Fl,{className:"tw-size-3"}),onRemove:e},xr.default.createElement(si,{className:"tw-max-w-40",tooltipContent:t,alwaysShowTooltip:!0},t))}function y_e({selectedText:t,onRemove:e}){if(oz(t)){let o=tN(t.url),i=xr.default.createElement("div",{className:"tw-text-left"},t.url);return xr.default.createElement(IS,{icon:xr.default.createElement(EJe,{faviconUrl:t.faviconUrl}),onRemove:e},xr.default.createElement(si,{className:"tw-max-w-40",tooltipContent:i,alwaysShowTooltip:!0},t.title||o),xr.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"Selection"))}let n=t.startLine===t.endLine?`L${t.startLine}`:`L${t.startLine}-${t.endLine}`,r=xr.default.createElement("div",{className:"tw-text-left"},t.notePath," (",n,")");return xr.default.createElement(IS,{icon:xr.default.createElement(Jo,{className:"tw-size-3"}),onRemove:e},xr.default.createElement(si,{className:"tw-max-w-40",tooltipContent:r,alwaysShowTooltip:!0},t.noteTitle),xr.default.createElement("span",{className:"tw-text-xs tw-text-faint"},n))}var xr,MJe=b(()=>{xr=L(B());Re();kS();ut();De();onn();rY()});function F6({className:t}){return uee.default.createElement("span",{onClick:e=>e.stopPropagation(),className:J("tw-pointer-events-auto tw-flex tw-shrink-0 tw-items-center tw-text-muted",t)},uee.default.createElement(rs,{content:lnn,side:"top",delayDuration:0},uee.default.createElement(TG,{className:"tw-size-3.5"})),uee.default.createElement("span",{className:"tw-sr-only"},lnn))}var uee,lnn,v_e=b(()=>{De();Lh();Re();uee=L(B()),lnn="Copilot license required"});function U6({disabled:t=!1,size:e="fit",variant:n="ghost2",className:r,value:o,onChange:i,models:s,apiKeySettings:a}){let[l,c]=(0,wa.useState)(null),u=s.find(p=>(p.enabled??!0)&&Jn(p)===o),d=s.filter(p=>p.enabled!==!1),f;return wa.default.createElement(up,null,wa.default.createElement(dp,{asChild:!0},wa.default.createElement(oe,{variant:n,size:e,disabled:t,className:J("tw-min-w-0 tw-justify-start tw-text-muted",r)},wa.default.createElement("div",{className:"tw-min-w-0 tw-flex-1 tw-truncate"},l?wa.default.createElement("span",{className:"tw-truncate tw-text-error"},"Model Load Failed"):u?wa.default.createElement(Xj,{model:u,iconSize:8}):wa.default.createElement("span",{className:"tw-truncate"},"Select Model")),u?._needsSelfHostWarning&&wa.default.createElement(Fy,{className:"tw-mt-0.5",stopPropagation:!1}),!t&&wa.default.createElement(Bs,{className:"tw-mt-0.5 tw-size-5 tw-shrink-0"}))),wa.default.createElement(Ac,{align:"start",className:"tw-max-h-64 tw-overflow-y-auto"},d.map(p=>{let m=p._disabledReason,h=a?AEe(p,a).hasApiKey:!0,g=!!m||!h,v=p._needsLicense?null:m??(h?null:"Needs API key"),y=p._group!==void 0&&p._group!==f,w=`__group__${p._group}__${Jn(p)}`;return f=p._group,wa.default.createElement(wa.default.Fragment,{key:Jn(p)},y&&wa.default.createElement(uUe,{key:w,className:"tw-text-xs tw-uppercase tw-tracking-wide tw-text-faint"},p._group),wa.default.createElement(co,{disabled:g,title:m??void 0,onSelect:_=>{if(g){_.preventDefault();return}try{c(null),i(Jn(p))}catch(S){let I="Model switch failed: "+kt(S);c(I);let C=s.find(k=>k.enabled!==!1&&Jn(k)===o);C&&i(Jn(C))}},className:g?"tw-cursor-not-allowed tw-opacity-50":""},wa.default.createElement("div",{className:"tw-min-w-0"},wa.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-1"},wa.default.createElement(Xj,{model:p,iconSize:12}),p._needsLicense&&wa.default.createElement(F6,null),p._needsSelfHostWarning&&wa.default.createElement(Fy,null)),p._subtitle&&wa.default.createElement("div",{className:"tw-truncate tw-text-xs tw-text-muted"},p._subtitle)),v&&wa.default.createElement("span",{className:"tw-ml-auto tw-text-smallest tw-text-faint"},v)))})))}var wa,w_e=b(()=>{wa=L(B());yt();xk();MZ();v_e();qj();Mie();eK();Re();De()});function b_e(t){return`${t.name}-${t.size}-${t.lastModified}-${t.type}`}function __e(t,e){if(e.length===0)return t;let n=new Set(t.map(b_e)),r=e.filter(o=>{let i=b_e(o);return n.has(i)?!1:(n.add(i),!0)});return r.length===0?t:[...t,...r]}var x_e=b(()=>{});var rQe={};sr(rQe,{$addUpdateTag:()=>won,$applyNodeReplacement:()=>Ree,$caretFromPoint:()=>lM,$caretRangeFromSelection:()=>yXe,$cloneWithProperties:()=>Ion,$comparePointCaretNext:()=>eQe,$copyNode:()=>GXe,$create:()=>x0r,$createLineBreakNode:()=>G6,$createNodeSelection:()=>RXe,$createParagraphNode:()=>n0,$createPoint:()=>n_,$createRangeSelection:()=>Yrn,$createRangeSelectionFromDom:()=>qIr,$createTabNode:()=>exe,$createTextNode:()=>Gu,$extendCaretToRange:()=>XXe,$getAdjacentChildCaret:()=>rV,$getAdjacentNode:()=>yon,$getAdjacentSiblingOrParentSiblingCaret:()=>E0r,$getCaretInDirection:()=>cM,$getCaretRange:()=>aM,$getCaretRangeInDirection:()=>nQe,$getCharacterOffsets:()=>cXe,$getChildCaret:()=>i0,$getChildCaretAtIndex:()=>Ron,$getChildCaretOrSelf:()=>Aon,$getCollapsedCaretRange:()=>Eon,$getCommonAncestor:()=>vee,$getCommonAncestorResultBranchOrder:()=>tQe,$getEditor:()=>ZXe,$getNearestNodeFromDOMNode:()=>sxe,$getNearestRootOrShadowRoot:()=>_on,$getNodeByKey:()=>ou,$getNodeByKeyOrThrow:()=>xon,$getPreviousSelection:()=>W$,$getRoot:()=>th,$getSelection:()=>pi,$getSiblingCaret:()=>Qu,$getState:()=>L_e,$getStateChange:()=>bIr,$getTextContent:()=>ZIr,$getTextNodeOffset:()=>t_,$getTextPointCaret:()=>sM,$getTextPointCaretSlice:()=>hXe,$getWritableNodeState:()=>kXe,$hasAncestor:()=>Z_e,$hasUpdateTag:()=>g0r,$insertNodes:()=>GIr,$isBlockElementNode:()=>VIr,$isChildCaret:()=>e_,$isDecoratorNode:()=>vs,$isElementNode:()=>Ye,$isExtendableTextPointCaret:()=>Non,$isInlineElementOrDecoratorNode:()=>y0r,$isLeafNode:()=>p0r,$isLineBreakNode:()=>$$,$isNodeCaret:()=>k0r,$isNodeSelection:()=>txe,$isParagraphNode:()=>o0r,$isRangeSelection:()=>jn,$isRootNode:()=>Qm,$isRootOrShadowRoot:()=>r_,$isSiblingCaret:()=>H$,$isTabNode:()=>NXe,$isTextNode:()=>dn,$isTextPointCaret:()=>r0,$isTextPointCaretSlice:()=>A0r,$isTokenOrSegmented:()=>XI,$isTokenOrTab:()=>tM,$nodesOfType:()=>h0r,$normalizeCaret:()=>Xb,$normalizeSelection__EXPERIMENTAL:()=>$_e,$onUpdate:()=>bon,$parseSerializedNode:()=>XIr,$removeTextFromCaretRange:()=>Oon,$rewindSiblingCaret:()=>aV,$selectAll:()=>m0r,$setCompositionKey:()=>Yu,$setPointFromCaret:()=>oV,$setSelection:()=>nh,$setSelectionFromCaretRange:()=>Mon,$setState:()=>_Ir,$splitAtPointCaretNext:()=>N0r,$splitNode:()=>v0r,$updateRangeSelectionFromCaretRange:()=>wee,ArtificialNode__DO_NOT_USE:()=>q_e,BLUR_COMMAND:()=>Lrn,CAN_REDO_COMMAND:()=>NIr,CAN_UNDO_COMMAND:()=>RIr,CLEAR_EDITOR_COMMAND:()=>MIr,CLEAR_HISTORY_COMMAND:()=>OIr,CLICK_COMMAND:()=>yrn,COLLABORATION_TAG:()=>ron,COMMAND_PRIORITY_CRITICAL:()=>c0r,COMMAND_PRIORITY_EDITOR:()=>i0r,COMMAND_PRIORITY_HIGH:()=>l0r,COMMAND_PRIORITY_LOW:()=>s0r,COMMAND_PRIORITY_NORMAL:()=>a0r,CONTROLLED_TEXT_INSERTION_COMMAND:()=>z6,COPY_COMMAND:()=>EXe,CUT_COMMAND:()=>MXe,DELETE_CHARACTER_COMMAND:()=>Iee,DELETE_LINE_COMMAND:()=>Pee,DELETE_WORD_COMMAND:()=>Tee,DRAGEND_COMMAND:()=>Nrn,DRAGOVER_COMMAND:()=>Orn,DRAGSTART_COMMAND:()=>Mrn,DROP_COMMAND:()=>Ern,DecoratorNode:()=>Aee,ElementNode:()=>iM,FOCUS_COMMAND:()=>Rrn,FORMAT_ELEMENT_COMMAND:()=>EIr,FORMAT_TEXT_COMMAND:()=>QE,HISTORIC_TAG:()=>QIr,HISTORY_MERGE_TAG:()=>M_e,HISTORY_PUSH_TAG:()=>e0r,INDENT_CONTENT_COMMAND:()=>PIr,INSERT_LINE_BREAK_COMMAND:()=>mee,INSERT_PARAGRAPH_COMMAND:()=>eXe,INSERT_TAB_COMMAND:()=>TIr,INTERNAL_$isBlock:()=>t0,IS_ALL_FORMATTING:()=>nrn,IS_BOLD:()=>tIr,IS_CODE:()=>rIr,IS_HIGHLIGHT:()=>J_e,IS_ITALIC:()=>nIr,IS_STRIKETHROUGH:()=>_ee,IS_SUBSCRIPT:()=>oIr,IS_SUPERSCRIPT:()=>iIr,IS_UNDERLINE:()=>xee,KEY_ARROW_DOWN_COMMAND:()=>Crn,KEY_ARROW_LEFT_COMMAND:()=>_rn,KEY_ARROW_RIGHT_COMMAND:()=>wrn,KEY_ARROW_UP_COMMAND:()=>Srn,KEY_BACKSPACE_COMMAND:()=>Irn,KEY_DELETE_COMMAND:()=>Prn,KEY_DOWN_COMMAND:()=>vrn,KEY_ENTER_COMMAND:()=>j_e,KEY_ESCAPE_COMMAND:()=>Trn,KEY_MODIFIER_COMMAND:()=>$rn,KEY_SPACE_COMMAND:()=>krn,KEY_TAB_COMMAND:()=>Arn,LineBreakNode:()=>K6,MOVE_TO_END:()=>brn,MOVE_TO_START:()=>xrn,NODE_STATE_KEY:()=>pIr,OUTDENT_CONTENT_COMMAND:()=>AIr,PASTE_COMMAND:()=>TXe,PASTE_TAG:()=>t0r,ParagraphNode:()=>J6,REDO_COMMAND:()=>AXe,REMOVE_TEXT_COMMAND:()=>tXe,RootNode:()=>Y6,SELECTION_CHANGE_COMMAND:()=>IXe,SELECTION_INSERT_CLIPBOARD_NODES_COMMAND:()=>IIr,SELECT_ALL_COMMAND:()=>nXe,SKIP_COLLAB_TAG:()=>n0r,SKIP_DOM_SELECTION_TAG:()=>ion,SKIP_SCROLL_INTO_VIEW_TAG:()=>oon,TEXT_TYPE_TO_FORMAT:()=>Uf,TabNode:()=>Z6,TextNode:()=>j$,UNDO_COMMAND:()=>PXe,buildImportMap:()=>DIr,createCommand:()=>Pr,createEditor:()=>u0r,createSharedNodeState:()=>crn,createState:()=>wIr,flipDirection:()=>uM,getDOMOwnerDocument:()=>qXe,getDOMSelection:()=>ES,getDOMSelectionFromTarget:()=>Son,getDOMTextNode:()=>z$,getEditorPropertyFromDOMNode:()=>Oee,getNearestEditorFromDOMNode:()=>BXe,getRegisteredNode:()=>UXe,getRegisteredNodeOrThrow:()=>FXe,isBlockDomNode:()=>pXe,isCurrentlyReadOnlyMode:()=>iV,isDOMDocumentNode:()=>lon,isDOMNode:()=>sV,isDOMTextNode:()=>MS,isDOMUnmanaged:()=>Pon,isDocumentFragment:()=>Con,isExactShortcutMatch:()=>Ui,isHTMLAnchorElement:()=>w0r,isHTMLElement:()=>Bp,isInlineDomNode:()=>kon,isLexicalEditor:()=>oxe,isModifierMatch:()=>gon,isSelectionCapturedInDecoratorInput:()=>jXe,isSelectionWithinEditor:()=>Mee,makeStepwiseIterator:()=>QXe,removeFromParent:()=>nM,resetRandomKey:()=>d0r,setDOMUnmanaged:()=>_0r,setNodeIndentFromDOM:()=>Ton});function tt(t,...e){let n=new URL("https://lexical.dev/docs/error"),r=new URLSearchParams;r.append("code",t);for(let o of e)r.append("v",o);throw n.search=r.toString(),Error(`Minified Lexical error #${t}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}function R_e(...t){let e=[];for(let n of t)if(n&&typeof n=="string")for(let[r]of n.matchAll(/\S+/g))e.push(r);return e}function irn(t,e,n,r,o,i){let s=t.getFirstChild();for(;s!==null;){let a=s.__key;s.__parent===e&&(Ye(s)&&irn(s,a,n,r,o,i),n.has(a)||i.delete(a),o.push(a)),s=s.getNextSibling()}}function hIr(t){CXe=t.timeStamp}function OJe(t,e,n){let r=t.nodeName==="BR",o=e.__lexicalLineBreak;return o&&(t===o||r&&t.previousSibling===o)||r&&ixe(t,n)!==void 0}function gIr(t,e,n){let r=ES(Rv(n)),o=null,i=null;r!==null&&r.anchorNode===t&&(o=r.anchorOffset,i=r.focusOffset);let s=t.nodeValue;s!==null&&WXe(e,s,o,i,!1)}function yIr(t,e,n){if(jn(t)){let r=t.anchor.getNode();if(r.is(n)&&t.format!==r.getFormat())return!1}return MS(e)&&n.isAttached()}function vIr(t,e,n,r){for(let o=t;o&&!Pon(o);o=Nee(o)){let i=ixe(o,e);if(i!==void 0){let s=ou(i,n);if(s)return vs(s)||!Bp(o)?void 0:[o,s]}else if(o===r)return[r,fon(n)]}}function srn(t,e,n){VJe=!0;let r=performance.now()-CXe>mIr;try{Tg(t,()=>{let o=pi()||function(f){return f.getEditorState().read(()=>{let p=pi();return p!==null?p.clone():null})}(t),i=new Map,s=t.getRootElement(),a=t._editorState,l=t._blockCursorElement,c=!1,u="";for(let f=0;f<e.length;f++){let p=e[f],m=p.type,h=p.target,g=vIr(h,t,a,s);if(!g)continue;let[v,y]=g;if(m==="characterData")r&&dn(y)&&MS(h)&&yIr(o,h,y)&&gIr(h,y,t);else if(m==="childList"){c=!0;let w=p.addedNodes;for(let I=0;I<w.length;I++){let C=w[I],k=uon(C),T=C.parentNode;if(T!=null&&C!==l&&k===null&&!OJe(C,T,t)){if(D$){let P=(Bp(C)?C.innerText:null)||C.nodeValue;P&&(u+=P)}T.removeChild(C)}}let _=p.removedNodes,S=_.length;if(S>0){let I=0;for(let C=0;C<S;C++){let k=_[C];(OJe(k,h,t)||l===k)&&(h.appendChild(k),I++)}S!==I&&i.set(v,y)}}}if(i.size>0)for(let[f,p]of i)p.reconcileObservedMutation(f,t);let d=n.takeRecords();if(d.length>0){for(let f=0;f<d.length;f++){let p=d[f],m=p.addedNodes,h=p.target;for(let g=0;g<m.length;g++){let v=m[g],y=v.parentNode;y==null||v.nodeName!=="BR"||OJe(v,h,t)||y.removeChild(v)}}n.takeRecords()}o!==null&&(c&&nh(o),D$&&von(t)&&o.insertRawText(u))})}finally{VJe=!1}}function arn(t){let e=t._observer;e!==null&&srn(t,e.takeRecords(),e)}function lrn(t){(function(e){CXe===0&&Rv(e).addEventListener("textInput",hIr,!0)})(t),t._observer=new MutationObserver((e,n)=>{srn(t,e,n)})}function wIr(t,e){return new qJe(t,e)}function L_e(t,e,n="latest"){let r=(n==="latest"?t.getLatest():t).__state;return r?r.getValue(e):e.defaultValue}function bIr(t,e,n){let r=L_e(t,n,"direct"),o=L_e(e,n,"direct");return n.isEqual(r,o)?null:[r,o]}function _Ir(t,e,n){let r;if(Zu(),typeof n=="function"){let i=t.getLatest(),s=L_e(i,e);if(r=n(s),e.isEqual(s,r))return i}else r=n;let o=t.getWritable();return kXe(o).updateFromKnown(e,r),o}function crn(t){let e=new Map,n=new Set;for(let r=typeof t=="function"?t:t.replace;r.prototype&&r.prototype.getType!==void 0;r=Object.getPrototypeOf(r)){let{ownNodeConfig:o}=YXe(r);if(o&&o.stateConfigs)for(let i of o.stateConfigs){let s;"stateConfig"in i?(s=i.stateConfig,i.flat&&n.add(s.key)):s=i,e.set(s.key,s)}}return{flatKeys:n,sharedConfigMap:e}}function kXe(t){let e=t.getWritable(),n=e.__state?e.__state.getWritable(e):new KJe(e,urn(e));return e.__state=n,n}function urn(t){return t.__state?t.__state.sharedNodeState:FXe(ZXe(),t.getType()).sharedNodeState}function fnn(t){if(t)for(let e in t)return t}function xIr(t){return t}function pnn(t,e,n){for(let[r,o]of e.knownState){if(t.has(r.key))continue;t.add(r.key);let i=n?n.getValue(r):r.defaultValue;if(i!==o&&!r.isEqual(i,o))return!0}return!1}function mnn(t,e,n){let{unknownState:r}=e,o=n?n.unknownState:void 0;if(r){for(let[i,s]of Object.entries(r))if(!t.has(i)&&(t.add(i),s!==(o?o[i]:void 0)))return!0}return!1}function hnn(t,e){let n=t.__state;return n&&n.node===t?n.getWritable(e):n}function gnn(t,e){let n=t.__mode,r=t.__format,o=t.__style,i=e.__mode,s=e.__format,a=e.__style,l=t.__state,c=e.__state;return(n===null||n===i)&&(r===null||r===s)&&(o===null||o===a)&&(t.__state===null||l===c||function(u,d){if(u===d)return!0;if(u&&d&&u.size!==d.size)return!1;let f=new Set;return!(u&&pnn(f,u,d)||d&&pnn(f,d,u)||u&&mnn(f,u,d)||d&&mnn(f,d,u))}(l,c))}function ynn(t,e){let n=t.mergeWithSibling(e),r=ba()._normalizedNodes;return r.add(t.__key),r.add(e.__key),n}function vnn(t){let e,n,r=t;if(r.__text!==""||!r.isSimpleText()||r.isUnmergeable()){for(;(e=r.getPreviousSibling())!==null&&dn(e)&&e.isSimpleText()&&!e.isUnmergeable();){if(e.__text!==""){if(gnn(e,r)){r=ynn(e,r);break}break}e.remove()}for(;(n=r.getNextSibling())!==null&&dn(n)&&n.isSimpleText()&&!n.isUnmergeable();){if(n.__text!==""){if(gnn(r,n)){r=ynn(r,n);break}break}n.remove()}}else r.remove()}function $_e(t){return wnn(t.anchor),wnn(t.focus),t}function wnn(t){for(;t.type==="element";){let e=t.getNode(),n=t.offset,r,o;if(n===e.getChildrenSize()?(r=e.getChildAtIndex(n-1),o=!0):(r=e.getChildAtIndex(n),o=!1),dn(r)){t.set(r.__key,o?r.getTextContentSize():0,"text",!0);break}if(!Ye(r))break;t.set(r.__key,o?r.getChildrenSize():0,"element",!0)}}function D_e(t,e){let n=U$.get(t);if(e!==null){let r=QJe(t);r.parentNode===e&&e.removeChild(r)}if(Qb.has(t)||jp._keyToDOMMap.delete(t),Ye(n)){let r=U_e(n,U$);JJe(r,0,r.length-1,null)}n!==void 0&&VXe(Cee,See,Q_e,n,"destroyed")}function JJe(t,e,n,r){let o=e;for(;o<=n;++o){let i=t[o];i!==void 0&&D_e(i,r)}}function R$(t,e){t.setProperty("text-align",e)}function frn(t,e){let n=rM.theme.indent;if(typeof n=="string"){let o=t.classList.contains(n);e>0&&!o?t.classList.add(n):e<1&&o&&t.classList.remove(n)}let r=getComputedStyle(t).getPropertyValue("--lexical-indent-base-value")||SIr;t.style.setProperty("padding-inline-start",e===0?"":`calc(${e} * ${r})`)}function prn(t,e){let n=t.style;e===0?R$(n,""):e===vXe?R$(n,"left"):e===wXe?R$(n,"center"):e===bXe?R$(n,"right"):e===_Xe?R$(n,"justify"):e===xXe?R$(n,"start"):e===SXe&&R$(n,"end")}function F_e(t,e){let n=Qb.get(t);n===void 0&&tt(60);let r=n.createDOM(rM,jp);if(function(o,i,s){let a=s._keyToDOMMap;(function(l,c,u){let d=`__lexicalKey_${c._key}`;l[d]=u})(i,s,o),a.set(o,i)}(t,r,jp),dn(n)?r.setAttribute("data-lexical-text","true"):vs(n)&&r.setAttribute("data-lexical-decorator","true"),Ye(n)){let o=n.__indent,i=n.__size;if(o!==0&&frn(r,o),i!==0){let a=i-1;(function(l,c,u,d){let f=Up;Up="",XJe(l,u,0,c,u.getDOMSlot(d)),hrn(u,d),Up=f})(U_e(n,Qb),a,n,r)}let s=n.__format;s!==0&&prn(r,s),n.isInline()||mrn(null,n,r),axe(n)&&(ru+=o0,QI+=o0)}else{let o=n.getTextContent();if(vs(n)){let i=n.decorate(jp,rM);i!==null&&grn(t,i),r.contentEditable="false"}else dn(n)&&(n.isDirectionless()||(Up+=o));ru+=o,QI+=o}return e!==null&&e.insertChild(r),VXe(Cee,See,Q_e,n,"created"),r}function XJe(t,e,n,r,o){let i=ru;ru="";let s=n;for(;s<=r;++s){F_e(t[s],o);let a=Qb.get(t[s]);a!==null&&dn(a)&&(TS===null&&(TS=a.getFormat()),PS===""&&(PS=a.getStyle()))}axe(e)&&(ru+=o0),o.element.__lexicalTextContent=ru,ru=i+ru}function bnn(t,e){if(t){let n=t.__last;if(n){let r=e.get(n);if(r)return $$(r)?"line-break":vs(r)&&r.isInline()?"decorator":null}return"empty"}return null}function mrn(t,e,n){let r=bnn(t,U$),o=bnn(e,Qb);r!==o&&e.getDOMSlot(n).setManagedLineBreak(o)}function hrn(t,e){let n=e.__lexicalDirTextContent||"",r=e.__lexicalDir||"";if(n!==Up||r!==P_e){let o=Up==="",i=o?P_e:function(s){return aIr.test(s)?"rtl":lIr.test(s)?"ltr":null}(Up);if(i!==r){let s=e.classList,a=rM.theme,l=r!==null?a[r]:void 0,c=i!==null?a[i]:void 0;if(l!==void 0){if(typeof l=="string"){let u=R_e(l);l=a[r]=u}s.remove(...l)}if(i===null||o&&i==="ltr")e.removeAttribute("dir");else{if(c!==void 0){if(typeof c=="string"){let u=R_e(c);c=a[i]=u}c!==void 0&&s.add(...c)}e.dir=i}kee||(t.getWritable().__dir=i)}P_e=i,e.__lexicalDirTextContent=Up,e.__lexicalDir=i}}function CIr(t,e,n){let r=Up;var o;Up="",TS=null,PS="",function(i,s,a){let l=ru,c=i.__size,u=s.__size;ru="";let d=a.element;if(c===1&&u===1){let f=i.__first,p=s.__first;if(f===p)pee(f,d);else{let h=QJe(f),g=F_e(p,null);try{d.replaceChild(g,h)}catch(v){if(typeof v=="object"&&v!=null){let y=`${v.toString()} Parent: ${d.tagName}, new child: {tag: ${g.tagName} key: ${p}}, old child: {tag: ${h.tagName}, key: ${f}}.`;throw new Error(y)}throw v}D_e(f,null)}let m=Qb.get(p);dn(m)&&(TS===null&&(TS=m.getFormat()),PS===""&&(PS=m.getStyle()))}else{let f=U_e(i,U$),p=U_e(s,Qb);if(f.length!==c&&tt(227),p.length!==u&&tt(228),c===0)u!==0&&XJe(p,s,0,u-1,a);else if(u===0){if(c!==0){let m=a.after==null&&a.before==null&&a.element.__lexicalLineBreak==null;JJe(f,0,c-1,m?null:d),m&&(d.textContent="")}}else(function(m,h,g,v,y,w){let _=v-1,S=y-1,I,C,k=w.getFirstChild(),T=0,P=0;for(;T<=_&&P<=S;){let $=h[T],U=g[P];if($===U)k=NJe(pee(U,w.element)),T++,P++;else{I===void 0&&(I=new Set(h)),C===void 0&&(C=new Set(g));let K=C.has($),se=I.has(U);if(K)if(se){let le=Q6(jp,U);le===k?k=NJe(pee(U,w.element)):(w.withBefore(k).insertChild(le),pee(U,w.element)),T++,P++}else F_e(U,w.withBefore(k)),P++;else k=NJe(QJe($)),D_e($,w.element),T++}let V=Qb.get(U);V!==null&&dn(V)&&(TS===null&&(TS=V.getFormat()),PS===""&&(PS=V.getStyle()))}let E=T>_,O=P>S;if(E&&!O){let $=g[S+1],U=$===void 0?null:jp.getElementByKey($);XJe(g,m,P,S,w.withBefore(U))}else O&&!E&&JJe(h,T,_,w.element)})(s,f,p,c,u,a)}axe(s)&&(ru+=o0),d.__lexicalTextContent=ru,ru=l+ru}(t,e,e.getDOMSlot(n)),hrn(e,n),o=e,TS==null||TS===o.__textFormat||kee||o.setTextFormat(TS),function(i){PS===""||PS===i.__textStyle||kee||i.setTextStyle(PS)}(e),Up=r}function U_e(t,e){let n=[],r=t.__first;for(;r!==null;){let o=e.get(r);o===void 0&&tt(101),n.push(r),r=o.__next}return n}function pee(t,e){let n=U$.get(t),r=Qb.get(t);n!==void 0&&r!==void 0||tt(61);let o=drn||ZJe.has(t)||GJe.has(t),i=Q6(jp,t);if(n===r&&!o){if(Ye(n)){let s=i.__lexicalTextContent;s!==void 0&&(ru+=s,QI+=s);let a=i.__lexicalDirTextContent;a!==void 0&&(Up+=a)}else{let s=n.getTextContent();dn(n)&&!n.isDirectionless()&&(Up+=s),QI+=s,ru+=s}return i}if(n!==r&&o&&VXe(Cee,See,Q_e,r,"updated"),r.updateDOM(n,i,rM)){let s=F_e(t,null);return e===null&&tt(62),e.replaceChild(s,i),D_e(t,null),s}if(Ye(n)&&Ye(r)){let s=r.__indent;s!==n.__indent&&frn(i,s);let a=r.__format;a!==n.__format&&prn(i,a),o&&(CIr(n,r,i),Qm(r)||r.isInline()||mrn(n,r,i)),axe(r)&&(ru+=o0,QI+=o0)}else{let s=r.getTextContent();if(vs(r)){let a=r.decorate(jp,rM);a!==null&&grn(t,a)}else dn(r)&&!r.isDirectionless()&&(Up+=s);ru+=s,QI+=s}if(!kee&&Qm(r)&&r.__cachedText!==QI){let s=r.getWritable();s.__cachedText=QI,r=s}return i}function grn(t,e){let n=jp._pendingDecorators,r=jp._decorators;if(n===null){if(r[t]===e)return;n=don(jp)}n[t]=e}function NJe(t){let e=t.nextSibling;return e!==null&&e===jp._blockCursorElement&&(e=e.nextSibling),e}function kIr(t,e,n,r,o,i){ru="",QI="",Up="",drn=r===q6,P_e=null,jp=n,rM=n._config,See=n._nodes,Q_e=jp._listeners.mutation,GJe=o,ZJe=i,U$=t._nodeMap,Qb=e._nodeMap,kee=e._readOnly,YJe=new Map(n._keyToDOMMap);let s=new Map;return Cee=s,pee("root",null),jp=void 0,See=void 0,GJe=void 0,ZJe=void 0,U$=void 0,Qb=void 0,rM=void 0,YJe=void 0,Cee=void 0,s}function QJe(t){let e=YJe.get(t);return e===void 0&&tt(75,t),e}function Pr(t){return{type:t}}function jrn(t,e,n,r,o){let i=t.anchor,s=t.focus,a=i.getNode(),l=ba(),c=ES(Rv(l)),u=c!==null?c.anchorNode:null,d=i.key,f=l.getElementByKey(d),p=n.length;return d!==s.key||!dn(a)||(!o&&(!O_e||Frn<r+50)||a.isDirty()&&p<2||pon(n))&&i.offset!==s.offset&&!a.isComposing()||XI(a)||a.isDirty()&&p>1||(o||!O_e)&&f!==null&&!a.isComposing()&&u!==z$(f)||c!==null&&e!==null&&(!e.collapsed||e.startContainer!==c.anchorNode||e.startOffset!==c.anchorOffset)||a.getFormat()!==t.format||a.getStyle()!==t.style||function(m,h){if(h.isSegmented())return!0;if(!m.isCollapsed())return!1;let g=m.anchor.offset,v=h.getParentOrThrow(),y=tM(h);return g===0?!h.canInsertTextBefore()||!v.canInsertTextBefore()&&!h.isComposing()||y||function(w){let _=w.getPreviousSibling();return(dn(_)||Ye(_)&&_.isInline())&&!_.canInsertTextAfter()}(h):g===h.getTextContentSize()&&(!h.canInsertTextAfter()||!v.canInsertTextAfter()&&!h.isComposing()||y)}(t,a)}function _nn(t,e){return MS(t)&&t.nodeValue!==null&&e!==0&&e!==t.nodeValue.length}function xnn(t,e,n){let{anchorNode:r,anchorOffset:o,focusNode:i,focusOffset:s}=t;iXe&&(iXe=!1,_nn(r,o)&&_nn(i,s)&&!L$)||Tg(e,()=>{if(!n)return void nh(null);if(!Mee(e,r,i))return;let a=pi();if(L$&&jn(a)&&a.isCollapsed()){let l=a.anchor,c=L$.anchor;(l.key===c.key&&l.offset===c.offset+1||l.offset===1&&c.getNode().is(l.getNode().getPreviousSibling()))&&(a=L$.clone(),nh(a))}if(L$=null,jn(a)){let l=a.anchor,c=l.getNode();if(a.isCollapsed()){t.type==="Range"&&t.anchorNode===t.focusNode&&(a.dirty=!0);let u=Rv(e).event,d=u?u.timeStamp:performance.now(),[f,p,m,h,g]=Urn,v=th(),y=e.isComposing()===!1&&v.getTextContent()==="";if(d<g+200&&l.offset===m&&l.key===h)A_e(a,f,p);else if(l.type==="text")dn(c)||tt(141),Brn(a,c);else if(l.type==="element"&&!y){Ye(c)||tt(259);let w=l.getNode();w.isEmpty()?function(_,S){let I=S.getTextFormat(),C=S.getTextStyle();A_e(_,I,C)}(a,w):A_e(a,0,"")}}else{let u=l.key,d=a.focus.key,f=a.getNodes(),p=f.length,m=a.isBackward(),h=m?s:o,g=m?o:s,v=m?d:u,y=m?u:d,w=nrn,_=!1;for(let S=0;S<p;S++){let I=f[S],C=I.getTextContentSize();if(dn(I)&&C!==0&&!(S===0&&I.__key===v&&h===C||S===p-1&&I.__key===y&&g===0)&&(_=!0,w&=I.getFormat(),w===0))break}a.format=_?w:0}}Kt(e,IXe,void 0)})}function A_e(t,e,n){t.format===e&&t.style===n||(t.format=e,t.style=n,t.dirty=!0)}function Brn(t,e){A_e(t,e.getFormat(),e.getStyle())}function zrn(t){if(!t.getTargetRanges)return null;let e=t.getTargetRanges();return e.length===0?null:e[0]}function S_e(t,e){let n=t._compositionKey;if(Yu(null),n!==null&&e!=null){if(e===""){let r=ou(n),o=z$(t.getElementByKey(n));return void(o!==null&&o.nodeValue!==null&&dn(r)&&WXe(r,o.nodeValue,null,null,!0))}if(e[e.length-1]===`
`){let r=pi();if(jn(r)){let o=r.focus;return r.anchor.set(o.key,o.offset,o.type),void Kt(t,j_e,null)}}}HXe(!0,t,e)}function Hrn(t){let e=t.__lexicalEventHandles;return e===void 0&&(e=[],t.__lexicalEventHandles=e),e}function Wrn(t){let e=Son(t.target);if(e===null)return;let n=BXe(e.anchorNode);if(n===null)return;sXe&&(sXe=!1,Tg(n,()=>{let l=W$(),c=e.anchorNode;(Bp(c)||MS(c))&&nh(nxe(l,e,n,t))}));let r=zXe(n),o=r[r.length-1],i=o._key,s=H6.get(i),a=s||o;a!==n&&xnn(e,a,!1),xnn(e,n,!0),n!==o?H6.set(i,n):s&&H6.delete(i)}function Snn(t){t._lexicalHandled=!0}function Cnn(t){return t._lexicalHandled===!0}function $Ir(t){let e=t.ownerDocument,n=B_e.get(e);if(n===void 0)return void LIr();let r=n-1;r>=0||tt(164),B_e.set(e,r),r===0&&e.removeEventListener("selectionchange",Wrn);let o=Oee(t);oxe(o)?(function(s){if(s._parentEditor!==null){let a=zXe(s),l=a[a.length-1]._key;H6.get(l)===s&&H6.delete(l)}else H6.delete(s._key)}(o),t.__lexicalEditor=null):o&&tt(198);let i=Hrn(t);for(let s=0;s<i.length;s++)i[s]();t.__lexicalEventHandles=[]}function aXe(t,e,n){Zu();let r=t.__key,o=t.getParent();if(o===null)return;let i=function(a){let l=pi();if(!jn(l)||!Ye(a))return l;let{anchor:c,focus:u}=l,d=c.getNode(),f=u.getNode();return Z_e(d,a)&&c.set(a.__key,0,"element"),Z_e(f,a)&&u.set(a.__key,0,"element"),l}(t),s=!1;if(jn(i)&&e){let a=i.anchor,l=i.focus;a.key===r&&(W_e(a,t,o,t.getPreviousSibling(),t.getNextSibling()),s=!0),l.key===r&&(W_e(l,t,o,t.getPreviousSibling(),t.getNextSibling()),s=!0)}else txe(i)&&e&&t.isSelected()&&t.selectPrevious();if(jn(i)&&e&&!s){let a=t.getIndexWithinParent();nM(t),H_e(i,o,a,-1)}else nM(t);n||r_(o)||o.canBeEmpty()||!o.isEmpty()||aXe(o,e),e&&i&&Qm(o)&&o.isEmpty()&&o.selectEnd()}function DIr(t){return t}function FIr(t){return{node:G6()}}function G6(){return Ree(new K6)}function $$(t){return t instanceof K6}function C_e(t){return MS(t)&&/^( |\t|\r?\n)+$/.test(t.textContent||"")}function $Je(t,e){return 16&e?"code":e&J_e?"mark":32&e?"sub":64&e?"sup":null}function DJe(t,e){return 1&e?"strong":2&e?"em":"span"}function Vrn(t,e,n,r,o){let i=r.classList,s=W6(o,"base");s!==void 0&&i.add(...s),s=W6(o,"underlineStrikethrough");let a=!1,l=e&xee&&e&_ee;s!==void 0&&(n&xee&&n&_ee?(a=!0,l||i.add(...s)):l&&i.remove(...s));for(let c in Uf){let u=Uf[c];if(s=W6(o,c),s!==void 0)if(n&u){if(a&&(c==="underline"||c==="strikethrough")){e&u&&i.remove(...s);continue}e&u&&(!l||c!=="underline")&&c!=="strikethrough"||i.add(...s)}else e&u&&i.remove(...s)}}function qrn(t,e,n){let r=e.firstChild,o=n.isComposing(),i=t+(o?X_e:"");if(r==null)e.textContent=i;else{let s=r.nodeValue;if(s!==i)if(o||D$){let[a,l,c]=function(u,d){let f=u.length,p=d.length,m=0,h=0;for(;m<f&&m<p&&u[m]===d[m];)m++;for(;h+m<f&&h+m<p&&u[f-h-1]===d[p-h-1];)h++;return[m,f-m-h,d.slice(m,p-h)]}(s,i);l!==0&&r.deleteData(a,l),r.insertData(a,c)}else r.nodeValue=i}}function knn(t,e,n,r,o,i){qrn(o,t,e);let s=i.theme.text;s!==void 0&&Vrn(0,0,r,t,s)}function k_e(t,e){let n=document.createElement(e);return n.appendChild(t),n}function UIr(t){return{forChild:OXe(t.style),node:null}}function jIr(t){let e=t,n=e.style.fontWeight==="normal";return{forChild:OXe(e.style,n?void 0:"bold"),node:null}}function BIr(t){if(!Bp(t))return!1;if(t.nodeName==="PRE")return!0;let e=t.style.whiteSpace;return typeof e=="string"&&e.startsWith("pre")}function zIr(t){let e=t;t.parentElement===null&&tt(129);let n=e.textContent||"";if(function(r){let o,i=r.parentNode,s=[r];for(;i!==null&&(o=Inn.get(i))===void 0&&!BIr(i);)s.push(i),i=i.parentNode;let a=o===void 0?i:o;for(let l=0;l<s.length;l++)Inn.set(s[l],a);return a}(e)!==null){let r=n.split(/(\r?\n|\t)/),o=[],i=r.length;for(let s=0;s<i;s++){let a=r[s];a===`
`||a===`\r
`?o.push(G6()):a===" "?o.push(exe()):a!==""&&o.push(Gu(a))}return{node:o}}if(n=n.replace(/\r/g,"").replace(/[ \t\n]+/g," "),n==="")return{node:null};if(n[0]===" "){let r=e,o=!0;for(;r!==null&&(r=Tnn(r,!1))!==null;){let i=r.textContent||"";if(i.length>0){/[ \t\n]$/.test(i)&&(n=n.slice(1)),o=!1;break}}o&&(n=n.slice(1))}if(n[n.length-1]===" "){let r=e,o=!0;for(;r!==null&&(r=Tnn(r,!0))!==null;)if((r.textContent||"").replace(/^( |\t|\r?\n)+/,"").length>0){o=!1;break}o&&(n=n.slice(0,n.length-1))}return n===""?{node:null}:{node:Gu(n)}}function Tnn(t,e){let n=t;for(;;){let r;for(;(r=e?n.nextSibling:n.previousSibling)===null;){let i=n.parentElement;if(i===null)return null;n=i}if(n=r,Bp(n)){let i=n.style.display;if(i===""&&!kon(n)||i!==""&&!i.startsWith("inline"))return null}let o=n;for(;(o=e?n.firstChild:n.lastChild)!==null;)n=o;if(MS(n))return n;if(n.nodeName==="BR")return null}}function YI(t){let e=HIr[t.nodeName.toLowerCase()];return e===void 0?{node:null}:{forChild:OXe(t.style,e),node:null}}function Gu(t=""){return Ree(new j$(t))}function dn(t){return t instanceof j$}function OXe(t,e){let n=t.fontWeight,r=t.textDecoration.split(" "),o=n==="700"||n==="bold",i=r.includes("line-through"),s=t.fontStyle==="italic",a=r.includes("underline"),l=t.verticalAlign;return c=>(dn(c)&&(o&&!c.hasFormat("bold")&&c.toggleFormat("bold"),i&&!c.hasFormat("strikethrough")&&c.toggleFormat("strikethrough"),s&&!c.hasFormat("italic")&&c.toggleFormat("italic"),a&&!c.hasFormat("underline")&&c.toggleFormat("underline"),l!=="sub"||c.hasFormat("subscript")||c.toggleFormat("subscript"),l!=="super"||c.hasFormat("superscript")||c.toggleFormat("superscript"),e&&!c.hasFormat(e)&&c.toggleFormat(e)),c)}function exe(){return Ree(new Z6)}function NXe(t){return t instanceof Z6}function n_(t,e,n){return new lXe(t,e,n)}function FJe(t,e){let n=e.__key,r=t.offset,o="element";if(dn(e)){o="text";let i=e.getTextContentSize();r>i&&(r=i)}else if(!Ye(e)){let i=e.getNextSibling();if(dn(i))n=i.__key,r=0,o="text";else{let s=e.getParent();s&&(n=s.__key,r=e.getIndexWithinParent()+1)}}t.set(n,r,o)}function Pnn(t,e){if(Ye(e)){let n=e.getLastDescendant();Ye(n)||dn(n)?FJe(t,n):FJe(t,e)}else FJe(t,e)}function jn(t){return t instanceof B$}function txe(t){return t instanceof z_e}function Ann(t){let e=t.offset;if(t.type==="text")return e;let n=t.getNode();return e===n.getChildrenSize()?n.getTextContent().length:0}function cXe(t){let e=t.getStartEndPoints();if(e===null)return[0,0];let[n,r]=e;return n.type==="element"&&r.type==="element"&&n.key===r.key&&n.offset===r.offset?[0,0]:[Ann(n),Ann(r)]}function Enn(t,e){for(let n=e;n;n=n.getParent()){if(Ye(n)){if(n.collapseAtStart(t))return!0;if(r_(n))break}if(n.getPreviousSibling())break}return!1}function Mnn(t,e,n){let r=t,o=r.getTextContent().split(/(?=\s)/g),i=o.length,s=0,a=0;for(let c=0;c<i;c++){let u=c===i-1;if(a=s,s+=o[c].length,e&&s===n||s>n||u){o.splice(c,1),u&&(a=void 0);break}}let l=o.join("").trim();l===""?r.remove():(r.setTextContent(l),r.select(a,a))}function Onn(t,e,n,r){let o,i=e;if(Bp(t)){let s=!1,a=t.childNodes,l=a.length,c=r._blockCursorElement;i===l&&(s=!0,i=l-1);let u=a[i],d=!1;if(u===c)u=a[i+1],d=!0;else if(c!==null){let f=c.parentNode;t===f&&e>Array.prototype.indexOf.call(f.children,c)&&i--}if(o=B6(u),dn(o))i=t_(o,s?"next":"previous");else{let f=B6(t);if(f===null)return null;if(Ye(f)){let p=r.getElementByKey(f.getKey());p===null&&tt(214),[f,i]=f.getDOMSlot(p).resolveChildIndex(f,p,t,e),Ye(f)||tt(215),s&&i>=f.getChildrenSize()&&(i=Math.max(0,f.getChildrenSize()-1));let h=f.getChildAtIndex(i);if(Ye(h)&&function(g,v,y){let w=g.getParent();return y===null||w===null||!w.canBeEmpty()||w!==y.getNode()}(h,0,n)){let g=s?h.getLastDescendant():h.getFirstDescendant();g===null?f=h:(h=g,f=Ye(h)?h:h.getParentOrThrow()),i=0}dn(h)?(o=h,f=null,i=t_(h,s?"next":"previous")):h!==f&&s&&!d&&(Ye(f)||tt(216),i=Math.min(f.getChildrenSize(),i+1))}else{let p=f.getIndexWithinParent();i=e===0&&vs(f)&&B6(t)===f?p:p+1,f=f.getParentOrThrow()}if(Ye(f))return n_(f.__key,i,"element")}}else o=B6(t);return dn(o)?n_(o.__key,t_(o,i,"clamp"),"text"):null}function Nnn(t,e,n){let r=t.offset,o=t.getNode();if(r===0){let i=o.getPreviousSibling(),s=o.getParent();if(e){if((n||!e)&&i===null&&Ye(s)&&s.isInline()){let a=s.getPreviousSibling();dn(a)&&t.set(a.__key,a.getTextContent().length,"text")}}else Ye(i)&&!n&&i.isInline()?t.set(i.__key,i.getChildrenSize(),"element"):dn(i)&&t.set(i.__key,i.getTextContent().length,"text")}else if(r===o.getTextContent().length){let i=o.getNextSibling(),s=o.getParent();if(e&&Ye(i)&&i.isInline())t.set(i.__key,0,"element");else if((n||e)&&i===null&&Ye(s)&&s.isInline()&&!s.canInsertTextAfter()){let a=s.getNextSibling();dn(a)&&t.set(a.__key,0,"text")}}}function Krn(t,e,n){if(t.type==="text"&&e.type==="text"){let r=t.isBefore(e),o=t.is(e);Nnn(t,r,o),Nnn(e,!r,o),o&&e.set(t.key,t.offset,t.type);let i=ba();if(i.isComposing()&&i._compositionKey!==t.key&&jn(n)){let s=n.anchor,a=n.focus;t.set(s.key,s.offset,s.type,!0),e.set(a.key,a.offset,a.type,!0)}}}function Grn(t,e,n,r,o,i){if(t===null||n===null||!Mee(o,t,n))return null;let s=Onn(t,e,jn(i)?i.anchor:null,o);if(s===null)return null;let a=Onn(n,r,jn(i)?i.focus:null,o);if(a===null)return null;if(s.type==="element"&&a.type==="element"){let l=B6(t),c=B6(n);if(vs(l)&&vs(c))return null}return Krn(s,a,i),[s,a]}function VIr(t){return Ye(t)&&!t.isInline()}function Zrn(t,e,n,r,o,i){let s=s0(),a=new B$(n_(t,e,o),n_(n,r,i),0,"");return a.dirty=!0,s._selection=a,a}function Yrn(){let t=n_("root",0,"element"),e=n_("root",0,"element");return new B$(t,e,0,"")}function RXe(){return new z_e(new Set)}function qIr(t,e){return nxe(null,t,e,null)}function nxe(t,e,n,r){let o=n._window;if(o===null)return null;let i=r||o.event,s=i?i.type:void 0,a=s==="selectionchange",l=!VJe&&(a||s==="beforeinput"||s==="compositionstart"||s==="compositionend"||s==="click"&&i&&i.detail===3||s==="drop"||s===void 0),c,u,d,f;if(jn(t)&&!l)return t.clone();if(e===null)return null;if(c=e.anchorNode,u=e.focusNode,d=e.anchorOffset,f=e.focusOffset,a&&jn(t)&&!Mee(n,c,u))return t.clone();let p=Grn(c,d,u,f,n,t);if(p===null)return null;let[m,h]=p;return new B$(m,h,jn(t)?t.format:0,jn(t)?t.style:"")}function pi(){return s0()._selection}function W$(){return ba()._editorState._selection}function H_e(t,e,n,r=1){let o=t.anchor,i=t.focus,s=o.getNode(),a=i.getNode();if(!e.is(s)&&!e.is(a))return;let l=e.__key;if(t.isCollapsed()){let c=o.offset;if(n<=c&&r>0||n<c&&r<0){let u=Math.max(0,c+r);o.set(l,u,"element"),i.set(l,u,"element"),Rnn(t)}}else{let c=t.isBackward(),u=c?i:o,d=u.getNode(),f=c?o:i,p=f.getNode();if(e.is(d)){let m=u.offset;(n<=m&&r>0||n<m&&r<0)&&u.set(l,Math.max(0,m+r),"element")}if(e.is(p)){let m=f.offset;(n<=m&&r>0||n<m&&r<0)&&f.set(l,Math.max(0,m+r),"element")}}Rnn(t)}function Rnn(t){let e=t.anchor,n=e.offset,r=t.focus,o=r.offset,i=e.getNode(),s=r.getNode();if(t.isCollapsed()){if(!Ye(i))return;let a=i.getChildrenSize(),l=n>=a,c=l?i.getChildAtIndex(a-1):i.getChildAtIndex(n);if(dn(c)){let u=0;l&&(u=c.getTextContentSize()),e.set(c.__key,u,"text"),r.set(c.__key,u,"text")}}else{if(Ye(i)){let a=i.getChildrenSize(),l=n>=a,c=l?i.getChildAtIndex(a-1):i.getChildAtIndex(n);if(dn(c)){let u=0;l&&(u=c.getTextContentSize()),e.set(c.__key,u,"text")}}if(Ye(s)){let a=s.getChildrenSize(),l=o>=a,c=l?s.getChildAtIndex(a-1):s.getChildAtIndex(o);if(dn(c)){let u=0;l&&(u=c.getTextContentSize()),r.set(c.__key,u,"text")}}}}function W_e(t,e,n,r,o){let i=null,s=0,a=null;r!==null?(i=r.__key,dn(r)?(s=r.getTextContentSize(),a="text"):Ye(r)&&(s=r.getChildrenSize(),a="element")):o!==null&&(i=o.__key,dn(o)?a="text":Ye(o)&&(a="element")),i!==null&&a!==null?t.set(i,s,a):(s=e.getIndexWithinParent(),s===-1&&(s=n.getChildrenSize()),t.set(n.__key,s,"element"))}function Lnn(t,e,n,r,o){t.type==="text"?t.set(n,t.offset+(e?0:o),"text"):t.offset>r.getIndexWithinParent()&&t.set(t.key,t.offset-1,"element")}function Jrn(t,e,n,r,o){try{t.setBaseAndExtent(e,n,r,o)}catch{}}function KIr(t,e,n,r,o,i,s){let a=r.anchorNode,l=r.focusNode,c=r.anchorOffset,u=r.focusOffset,d=document.activeElement;if(o.has(ron)&&d!==i||d!==null&&jXe(d))return;if(!jn(e))return void(t!==null&&Mee(n,a,l)&&r.removeAllRanges());let f=e.anchor,p=e.focus,m=f.key,h=p.key,g=Q6(n,m),v=Q6(n,h),y=f.offset,w=p.offset,_=e.format,S=e.style,I=e.isCollapsed(),C=g,k=v,T=!1;if(f.type==="text"){C=z$(g);let V=f.getNode();T=V.getFormat()!==_||V.getStyle()!==S}else jn(t)&&t.anchor.type==="text"&&(T=!0);var P,E,O,$,U;if(p.type==="text"&&(k=z$(v)),C!==null&&k!==null&&(I&&(t===null||T||jn(t)&&(t.format!==_||t.style!==S))&&(P=_,E=S,O=y,$=m,U=performance.now(),Urn=[P,E,O,$,U]),c!==y||u!==w||a!==C||l!==k||r.type==="Range"&&I||(d!==null&&i.contains(d)||i.focus({preventScroll:!0}),f.type==="element"))){if(Jrn(r,C,y,k,w),!o.has(oon)&&e.isCollapsed()&&i!==null&&i===document.activeElement){let V=jn(e)&&e.anchor.type==="element"?C.childNodes[y]||null:r.rangeCount>0?r.getRangeAt(0):null;if(V!==null){let K;if(V instanceof Text){let se=document.createRange();se.selectNode(V),K=se.getBoundingClientRect()}else K=V.getBoundingClientRect();(function(se,le,Q){let ne=qXe(Q),ee=KXe(ne);if(ne===null||ee===null)return;let{top:ae,bottom:q}=le,F=0,z=0,N=Q;for(;N!==null;){let R=N===ne.body;if(R)F=0,z=Rv(se).innerHeight;else{let D=N.getBoundingClientRect();F=D.top,z=D.bottom}let X=0;if(ae<F?X=-(F-ae):q>z&&(X=q-z),X!==0)if(R)ee.scrollBy(0,X);else{let D=N.scrollTop;N.scrollTop+=X;let G=N.scrollTop-D;ae-=G,q-=G}if(R)break;N=Nee(N)}})(n,K,i)}}iXe=!0}}function GIr(t){let e=pi()||W$();e===null&&(e=th().selectEnd()),e.insertNodes(t)}function ZIr(){let t=pi();return t===null?"":t.getTextContent()}function UJe(t){let e=t;t.isCollapsed()||e.removeText();let n=pi();jn(n)&&(e=n),jn(e)||tt(161);let r=e.anchor,o=r.getNode(),i=r.offset;for(;!t0(o);){let s=o;if([o,i]=YIr(o,i),s.is(o))break}return i}function YIr(t,e){let n=t.getParent();if(!n){let o=n0();return th().append(o),o.select(),[th(),0]}if(dn(t)){let o=t.splitText(e);if(o.length===0)return[n,t.getIndexWithinParent()];let i=e===0?0:1;return[n,o[0].getIndexWithinParent()+i]}if(!Ye(t)||e===0)return[n,t.getIndexWithinParent()];let r=t.getChildAtIndex(e);if(r){let o=new B$(n_(t.__key,e,"element"),n_(t.__key,e,"element"),0,""),i=t.insertNewAfter(o);i&&i.append(r,...r.getNextSiblings())}return[n,t.getIndexWithinParent()+1]}function $nn(t,e,n,r,o="decorators-and-blocks"){if(e==="move"&&r==="character"&&!t.isCollapsed()){let[u,d]=n===t.isBackward()?[t.focus,t.anchor]:[t.anchor,t.focus];return d.set(u.key,u.offset,u.type),!0}let i=lM(t.focus,n?"previous":"next"),s=r==="lineboundary",a=e==="move",l=i,c=o==="decorators-and-blocks";if(!Non(l)){for(let u of l){c=!1;let{origin:d}=u;if(!vs(d)||d.isIsolated()||(l=u,!s||!d.isInline()))break}if(c)for(let u of XXe(i).iterNodeCarets(e==="extend"?"shadowRoot":"root")){if(e_(u))u.origin.isInline()||(l=u);else{if(Ye(u.origin))continue;vs(u.origin)&&!u.origin.isInline()&&(l=u)}break}}if(l===i)return!1;if(a&&!s&&vs(l.origin)&&l.origin.isKeyboardSelectable()){let u=RXe();return u.add(l.origin.getKey()),nh(u),!0}return l=Xb(l),a&&oV(t.anchor,l),oV(t.focus,l),c||!s}function iV(){return eh||Ju!==null&&Ju._readOnly}function Zu(){eh&&tt(13)}function Xrn(){E_e>99&&tt(14)}function s0(){return Ju===null&&tt(195,Qrn()),Ju}function ba(){return Xu===null&&tt(196,Qrn()),Xu}function Qrn(){let t=0,e=new Set,n=X6.version;if(typeof window<"u")for(let o of document.querySelectorAll("[contenteditable]")){let i=Oee(o);if(oxe(i))t++;else if(i){let s=String(i.constructor.version||"<0.17.1");s===n&&(s+=" (separately built, likely a bundler configuration issue)"),e.add(s)}}let r=` Detected on the page: ${t} compatible editor(s) with version ${n}`;return e.size&&(r+=` and incompatible editors with versions ${Array.from(e).join(", ")}`),r}function JIr(){return Xu}function Fnn(t,e,n){let r=e.__type,o=FXe(t,r),i=n.get(r);i===void 0&&(i=Array.from(o.transforms),n.set(r,i));let s=i.length;for(let a=0;a<s&&(i[a](e),e.isAttached());a++);}function Unn(t,e){return t!==void 0&&t.__key!==e&&t.isAttached()}function eon(t,e){if(!e)return;let n=t._updateTags,r=e;Array.isArray(e)||(r=[e]);for(let o of r)n.add(o)}function XIr(t){return LXe(t,ba()._nodes)}function LXe(t,e){let n=t.type,r=e.get(n);r===void 0&&tt(17,n);let o=r.klass;t.type!==o.getType()&&tt(18,o.name);let i=o.importJSON(t),s=t.children;if(Ye(i)&&Array.isArray(s))for(let a=0;a<s.length;a++){let l=LXe(s[a],e);i.append(l)}return i}function jnn(t,e,n){let r=Ju,o=eh,i=Xu;Ju=e,eh=!0,Xu=t;try{return n()}finally{Ju=r,eh=o,Xu=i}}function e0(t,e){let n=t._pendingEditorState,r=t._rootElement,o=t._headless||r===null;if(n===null)return;let i=t._editorState,s=i._selection,a=n._selection,l=t._dirtyType!==F$,c=Ju,u=eh,d=Xu,f=t._updating,p=t._observer,m=null;if(t._pendingEditorState=null,t._editorState=n,!o&&l&&p!==null){Xu=t,Ju=n,eh=!1,t._updating=!0;try{let I=t._dirtyType,C=t._dirtyElements,k=t._dirtyLeaves;p.disconnect(),m=kIr(i,n,t,I,C,k)}catch(I){if(I instanceof Error&&t._onError(I),jJe)throw I;return son(t,null,r,n),lrn(t),t._dirtyType=q6,jJe=!0,e0(t,i),void(jJe=!1)}finally{p.observe(r,Dnn),t._updating=f,Ju=c,eh=u,Xu=d}}n._readOnly||(n._readOnly=!0);let h=t._dirtyLeaves,g=t._dirtyElements,v=t._normalizedNodes,y=t._updateTags,w=t._deferred;l&&(t._dirtyType=F$,t._cloneNotNeeded.clear(),t._dirtyLeaves=new Set,t._dirtyElements=new Map,t._normalizedNodes=new Set,t._updateTags=new Set),function(I,C){let k=I._decorators,T=I._pendingDecorators||k,P=C._nodeMap,E;for(E in T)P.has(E)||(T===k&&(T=don(I)),delete T[E])}(t,n);let _=o?null:ES(Rv(t));if(t._editable&&_!==null&&(l||a===null||a.dirty)&&r!==null&&!y.has(ion)){Xu=t,Ju=n;try{if(p!==null&&p.disconnect(),l||a===null||a.dirty){let I=t._blockCursorElement;I!==null&&fXe(I,t,r),KIr(s,a,t,_,y,r)}(function(I,C,k){let T=I._blockCursorElement;if(jn(k)&&k.isCollapsed()&&k.anchor.type==="element"&&C.contains(document.activeElement)){let P=k.anchor,E=P.getNode(),O=P.offset,$=!1,U=null;if(O===E.getChildrenSize())zJe(E.getChildAtIndex(O-1))&&($=!0);else{let V=E.getChildAtIndex(O);if(V!==null&&zJe(V)){let K=V.getPreviousSibling();(K===null||zJe(K))&&($=!0,U=I.getElementByKey(V.__key))}}if($){let V=I.getElementByKey(E.__key);return T===null&&(I._blockCursorElement=T=function(K){let se=K.theme,le=document.createElement("div");le.contentEditable="false",le.setAttribute("data-lexical-cursor","true");let Q=se.blockCursor;if(Q!==void 0){if(typeof Q=="string"){let ne=R_e(Q);Q=se.blockCursor=ne}Q!==void 0&&le.classList.add(...Q)}return le}(I._config)),C.style.caretColor="transparent",void(U===null?V.appendChild(T):V.insertBefore(T,U))}}T!==null&&fXe(T,I,C)})(t,r,a)}finally{p!==null&&p.observe(r,Dnn),Xu=d,Ju=c}}m!==null&&function(I,C,k,T,P){let E=Array.from(I._listeners.mutation),O=E.length;for(let $=0;$<O;$++){let[U,V]=E[$];for(let K of V){let se=C.get(K);se!==void 0&&U(se,{dirtyLeaves:T,prevEditorState:P,updateTags:k})}}}(t,m,y,h,i),jn(a)||a===null||s!==null&&s.is(a)||t.dispatchCommand(IXe,void 0);let S=t._pendingDecorators;S!==null&&(t._decorators=S,t._pendingDecorators=null,yee("decorator",t,!0,S)),function(I,C,k){let T=Vnn(C),P=Vnn(k);T!==P&&yee("textcontent",I,!0,P)}(t,e||i,n),yee("update",t,!0,{dirtyElements:g,dirtyLeaves:h,editorState:n,mutatedNodes:m,normalizedNodes:v,prevEditorState:e||i,tags:y}),function(I,C){if(I._deferred=[],C.length!==0){let k=I._updating;I._updating=!0;try{for(let T=0;T<C.length;T++)C[T]()}finally{I._updating=k}}}(t,w),function(I){let C=I._updates;if(C.length!==0){let k=C.shift();if(k){let[T,P]=k;rxe(I,T,P)}}}(t)}function yee(t,e,n,...r){let o=e._updating;e._updating=n;try{let i=Array.from(e._listeners[t]);for(let s=0;s<i.length;s++)i[s].apply(null,r)}finally{e._updating=o}}function Bnn(t,e){let n=t._updates,r=e||!1;for(;n.length!==0;){let o=n.shift();if(o){let[i,s]=o,a=t._pendingEditorState,l;s!==void 0&&(l=s.onUpdate,s.skipTransforms&&(r=!0),s.discrete&&(a===null&&tt(191),a._flushSync=!0),l&&t._deferred.push(l),eon(t,s.tag)),a==null?rxe(t,i,s):i()}}return r}function rxe(t,e,n){let r=t._updateTags,o,i=!1,s=!1;n!==void 0&&(o=n.onUpdate,eon(t,n.tag),i=n.skipTransforms||!1,s=n.discrete||!1),o&&t._deferred.push(o);let a=t._editorState,l=t._pendingEditorState,c=!1;(l===null||l._readOnly)&&(l=t._pendingEditorState=ton(l||a),c=!0),l._flushSync=s;let u=Ju,d=eh,f=Xu,p=t._updating;Ju=l,eh=!1,t._updating=!0,Xu=t;let m=t._headless||t.getRootElement()===null;DXe(null);try{c&&(m?a._selection!==null&&(l._selection=a._selection.clone()):l._selection=function(y,w){let _=y.getEditorState()._selection,S=ES(Rv(y));return jn(_)||_==null?nxe(_,S,y,w):_.clone()}(t,n&&n.event||null));let g=t._compositionKey;e(),i=Bnn(t,i),function(y,w){let _=w.getEditorState()._selection,S=y._selection;if(jn(S)){let I=S.anchor,C=S.focus,k;if(I.type==="text"&&(k=I.getNode(),k.selectionTransform(_,S)),C.type==="text"){let T=C.getNode();k!==T&&T.selectionTransform(_,S)}}}(l,t),t._dirtyType!==F$&&(i?function(y,w){let _=w._dirtyLeaves,S=y._nodeMap;for(let I of _){let C=S.get(I);dn(C)&&C.isAttached()&&C.isSimpleText()&&!C.isUnmergeable()&&vnn(C)}}(l,t):function(y,w){let _=w._dirtyLeaves,S=w._dirtyElements,I=y._nodeMap,C=eM(),k=new Map,T=_,P=T.size,E=S,O=E.size;for(;P>0||O>0;){if(P>0){w._dirtyLeaves=new Set;for(let $ of T){let U=I.get($);dn(U)&&U.isAttached()&&U.isSimpleText()&&!U.isUnmergeable()&&vnn(U),U!==void 0&&Unn(U,C)&&Fnn(w,U,k),_.add($)}if(T=w._dirtyLeaves,P=T.size,P>0){E_e++;continue}}w._dirtyLeaves=new Set,w._dirtyElements=new Map,E.delete("root")&&E.set("root",!0);for(let $ of E){let U=$[0],V=$[1];if(S.set(U,V),!V)continue;let K=I.get(U);K!==void 0&&Unn(K,C)&&Fnn(w,K,k)}T=w._dirtyLeaves,P=T.size,E=w._dirtyElements,O=E.size,E_e++}w._dirtyLeaves=_,w._dirtyElements=S}(l,t),Bnn(t),function(y,w,_,S){let I=y._nodeMap,C=w._nodeMap,k=[];for(let[T]of S){let P=C.get(T);P!==void 0&&(P.isAttached()||(Ye(P)&&irn(P,T,I,C,k,S),I.has(T)||S.delete(T),k.push(T)))}for(let T of k)C.delete(T);for(let T of _){let P=C.get(T);P===void 0||P.isAttached()||(I.has(T)||_.delete(T),C.delete(T))}}(a,l,t._dirtyLeaves,t._dirtyElements)),g!==t._compositionKey&&(l._flushSync=!0);let v=l._selection;if(jn(v)){let y=l._nodeMap,w=v.anchor.key,_=v.focus.key;y.get(w)!==void 0&&y.get(_)!==void 0||tt(19)}else txe(v)&&v._nodes.size===0&&(l._selection=null)}catch(g){return g instanceof Error&&t._onError(g),t._pendingEditorState=a,t._dirtyType=q6,t._cloneNotNeeded.clear(),t._dirtyLeaves=new Set,t._dirtyElements.clear(),void e0(t)}finally{Ju=u,eh=d,Xu=f,t._updating=p,E_e=0}t._dirtyType!==F$||t._deferred.length>0||function(g,v){let y=v.getEditorState()._selection,w=g._selection;if(w!==null){if(w.dirty||!w.is(y))return!0}else if(y!==null)return!0;return!1}(l,t)?l._flushSync?(l._flushSync=!1,e0(t)):c&&f0r(()=>{e0(t)}):(l._flushSync=!1,c&&(r.clear(),t._deferred=[],t._pendingEditorState=null))}function Tg(t,e,n){Xu===t&&n===void 0?e():rxe(t,e,n)}function znn(t,e){let n=[],r=e;for(;r!==t&&r!==null;r=r.parentNode){let o=0;for(let i=r.previousSibling;i!==null;i=i.previousSibling)o++;n.push(o)}return r!==t&&tt(225),n.reverse()}function Ye(t){return t instanceof iM}function Hnn(t,e,n){let r=t.getNode();for(;r;){let o=r.__key;if(e.has(o)&&!n.has(o))return!0;r=r.getParent()}return!1}function vs(t){return t instanceof Aee}function Qm(t){return t instanceof Y6}function ton(t){return new V_e(new Map(t._nodeMap))}function $Xe(){return new V_e(new Map([["root",new Y6]]))}function non(t){let e=t.exportJSON(),n=t.constructor;if(e.type!==n.getType()&&tt(130,n.name),Ye(t)){let r=e.children;Array.isArray(r)||tt(59,n.name);let o=t.getChildren();for(let i=0;i<o.length;i++){let s=non(o[i]);r.push(s)}}return e}function r0r(t){let e=n0();return t.style&&(e.setFormat(t.style.textAlign),Ton(t,e)),{node:e}}function n0(){return Ree(new J6)}function o0r(t){return t instanceof J6}function son(t,e,n,r){let o=t._keyToDOMMap;o.clear(),t._editorState=$Xe(),t._pendingEditorState=r,t._compositionKey=null,t._dirtyType=F$,t._cloneNotNeeded.clear(),t._dirtyLeaves=new Set,t._dirtyElements.clear(),t._normalizedNodes=new Set,t._updateTags=new Set,t._updates=[],t._blockCursorElement=null;let i=t._observer;i!==null&&(i.disconnect(),t._observer=null),e!==null&&(e.textContent=""),n!==null&&(n.textContent="",o.set("root",n))}function u0r(t){let e=t||{},n=JIr(),r=e.theme||{},o=t===void 0?n:e.parentEditor||null,i=e.disableEvents||!1,s=$Xe(),a=e.namespace||(o!==null?o._config.namespace:mon()),l=e.editorState,c=[Y6,j$,K6,Z6,J6,q_e,...e.nodes||[]],{onError:u,html:d}=e,f=e.editable===void 0||e.editable,p;if(t===void 0&&n!==null)p=n._nodes;else{p=new Map;for(let h=0;h<c.length;h++){let g=c[h],v=null,y=null;if(typeof g!="function"){let C=g;g=C.replace,v=C.with,y=C.withKlass||null}let{ownNodeConfig:w}=YXe(g),_=g.getType(),S=g.transform(),I=new Set;w&&w.$transform&&I.add(w.$transform),S!==null&&I.add(S),p.set(_,{exportDOM:d&&d.export?d.export.get(g):void 0,klass:g,replace:v,replaceWithKlass:y,sharedNodeState:crn(c[h]),transforms:I})}}let m=new X6(s,o,p,{disableEvents:i,namespace:a,theme:r},u||console.error,function(h,g){let v=new Map,y=new Set,w=_=>{Object.keys(_).forEach(S=>{let I=v.get(S);I===void 0&&(I=[],v.set(S,I)),I.push(_[S])})};return h.forEach(_=>{let S=_.klass.importDOM;if(S==null||y.has(S))return;y.add(S);let I=S.call(_.klass);I!==null&&w(I)}),g&&w(g),v}(p,d?d.import:void 0),f,t);return l!==void 0&&(m._pendingEditorState=l,m._dirtyType=q6),m}function DXe(t){dXe=t}function d0r(){aon=1}function FXe(t,e){let n=UXe(t,e);return n===void 0&&tt(30,e),n}function UXe(t,e){return t._nodes.get(e)}function Wnn(t){return vs(sxe(t))}function jXe(t){let e=document.activeElement;if(!Bp(e))return!1;let n=e.nodeName;return vs(sxe(t))&&(n==="INPUT"||n==="TEXTAREA"||e.contentEditable==="true"&&Oee(e)==null)}function Mee(t,e,n){let r=t.getRootElement();try{return r!==null&&r.contains(e)&&r.contains(n)&&e!==null&&!jXe(e)&&BXe(e)===t}catch{return!1}}function oxe(t){return t instanceof X6}function BXe(t){let e=t;for(;e!=null;){let n=Oee(e);if(oxe(n))return n;e=Nee(e)}return null}function Oee(t){return t?t.__lexicalEditor:null}function tM(t){return NXe(t)||t.isToken()}function XI(t){return tM(t)||t.isSegmented()}function MS(t){return sV(t)&&t.nodeType===Zkr}function lon(t){return sV(t)&&t.nodeType===Ykr}function z$(t){let e=t;for(;e!=null;){if(MS(e))return e;e=e.firstChild}return null}function K_e(t,e,n){let r=Uf[e];if(n!==null&&(t&r)==(n&r))return t;let o=t^r;return e==="subscript"?o&=~Uf.superscript:e==="superscript"?o&=~Uf.subscript:e==="lowercase"?(o&=~Uf.uppercase,o&=~Uf.capitalize):e==="uppercase"?(o&=~Uf.lowercase,o&=~Uf.capitalize):e==="capitalize"&&(o&=~Uf.lowercase,o&=~Uf.uppercase),o}function p0r(t){return dn(t)||$$(t)||vs(t)}function con(t,e){let n=function(){let s=dXe;return dXe=null,s}();if((e=e||n&&n.__key)!=null)return void(t.__key=e);Zu(),Xrn();let r=ba(),o=s0(),i=""+aon++;o._nodeMap.set(i,t),Ye(t)?r._dirtyElements.set(i,!0):r._dirtyLeaves.add(i),r._cloneNotNeeded.add(i),r._dirtyType=trn,t.__key=i}function nM(t){let e=t.getParent();if(e!==null){let n=t.getWritable(),r=e.getWritable(),o=t.getPreviousSibling(),i=t.getNextSibling(),s=i!==null?i.__key:null,a=o!==null?o.__key:null,l=o!==null?o.getWritable():null,c=i!==null?i.getWritable():null;o===null&&(r.__first=s),i===null&&(r.__last=a),l!==null&&(l.__next=s),c!==null&&(c.__prev=a),n.__prev=null,n.__next=null,n.__parent=null,r.__size--}}function G_e(t){Xrn();let e=t.getLatest(),n=e.__parent,r=s0(),o=ba(),i=r._nodeMap,s=o._dirtyElements;n!==null&&function(l,c,u){let d=l;for(;d!==null;){if(u.has(d))return;let f=c.get(d);if(f===void 0)break;u.set(d,!1),d=f.__parent}}(n,i,s);let a=e.__key;o._dirtyType=trn,Ye(t)?s.set(a,!0):o._dirtyLeaves.add(a)}function Yu(t){Zu();let e=ba(),n=e._compositionKey;if(t!==n){if(e._compositionKey=t,n!==null){let r=ou(n);r!==null&&r.getWritable()}if(t!==null){let r=ou(t);r!==null&&r.getWritable()}}}function eM(){return iV()?null:ba()._compositionKey}function ou(t,e){let n=(e||s0())._nodeMap.get(t);return n===void 0?null:n}function uon(t,e){let n=ixe(t,ba());return n!==void 0?ou(n,e):null}function ixe(t,e){return t[`__lexicalKey_${e._key}`]}function sxe(t,e){let n=t;for(;n!=null;){let r=uon(n,e);if(r!==null)return r;n=Nee(n)}return null}function don(t){let e=t._decorators,n=Object.assign({},e);return t._pendingDecorators=n,n}function Vnn(t){return t.read(()=>th().getTextContent())}function th(){return fon(s0())}function fon(t){return t._nodeMap.get("root")}function nh(t){Zu();let e=s0();t!==null&&(t.dirty=!0,t.setCachedNodes(null)),e._selection=t}function B6(t){let e=ba(),n=function(r,o){let i=r;for(;i!=null;){let s=ixe(i,o);if(s!==void 0)return s;i=Nee(i)}return null}(t,e);return n===null?t===e.getRootElement()?ou("root"):null:ou(n)}function pon(t){return/[\uD800-\uDBFF][\uDC00-\uDFFF]/g.test(t)}function zXe(t){let e=[],n=t;for(;n!==null;)e.push(n),n=n._parentEditor;return e}function mon(){return Math.random().toString(36).replace(/[^a-z]+/g,"").substring(0,5)}function hon(t){return MS(t)?t.nodeValue:null}function HXe(t,e,n){let r=ES(Rv(e));if(r===null)return;let o=r.anchorNode,{anchorOffset:i,focusOffset:s}=r;if(o!==null){let a=hon(o),l=sxe(o);if(a!==null&&dn(l)){if(a===X_e&&n){let c=n.length;a=n,i=c,s=c}a!==null&&WXe(l,a,i,s,t)}}}function WXe(t,e,n,r,o){let i=t;if(i.isAttached()&&(o||!i.isDirty())){let s=i.isComposing(),a=e;(s||o)&&e[e.length-1]===X_e&&(a=e.slice(0,-1));let l=i.getTextContent();if(o||a!==l){if(a===""){if(Yu(null),bee||V6||N_e)i.remove();else{let h=ba();setTimeout(()=>{h.update(()=>{i.isAttached()&&i.remove()})},20)}return}let c=i.getParent(),u=W$(),d=i.getTextContentSize(),f=eM(),p=i.getKey();if(i.isToken()||f!==null&&p===f&&!s||jn(u)&&(c!==null&&!c.canInsertTextBefore()&&u.anchor.offset===0||u.anchor.key===t.__key&&u.anchor.offset===0&&!i.canInsertTextBefore()&&!s||u.focus.key===t.__key&&u.focus.offset===d&&!i.canInsertTextAfter()&&!s))return void i.markDirty();let m=pi();if(!jn(m)||n===null||r===null)return void qnn(i,a,m);if(m.setTextNodeRange(i,n,i,r),i.isSegmented()){let h=Gu(i.getTextContent());i.replace(h),i=h}qnn(i,a,m)}}}function qnn(t,e,n){if(t.setTextContent(e),jn(n)){let r=t.getKey();for(let o of["anchor","focus"]){let i=n[o];i.type==="text"&&i.key===r&&(i.offset=t_(t,i.offset,"clamp"))}}}function I_e(t,e,n){let r=e[n]||!1;return r==="any"||r===t[n]}function gon(t,e){return I_e(t,e,"altKey")&&I_e(t,e,"ctrlKey")&&I_e(t,e,"shiftKey")&&I_e(t,e,"metaKey")}function Ui(t,e,n){return gon(t,n)&&t.key.toLowerCase()===e.toLowerCase()}function Gnn(t){return t.key==="Backspace"}function Znn(t){return Ui(t,"a",JI)}function m0r(t){let e=th();if(jn(t)){let n=t.anchor,r=t.focus,o=n.getNode().getTopLevelElementOrThrow().getParentOrThrow();return n.set(o.getKey(),0,"element"),r.set(o.getKey(),o.getChildrenSize(),"element"),$_e(t),t}{let n=e.select(0,e.getChildrenSize());return nh($_e(n)),n}}function W6(t,e){t.__lexicalClassNameCache===void 0&&(t.__lexicalClassNameCache={});let n=t.__lexicalClassNameCache,r=n[e];if(r!==void 0)return r;let o=t[e];if(typeof o=="string"){let i=R_e(o);return n[e]=i,i}return o}function VXe(t,e,n,r,o){if(n.size===0)return;let i=r.__type,s=r.__key,a=e.get(i);a===void 0&&tt(33,i);let l=a.klass,c=t.get(l);c===void 0&&(c=new Map,t.set(l,c));let u=c.get(s),d=u==="destroyed"&&o==="created";(u===void 0||d)&&c.set(s,d?"updated":o)}function h0r(t){let e=t.getType(),n=s0();if(n._readOnly){let i=mXe(n).get(e);return i?Array.from(i.values()):[]}let r=n._nodeMap,o=[];for(let[,i]of r)i instanceof t&&i.__type===e&&i.isAttached()&&o.push(i);return o}function Ynn(t,e,n){let r=t.getParent(),o=n,i=t;return r!==null&&(e&&n===0?(o=i.getIndexWithinParent(),i=r):e||n!==i.getChildrenSize()||(o=i.getIndexWithinParent()+1,i=r)),i.getChildAtIndex(e?o-1:o)}function yon(t,e){let n=t.offset;if(t.type==="element")return Ynn(t.getNode(),e,n);{let r=t.getNode();if(e&&n===0||!e&&n===r.getTextContentSize()){let o=e?r.getPreviousSibling():r.getNextSibling();return o===null?Ynn(r.getParentOrThrow(),e,r.getIndexWithinParent()+(e?0:1)):o}}return null}function von(t){let e=Rv(t).event,n=e&&e.inputType;return n==="insertFromPaste"||n==="insertFromPasteAsQuotation"}function Kt(t,e,n){return function(r,o,i){let s=zXe(r);for(let a=4;a>=0;a--)for(let l=0;l<s.length;l++){let c=s[l],u=c._commands.get(o);if(u!==void 0){let d=u[a];if(d!==void 0){let f=Array.from(d),p=f.length,m=!1;if(Tg(c,()=>{for(let h=0;h<p;h++)if(f[h](i,r))return void(m=!0)}),m)return m}}}return!1}(t,e,n)}function axe(t){return!Qm(t)&&!t.isLastChild()&&!t.isInline()}function Q6(t,e){let n=t._keyToDOMMap.get(e);return n===void 0&&tt(75,e),n}function Nee(t){let e=t.assignedSlot||t.parentElement;return Con(e)?e.host:e}function qXe(t){return lon(t)?t:Bp(t)?t.ownerDocument:null}function g0r(t){return ba()._updateTags.has(t)}function won(t){Zu(),ba()._updateTags.add(t)}function bon(t){Zu(),ba()._deferred.push(t)}function Z_e(t,e){let n=t.getParent();for(;n!==null;){if(n.is(e))return!0;n=n.getParent()}return!1}function KXe(t){let e=qXe(t);return e?e.defaultView:null}function Rv(t){let e=t._window;return e===null&&tt(78),e}function y0r(t){return Ye(t)&&t.isInline()||vs(t)&&t.isInline()}function _on(t){let e=t.getParentOrThrow();for(;e!==null;){if(r_(e))return e;e=e.getParentOrThrow()}return e}function r_(t){return Qm(t)||Ye(t)&&t.isShadowRoot()}function GXe(t){let e=t.constructor.clone(t);return con(e,null),e.afterCloneFrom(t),e}function Ree(t){let e=ba(),n=t.getType(),r=UXe(e,n);r===void 0&&tt(200,t.constructor.name,n);let{replace:o,replaceWithKlass:i}=r;if(o!==null){let s=o(t),a=s.constructor;return i!==null?s instanceof i||tt(201,i.name,i.getType(),a.name,a.getType(),t.constructor.name,n):s instanceof t.constructor&&a!==t.constructor||tt(202,a.name,a.getType(),t.constructor.name,n),s.__key===t.__key&&tt(203,t.constructor.name,n,a.name,a.getType()),s}return t}function BJe(t,e){!Qm(t.getParent())||Ye(e)||vs(e)||tt(99)}function xon(t){let e=ou(t);return e===null&&tt(63,t),e}function zJe(t){return(vs(t)||Ye(t)&&!t.canBeEmpty())&&!t.isInline()}function fXe(t,e,n){n.style.removeProperty("caret-color"),e._blockCursorElement=null;let r=t.parentElement;r!==null&&r.removeChild(t)}function ES(t){return o_?(t||window).getSelection():null}function Son(t){let e=KXe(t);return e?e.getSelection():null}function v0r(t,e){let n=t.getChildAtIndex(e);n==null&&(n=t),r_(t)&&tt(102);let r=s=>{let a=s.getParentOrThrow(),l=r_(a),c=s!==n||l?GXe(s):s;if(l)return Ye(s)&&Ye(c)||tt(133),s.insertAfter(c),[s,c,c];{let[u,d,f]=r(a),p=s.getNextSiblings();return f.append(c,...p),[u,d,c]}},[o,i]=r(n);return[o,i]}function w0r(t){return Bp(t)&&t.tagName==="A"}function Bp(t){return sV(t)&&t.nodeType===Gkr}function sV(t){return typeof t=="object"&&t!==null&&"nodeType"in t&&typeof t.nodeType=="number"}function Con(t){return sV(t)&&t.nodeType===Jkr}function kon(t){let e=new RegExp(/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|mark|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var|#text)$/,"i");return t.nodeName.match(e)!==null}function pXe(t){let e=new RegExp(/^(address|article|aside|blockquote|canvas|dd|div|dl|dt|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hr|li|main|nav|noscript|ol|p|pre|section|table|td|tfoot|ul|video)$/,"i");return t.nodeName.match(e)!==null}function t0(t){if(vs(t)&&!t.isInline())return!0;if(!Ye(t)||r_(t))return!1;let e=t.getFirstChild(),n=e===null||$$(e)||dn(e)||e.isInline();return!t.isInline()&&t.canBeEmpty()!==!1&&n}function HJe(t,e){let n=t;for(;n!==null&&n.getParent()!==null&&!e(n);)n=n.getParentOrThrow();return e(n)?n:null}function ZXe(){return ba()}function mXe(t){if(!t._readOnly&&t.isEmpty())return b0r;t._readOnly||tt(192);let e=Jnn.get(t);return e||(e=function(n){let r=new Map;for(let[o,i]of n._nodeMap){let s=i.__type,a=r.get(s);a||(a=new Map,r.set(s,a)),a.set(o,i)}return r}(t),Jnn.set(t,e)),e}function Ion(t){let e=t.constructor.clone(t);return e.afterCloneFrom(t),e}function Ton(t,e){let n=parseInt(t.style.paddingInlineStart,10)||0,r=Math.round(n/40);e.setIndent(r)}function _0r(t){t.__lexicalUnmanaged=!0}function Pon(t){return t.__lexicalUnmanaged===!0}function fee(t,e){return function(n,r){return Object.prototype.hasOwnProperty.call(n,r)}(t,e)&&t[e]!==oM[e]}function YXe(t){let e=dnn in t.prototype?t.prototype[dnn]():void 0,n=function(s){return s===Aee||s===iM||s===oM}(t),r=!n&&fee(t,"getType")?t.getType():void 0,o,i=r;if(e)if(r)o=e[r];else for(let[s,a]of Object.entries(e))i=s,o=a;if(!n&&i&&(fee(t,"getType")||(t.getType=()=>i),fee(t,"clone")||(t.clone=s=>(DXe(s),new t)),fee(t,"importJSON")||(t.importJSON=o&&o.$importJSON||(s=>new t().updateFromJSON(s))),!fee(t,"importDOM")&&o)){let{importDOM:s}=o;s&&(t.importDOM=()=>s)}return{ownNodeConfig:o,ownNodeType:i}}function x0r(t){let e=ZXe();return Zu(),new(e.resolveRegisteredNodeAfterReplacements(e.getRegisteredNode(t))).klass}function uM(t){return S0r[t]}function JXe(t,e="root"){return C0r[e](t)?null:t}function r0(t){return t instanceof nV}function k0r(t){return t instanceof eV}function H$(t){return t instanceof tV}function e_(t){return t instanceof Eee}function Qu(t,e){return t?new T0r[e](t):null}function sM(t,e,n){return t?new I0r[e](t,t_(t,n)):null}function t_(t,e,n="error"){let r=t.getTextContentSize(),o=e==="next"?r:e==="previous"?0:e;return(o<0||o>r)&&(n!=="clamp"&&function(i,...s){let a=new URL("https://lexical.dev/docs/error"),l=new URLSearchParams;l.append("code",i);for(let c of s)l.append("v",c);a.search=l.toString(),console.warn(`Minified Lexical warning #${i}; visit ${a.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}(284,String(e),String(r),t.getKey()),o=o<0?0:r),o}function hXe(t,e){return new Y_e(t,e)}function i0(t,e){return Ye(t)?new P0r[e](t):null}function Aon(t){return t&&t.getChildCaret()||t}function rV(t){return t&&Aon(t.getAdjacentCaret())}function A0r(t){return t instanceof Y_e}function XXe(t){return aM(t,Qu(th(),t.direction))}function Eon(t){return aM(t,t)}function aM(t,e){return t.direction!==e.direction&&tt(265),new gXe(t,e,t.direction)}function QXe(t){let{initial:e,hasNext:n,step:r,map:o}=t,i=e;return{[Symbol.iterator](){return this},next(){if(!n(i))return{done:!0,value:void 0};let s={done:!1,value:o(i)};return i=r(i),s}}}function eQe(t,e){let n=vee(t.origin,e.origin);switch(n===null&&tt(275,t.origin.getKey(),e.origin.getKey()),n.type){case"same":{let r=t.type==="text",o=e.type==="text";return r&&o?function(i,s){return Math.sign(i-s)}(t.offset,e.offset):t.type===e.type?0:r?-1:o?1:t.type==="child"?-1:1}case"ancestor":return t.type==="child"?-1:1;case"descendant":return e.type==="child"?1:-1;case"branch":return tQe(n)}}function tQe(t){let{a:e,b:n}=t,r=e.__key,o=n.__key,i=e,s=n;for(;i&&s;i=i.getNextSibling(),s=s.getNextSibling()){if(i.__key===o)return-1;if(s.__key===r)return 1}return i===null?1:-1}function T_e(t,e){return e.is(t)}function Xnn(t){return Ye(t)?[t.getLatest(),null]:[t.getParent(),t.getLatest()]}function vee(t,e){if(t.is(e))return{commonAncestor:t,type:"same"};let n=new Map;for(let[r,o]=Xnn(t);r;o=r,r=r.getParent())n.set(r,o);for(let[r,o]=Xnn(e);r;o=r,r=r.getParent()){let i=n.get(r);if(i!==void 0)return i===null?(T_e(t,r)||tt(276),{commonAncestor:r,type:"ancestor"}):o===null?(T_e(e,r)||tt(277),{commonAncestor:r,type:"descendant"}):((Ye(i)||T_e(t,i))&&(Ye(o)||T_e(e,o))&&r.is(i.getParent())&&r.is(o.getParent())||tt(278),{a:i,b:o,commonAncestor:r,type:"branch"})}return null}function lM(t,e){let{type:n,key:r,offset:o}=t,i=xon(t.key);return n==="text"?(dn(i)||tt(266,i.getType(),r),sM(i,e,o)):(Ye(i)||tt(267,i.getType(),r),Ron(i,t.offset,e))}function oV(t,e){let{origin:n,direction:r}=e,o=r==="next";r0(e)?t.set(n.getKey(),e.offset,"text"):H$(e)?dn(n)?t.set(n.getKey(),t_(n,r),"text"):t.set(n.getParentOrThrow().getKey(),n.getIndexWithinParent()+(o?1:0),"element"):(e_(e)&&Ye(n)||tt(268),t.set(n.getKey(),o?0:n.getChildrenSize(),"element"))}function Mon(t){let e=pi(),n=jn(e)?e:Yrn();return wee(n,t),nh(n),n}function wee(t,e){oV(t.anchor,e.anchor),oV(t.focus,e.focus)}function yXe(t){let{anchor:e,focus:n}=t,r=lM(e,"next"),o=lM(n,"next"),i=eQe(r,o)<=0?"next":"previous";return aM(cM(r,i),cM(o,i))}function aV(t){let{direction:e,origin:n}=t,r=Qu(n,uM(e)).getNodeAtCaret();return r?Qu(r,e):i0(n.getParentOrThrow(),e)}function Qnn(t,e="root"){let n=[t];for(let r=e_(t)?t.getParentCaret(e):t.getSiblingCaret();r!==null;r=r.getParentCaret(e))n.push(aV(r));return n}function WJe(t){return!!t&&t.origin.isAttached()}function Oon(t,e="removeEmptySlices"){if(t.isCollapsed())return t;let n="root",r="next",o=e,i=nQe(t,r),s=Qnn(i.anchor,n),a=Qnn(i.focus.getFlipped(),n),l=new Set,c=[];for(let m of i.iterNodeCarets(n))if(e_(m))l.add(m.origin.getKey());else if(H$(m)){let{origin:h}=m;Ye(h)&&!l.has(h.getKey())||c.push(h)}for(let m of c)m.remove();for(let m of i.getTextSlices()){if(!m)continue;let{origin:h}=m.caret,g=h.getTextContentSize(),v=aV(Qu(h,r)),y=h.getMode();if(Math.abs(m.distance)===g&&o==="removeEmptySlices"||y==="token"&&m.distance!==0)v.remove();else if(m.distance!==0){o="removeEmptySlices";let w=m.removeTextSlice(),_=m.caret.origin;if(y==="segmented"){let S=w.origin,I=Gu(S.getTextContent()).setStyle(S.getStyle()).setFormat(S.getFormat());v.replaceOrInsert(I),w=sM(I,r,w.offset)}_.is(s[0].origin)&&(s[0]=w),_.is(a[0].origin)&&(a[0]=w.getFlipped())}}let u,d;for(let m of s)if(WJe(m)){u=Xb(m);break}for(let m of a)if(WJe(m)){d=Xb(m);break}let f=function(m,h,g){if(!m||!h)return null;let v=m.getParentAtCaret(),y=h.getParentAtCaret();if(!v||!y)return null;let w=v.getParents().reverse();w.push(v);let _=y.getParents().reverse();_.push(y);let S=Math.min(w.length,_.length),I;for(I=0;I<S&&w[I]===_[I];I++);let C=(P,E)=>{let O;for(let $=I;$<P.length;$++){let U=P[$];if(r_(U))return;!O&&E(U)&&(O=U)}return O},k=C(w,t0),T=k&&C(_,P=>g.has(P.getKey())&&t0(P));return k&&T?[k,T]:null}(u,d,l);if(f){let[m,h]=f;i0(m,"previous").splice(0,h.getChildren()),h.remove()}let p=[u,d,...s,...a].find(WJe);if(p)return Eon(cM(Xb(p),t.direction));tt(269,JSON.stringify(s.map(m=>m.origin.__key)))}function Xb(t){let e=function(o){let i=o;for(;e_(i);){let s=rV(i);if(!e_(s))break;i=s}return i}(t.getLatest()),{direction:n}=e;if(dn(e.origin))return r0(e)?e:sM(e.origin,n,n);let r=e.getAdjacentCaret();return H$(r)&&dn(r.origin)?sM(r.origin,n,uM(n)):e}function Non(t){return r0(t)&&t.offset!==t_(t.origin,t.direction)}function cM(t,e){return t.direction===e?t:t.getFlipped()}function nQe(t,e){return t.direction===e?t:aM(cM(t.focus,e),cM(t.anchor,e))}function Ron(t,e,n){let r=i0(t,"next");for(let o=0;o<e;o++){let i=r.getAdjacentCaret();if(i===null)break;r=i}return cM(r,n)}function E0r(t,e="root"){let n=0,r=t,o=rV(r);for(;o===null;){if(n--,o=r.getParentCaret(e),!o)return null;r=o,o=rV(r)}return o&&[o,n]}function M0r(t){let{origin:e,offset:n,direction:r}=t;if(n===t_(e,r))return t.getSiblingCaret();if(n===t_(e,uM(r)))return aV(t.getSiblingCaret());let[o]=e.splitText(n);return dn(o)||tt(281),cM(Qu(o,"next"),r)}function O0r(t,e){return!0}function N0r(t,{$copyElementNode:e=GXe,$splitTextPointCaretNext:n=M0r,rootMode:r="shadowRoot",$shouldSplit:o=O0r}={}){if(r0(t))return n(t);let i=t.getParentCaret(r);if(i){let{origin:s}=i;if(e_(t)&&(!s.canBeEmpty()||!o(s,"first")))return aV(i);let a=function(l){let c=[];for(let u=l.getAdjacentCaret();u;u=u.getAdjacentCaret())c.push(u.origin);return c}(t);(a.length>0||s.canBeEmpty()&&o(s,"last"))&&i.insert(e(s).splice(0,0,a))}return i}var o_,qkr,AS,D$,O_e,bee,V6,Kkr,ern,cnn,N_e,Gkr,Zkr,Ykr,Jkr,F$,trn,q6,Xkr,Qkr,eIr,tIr,nIr,_ee,xee,rIr,oIr,iIr,J_e,nrn,vXe,wXe,bXe,_Xe,xXe,SXe,X_e,o0,sIr,rrn,orn,aIr,lIr,Uf,cIr,unn,uIr,dIr,fIr,pIr,dnn,mIr,VJe,CXe,qJe,KJe,rM,jp,See,Q_e,GJe,ZJe,U$,Qb,YJe,Cee,ru,Up,TS,PS,QI,drn,kee,P_e,SIr,IXe,IIr,yrn,Iee,mee,eXe,z6,TXe,tXe,Tee,Pee,QE,PXe,AXe,vrn,wrn,brn,_rn,xrn,Srn,Crn,j_e,krn,Irn,Trn,Prn,Arn,TIr,PIr,AIr,Ern,EIr,Mrn,Orn,Nrn,EXe,MXe,nXe,MIr,OIr,NIr,RIr,Rrn,Lrn,$rn,ZI,rXe,oXe,hee,Drn,Frn,j6,B_e,iXe,sXe,gee,dee,RJe,LJe,L$,Urn,H6,LIr,oM,K6,j$,Inn,HIr,Z6,lXe,z_e,B$,WIr,Ju,Xu,eh,jJe,E_e,Dnn,uXe,iM,Aee,Y6,V_e,QIr,e0r,M_e,t0r,ron,n0r,oon,ion,q_e,J6,i0r,s0r,a0r,l0r,c0r,X6,dXe,aon,f0r,JI,Knn,Jnn,b0r,S0r,eV,Eee,C0r,tV,nV,I0r,T0r,P0r,gXe,Y_e,Lon=b(()=>{o_=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0,qkr=o_&&"documentMode"in document?document.documentMode:null,AS=o_&&/Mac|iPod|iPhone|iPad/.test(navigator.platform),D$=o_&&/^(?!.*Seamonkey)(?=.*Firefox).*/i.test(navigator.userAgent),O_e=!(!o_||!("InputEvent"in window)||qkr)&&"getTargetRanges"in new window.InputEvent("input"),bee=o_&&/Version\/[\d.]+.*Safari/.test(navigator.userAgent),V6=o_&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,Kkr=o_&&/Android/.test(navigator.userAgent),ern=o_&&/^(?=.*Chrome).*/i.test(navigator.userAgent),cnn=o_&&Kkr&&ern,N_e=o_&&/AppleWebKit\/[\d.]+/.test(navigator.userAgent)&&!ern;Gkr=1,Zkr=3,Ykr=9,Jkr=11,F$=0,trn=1,q6=2,Xkr=0,Qkr=1,eIr=2,tIr=1,nIr=2,_ee=4,xee=8,rIr=16,oIr=32,iIr=64,J_e=128,nrn=1792|(112|(3|_ee|xee)|J_e),vXe=1,wXe=2,bXe=3,_Xe=4,xXe=5,SXe=6,X_e=bee||V6||N_e?"\xA0":"\u200B",o0=`
`,sIr=D$?"\xA0":X_e,rrn="\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC",orn="A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u0300-\u0590\u0800-\u1FFF\u200E\u2C00-\uFB1C\uFE00-\uFE6F\uFEFD-\uFFFF",aIr=new RegExp("^[^"+orn+"]*["+rrn+"]"),lIr=new RegExp("^[^"+rrn+"]*["+orn+"]"),Uf={bold:1,capitalize:1024,code:16,highlight:J_e,italic:2,lowercase:256,strikethrough:_ee,subscript:32,superscript:64,underline:xee,uppercase:512},cIr={directionless:1,unmergeable:2},unn={center:wXe,end:SXe,justify:_Xe,left:vXe,right:bXe,start:xXe},uIr={[wXe]:"center",[SXe]:"end",[_Xe]:"justify",[vXe]:"left",[bXe]:"right",[xXe]:"start"},dIr={normal:0,segmented:2,token:1},fIr={[Xkr]:"normal",[eIr]:"segmented",[Qkr]:"token"},pIr="$",dnn="$config";mIr=100,VJe=!1,CXe=0;qJe=class{constructor(e,n){this.key=e,this.parse=n.parse.bind(n),this.unparse=(n.unparse||xIr).bind(n),this.isEqual=(n.isEqual||Object.is).bind(n),this.defaultValue=this.parse(void 0)}};KJe=class t{constructor(e,n,r=void 0,o=new Map,i=void 0){this.node=e,this.sharedNodeState=n,this.unknownState=r,this.knownState=o;let{sharedConfigMap:s}=this.sharedNodeState,a=i!==void 0?i:function(l,c,u){let d=u.size;if(c)for(let f in c){let p=l.get(f);p&&u.has(p)||d++}return d}(s,r,o);this.size=a}getValue(e){let n=this.knownState.get(e);if(n!==void 0)return n;this.sharedNodeState.sharedConfigMap.set(e.key,e);let r=e.defaultValue;if(this.unknownState&&e.key in this.unknownState){let o=this.unknownState[e.key];o!==void 0&&(r=e.parse(o)),this.updateFromKnown(e,r)}return r}getInternalState(){return[this.unknownState,this.knownState]}toJSON(){let e={...this.unknownState},n={};for(let[r,o]of this.knownState)r.isEqual(o,r.defaultValue)?delete e[r.key]:e[r.key]=r.unparse(o);for(let r of this.sharedNodeState.flatKeys)r in e&&(n[r]=e[r],delete e[r]);return fnn(e)&&(n.$=e),n}getWritable(e){if(this.node===e)return this;let{sharedNodeState:n,unknownState:r}=this,o=new Map(this.knownState);return new t(e,n,function(i,s,a){let l;if(a)for(let[c,u]of Object.entries(a)){let d=i.get(c);d?s.has(d)||s.set(d,d.parse(u)):(l=l||{},l[c]=u)}return l}(n.sharedConfigMap,o,r),o,this.size)}updateFromKnown(e,n){let r=e.key;this.sharedNodeState.sharedConfigMap.set(r,e);let{knownState:o,unknownState:i}=this;o.has(e)||i&&r in i||(i&&(delete i[r],this.unknownState=fnn(i)),this.size++),o.set(e,n)}updateFromUnknown(e,n){let r=this.sharedNodeState.sharedConfigMap.get(e);r?this.updateFromKnown(r,r.parse(n)):(this.unknownState=this.unknownState||{},e in this.unknownState||this.size++,this.unknownState[e]=n)}updateFromJSON(e){let{knownState:n}=this;for(let r of n.keys())n.set(r,r.defaultValue);if(this.size=n.size,this.unknownState=void 0,e)for(let[r,o]of Object.entries(e))this.updateFromUnknown(r,o)}};ru="",Up="",TS=null,PS="",QI="",drn=!1,kee=!1,P_e=null;SIr="40px";IXe=Pr("SELECTION_CHANGE_COMMAND"),IIr=Pr("SELECTION_INSERT_CLIPBOARD_NODES_COMMAND"),yrn=Pr("CLICK_COMMAND"),Iee=Pr("DELETE_CHARACTER_COMMAND"),mee=Pr("INSERT_LINE_BREAK_COMMAND"),eXe=Pr("INSERT_PARAGRAPH_COMMAND"),z6=Pr("CONTROLLED_TEXT_INSERTION_COMMAND"),TXe=Pr("PASTE_COMMAND"),tXe=Pr("REMOVE_TEXT_COMMAND"),Tee=Pr("DELETE_WORD_COMMAND"),Pee=Pr("DELETE_LINE_COMMAND"),QE=Pr("FORMAT_TEXT_COMMAND"),PXe=Pr("UNDO_COMMAND"),AXe=Pr("REDO_COMMAND"),vrn=Pr("KEYDOWN_COMMAND"),wrn=Pr("KEY_ARROW_RIGHT_COMMAND"),brn=Pr("MOVE_TO_END"),_rn=Pr("KEY_ARROW_LEFT_COMMAND"),xrn=Pr("MOVE_TO_START"),Srn=Pr("KEY_ARROW_UP_COMMAND"),Crn=Pr("KEY_ARROW_DOWN_COMMAND"),j_e=Pr("KEY_ENTER_COMMAND"),krn=Pr("KEY_SPACE_COMMAND"),Irn=Pr("KEY_BACKSPACE_COMMAND"),Trn=Pr("KEY_ESCAPE_COMMAND"),Prn=Pr("KEY_DELETE_COMMAND"),Arn=Pr("KEY_TAB_COMMAND"),TIr=Pr("INSERT_TAB_COMMAND"),PIr=Pr("INDENT_CONTENT_COMMAND"),AIr=Pr("OUTDENT_CONTENT_COMMAND"),Ern=Pr("DROP_COMMAND"),EIr=Pr("FORMAT_ELEMENT_COMMAND"),Mrn=Pr("DRAGSTART_COMMAND"),Orn=Pr("DRAGOVER_COMMAND"),Nrn=Pr("DRAGEND_COMMAND"),EXe=Pr("COPY_COMMAND"),MXe=Pr("CUT_COMMAND"),nXe=Pr("SELECT_ALL_COMMAND"),MIr=Pr("CLEAR_EDITOR_COMMAND"),OIr=Pr("CLEAR_HISTORY_COMMAND"),NIr=Pr("CAN_REDO_COMMAND"),RIr=Pr("CAN_UNDO_COMMAND"),Rrn=Pr("FOCUS_COMMAND"),Lrn=Pr("BLUR_COMMAND"),$rn=Pr("KEY_MODIFIER_COMMAND"),ZI=Object.freeze({}),rXe=30,oXe=[["keydown",function(t,e){if(hee=t.timeStamp,Drn=t.key,!e.isComposing()&&!Kt(e,vrn,t)&&t.key!=null){if(RJe&&Gnn(t))return Tg(e,()=>{S_e(e,LJe)}),RJe=!1,void(LJe="");if(function(n){return Ui(n,"ArrowRight",{shiftKey:"any"})}(t))Kt(e,wrn,t);else if(function(n){return Ui(n,"ArrowRight",JI)}(t))Kt(e,brn,t);else if(function(n){return Ui(n,"ArrowLeft",{shiftKey:"any"})}(t))Kt(e,_rn,t);else if(function(n){return Ui(n,"ArrowLeft",JI)}(t))Kt(e,xrn,t);else if(function(n){return Ui(n,"ArrowUp",{altKey:"any",shiftKey:"any"})}(t))Kt(e,Srn,t);else if(function(n){return Ui(n,"ArrowDown",{altKey:"any",shiftKey:"any"})}(t))Kt(e,Crn,t);else if(function(n){return Ui(n,"Enter",{altKey:"any",ctrlKey:"any",metaKey:"any",shiftKey:!0})}(t))gee=!0,Kt(e,j_e,t);else if(function(n){return n.key===" "}(t))Kt(e,krn,t);else if(function(n){return AS&&Ui(n,"o",{ctrlKey:!0})}(t))t.preventDefault(),gee=!0,Kt(e,mee,!0);else if(function(n){return Ui(n,"Enter",{altKey:"any",ctrlKey:"any",metaKey:"any"})}(t))gee=!1,Kt(e,j_e,t);else if(function(n){return Ui(n,"Backspace",{shiftKey:"any"})||AS&&Ui(n,"h",{ctrlKey:!0})}(t))Gnn(t)?Kt(e,Irn,t):(t.preventDefault(),Kt(e,Iee,!0));else if(function(n){return n.key==="Escape"}(t))Kt(e,Trn,t);else if(function(n){return Ui(n,"Delete",{})||AS&&Ui(n,"d",{ctrlKey:!0})}(t))(function(n){return n.key==="Delete"})(t)?Kt(e,Prn,t):(t.preventDefault(),Kt(e,Iee,!1));else if(function(n){return Ui(n,"Backspace",Knn)}(t))t.preventDefault(),Kt(e,Tee,!0);else if(function(n){return Ui(n,"Delete",Knn)}(t))t.preventDefault(),Kt(e,Tee,!1);else if(function(n){return AS&&Ui(n,"Backspace",{metaKey:!0})}(t))t.preventDefault(),Kt(e,Pee,!0);else if(function(n){return AS&&(Ui(n,"Delete",{metaKey:!0})||Ui(n,"k",{ctrlKey:!0}))}(t))t.preventDefault(),Kt(e,Pee,!1);else if(function(n){return Ui(n,"b",JI)}(t))t.preventDefault(),Kt(e,QE,"bold");else if(function(n){return Ui(n,"u",JI)}(t))t.preventDefault(),Kt(e,QE,"underline");else if(function(n){return Ui(n,"i",JI)}(t))t.preventDefault(),Kt(e,QE,"italic");else if(function(n){return Ui(n,"Tab",{shiftKey:"any"})}(t))Kt(e,Arn,t);else if(function(n){return Ui(n,"z",JI)}(t))t.preventDefault(),Kt(e,PXe,void 0);else if(function(n){return AS?Ui(n,"z",{metaKey:!0,shiftKey:!0}):Ui(n,"y",{ctrlKey:!0})||Ui(n,"z",{ctrlKey:!0,shiftKey:!0})}(t))t.preventDefault(),Kt(e,AXe,void 0);else{let n=e._editorState._selection;n===null||jn(n)?Znn(t)&&(t.preventDefault(),Kt(e,nXe,t)):function(r){return Ui(r,"c",JI)}(t)?(t.preventDefault(),Kt(e,EXe,t)):function(r){return Ui(r,"x",JI)}(t)?(t.preventDefault(),Kt(e,MXe,t)):Znn(t)&&(t.preventDefault(),Kt(e,nXe,t))}(function(n){return n.ctrlKey||n.shiftKey||n.altKey||n.metaKey})(t)&&Kt(e,$rn,t)}}],["pointerdown",function(t,e){let n=t.target,r=t.pointerType;sV(n)&&r!=="touch"&&r!=="pen"&&t.button===0&&Tg(e,()=>{Wnn(n)||(sXe=!0)})}],["compositionstart",function(t,e){Tg(e,()=>{let n=pi();if(jn(n)&&!e.isComposing()){let r=n.anchor,o=n.anchor.getNode();Yu(r.key),(t.timeStamp<hee+rXe||r.type==="element"||!n.isCollapsed()||o.getFormat()!==n.format||dn(o)&&o.getStyle()!==n.style)&&Kt(e,z6,sIr)}})}],["compositionend",function(t,e){D$?dee=!0:V6||!bee&&!N_e?Tg(e,()=>{S_e(e,t.data)}):(RJe=!0,LJe=t.data)}],["input",function(t,e){t.stopPropagation(),Tg(e,()=>{if(Bp(t.target)&&Wnn(t.target))return;let n=pi(),r=t.data,o=zrn(t);if(r!=null&&jn(n)&&jrn(n,o,r,t.timeStamp,!1)){dee&&(S_e(e,r),dee=!1);let i=n.anchor.getNode(),s=ES(Rv(e));if(s===null)return;let a=n.isBackward(),l=a?n.anchor.offset:n.focus.offset,c=a?n.focus.offset:n.anchor.offset;O_e&&!n.isCollapsed()&&dn(i)&&s.anchorNode!==null&&i.getTextContent().slice(0,l)+r+i.getTextContent().slice(l+c)===hon(s.anchorNode)||Kt(e,z6,r);let u=r.length;D$&&u>1&&t.inputType==="insertCompositionText"&&!e.isComposing()&&(n.anchor.offset-=u),bee||V6||N_e||!e.isComposing()||(hee=0,Yu(null))}else HXe(!1,e,r!==null?r:void 0),dee&&(S_e(e,r||void 0),dee=!1);(function(){Zu();let i=ba();arn(i)})()},{event:t}),j6=null}],["click",function(t,e){Tg(e,()=>{let n=pi(),r=ES(Rv(e)),o=W$();if(r){if(jn(n)){let i=n.anchor,s=i.getNode();if(i.type==="element"&&i.offset===0&&n.isCollapsed()&&!Qm(s)&&th().getChildrenSize()===1&&s.getTopLevelElementOrThrow().isEmpty()&&o!==null&&n.is(o))r.removeAllRanges(),n.dirty=!0;else if(t.detail===3&&!n.isCollapsed()&&s!==n.focus.getNode()){let a=function(l,c){let u=l;for(;u!==th()&&u!=null;){if(c(u))return u;u=u.getParent()}return null}(s,l=>Ye(l)&&!l.isInline());Ye(a)&&a.select(0)}}else if(t.pointerType==="touch"||t.pointerType==="pen"){let i=r.anchorNode;(Bp(i)||MS(i))&&nh(nxe(o,r,e,t))}}Kt(e,yrn,t)})}],["cut",ZI],["copy",ZI],["dragstart",ZI],["dragover",ZI],["dragend",ZI],["paste",ZI],["focus",ZI],["blur",ZI],["drop",ZI]];O_e&&oXe.push(["beforeinput",(t,e)=>function(n,r){let o=n.inputType,i=zrn(n);o==="deleteCompositionText"||D$&&von(r)||o!=="insertCompositionText"&&Tg(r,()=>{let s=pi();if(o==="deleteContentBackward"){if(s===null){let p=W$();if(!jn(p))return;nh(p.clone())}if(jn(s)){let p=s.anchor.key===s.focus.key;if(a=n.timeStamp,Drn==="MediaLast"&&a<hee+rXe&&r.isComposing()&&p){if(Yu(null),hee=0,setTimeout(()=>{Tg(r,()=>{Yu(null)})},rXe),jn(s)){let m=s.anchor.getNode();m.markDirty(),dn(m)||tt(142),Brn(s,m)}}else{Yu(null),n.preventDefault();let m=s.anchor.getNode(),h=m.getTextContent(),g=m.canInsertTextAfter(),v=s.anchor.offset===0&&s.focus.offset===h.length,y=cnn&&p&&!v&&g;if(y&&s.isCollapsed()&&(y=!vs(yon(s.anchor,!0))),!y){Kt(r,Iee,!0);let w=pi();cnn&&jn(w)&&w.isCollapsed()&&(L$=w,setTimeout(()=>L$=null))}}return}}var a;if(!jn(s))return;let l=n.data;j6!==null&&HXe(!1,r,j6),s.dirty&&j6===null||!s.isCollapsed()||Qm(s.anchor.getNode())||i===null||s.applyDOMRange(i),j6=null;let c=s.anchor,u=s.focus,d=c.getNode(),f=u.getNode();if(o!=="insertText"&&o!=="insertTranspose")switch(n.preventDefault(),o){case"insertFromYank":case"insertFromDrop":case"insertReplacementText":Kt(r,z6,n);break;case"insertFromComposition":Yu(null),Kt(r,z6,n);break;case"insertLineBreak":Yu(null),Kt(r,mee,!1);break;case"insertParagraph":Yu(null),gee&&!V6?(gee=!1,Kt(r,mee,!1)):Kt(r,eXe,void 0);break;case"insertFromPaste":case"insertFromPasteAsQuotation":Kt(r,TXe,n);break;case"deleteByComposition":(function(p,m){return p!==m||Ye(p)||Ye(m)||!tM(p)||!tM(m)})(d,f)&&Kt(r,tXe,n);break;case"deleteByDrag":case"deleteByCut":Kt(r,tXe,n);break;case"deleteContent":Kt(r,Iee,!1);break;case"deleteWordBackward":Kt(r,Tee,!0);break;case"deleteWordForward":Kt(r,Tee,!1);break;case"deleteHardLineBackward":case"deleteSoftLineBackward":Kt(r,Pee,!0);break;case"deleteContentForward":case"deleteHardLineForward":case"deleteSoftLineForward":Kt(r,Pee,!1);break;case"formatStrikeThrough":Kt(r,QE,"strikethrough");break;case"formatBold":Kt(r,QE,"bold");break;case"formatItalic":Kt(r,QE,"italic");break;case"formatUnderline":Kt(r,QE,"underline");break;case"historyUndo":Kt(r,PXe,void 0);break;case"historyRedo":Kt(r,AXe,void 0)}else{if(l===`
`)n.preventDefault(),Kt(r,mee,!1);else if(l===o0)n.preventDefault(),Kt(r,eXe,void 0);else if(l==null&&n.dataTransfer){let p=n.dataTransfer.getData("text/plain");n.preventDefault(),s.insertRawText(p)}else l!=null&&jrn(s,i,l,n.timeStamp,!0)?(n.preventDefault(),Kt(r,z6,l)):j6=l;Frn=n.timeStamp}})}(t,e)]);hee=0,Drn=null,Frn=0,j6=null,B_e=new WeakMap,iXe=!1,sXe=!1,gee=!1,dee=!1,RJe=!1,LJe="",L$=null,Urn=[0,"",0,"root",0];H6=new Map;LIr=()=>{};oM=class{static getType(){let{ownNodeType:e}=YXe(this);return e===void 0&&tt(64,this.name),e}static clone(e){tt(65,this.name)}$config(){return{}}config(e,n){let r=n.extends||Object.getPrototypeOf(this.constructor);return Object.assign(n,{extends:r,type:e}),{[e]:n}}afterCloneFrom(e){this.__key===e.__key?(this.__parent=e.__parent,this.__next=e.__next,this.__prev=e.__prev,this.__state=e.__state):e.__state&&(this.__state=e.__state.getWritable(this))}constructor(e){this.__type=this.constructor.getType(),this.__parent=null,this.__prev=null,this.__next=null,Object.defineProperty(this,"__state",{configurable:!0,enumerable:!1,value:void 0,writable:!0}),con(this,e)}getType(){return this.__type}isInline(){tt(137,this.constructor.name)}isAttached(){let e=this.__key;for(;e!==null;){if(e==="root")return!0;let n=ou(e);if(n===null)break;e=n.__parent}return!1}isSelected(e){let n=e||pi();if(n==null)return!1;let r=n.getNodes().some(o=>o.__key===this.__key);if(dn(this))return r;if(jn(n)&&n.anchor.type==="element"&&n.focus.type==="element"){if(n.isCollapsed())return!1;let o=this.getParent();if(vs(this)&&this.isInline()&&o){let i=n.isBackward()?n.focus:n.anchor;if(o.is(i.getNode())&&i.offset===o.getChildrenSize()&&this.is(o.getLastChild()))return!1}}return r}getKey(){return this.__key}getIndexWithinParent(){let e=this.getParent();if(e===null)return-1;let n=e.getFirstChild(),r=0;for(;n!==null;){if(this.is(n))return r;r++,n=n.getNextSibling()}return-1}getParent(){let e=this.getLatest().__parent;return e===null?null:ou(e)}getParentOrThrow(){let e=this.getParent();return e===null&&tt(66,this.__key),e}getTopLevelElement(){let e=this;for(;e!==null;){let n=e.getParent();if(r_(n))return Ye(e)||e===this&&vs(e)||tt(194),e;e=n}return null}getTopLevelElementOrThrow(){let e=this.getTopLevelElement();return e===null&&tt(67,this.__key),e}getParents(){let e=[],n=this.getParent();for(;n!==null;)e.push(n),n=n.getParent();return e}getParentKeys(){let e=[],n=this.getParent();for(;n!==null;)e.push(n.__key),n=n.getParent();return e}getPreviousSibling(){let e=this.getLatest().__prev;return e===null?null:ou(e)}getPreviousSiblings(){let e=[],n=this.getParent();if(n===null)return e;let r=n.getFirstChild();for(;r!==null&&!r.is(this);)e.push(r),r=r.getNextSibling();return e}getNextSibling(){let e=this.getLatest().__next;return e===null?null:ou(e)}getNextSiblings(){let e=[],n=this.getNextSibling();for(;n!==null;)e.push(n),n=n.getNextSibling();return e}getCommonAncestor(e){let n=Ye(this)?this:this.getParent(),r=Ye(e)?e:e.getParent(),o=n&&r?vee(n,r):null;return o?o.commonAncestor:null}is(e){return e!=null&&this.__key===e.__key}isBefore(e){let n=vee(this,e);return n!==null&&(n.type==="descendant"||(n.type==="branch"?tQe(n)===-1:(n.type!=="same"&&n.type!=="ancestor"&&tt(279),!1)))}isParentOf(e){let n=vee(this,e);return n!==null&&n.type==="ancestor"}getNodesBetween(e){let n=this.isBefore(e),r=[],o=new Set,i=this;for(;i!==null;){let s=i.__key;if(o.has(s)||(o.add(s),r.push(i)),i===e)break;let a=Ye(i)?n?i.getFirstChild():i.getLastChild():null;if(a!==null){i=a;continue}let l=n?i.getNextSibling():i.getPreviousSibling();if(l!==null){i=l;continue}let c=i.getParentOrThrow();if(o.has(c.__key)||r.push(c),c===e)break;let u=null,d=c;do{if(d===null&&tt(68),u=n?d.getNextSibling():d.getPreviousSibling(),d=d.getParent(),d===null)break;u!==null||o.has(d.__key)||r.push(d)}while(u===null);i=u}return n||r.reverse(),r}isDirty(){let e=ba()._dirtyLeaves;return e!==null&&e.has(this.__key)}getLatest(){let e=ou(this.__key);return e===null&&tt(113),e}getWritable(){Zu();let e=s0(),n=ba(),r=e._nodeMap,o=this.__key,i=this.getLatest(),s=n._cloneNotNeeded,a=pi();if(a!==null&&a.setCachedNodes(null),s.has(o))return G_e(i),i;let l=Ion(i);return s.add(o),G_e(l),r.set(o,l),l}getTextContent(){return""}getTextContentSize(){return this.getTextContent().length}createDOM(e,n){tt(70)}updateDOM(e,n,r){tt(71)}exportDOM(e){return{element:this.createDOM(e._config,e)}}exportJSON(){let e=this.__state?this.__state.toJSON():void 0;return{type:this.__type,version:1,...e}}static importJSON(e){tt(18,this.name)}updateFromJSON(e){return function(n,r){let o=n.getWritable(),i=r.$,s=i;for(let a of urn(o).flatKeys)a in r&&(s!==void 0&&s!==i||(s={...i}),s[a]=r[a]);return(o.__state||s)&&kXe(n).updateFromJSON(s),o}(this,e)}static transform(){return null}remove(e){aXe(this,!0,e)}replace(e,n){Zu();let r=pi();r!==null&&(r=r.clone()),BJe(this,e);let o=this.getLatest(),i=this.__key,s=e.__key,a=e.getWritable(),l=this.getParentOrThrow().getWritable(),c=l.__size;nM(a);let u=o.getPreviousSibling(),d=o.getNextSibling(),f=o.__prev,p=o.__next,m=o.__parent;if(aXe(o,!1,!0),u===null?l.__first=s:u.getWritable().__next=s,a.__prev=f,d===null?l.__last=s:d.getWritable().__prev=s,a.__next=p,a.__parent=m,l.__size=c,n&&(Ye(this)&&Ye(a)||tt(139),this.getChildren().forEach(h=>{a.append(h)})),jn(r)){nh(r);let h=r.anchor,g=r.focus;h.key===i&&Pnn(h,a),g.key===i&&Pnn(g,a)}return eM()===i&&Yu(s),a}insertAfter(e,n=!0){Zu(),BJe(this,e);let r=this.getWritable(),o=e.getWritable(),i=o.getParent(),s=pi(),a=!1,l=!1;if(i!==null){let p=e.getIndexWithinParent();if(nM(o),jn(s)){let m=i.__key,h=s.anchor,g=s.focus;a=h.type==="element"&&h.key===m&&h.offset===p+1,l=g.type==="element"&&g.key===m&&g.offset===p+1}}let c=this.getNextSibling(),u=this.getParentOrThrow().getWritable(),d=o.__key,f=r.__next;if(c===null?u.__last=d:c.getWritable().__prev=d,u.__size++,r.__next=d,o.__next=f,o.__prev=r.__key,o.__parent=r.__parent,n&&jn(s)){let p=this.getIndexWithinParent();H_e(s,u,p+1);let m=u.__key;a&&s.anchor.set(m,p+2,"element"),l&&s.focus.set(m,p+2,"element")}return e}insertBefore(e,n=!0){Zu(),BJe(this,e);let r=this.getWritable(),o=e.getWritable(),i=o.__key;nM(o);let s=this.getPreviousSibling(),a=this.getParentOrThrow().getWritable(),l=r.__prev,c=this.getIndexWithinParent();s===null?a.__first=i:s.getWritable().__next=i,a.__size++,r.__prev=i,o.__prev=l,o.__next=r.__key,o.__parent=r.__parent;let u=pi();return n&&jn(u)&&H_e(u,this.getParentOrThrow(),c),e}isParentRequired(){return!1}createParentElementNode(){return n0()}selectStart(){return this.selectPrevious()}selectEnd(){return this.selectNext(0,0)}selectPrevious(e,n){Zu();let r=this.getPreviousSibling(),o=this.getParentOrThrow();if(r===null)return o.select(0,0);if(Ye(r))return r.select();if(!dn(r)){let i=r.getIndexWithinParent()+1;return o.select(i,i)}return r.select(e,n)}selectNext(e,n){Zu();let r=this.getNextSibling(),o=this.getParentOrThrow();if(r===null)return o.select();if(Ye(r))return r.select(0,0);if(!dn(r)){let i=r.getIndexWithinParent();return o.select(i,i)}return r.select(e,n)}markDirty(){this.getWritable()}reconcileObservedMutation(e,n){this.markDirty()}},K6=class t extends oM{static getType(){return"linebreak"}static clone(e){return new t(e.__key)}constructor(e){super(e)}getTextContent(){return`
`}createDOM(){return document.createElement("br")}updateDOM(){return!1}isInline(){return!0}static importDOM(){return{br:e=>function(n){let r=n.parentElement;if(r!==null&&pXe(r)){let o=r.firstChild;if(o===n||o.nextSibling===n&&C_e(o)){let i=r.lastChild;if(i===n||i.previousSibling===n&&C_e(i))return!0}}return!1}(e)||function(n){let r=n.parentElement;if(r!==null&&pXe(r)){let o=r.firstChild;if(o===n||o.nextSibling===n&&C_e(o))return!1;let i=r.lastChild;if(i===n||i.previousSibling===n&&C_e(i))return!0}return!1}(e)?null:{conversion:FIr,priority:0}}}static importJSON(e){return G6().updateFromJSON(e)}};j$=class t extends oM{static getType(){return"text"}static clone(e){return new t(e.__text,e.__key)}afterCloneFrom(e){super.afterCloneFrom(e),this.__text=e.__text,this.__format=e.__format,this.__style=e.__style,this.__mode=e.__mode,this.__detail=e.__detail}constructor(e="",n){super(n),this.__text=e,this.__format=0,this.__style="",this.__mode=0,this.__detail=0}getFormat(){return this.getLatest().__format}getDetail(){return this.getLatest().__detail}getMode(){let e=this.getLatest();return fIr[e.__mode]}getStyle(){return this.getLatest().__style}isToken(){return this.getLatest().__mode===1}isComposing(){return this.__key===eM()}isSegmented(){return this.getLatest().__mode===2}isDirectionless(){return!!(1&this.getLatest().__detail)}isUnmergeable(){return!!(2&this.getLatest().__detail)}hasFormat(e){let n=Uf[e];return!!(this.getFormat()&n)}isSimpleText(){return this.__type==="text"&&this.__mode===0}getTextContent(){return this.getLatest().__text}getFormatFlags(e,n){return K_e(this.getLatest().__format,e,n)}canHaveFormat(){return!0}isInline(){return!0}createDOM(e,n){let r=this.__format,o=$Je(0,r),i=DJe(0,r),s=o===null?i:o,a=document.createElement(s),l=a;this.hasFormat("code")&&a.setAttribute("spellcheck","false"),o!==null&&(l=document.createElement(i),a.appendChild(l)),knn(l,this,0,r,this.__text,e);let c=this.__style;return c!==""&&(a.style.cssText=c),a}updateDOM(e,n,r){let o=this.__text,i=e.__format,s=this.__format,a=$Je(0,i),l=$Je(0,s),c=DJe(0,i),u=DJe(0,s);if((a===null?c:a)!==(l===null?u:l))return!0;if(a===l&&c!==u){let h=n.firstChild;h==null&&tt(48);let g=document.createElement(u);return knn(g,this,0,s,o,r),n.replaceChild(g,h),!1}let d=n;l!==null&&a!==null&&(d=n.firstChild,d==null&&tt(49)),qrn(o,d,this);let f=r.theme.text;f!==void 0&&i!==s&&Vrn(0,i,s,d,f);let p=e.__style,m=this.__style;return p!==m&&(n.style.cssText=m),!1}static importDOM(){return{"#text":()=>({conversion:zIr,priority:0}),b:()=>({conversion:jIr,priority:0}),code:()=>({conversion:YI,priority:0}),em:()=>({conversion:YI,priority:0}),i:()=>({conversion:YI,priority:0}),mark:()=>({conversion:YI,priority:0}),s:()=>({conversion:YI,priority:0}),span:()=>({conversion:UIr,priority:0}),strong:()=>({conversion:YI,priority:0}),sub:()=>({conversion:YI,priority:0}),sup:()=>({conversion:YI,priority:0}),u:()=>({conversion:YI,priority:0})}}static importJSON(e){return Gu().updateFromJSON(e)}updateFromJSON(e){return super.updateFromJSON(e).setTextContent(e.text).setFormat(e.format).setDetail(e.detail).setMode(e.mode).setStyle(e.style)}exportDOM(e){let{element:n}=super.exportDOM(e);return Bp(n)||tt(132),n.style.whiteSpace="pre-wrap",this.hasFormat("lowercase")?n.style.textTransform="lowercase":this.hasFormat("uppercase")?n.style.textTransform="uppercase":this.hasFormat("capitalize")&&(n.style.textTransform="capitalize"),this.hasFormat("bold")&&(n=k_e(n,"b")),this.hasFormat("italic")&&(n=k_e(n,"i")),this.hasFormat("strikethrough")&&(n=k_e(n,"s")),this.hasFormat("underline")&&(n=k_e(n,"u")),{element:n}}exportJSON(){return{detail:this.getDetail(),format:this.getFormat(),mode:this.getMode(),style:this.getStyle(),text:this.getTextContent(),...super.exportJSON()}}selectionTransform(e,n){}setFormat(e){let n=this.getWritable();return n.__format=typeof e=="string"?Uf[e]:e,n}setDetail(e){let n=this.getWritable();return n.__detail=typeof e=="string"?cIr[e]:e,n}setStyle(e){let n=this.getWritable();return n.__style=e,n}toggleFormat(e){let n=K_e(this.getFormat(),e,null);return this.setFormat(n)}toggleDirectionless(){let e=this.getWritable();return e.__detail^=1,e}toggleUnmergeable(){let e=this.getWritable();return e.__detail^=2,e}setMode(e){let n=dIr[e];if(this.__mode===n)return this;let r=this.getWritable();return r.__mode=n,r}setTextContent(e){if(this.__text===e)return this;let n=this.getWritable();return n.__text=e,n}select(e,n){Zu();let r=e,o=n,i=pi(),s=this.getTextContent(),a=this.__key;if(typeof s=="string"){let l=s.length;r===void 0&&(r=l),o===void 0&&(o=l)}else r=0,o=0;if(!jn(i))return Zrn(a,r,a,o,"text","text");{let l=eM();l!==i.anchor.key&&l!==i.focus.key||Yu(a),i.setTextNodeRange(this,r,this,o)}return i}selectStart(){return this.select(0,0)}selectEnd(){let e=this.getTextContentSize();return this.select(e,e)}spliceText(e,n,r,o){let i=this.getWritable(),s=i.__text,a=r.length,l=e;l<0&&(l=a+l,l<0&&(l=0));let c=pi();if(o&&jn(c)){let d=e+a;c.setTextNodeRange(i,d,i,d)}let u=s.slice(0,l)+r+s.slice(l+n);return i.__text=u,i}canInsertTextBefore(){return!0}canInsertTextAfter(){return!0}splitText(...e){Zu();let n=this.getLatest(),r=n.getTextContent();if(r==="")return[];let o=n.__key,i=eM(),s=r.length;e.sort((k,T)=>k-T),e.push(s);let a=[],l=e.length;for(let k=0,T=0;k<s&&T<=l;T++){let P=e[T];P>k&&(a.push(r.slice(k,P)),k=P)}let c=a.length;if(c===1)return[n];let u=a[0],d=n.getParent(),f,p=n.getFormat(),m=n.getStyle(),h=n.__detail,g=!1,v=null,y=null,w=pi();if(jn(w)){let[k,T]=w.isBackward()?[w.focus,w.anchor]:[w.anchor,w.focus];k.type==="text"&&k.key===o&&(v=k),T.type==="text"&&T.key===o&&(y=T)}n.isSegmented()?(f=Gu(u),f.__format=p,f.__style=m,f.__detail=h,f.__state=hnn(n,f),g=!0):f=n.setTextContent(u);let _=[f];for(let k=1;k<c;k++){let T=Gu(a[k]);T.__format=p,T.__style=m,T.__detail=h,T.__state=hnn(n,T);let P=T.__key;i===o&&Yu(P),_.push(T)}let S=v?v.offset:null,I=y?y.offset:null,C=0;for(let k of _){if(!v&&!y)break;let T=C+k.getTextContentSize();if(v!==null&&S!==null&&S<=T&&S>=C&&(v.set(k.getKey(),S-C,"text"),S<T&&(v=null)),y!==null&&I!==null&&I<=T&&I>=C){y.set(k.getKey(),I-C,"text");break}C=T}if(d!==null){(function(P){let E=P.getPreviousSibling(),O=P.getNextSibling();E!==null&&G_e(E),O!==null&&G_e(O)})(this);let k=d.getWritable(),T=this.getIndexWithinParent();g?(k.splice(T,0,_),this.remove()):k.splice(T,1,_),jn(w)&&H_e(w,d,T,c-1)}return _}mergeWithSibling(e){let n=e===this.getPreviousSibling();n||e===this.getNextSibling()||tt(50);let r=this.__key,o=e.__key,i=this.__text,s=i.length;eM()===o&&Yu(r);let a=pi();if(jn(a)){let d=a.anchor,f=a.focus;d!==null&&d.key===o&&Lnn(d,n,r,e,s),f!==null&&f.key===o&&Lnn(f,n,r,e,s)}let l=e.__text,c=n?l+i:i+l;this.setTextContent(c);let u=this.getWritable();return e.remove(),u}isTextEntity(){return!1}};Inn=new WeakMap;HIr={code:"code",em:"italic",i:"italic",mark:"highlight",s:"strikethrough",strong:"bold",sub:"subscript",sup:"superscript",u:"underline"};Z6=class t extends j${static getType(){return"tab"}static clone(e){return new t(e.__key)}constructor(e){super(" ",e),this.__detail=2}static importDOM(){return null}createDOM(e){let n=super.createDOM(e),r=W6(e.theme,"tab");return r!==void 0&&n.classList.add(...r),n}static importJSON(e){return exe().updateFromJSON(e)}setTextContent(e){return e!==" "&&e!==""&&tt(126),super.setTextContent(" ")}spliceText(e,n,r,o){return r===""&&n===0||r===" "&&n===1||tt(286),this}setDetail(e){return e!==2&&tt(127),this}setMode(e){return e!=="normal"&&tt(128),this}canInsertTextBefore(){return!1}canInsertTextAfter(){return!1}};lXe=class{constructor(e,n,r){this._selection=null,this.key=e,this.offset=n,this.type=r}is(e){return this.key===e.key&&this.offset===e.offset&&this.type===e.type}isBefore(e){return this.key===e.key?this.offset<e.offset:eQe(Xb(lM(this,"next")),Xb(lM(e,"next")))<0}getNode(){let e=ou(this.key);return e===null&&tt(20),e}set(e,n,r,o){let i=this._selection,s=this.key;o&&this.key===e&&this.offset===n&&this.type===r||(this.key=e,this.offset=n,this.type=r,iV()||(eM()===s&&Yu(e),i!==null&&(i.setCachedNodes(null),i.dirty=!0)))}};z_e=class t{constructor(e){this._cachedNodes=null,this._nodes=e,this.dirty=!1}getCachedNodes(){return this._cachedNodes}setCachedNodes(e){this._cachedNodes=e}is(e){if(!txe(e))return!1;let n=this._nodes,r=e._nodes;return n.size===r.size&&Array.from(n).every(o=>r.has(o))}isCollapsed(){return!1}isBackward(){return!1}getStartEndPoints(){return null}add(e){this.dirty=!0,this._nodes.add(e),this._cachedNodes=null}delete(e){this.dirty=!0,this._nodes.delete(e),this._cachedNodes=null}clear(){this.dirty=!0,this._nodes.clear(),this._cachedNodes=null}has(e){return this._nodes.has(e)}clone(){return new t(new Set(this._nodes))}extract(){return this.getNodes()}insertRawText(e){}insertText(){}insertNodes(e){let n=this.getNodes(),r=n.length,o=n[r-1],i;if(dn(o))i=o.select();else{let s=o.getIndexWithinParent()+1;i=o.getParentOrThrow().select(s,s)}i.insertNodes(e);for(let s=0;s<r;s++)n[s].remove()}getNodes(){let e=this._cachedNodes;if(e!==null)return e;let n=this._nodes,r=[];for(let o of n){let i=ou(o);i!==null&&r.push(i)}return iV()||(this._cachedNodes=r),r}getTextContent(){let e=this.getNodes(),n="";for(let r=0;r<e.length;r++)n+=e[r].getTextContent();return n}deleteNodes(){let e=this.getNodes();if((pi()||W$())===this&&e[0]){let n=Qu(e[0],"next");Mon(aM(n,n))}for(let n of e)n.remove()}};B$=class t{constructor(e,n,r,o){this.anchor=e,this.focus=n,e._selection=this,n._selection=this,this._cachedNodes=null,this.format=r,this.style=o,this.dirty=!1}getCachedNodes(){return this._cachedNodes}setCachedNodes(e){this._cachedNodes=e}is(e){return!!jn(e)&&this.anchor.is(e.anchor)&&this.focus.is(e.focus)&&this.format===e.format&&this.style===e.style}isCollapsed(){return this.anchor.is(this.focus)}getNodes(){let e=this._cachedNodes;if(e!==null)return e;let n=function(r){let o=[],[i,s]=r.getTextSlices();i&&o.push(i.caret.origin);let a=new Set,l=new Set;for(let c of r)if(e_(c)){let{origin:u}=c;o.length===0?a.add(u):(l.add(u),o.push(u))}else{let{origin:u}=c;Ye(u)&&l.has(u)||o.push(u)}if(s&&o.push(s.caret.origin),H$(r.focus)&&Ye(r.focus.origin)&&r.focus.getNodeAtCaret()===null)for(let c=i0(r.focus.origin,"previous");e_(c)&&a.has(c.origin)&&!c.origin.isEmpty()&&c.origin.is(o[o.length-1]);c=rV(c))a.delete(c.origin),o.pop();for(;o.length>1;){let c=o[o.length-1];if(!Ye(c)||l.has(c)||c.isEmpty()||a.has(c))break;o.pop()}if(o.length===0&&r.isCollapsed()){let c=Xb(r.anchor),u=Xb(r.anchor.getFlipped()),d=p=>r0(p)?p.origin:p.getNodeAtCaret(),f=d(c)||d(u)||(r.anchor.getNodeAtCaret()?c.origin:u.origin);o.push(f)}return o}(nQe(yXe(this),"next"));return iV()||(this._cachedNodes=n),n}setTextNodeRange(e,n,r,o){this.anchor.set(e.__key,n,"text"),this.focus.set(r.__key,o,"text")}getTextContent(){let e=this.getNodes();if(e.length===0)return"";let n=e[0],r=e[e.length-1],o=this.anchor,i=this.focus,s=o.isBefore(i),[a,l]=cXe(this),c="",u=!0;for(let d=0;d<e.length;d++){let f=e[d];if(Ye(f)&&!f.isInline())u||(c+=`
`),u=!f.isEmpty();else if(u=!1,dn(f)){let p=f.getTextContent();f===n?f===r?o.type==="element"&&i.type==="element"&&i.offset!==o.offset||(p=a<l?p.slice(a,l):p.slice(l,a)):p=s?p.slice(a):p.slice(l):f===r&&(p=s?p.slice(0,l):p.slice(0,a)),c+=p}else!vs(f)&&!$$(f)||f===r&&this.isCollapsed()||(c+=f.getTextContent())}return c}applyDOMRange(e){let n=ba(),r=n.getEditorState()._selection,o=Grn(e.startContainer,e.startOffset,e.endContainer,e.endOffset,n,r);if(o===null)return;let[i,s]=o;this.anchor.set(i.key,i.offset,i.type,!0),this.focus.set(s.key,s.offset,s.type,!0),$_e(this)}clone(){let e=this.anchor,n=this.focus;return new t(n_(e.key,e.offset,e.type),n_(n.key,n.offset,n.type),this.format,this.style)}toggleFormat(e){this.format=K_e(this.format,e,null),this.dirty=!0}setFormat(e){this.format=e,this.dirty=!0}setStyle(e){this.style=e,this.dirty=!0}hasFormat(e){let n=Uf[e];return!!(this.format&n)}insertRawText(e){let n=e.split(/(\r?\n|\t)/),r=[],o=n.length;for(let i=0;i<o;i++){let s=n[i];s===`
`||s===`\r
`?r.push(G6()):s===" "?r.push(exe()):r.push(Gu(s))}this.insertNodes(r)}insertText(e){let n=this.anchor,r=this.focus,o=this.format,i=this.style,s=n,a=r;!this.isCollapsed()&&r.isBefore(n)&&(s=r,a=n),s.type==="element"&&function(g,v,y,w){let _=g.getNode(),S=_.getChildAtIndex(g.offset),I=Gu(),C=Qm(_)?n0().append(I):I;I.setFormat(y),I.setStyle(w),S===null?_.append(C):S.insertBefore(C),g.is(v)&&v.set(I.__key,0,"text"),g.set(I.__key,0,"text")}(s,a,o,i),a.type==="element"&&oV(a,Xb(lM(a,"next")));let l=s.offset,c=a.offset,u=this.getNodes(),d=u.length,f=u[0];dn(f)||tt(26);let p=f.getTextContent().length,m=f.getParentOrThrow(),h=u[d-1];if(d===1&&a.type==="element"&&(c=p,a.set(s.key,c,"text")),this.isCollapsed()&&l===p&&(XI(f)||!f.canInsertTextAfter()||!m.canInsertTextAfter()&&f.getNextSibling()===null)){let g=f.getNextSibling();if(dn(g)&&g.canInsertTextBefore()&&!XI(g)||(g=Gu(),g.setFormat(o),g.setStyle(i),m.canInsertTextAfter()?f.insertAfter(g):m.insertAfter(g)),g.select(0,0),f=g,e!=="")return void this.insertText(e)}else if(this.isCollapsed()&&l===0&&(XI(f)||!f.canInsertTextBefore()||!m.canInsertTextBefore()&&f.getPreviousSibling()===null)){let g=f.getPreviousSibling();if(dn(g)&&!XI(g)||(g=Gu(),g.setFormat(o),m.canInsertTextBefore()?f.insertBefore(g):m.insertBefore(g)),g.select(),f=g,e!=="")return void this.insertText(e)}else if(f.isSegmented()&&l!==p){let g=Gu(f.getTextContent());g.setFormat(o),f.replace(g),f=g}else if(!this.isCollapsed()&&e!==""){let g=h.getParent();if(!m.canInsertTextBefore()||!m.canInsertTextAfter()||Ye(g)&&(!g.canInsertTextBefore()||!g.canInsertTextAfter()))return this.insertText(""),Krn(this.anchor,this.focus,null),void this.insertText(e)}if(d===1){if(tM(f)){let w=Gu(e);return w.select(),void f.replace(w)}let g=f.getFormat(),v=f.getStyle();if(l!==c||g===o&&v===i){if(NXe(f)){let w=Gu(e);return w.setFormat(o),w.setStyle(i),w.select(),void f.replace(w)}}else{if(f.getTextContent()!==""){let w=Gu(e);if(w.setFormat(o),w.setStyle(i),w.select(),l===0)f.insertBefore(w,!1);else{let[_]=f.splitText(l);_.insertAfter(w,!1)}return void(w.isComposing()&&this.anchor.type==="text"&&(this.anchor.offset-=e.length))}f.setFormat(o),f.setStyle(i)}let y=c-l;f=f.spliceText(l,y,e,!0),f.getTextContent()===""?f.remove():this.anchor.type==="text"&&(f.isComposing()?this.anchor.offset-=e.length:(this.format=g,this.style=v))}else{let g=new Set([...f.getParentKeys(),...h.getParentKeys()]),v=Ye(f)?f:f.getParentOrThrow(),y=Ye(h)?h:h.getParentOrThrow(),w=h;if(!v.is(y)&&y.isInline())do w=y,y=y.getParentOrThrow();while(y.isInline());if(a.type==="text"&&(c!==0||h.getTextContent()==="")||a.type==="element"&&h.getIndexWithinParent()<c)if(dn(h)&&!tM(h)&&c!==h.getTextContentSize()){if(h.isSegmented()){let k=Gu(h.getTextContent());h.replace(k),h=k}Qm(a.getNode())||a.type!=="text"||(h=h.spliceText(0,c,"")),g.add(h.__key)}else{let k=h.getParentOrThrow();k.canBeEmpty()||k.getChildrenSize()!==1?h.remove():k.remove()}else g.add(h.__key);let _=y.getChildren(),S=new Set(u),I=v.is(y),C=v.isInline()&&f.getNextSibling()===null?v:f;for(let k=_.length-1;k>=0;k--){let T=_[k];if(T.is(f)||Ye(T)&&T.isParentOf(f))break;T.isAttached()&&(!S.has(T)||T.is(w)?I||C.insertAfter(T,!1):T.remove())}if(!I){let k=y,T=null;for(;k!==null;){let P=k.getChildren(),E=P.length;(E===0||P[E-1].is(T))&&(g.delete(k.__key),T=k),k=k.getParent()}}if(tM(f))if(l===p)f.select();else{let k=Gu(e);k.select(),f.replace(k)}else f=f.spliceText(l,p-l,e,!0),f.getTextContent()===""?f.remove():f.isComposing()&&this.anchor.type==="text"&&(this.anchor.offset-=e.length);for(let k=1;k<d;k++){let T=u[k],P=T.__key;g.has(P)||T.remove()}}}removeText(){let e=pi()===this;wee(this,Oon(yXe(this))),e&&pi()!==this&&nh(this)}formatText(e,n=null){if(this.isCollapsed())return this.toggleFormat(e),void Yu(null);let r=this.getNodes(),o=[];for(let _ of r)dn(_)&&o.push(_);let i=_=>{r.forEach(S=>{if(Ye(S)){let I=S.getFormatFlags(e,_);S.setTextFormat(I)}})},s=o.length;if(s===0)return this.toggleFormat(e),Yu(null),void i(n);let a=this.anchor,l=this.focus,c=this.isBackward(),u=c?l:a,d=c?a:l,f=0,p=o[0],m=u.type==="element"?0:u.offset;if(u.type==="text"&&m===p.getTextContentSize()&&(f=1,p=o[1],m=0),p==null)return;let h=p.getFormatFlags(e,n);i(h);let g=s-1,v=o[g],y=d.type==="text"?d.offset:v.getTextContentSize();if(p.is(v)){if(m===y)return;if(XI(p)||m===0&&y===p.getTextContentSize())p.setFormat(h);else{let _=p.splitText(m,y),S=m===0?_[0]:_[1];S.setFormat(h),u.type==="text"&&u.set(S.__key,0,"text"),d.type==="text"&&d.set(S.__key,y-m,"text")}return void(this.format=h)}m===0||XI(p)||([,p]=p.splitText(m),m=0),p.setFormat(h);let w=v.getFormatFlags(e,h);y>0&&(y===v.getTextContentSize()||XI(v)||([v]=v.splitText(y)),v.setFormat(w));for(let _=f+1;_<g;_++){let S=o[_],I=S.getFormatFlags(e,w);S.setFormat(I)}u.type==="text"&&u.set(p.__key,m,"text"),d.type==="text"&&d.set(v.__key,y,"text"),this.format=h|w}insertNodes(e){if(e.length===0)return;if(this.isCollapsed()||this.removeText(),this.anchor.key==="root"){this.insertParagraph();let m=pi();return jn(m)||tt(134),m.insertNodes(e)}let n=(this.isBackward()?this.focus:this.anchor).getNode(),r=HJe(n,t0),o=e[e.length-1];if(Ye(r)&&"__language"in r){if("__language"in e[0])this.insertText(e[0].getTextContent());else{let m=UJe(this);r.splice(m,0,e),o.selectEnd()}return}if(!e.some(m=>(Ye(m)||vs(m))&&!m.isInline())){Ye(r)||tt(211,n.constructor.name,n.getType());let m=UJe(this);return r.splice(m,0,e),void o.selectEnd()}let i=function(m){let h=n0(),g=null;for(let v=0;v<m.length;v++){let y=m[v],w=$$(y);if(w||vs(y)&&y.isInline()||Ye(y)&&y.isInline()||dn(y)||y.isParentRequired()){if(g===null&&(g=y.createParentElementNode(),h.append(g),w))continue;g!==null&&g.append(y)}else h.append(y),g=null}return h}(e),s=i.getLastDescendant(),a=i.getChildren(),l=!Ye(r)||!r.isEmpty()?this.insertParagraph():null,c=a[a.length-1],u=a[0];var d;Ye(d=u)&&t0(d)&&!d.isEmpty()&&Ye(r)&&(!r.isEmpty()||r.canMergeWhenEmpty())&&(Ye(r)||tt(211,n.constructor.name,n.getType()),r.append(...u.getChildren()),u=a[1]),u&&(r===null&&tt(212,n.constructor.name,n.getType()),function(m,h,g){let v=h.getParentOrThrow().getLastChild(),y=h,w=[h];for(;y!==v;)y.getNextSibling()||tt(140),y=y.getNextSibling(),w.push(y);let _=m;for(let S of w)_=_.insertAfter(S)}(r,u));let f=HJe(s,t0);l&&Ye(f)&&(l.canMergeWhenEmpty()||t0(c))&&(f.append(...l.getChildren()),l.remove()),Ye(r)&&r.isEmpty()&&r.remove(),s.selectEnd();let p=Ye(r)?r.getLastChild():null;$$(p)&&f!==r&&p.remove()}insertParagraph(){if(this.anchor.key==="root"){let s=n0();return th().splice(this.anchor.offset,0,[s]),s.select(),s}let e=UJe(this),n=HJe(this.anchor.getNode(),t0);Ye(n)||tt(213);let r=n.getChildAtIndex(e),o=r?[r,...r.getNextSiblings()]:[],i=n.insertNewAfter(this,!1);return i?(i.append(...o),i.selectStart(),i):null}insertLineBreak(e){let n=G6();if(this.insertNodes([n]),e){let r=n.getParentOrThrow(),o=n.getIndexWithinParent();r.select(o,o)}}extract(){let e=this.getNodes(),n=e.length,r=n-1,o=this.anchor,i=this.focus,s=e[0],a=e[r],[l,c]=cXe(this);if(n===0)return[];if(n===1){if(dn(s)&&!this.isCollapsed()){let d=l>c?c:l,f=l>c?l:c,p=s.splitText(d,f),m=d===0?p[0]:p[1];return m!=null?[m]:[]}return[s]}let u=o.isBefore(i);if(dn(s)){let d=u?l:c;d===s.getTextContentSize()?e.shift():d!==0&&([,s]=s.splitText(d),e[0]=s)}if(dn(a)){let d=a.getTextContent().length,f=u?c:l;f===0?e.pop():f!==d&&([a]=a.splitText(f),e[r]=a)}return e}modify(e,n,r){if($nn(this,e,n,r))return;let o=e==="move",i=ba(),s=ES(Rv(i));if(!s)return;let a=i._blockCursorElement,l=i._rootElement,c=this.focus.getNode();if(l===null||a===null||!Ye(c)||c.isInline()||c.canBeEmpty()||fXe(a,i,l),this.dirty){let u=Q6(i,this.anchor.key),d=Q6(i,this.focus.key);this.anchor.type==="text"&&(u=z$(u)),this.focus.type==="text"&&(d=z$(d)),u&&d&&Jrn(s,u,this.anchor.offset,d,this.focus.offset)}if(function(u,d,f,p){u.modify(d,f,p)}(s,e,n?"backward":"forward",r),s.rangeCount>0){let u=s.getRangeAt(0),d=this.anchor.getNode(),f=Qm(d)?d:_on(d);if(this.applyDOMRange(u),this.dirty=!0,!o){let p=this.getNodes(),m=[],h=!1;for(let g=0;g<p.length;g++){let v=p[g];Z_e(v,f)?m.push(v):h=!0}if(h&&m.length>0)if(n){let g=m[0];Ye(g)?g.selectStart():g.getParentOrThrow().selectStart()}else{let g=m[m.length-1];Ye(g)?g.selectEnd():g.getParentOrThrow().selectEnd()}s.anchorNode===u.startContainer&&s.anchorOffset===u.startOffset||function(g){let v=g.focus,y=g.anchor,w=y.key,_=y.offset,S=y.type;y.set(v.key,v.offset,v.type,!0),v.set(w,_,S,!0)}(this)}}r==="lineboundary"&&$nn(this,e,n,r,"decorators")}forwardDeletion(e,n,r){if(!r&&(e.type==="element"&&Ye(n)&&e.offset===n.getChildrenSize()||e.type==="text"&&e.offset===n.getTextContentSize())){let o=n.getParent(),i=n.getNextSibling()||(o===null?null:o.getNextSibling());if(Ye(i)&&i.isShadowRoot())return!0}return!1}deleteCharacter(e){let n=this.isCollapsed();if(this.isCollapsed()){let r=this.anchor,o=r.getNode();if(this.forwardDeletion(r,o,e))return;let i=XXe(lM(r,e?"previous":"next"));if(i.getTextSlices().every(a=>a===null||a.distance===0)){let a={type:"initial"};for(let l of i.iterNodeCarets("shadowRoot"))if(e_(l)){if(!l.origin.isInline()){if(l.origin.isShadowRoot()){if(a.type==="merge-block")break;if(Ye(i.anchor.origin)&&i.anchor.origin.isEmpty()){let c=Xb(l);wee(this,aM(c,c)),i.anchor.origin.remove()}return}a.type!=="merge-next-block"&&a.type!=="merge-block"||(a={block:a.block,caret:l,type:"merge-block"})}}else{if(a.type==="merge-block")break;if(H$(l)){if(Ye(l.origin)){if(l.origin.isInline()){if(!l.origin.isParentOf(i.anchor.origin))break}else a={block:l.origin,type:"merge-next-block"};continue}if(vs(l.origin)){if(!l.origin.isIsolated())if(a.type==="merge-next-block"&&(l.origin.isKeyboardSelectable()||!l.origin.isInline())&&Ye(i.anchor.origin)&&i.anchor.origin.isEmpty()){i.anchor.origin.remove();let c=RXe();c.add(l.origin.getKey()),nh(c)}else l.origin.remove();return}break}}if(a.type==="merge-block"){let{caret:l,block:c}=a;return wee(this,aM(!l.origin.isEmpty()&&c.isEmpty()?aV(Qu(c,l.direction)):i.anchor,l)),this.removeText()}}let s=this.focus;if(this.modify("extend",e,"character"),this.isCollapsed()){if(e&&r.offset===0&&Enn(this,r.getNode()))return}else{let a=s.type==="text"?s.getNode():null;if(o=r.type==="text"?r.getNode():null,a!==null&&a.isSegmented()){let l=s.offset,c=a.getTextContentSize();if(a.is(o)||e&&l!==c||!e&&l!==0)return void Mnn(a,e,l)}else if(o!==null&&o.isSegmented()){let l=r.offset,c=o.getTextContentSize();if(o.is(a)||e&&l!==0||!e&&l!==c)return void Mnn(o,e,l)}(function(l,c){let u=l.anchor,d=l.focus,f=u.getNode(),p=d.getNode();if(f===p&&u.type==="text"&&d.type==="text"){let m=u.offset,h=d.offset,g=m<h,v=g?m:h,y=g?h:m,w=y-1;v!==w&&function(_){return!(pon(_)||WIr(_))}(f.getTextContent().slice(v,y))&&(c?d.set(d.key,w,d.type):u.set(u.key,w,u.type))}})(this,e)}}if(this.removeText(),e&&!n&&this.isCollapsed()&&this.anchor.type==="element"&&this.anchor.offset===0){let r=this.anchor.getNode();r.isEmpty()&&Qm(r.getParent())&&r.getPreviousSibling()===null&&Enn(this,r)}}deleteLine(e){this.isCollapsed()&&this.modify("extend",e,"lineboundary"),this.isCollapsed()?this.deleteCharacter(e):this.removeText()}deleteWord(e){if(this.isCollapsed()){let n=this.anchor,r=n.getNode();if(this.forwardDeletion(n,r,e))return;this.modify("extend",e,"word")}this.removeText()}isBackward(){return this.focus.isBefore(this.anchor)}getStartEndPoints(){return[this.anchor,this.focus]}};WIr=(()=>{try{let t=new RegExp("\\p{Emoji}","u"),e=t.test.bind(t);if(e("\u2764\uFE0F")&&e("#\uFE0F\u20E3")&&e("\u{1F44D}"))return e}catch{}return()=>!1})();Ju=null,Xu=null,eh=!1,jJe=!1,E_e=0,Dnn={characterData:!0,childList:!0,subtree:!0};uXe=class t{constructor(e,n,r){this.element=e,this.before=n||null,this.after=r||null}withBefore(e){return new t(this.element,e,this.after)}withAfter(e){return new t(this.element,this.before,e)}withElement(e){return this.element===e?this:new t(e,this.before,this.after)}insertChild(e){let n=this.before||this.getManagedLineBreak();return n!==null&&n.parentElement!==this.element&&tt(222),this.element.insertBefore(e,n),this}removeChild(e){return e.parentElement!==this.element&&tt(223),this.element.removeChild(e),this}replaceChild(e,n){return n.parentElement!==this.element&&tt(224),this.element.replaceChild(e,n),this}getFirstChild(){let e=this.after?this.after.nextSibling:this.element.firstChild;return e===this.before||e===this.getManagedLineBreak()?null:e}getManagedLineBreak(){return this.element.__lexicalLineBreak||null}setManagedLineBreak(e){if(e===null)this.removeManagedLineBreak();else{let n=e==="decorator"&&(V6||bee);this.insertManagedLineBreak(n)}}removeManagedLineBreak(){let e=this.getManagedLineBreak();if(e){let n=this.element,r=e.nodeName==="IMG"?e.nextSibling:null;r&&n.removeChild(r),n.removeChild(e),n.__lexicalLineBreak=void 0}}insertManagedLineBreak(e){let n=this.getManagedLineBreak();if(n){if(e===(n.nodeName==="IMG"))return;this.removeManagedLineBreak()}let r=this.element,o=this.before,i=document.createElement("br");if(r.insertBefore(i,o),e){let s=document.createElement("img");s.setAttribute("data-lexical-linebreak","true"),s.style.cssText="display: inline !important; border: 0px !important; margin: 0px !important;",s.alt="",r.insertBefore(s,i),r.__lexicalLineBreak=s}else r.__lexicalLineBreak=i}getFirstChildOffset(){let e=0;for(let n=this.after;n!==null;n=n.previousSibling)e++;return e}resolveChildIndex(e,n,r,o){if(r===this.element){let l=this.getFirstChildOffset();return[e,Math.min(l+e.getChildrenSize(),Math.max(l,o))]}let i=znn(n,r);i.push(o);let s=znn(n,this.element),a=e.getIndexWithinParent();for(let l=0;l<s.length;l++){let c=i[l],u=s[l];if(c===void 0||c<u)break;if(c>u){a+=1;break}}return[e.getParentOrThrow(),a]}};iM=class extends oM{constructor(e){super(e),this.__first=null,this.__last=null,this.__size=0,this.__format=0,this.__style="",this.__indent=0,this.__dir=null,this.__textFormat=0,this.__textStyle=""}afterCloneFrom(e){super.afterCloneFrom(e),this.__key===e.__key&&(this.__first=e.__first,this.__last=e.__last,this.__size=e.__size),this.__indent=e.__indent,this.__format=e.__format,this.__style=e.__style,this.__dir=e.__dir,this.__textFormat=e.__textFormat,this.__textStyle=e.__textStyle}getFormat(){return this.getLatest().__format}getFormatType(){let e=this.getFormat();return uIr[e]||""}getStyle(){return this.getLatest().__style}getIndent(){return this.getLatest().__indent}getChildren(){let e=[],n=this.getFirstChild();for(;n!==null;)e.push(n),n=n.getNextSibling();return e}getChildrenKeys(){let e=[],n=this.getFirstChild();for(;n!==null;)e.push(n.__key),n=n.getNextSibling();return e}getChildrenSize(){return this.getLatest().__size}isEmpty(){return this.getChildrenSize()===0}isDirty(){let e=ba()._dirtyElements;return e!==null&&e.has(this.__key)}isLastChild(){let e=this.getLatest(),n=this.getParentOrThrow().getLastChild();return n!==null&&n.is(e)}getAllTextNodes(){let e=[],n=this.getFirstChild();for(;n!==null;){if(dn(n)&&e.push(n),Ye(n)){let r=n.getAllTextNodes();e.push(...r)}n=n.getNextSibling()}return e}getFirstDescendant(){let e=this.getFirstChild();for(;Ye(e);){let n=e.getFirstChild();if(n===null)break;e=n}return e}getLastDescendant(){let e=this.getLastChild();for(;Ye(e);){let n=e.getLastChild();if(n===null)break;e=n}return e}getDescendantByIndex(e){let n=this.getChildren(),r=n.length;if(e>=r){let i=n[r-1];return Ye(i)&&i.getLastDescendant()||i||null}let o=n[e];return Ye(o)&&o.getFirstDescendant()||o||null}getFirstChild(){let e=this.getLatest().__first;return e===null?null:ou(e)}getFirstChildOrThrow(){let e=this.getFirstChild();return e===null&&tt(45,this.__key),e}getLastChild(){let e=this.getLatest().__last;return e===null?null:ou(e)}getLastChildOrThrow(){let e=this.getLastChild();return e===null&&tt(96,this.__key),e}getChildAtIndex(e){let n=this.getChildrenSize(),r,o;if(e<n/2){for(r=this.getFirstChild(),o=0;r!==null&&o<=e;){if(o===e)return r;r=r.getNextSibling(),o++}return null}for(r=this.getLastChild(),o=n-1;r!==null&&o>=e;){if(o===e)return r;r=r.getPreviousSibling(),o--}return null}getTextContent(){let e="",n=this.getChildren(),r=n.length;for(let o=0;o<r;o++){let i=n[o];e+=i.getTextContent(),Ye(i)&&o!==r-1&&!i.isInline()&&(e+=o0)}return e}getTextContentSize(){let e=0,n=this.getChildren(),r=n.length;for(let o=0;o<r;o++){let i=n[o];e+=i.getTextContentSize(),Ye(i)&&o!==r-1&&!i.isInline()&&(e+=o0.length)}return e}getDirection(){return this.getLatest().__dir}getTextFormat(){return this.getLatest().__textFormat}hasFormat(e){if(e!==""){let n=unn[e];return!!(this.getFormat()&n)}return!1}hasTextFormat(e){let n=Uf[e];return!!(this.getTextFormat()&n)}getFormatFlags(e,n){return K_e(this.getLatest().__textFormat,e,n)}getTextStyle(){return this.getLatest().__textStyle}select(e,n){Zu();let r=pi(),o=e,i=n,s=this.getChildrenSize();if(!this.canBeEmpty()){if(e===0&&n===0){let l=this.getFirstChild();if(dn(l)||Ye(l))return l.select(0,0)}else if(!(e!==void 0&&e!==s||n!==void 0&&n!==s)){let l=this.getLastChild();if(dn(l)||Ye(l))return l.select()}}o===void 0&&(o=s),i===void 0&&(i=s);let a=this.__key;return jn(r)?(r.anchor.set(a,o,"element"),r.focus.set(a,i,"element"),r.dirty=!0,r):Zrn(a,o,a,i,"element","element")}selectStart(){let e=this.getFirstDescendant();return e?e.selectStart():this.select()}selectEnd(){let e=this.getLastDescendant();return e?e.selectEnd():this.select()}clear(){let e=this.getWritable();return this.getChildren().forEach(n=>n.remove()),e}append(...e){return this.splice(this.getChildrenSize(),0,e)}setDirection(e){let n=this.getWritable();return n.__dir=e,n}setFormat(e){return this.getWritable().__format=e!==""?unn[e]:0,this}setStyle(e){return this.getWritable().__style=e||"",this}setTextFormat(e){let n=this.getWritable();return n.__textFormat=e,n}setTextStyle(e){let n=this.getWritable();return n.__textStyle=e,n}setIndent(e){return this.getWritable().__indent=e,this}splice(e,n,r){let o=r.length,i=this.getChildrenSize(),s=this.getWritable();e+n<=i||tt(226,String(e),String(n),String(i));let a=s.__key,l=[],c=[],u=this.getChildAtIndex(e+n),d=null,f=i-n+o;if(e!==0)if(e===i)d=this.getLastChild();else{let m=this.getChildAtIndex(e);m!==null&&(d=m.getPreviousSibling())}if(n>0){let m=d===null?this.getFirstChild():d.getNextSibling();for(let h=0;h<n;h++){m===null&&tt(100);let g=m.getNextSibling(),v=m.__key;nM(m.getWritable()),c.push(v),m=g}}let p=d;for(let m=0;m<o;m++){let h=r[m];p!==null&&h.is(p)&&(d=p=p.getPreviousSibling());let g=h.getWritable();g.__parent===a&&f--,nM(g);let v=h.__key;if(p===null)s.__first=v,g.__prev=null;else{let y=p.getWritable();y.__next=v,g.__prev=y.__key}h.__key===a&&tt(76),g.__parent=a,l.push(v),p=h}if(e+n===i)p!==null&&(p.getWritable().__next=null,s.__last=p.__key);else if(u!==null){let m=u.getWritable();if(p!==null){let h=p.getWritable();m.__prev=p.__key,h.__next=u.__key}else m.__prev=null}if(s.__size=f,c.length){let m=pi();if(jn(m)){let h=new Set(c),g=new Set(l),{anchor:v,focus:y}=m;Hnn(v,h,g)&&W_e(v,v.getNode(),this,d,u),Hnn(y,h,g)&&W_e(y,y.getNode(),this,d,u),f!==0||this.canBeEmpty()||r_(this)||this.remove()}}return s}getDOMSlot(e){return new uXe(e)}exportDOM(e){let{element:n}=super.exportDOM(e);if(Bp(n)){let r=this.getIndent();r>0&&(n.style.paddingInlineStart=40*r+"px");let o=this.getDirection();o&&(n.dir=o)}return{element:n}}exportJSON(){let e={children:[],direction:this.getDirection(),format:this.getFormatType(),indent:this.getIndent(),...super.exportJSON()},n=this.getTextFormat(),r=this.getTextStyle();return n!==0&&(e.textFormat=n),r!==""&&(e.textStyle=r),e}updateFromJSON(e){return super.updateFromJSON(e).setFormat(e.format).setIndent(e.indent).setDirection(e.direction).setTextFormat(e.textFormat||0).setTextStyle(e.textStyle||"")}insertNewAfter(e,n){return null}canIndent(){return!0}collapseAtStart(e){return!1}excludeFromCopy(e){return!1}canReplaceWith(e){return!0}canInsertAfter(e){return!0}canBeEmpty(){return!0}canInsertTextBefore(){return!0}canInsertTextAfter(){return!0}isInline(){return!1}isShadowRoot(){return!1}canMergeWith(e){return!1}extractWithChild(e,n,r){return!1}canMergeWhenEmpty(){return!1}reconcileObservedMutation(e,n){let r=this.getDOMSlot(e),o=r.getFirstChild();for(let i=this.getFirstChild();i;i=i.getNextSibling()){let s=n.getElementByKey(i.getKey());s!==null&&(o==null?(r.insertChild(s),o=s):o!==s&&r.replaceChild(s,o),o=o.nextSibling)}}};Aee=class extends oM{decorate(e,n){tt(47)}isIsolated(){return!1}isInline(){return!0}isKeyboardSelectable(){return!0}};Y6=class t extends iM{static getType(){return"root"}static clone(){return new t}constructor(){super("root"),this.__cachedText=null}getTopLevelElementOrThrow(){tt(51)}getTextContent(){let e=this.__cachedText;return!iV()&&ba()._dirtyType!==F$||e===null?super.getTextContent():e}remove(){tt(52)}replace(e){tt(53)}insertBefore(e){tt(54)}insertAfter(e){tt(55)}updateDOM(e,n){return!1}splice(e,n,r){for(let o of r)Ye(o)||vs(o)||tt(282);return super.splice(e,n,r)}static importJSON(e){return th().updateFromJSON(e)}collapseAtStart(){return!0}};V_e=class t{constructor(e,n){this._nodeMap=e,this._selection=n||null,this._flushSync=!1,this._readOnly=!1}isEmpty(){return this._nodeMap.size===1&&this._selection===null}read(e,n){return jnn(n&&n.editor||null,this,e)}clone(e){let n=new t(this._nodeMap,e===void 0?this._selection:e);return n._readOnly=!0,n}toJSON(){return jnn(null,this,()=>({root:non(th())}))}},QIr="historic",e0r="history-push",M_e="history-merge",t0r="paste",ron="collaboration",n0r="skip-collab",oon="skip-scroll-into-view",ion="skip-dom-selection",q_e=class extends iM{static getType(){return"artificial"}createDOM(e){return document.createElement("div")}},J6=class t extends iM{static getType(){return"paragraph"}static clone(e){return new t(e.__key)}createDOM(e){let n=document.createElement("p"),r=W6(e.theme,"paragraph");return r!==void 0&&n.classList.add(...r),n}updateDOM(e,n,r){return!1}static importDOM(){return{p:e=>({conversion:r0r,priority:0})}}exportDOM(e){let{element:n}=super.exportDOM(e);if(Bp(n)){this.isEmpty()&&n.append(document.createElement("br"));let r=this.getFormatType();r&&(n.style.textAlign=r)}return{element:n}}static importJSON(e){return n0().updateFromJSON(e)}exportJSON(){return{...super.exportJSON(),textFormat:this.getTextFormat(),textStyle:this.getTextStyle()}}insertNewAfter(e,n){let r=n0();r.setTextFormat(e.format),r.setTextStyle(e.style);let o=this.getDirection();return r.setDirection(o),r.setFormat(this.getFormatType()),r.setStyle(this.getStyle()),this.insertAfter(r,n),r}collapseAtStart(){let e=this.getChildren();if(e.length===0||dn(e[0])&&e[0].getTextContent().trim()===""){if(this.getNextSibling()!==null)return this.selectNext(),this.remove(),!0;if(this.getPreviousSibling()!==null)return this.selectPrevious(),this.remove(),!0}return!1}};i0r=0,s0r=1,a0r=2,l0r=3,c0r=4;X6=class{constructor(e,n,r,o,i,s,a,l){this._createEditorArgs=l,this._parentEditor=n,this._rootElement=null,this._editorState=e,this._pendingEditorState=null,this._compositionKey=null,this._deferred=[],this._keyToDOMMap=new Map,this._updates=[],this._updating=!1,this._listeners={decorator:new Set,editable:new Set,mutation:new Map,root:new Set,textcontent:new Set,update:new Set},this._commands=new Map,this._config=o,this._nodes=r,this._decorators={},this._pendingDecorators=null,this._dirtyType=F$,this._cloneNotNeeded=new Set,this._dirtyLeaves=new Set,this._dirtyElements=new Map,this._normalizedNodes=new Set,this._updateTags=new Set,this._observer=null,this._key=mon(),this._onError=i,this._htmlConversions=s,this._editable=a,this._headless=n!==null&&n._headless,this._window=null,this._blockCursorElement=null}isComposing(){return this._compositionKey!=null}registerUpdateListener(e){let n=this._listeners.update;return n.add(e),()=>{n.delete(e)}}registerEditableListener(e){let n=this._listeners.editable;return n.add(e),()=>{n.delete(e)}}registerDecoratorListener(e){let n=this._listeners.decorator;return n.add(e),()=>{n.delete(e)}}registerTextContentListener(e){let n=this._listeners.textcontent;return n.add(e),()=>{n.delete(e)}}registerRootListener(e){let n=this._listeners.root;return e(this._rootElement,null),n.add(e),()=>{e(null,this._rootElement),n.delete(e)}}registerCommand(e,n,r){r===void 0&&tt(35);let o=this._commands;o.has(e)||o.set(e,[new Set,new Set,new Set,new Set,new Set]);let i=o.get(e);i===void 0&&tt(36,String(e));let s=i[r];return s.add(n),()=>{s.delete(n),i.every(a=>a.size===0)&&o.delete(e)}}registerMutationListener(e,n,r){let o=this.resolveRegisteredNodeAfterReplacements(this.getRegisteredNode(e)).klass,i=this._listeners.mutation,s=i.get(n);s===void 0&&(s=new Set,i.set(n,s)),s.add(o);let a=r&&r.skipInitialization;return a!==void 0&&a||this.initializeMutationListener(n,o),()=>{s.delete(o),s.size===0&&i.delete(n)}}getRegisteredNode(e){let n=this._nodes.get(e.getType());return n===void 0&&tt(37,e.name),n}resolveRegisteredNodeAfterReplacements(e){for(;e.replaceWithKlass;)e=this.getRegisteredNode(e.replaceWithKlass);return e}initializeMutationListener(e,n){let r=this._editorState,o=mXe(r).get(n.getType());if(!o)return;let i=new Map;for(let s of o.keys())i.set(s,"created");i.size>0&&e(i,{dirtyLeaves:new Set,prevEditorState:r,updateTags:new Set(["registerMutationListener"])})}registerNodeTransformToKlass(e,n){let r=this.getRegisteredNode(e);return r.transforms.add(n),r}registerNodeTransform(e,n){let r=this.registerNodeTransformToKlass(e,n),o=[r],i=r.replaceWithKlass;if(i!=null){let s=this.registerNodeTransformToKlass(i,n);o.push(s)}return function(s,a){let l=mXe(s.getEditorState()),c=[];for(let u of a){let d=l.get(u);d&&c.push(d)}c.length!==0&&s.update(()=>{for(let u of c)for(let d of u.keys()){let f=ou(d);f&&f.markDirty()}},s._pendingEditorState===null?{tag:M_e}:void 0)}(this,o.map(s=>s.klass.getType())),()=>{o.forEach(s=>s.transforms.delete(n))}}hasNode(e){return this._nodes.has(e.getType())}hasNodes(e){return e.every(this.hasNode.bind(this))}dispatchCommand(e,n){return Kt(this,e,n)}getDecorators(){return this._decorators}getRootElement(){return this._rootElement}getKey(){return this._key}setRootElement(e){let n=this._rootElement;if(e!==n){let r=W6(this._config.theme,"root"),o=this._pendingEditorState||this._editorState;if(this._rootElement=e,son(this,n,e,o),n!==null&&(this._config.disableEvents||$Ir(n),r!=null&&n.classList.remove(...r)),e!==null){let i=KXe(e),s=e.style;s.userSelect="text",s.whiteSpace="pre-wrap",s.wordBreak="break-word",e.setAttribute("data-lexical-editor","true"),this._window=i,this._dirtyType=q6,lrn(this),this._updateTags.add(M_e),e0(this),this._config.disableEvents||function(a,l){let c=a.ownerDocument,u=B_e.get(c);(u===void 0||u<1)&&c.addEventListener("selectionchange",Wrn),B_e.set(c,(u||0)+1),a.__lexicalEditor=l;let d=Hrn(a);for(let f=0;f<oXe.length;f++){let[p,m]=oXe[f],h=typeof m=="function"?g=>{Cnn(g)||(Snn(g),(l.isEditable()||p==="click")&&m(g,l))}:g=>{if(Cnn(g))return;Snn(g);let v=l.isEditable();switch(p){case"cut":return v&&Kt(l,MXe,g);case"copy":return Kt(l,EXe,g);case"paste":return v&&Kt(l,TXe,g);case"dragstart":return v&&Kt(l,Mrn,g);case"dragover":return v&&Kt(l,Orn,g);case"dragend":return v&&Kt(l,Nrn,g);case"focus":return v&&Kt(l,Rrn,g);case"blur":return v&&Kt(l,Lrn,g);case"drop":return v&&Kt(l,Ern,g)}};a.addEventListener(p,h),d.push(()=>{a.removeEventListener(p,h)})}}(e,this),r!=null&&e.classList.add(...r)}else this._window=null,this._updateTags.add(M_e),e0(this);yee("root",this,!1,e,n)}}getElementByKey(e){return this._keyToDOMMap.get(e)||null}getEditorState(){return this._editorState}setEditorState(e,n){e.isEmpty()&&tt(38);let r=e;r._readOnly&&(r=ton(e),r._selection=e._selection?e._selection.clone():null),arn(this);let o=this._pendingEditorState,i=this._updateTags,s=n!==void 0?n.tag:null;o===null||o.isEmpty()||(s!=null&&i.add(s),e0(this)),this._pendingEditorState=r,this._dirtyType=q6,this._dirtyElements.set("root",!1),this._compositionKey=null,s!=null&&i.add(s),this._updating||e0(this)}parseEditorState(e,n){return function(r,o,i){let s=$Xe(),a=Ju,l=eh,c=Xu,u=o._dirtyElements,d=o._dirtyLeaves,f=o._cloneNotNeeded,p=o._dirtyType;o._dirtyElements=new Map,o._dirtyLeaves=new Set,o._cloneNotNeeded=new Set,o._dirtyType=0,Ju=s,eh=!1,Xu=o,DXe(null);try{let m=o._nodes;LXe(r.root,m),i&&i(),s._readOnly=!0}catch(m){m instanceof Error&&o._onError(m)}finally{o._dirtyElements=u,o._dirtyLeaves=d,o._cloneNotNeeded=f,o._dirtyType=p,Ju=a,eh=l,Xu=c}return s}(typeof e=="string"?JSON.parse(e):e,this,n)}read(e){return e0(this),this.getEditorState().read(e,{editor:this})}update(e,n){(function(r,o,i){r._updating?r._updates.push([o,i]):rxe(r,o,i)})(this,e,n)}focus(e,n={}){let r=this._rootElement;r!==null&&(r.setAttribute("autocapitalize","off"),Tg(this,()=>{let o=pi(),i=th();o!==null?o.dirty||nh(o.clone()):i.getChildrenSize()!==0&&(n.defaultSelection==="rootStart"?i.selectStart():i.selectEnd()),won("focus"),bon(()=>{r.removeAttribute("autocapitalize"),e&&e()})}),this._pendingEditorState===null&&r.removeAttribute("autocapitalize"))}blur(){let e=this._rootElement;e!==null&&e.blur();let n=ES(this._window);n!==null&&n.removeAllRanges()}isEditable(){return this._editable}setEditable(e){this._editable!==e&&(this._editable=e,yee("editable",this,!0,e))}toJSON(){return{editorState:this._editorState.toJSON()}}};X6.version="0.34.0+prod.esm";dXe=null;aon=1;f0r=typeof queueMicrotask=="function"?queueMicrotask:t=>{Promise.resolve().then(t)};JI={ctrlKey:!AS,metaKey:AS},Knn={altKey:AS,ctrlKey:!AS};Jnn=new WeakMap,b0r=new Map;S0r={next:"previous",previous:"next"},eV=class{constructor(e){this.origin=e}[Symbol.iterator](){return QXe({hasNext:H$,initial:this.getAdjacentCaret(),map:e=>e,step:e=>e.getAdjacentCaret()})}getAdjacentCaret(){return Qu(this.getNodeAtCaret(),this.direction)}getSiblingCaret(){return Qu(this.origin,this.direction)}remove(){let e=this.getNodeAtCaret();return e&&e.remove(),this}replaceOrInsert(e,n){let r=this.getNodeAtCaret();return e.is(this.origin)||e.is(r)||(r===null?this.insert(e):r.replace(e,n)),this}splice(e,n,r="next"){let o=r===this.direction?n:Array.from(n).reverse(),i=this,s=this.getParentAtCaret(),a=new Map;for(let l=i.getAdjacentCaret();l!==null&&a.size<e;l=l.getAdjacentCaret()){let c=l.origin.getWritable();a.set(c.getKey(),c)}for(let l of o){if(a.size>0){let c=i.getNodeAtCaret();if(c){if(a.delete(c.getKey()),a.delete(l.getKey()),!(c.is(l)||i.origin.is(l))){let u=l.getParent();u&&u.is(s)&&l.remove(),c.replace(l)}}else c===null&&tt(263,Array.from(a).join(" "))}else i.insert(l);i=Qu(l,this.direction)}for(let l of a.values())l.remove();return this}},Eee=class t extends eV{constructor(){super(...arguments);M(this,"type","child")}getLatest(){let n=this.origin.getLatest();return n===this.origin?this:i0(n,this.direction)}getParentCaret(n="root"){return Qu(JXe(this.getParentAtCaret(),n),this.direction)}getFlipped(){let n=uM(this.direction);return Qu(this.getNodeAtCaret(),n)||i0(this.origin,n)}getParentAtCaret(){return this.origin}getChildCaret(){return this}isSameNodeCaret(n){return n instanceof t&&this.direction===n.direction&&this.origin.is(n.origin)}isSamePointCaret(n){return this.isSameNodeCaret(n)}},C0r={root:Qm,shadowRoot:r_};tV=class t extends eV{constructor(){super(...arguments);M(this,"type","sibling")}getLatest(){let n=this.origin.getLatest();return n===this.origin?this:Qu(n,this.direction)}getSiblingCaret(){return this}getParentAtCaret(){return this.origin.getParent()}getChildCaret(){return Ye(this.origin)?i0(this.origin,this.direction):null}getParentCaret(n="root"){return Qu(JXe(this.getParentAtCaret(),n),this.direction)}getFlipped(){let n=uM(this.direction);return Qu(this.getNodeAtCaret(),n)||i0(this.origin.getParentOrThrow(),n)}isSamePointCaret(n){return n instanceof t&&this.direction===n.direction&&this.origin.is(n.origin)}isSameNodeCaret(n){return(n instanceof t||n instanceof nV)&&this.direction===n.direction&&this.origin.is(n.origin)}},nV=class t extends eV{constructor(n,r){super(n);M(this,"type","text");this.offset=r}getLatest(){let n=this.origin.getLatest();return n===this.origin?this:sM(n,this.direction,this.offset)}getParentAtCaret(){return this.origin.getParent()}getChildCaret(){return null}getParentCaret(n="root"){return Qu(JXe(this.getParentAtCaret(),n),this.direction)}getFlipped(){return sM(this.origin,uM(this.direction),this.offset)}isSamePointCaret(n){return n instanceof t&&this.direction===n.direction&&this.origin.is(n.origin)&&this.offset===n.offset}isSameNodeCaret(n){return(n instanceof tV||n instanceof t)&&this.direction===n.direction&&this.origin.is(n.origin)}getSiblingCaret(){return Qu(this.origin,this.direction)}};I0r={next:class extends nV{constructor(){super(...arguments);M(this,"direction","next")}getNodeAtCaret(){return this.origin.getNextSibling()}insert(e){return this.origin.insertAfter(e),this}},previous:class extends nV{constructor(){super(...arguments);M(this,"direction","previous")}getNodeAtCaret(){return this.origin.getPreviousSibling()}insert(e){return this.origin.insertBefore(e),this}}},T0r={next:class extends tV{constructor(){super(...arguments);M(this,"direction","next")}getNodeAtCaret(){return this.origin.getNextSibling()}insert(e){return this.origin.insertAfter(e),this}},previous:class extends tV{constructor(){super(...arguments);M(this,"direction","previous")}getNodeAtCaret(){return this.origin.getPreviousSibling()}insert(e){return this.origin.insertBefore(e),this}}},P0r={next:class extends Eee{constructor(){super(...arguments);M(this,"direction","next")}getNodeAtCaret(){return this.origin.getFirstChild()}insert(e){return this.origin.splice(0,0,[e]),this}},previous:class extends Eee{constructor(){super(...arguments);M(this,"direction","previous")}getNodeAtCaret(){return this.origin.getLastChild()}insert(e){return this.origin.splice(this.origin.getChildrenSize(),0,[e]),this}}};gXe=class t{constructor(e,n,r){M(this,"type","node-caret-range");this.anchor=e,this.focus=n,this.direction=r}getLatest(){let e=this.anchor.getLatest(),n=this.focus.getLatest();return e===this.anchor&&n===this.focus?this:new t(e,n,this.direction)}isCollapsed(){return this.anchor.isSamePointCaret(this.focus)}getTextSlices(){let e=o=>{let i=this[o].getLatest();return r0(i)?function(s,a){let{direction:l,origin:c}=s,u=t_(c,a==="focus"?uM(l):l);return hXe(s,u-s.offset)}(i,o):null},n=e("anchor"),r=e("focus");if(n&&r){let{caret:o}=n,{caret:i}=r;if(o.isSameNodeCaret(i))return[hXe(o,i.offset-o.offset),null]}return[n,r]}iterNodeCarets(e="root"){let n=r0(this.anchor)?this.anchor.getSiblingCaret():this.anchor.getLatest(),r=this.focus.getLatest(),o=r0(r),i=s=>s.isSameNodeCaret(r)?null:rV(s)||s.getParentCaret(e);return QXe({hasNext:s=>s!==null&&!(o&&r.isSameNodeCaret(s)),initial:n.isSameNodeCaret(r)?null:i(n),map:s=>s,step:i})}[Symbol.iterator](){return this.iterNodeCarets("root")}},Y_e=class{constructor(e,n){M(this,"type","slice");this.caret=e,this.distance=n}getSliceIndices(){let{distance:e,caret:{offset:n}}=this,r=n+e;return r<n?[r,n]:[n,r]}getTextContent(){let[e,n]=this.getSliceIndices();return this.caret.origin.getTextContent().slice(e,n)}getTextContentSize(){return Math.abs(this.distance)}removeTextSlice(){let{caret:{origin:e,direction:n}}=this,[r,o]=this.getSliceIndices(),i=e.getTextContent();return sM(e.setTextContent(i.slice(0,r)+i.slice(o)),n,r)}}});var he,jvi,Bvi,lV,$on,dM,zvi,Hvi,Wvi,oQe,Vvi,a0,qvi,iQe,Kvi,Don,i_,Fon,Lee,Gvi,Zvi,sQe,Uon,Yvi,jon,fM,Jvi,aQe,Bon,Xvi,Qvi,lxe,ewi,twi,zon,nwi,$ee,ho,qn,l0,Hon,rwi,owi,iwi,swi,awi,lwi,Won,cwi,uwi,cxe,Dee,uxe,io,Von,dwi,qon,fwi,pwi,mwi,Kon,gn,cV,V$,Gon,hwi,Ho,dxe,gwi,lQe,ywi,vwi,Zon,wwi,bwi,Yon,_wi,Jon,fxe,xwi,Swi,uV,Xon,Qon,ein,tin,Cwi,cQe,nin,Fee,Uee,rin,oin,kwi,Iwi,pxe,Rs,c0,dV,Twi,iin,mxe,sin,fV,ain,lin,Pwi,Awi,cin,uin,hxe,Ewi,Mwi,Owi,Nwi,gxe,pV,din,Rwi,uQe,fin,Lwi,jee,$wi,Dwi,Fwi,Uwi,jwi,Bwi,zwi,Hwi,Wwi,pin,min,hin,gin,yin,vin,Vwi,mV,yxe,qwi,Kwi,hV,Gwi,Zwi,Ywi,Jwi,Xwi,vxe,win,Qwi,bin,_in,ebi,tbi,xin,Sin,nbi,rbi,obi,ibi,sbi,OS,Cin,abi,kin,Iin,lbi,cbi,ubi,dbi,dQe,fbi,Tin,pbi,mbi,Pin,hbi,Ain,gbi,ybi,vbi,wbi,bbi,fQe,_bi,Ein,wxe,Bee,xbi,Sbi,Cbi,Min,pQe,kbi,Ibi,Tbi,Pbi,$o=b(()=>{Lon();he=rQe,jvi=he.$addUpdateTag,Bvi=he.$applyNodeReplacement,lV=he.$caretFromPoint,$on=he.$caretRangeFromSelection,dM=he.$cloneWithProperties,zvi=he.$comparePointCaretNext,Hvi=he.$copyNode,Wvi=he.$create,oQe=he.$createLineBreakNode,Vvi=he.$createNodeSelection,a0=he.$createParagraphNode,qvi=he.$createPoint,iQe=he.$createRangeSelection,Kvi=he.$createRangeSelectionFromDom,Don=he.$createTabNode,i_=he.$createTextNode,Fon=he.$extendCaretToRange,Lee=he.$getAdjacentChildCaret,Gvi=he.$getAdjacentNode,Zvi=he.$getAdjacentSiblingOrParentSiblingCaret,sQe=he.$getCaretInDirection,Uon=he.$getCaretRange,Yvi=he.$getCaretRangeInDirection,jon=he.$getCharacterOffsets,fM=he.$getChildCaret,Jvi=he.$getChildCaretAtIndex,aQe=he.$getChildCaretOrSelf,Bon=he.$getCollapsedCaretRange,Xvi=he.$getCommonAncestor,Qvi=he.$getCommonAncestorResultBranchOrder,lxe=he.$getEditor,ewi=he.$getNearestNodeFromDOMNode,twi=he.$getNearestRootOrShadowRoot,zon=he.$getNodeByKey,nwi=he.$getNodeByKeyOrThrow,$ee=he.$getPreviousSelection,ho=he.$getRoot,qn=he.$getSelection,l0=he.$getSiblingCaret,Hon=he.$getState,rwi=he.$getStateChange,owi=he.$getTextContent,iwi=he.$getTextNodeOffset,swi=he.$getTextPointCaret,awi=he.$getTextPointCaretSlice,lwi=he.$getWritableNodeState,Won=he.$hasAncestor,cwi=he.$hasUpdateTag,uwi=he.$insertNodes,cxe=he.$isBlockElementNode,Dee=he.$isChildCaret,uxe=he.$isDecoratorNode,io=he.$isElementNode,Von=he.$isExtendableTextPointCaret,dwi=he.$isInlineElementOrDecoratorNode,qon=he.$isLeafNode,fwi=he.$isLineBreakNode,pwi=he.$isNodeCaret,mwi=he.$isNodeSelection,Kon=he.$isParagraphNode,gn=he.$isRangeSelection,cV=he.$isRootNode,V$=he.$isRootOrShadowRoot,Gon=he.$isSiblingCaret,hwi=he.$isTabNode,Ho=he.$isTextNode,dxe=he.$isTextPointCaret,gwi=he.$isTextPointCaretSlice,lQe=he.$isTokenOrSegmented,ywi=he.$isTokenOrTab,vwi=he.$nodesOfType,Zon=he.$normalizeCaret,wwi=he.$normalizeSelection__EXPERIMENTAL,bwi=he.$onUpdate,Yon=he.$parseSerializedNode,_wi=he.$removeTextFromCaretRange,Jon=he.$rewindSiblingCaret,fxe=he.$selectAll,xwi=he.$setCompositionKey,Swi=he.$setPointFromCaret,uV=he.$setSelection,Xon=he.$setSelectionFromCaretRange,Qon=he.$setState,ein=he.$splitAtPointCaretNext,tin=he.$splitNode,Cwi=he.$updateRangeSelectionFromCaretRange,cQe=he.ArtificialNode__DO_NOT_USE,nin=he.BLUR_COMMAND,Fee=he.CAN_REDO_COMMAND,Uee=he.CAN_UNDO_COMMAND,rin=he.CLEAR_EDITOR_COMMAND,oin=he.CLEAR_HISTORY_COMMAND,kwi=he.CLICK_COMMAND,Iwi=he.COLLABORATION_TAG,pxe=he.COMMAND_PRIORITY_CRITICAL,Rs=he.COMMAND_PRIORITY_EDITOR,c0=he.COMMAND_PRIORITY_HIGH,dV=he.COMMAND_PRIORITY_LOW,Twi=he.COMMAND_PRIORITY_NORMAL,iin=he.CONTROLLED_TEXT_INSERTION_COMMAND,mxe=he.COPY_COMMAND,sin=he.CUT_COMMAND,fV=he.DELETE_CHARACTER_COMMAND,ain=he.DELETE_LINE_COMMAND,lin=he.DELETE_WORD_COMMAND,Pwi=he.DRAGEND_COMMAND,Awi=he.DRAGOVER_COMMAND,cin=he.DRAGSTART_COMMAND,uin=he.DROP_COMMAND,hxe=he.DecoratorNode,Ewi=he.ElementNode,Mwi=he.FOCUS_COMMAND,Owi=he.FORMAT_ELEMENT_COMMAND,Nwi=he.FORMAT_TEXT_COMMAND,gxe=he.HISTORIC_TAG,pV=he.HISTORY_MERGE_TAG,din=he.HISTORY_PUSH_TAG,Rwi=he.INDENT_CONTENT_COMMAND,uQe=he.INSERT_LINE_BREAK_COMMAND,fin=he.INSERT_PARAGRAPH_COMMAND,Lwi=he.INSERT_TAB_COMMAND,jee=he.INTERNAL_$isBlock,$wi=he.IS_ALL_FORMATTING,Dwi=he.IS_BOLD,Fwi=he.IS_CODE,Uwi=he.IS_HIGHLIGHT,jwi=he.IS_ITALIC,Bwi=he.IS_STRIKETHROUGH,zwi=he.IS_SUBSCRIPT,Hwi=he.IS_SUPERSCRIPT,Wwi=he.IS_UNDERLINE,pin=he.KEY_ARROW_DOWN_COMMAND,min=he.KEY_ARROW_LEFT_COMMAND,hin=he.KEY_ARROW_RIGHT_COMMAND,gin=he.KEY_ARROW_UP_COMMAND,yin=he.KEY_BACKSPACE_COMMAND,vin=he.KEY_DELETE_COMMAND,Vwi=he.KEY_DOWN_COMMAND,mV=he.KEY_ENTER_COMMAND,yxe=he.KEY_ESCAPE_COMMAND,qwi=he.KEY_MODIFIER_COMMAND,Kwi=he.KEY_SPACE_COMMAND,hV=he.KEY_TAB_COMMAND,Gwi=he.LineBreakNode,Zwi=he.MOVE_TO_END,Ywi=he.MOVE_TO_START,Jwi=he.NODE_STATE_KEY,Xwi=he.OUTDENT_CONTENT_COMMAND,vxe=he.PASTE_COMMAND,win=he.PASTE_TAG,Qwi=he.ParagraphNode,bin=he.REDO_COMMAND,_in=he.REMOVE_TEXT_COMMAND,ebi=he.RootNode,tbi=he.SELECTION_CHANGE_COMMAND,xin=he.SELECTION_INSERT_CLIPBOARD_NODES_COMMAND,Sin=he.SELECT_ALL_COMMAND,nbi=he.SKIP_COLLAB_TAG,rbi=he.SKIP_DOM_SELECTION_TAG,obi=he.SKIP_SCROLL_INTO_VIEW_TAG,ibi=he.TEXT_TYPE_TO_FORMAT,sbi=he.TabNode,OS=he.TextNode,Cin=he.UNDO_COMMAND,abi=he.buildImportMap,kin=he.createCommand,Iin=he.createEditor,lbi=he.createSharedNodeState,cbi=he.createState,ubi=he.flipDirection,dbi=he.getDOMOwnerDocument,dQe=he.getDOMSelection,fbi=he.getDOMSelectionFromTarget,Tin=he.getDOMTextNode,pbi=he.getEditorPropertyFromDOMNode,mbi=he.getNearestEditorFromDOMNode,Pin=he.getRegisteredNode,hbi=he.getRegisteredNodeOrThrow,Ain=he.isBlockDomNode,gbi=he.isCurrentlyReadOnlyMode,ybi=he.isDOMDocumentNode,vbi=he.isDOMNode,wbi=he.isDOMTextNode,bbi=he.isDOMUnmanaged,fQe=he.isDocumentFragment,_bi=he.isExactShortcutMatch,Ein=he.isHTMLAnchorElement,wxe=he.isHTMLElement,Bee=he.isInlineDomNode,xbi=he.isLexicalEditor,Sbi=he.isModifierMatch,Cbi=he.isSelectionCapturedInDecoratorInput,Min=he.isSelectionWithinEditor,pQe=he.makeStepwiseIterator,kbi=he.removeFromParent,Ibi=he.resetRandomKey,Tbi=he.setDOMUnmanaged,Pbi=he.setNodeIndentFromDOM});function Oin(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Nin(...t){return e=>{let n=!1,r=t.map(o=>{let i=Oin(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():Oin(t[o],null)}}}}var R0r,Rin=b(()=>{R0r=L(B(),1)});function Lin(t){let e=L0r(t),n=iu.forwardRef((r,o)=>{let{children:i,...s}=r,a=iu.Children.toArray(i),l=a.find(D0r);if(l){let c=l.props.children,u=a.map(d=>d===l?iu.Children.count(c)>1?iu.Children.only(null):iu.isValidElement(c)?c.props.children:null:d);return(0,bxe.jsx)(e,{...s,ref:o,children:iu.isValidElement(c)?iu.cloneElement(c,void 0,u):null})}return(0,bxe.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function L0r(t){let e=iu.forwardRef((n,r)=>{let{children:o,...i}=n;if(iu.isValidElement(o)){let s=U0r(o),a=F0r(i,o.props);return o.type!==iu.Fragment&&(a.ref=r?Nin(r,s):s),iu.cloneElement(o,a)}return iu.Children.count(o)>1?iu.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}function D0r(t){return iu.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===$0r}function F0r(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function U0r(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var iu,bxe,$0r,$in=b(()=>{iu=L(B(),1);Rin();bxe=L(Mt(),1);$0r=Symbol("radix.slottable")});var Din,j0r,Fin,B0r,Uin,jin=b(()=>{Din=L(B(),1),j0r=L(Es(),1);$in();Fin=L(Mt(),1),B0r=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Uin=B0r.reduce((t,e)=>{let n=Lin(`Primitive.${e}`),r=Din.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,Fin.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{})});function W0r(t){return H0r.includes(t)}var zin,Hin,z0r,Bin,H0r,Win,mQe,Vin=b(()=>{zin=L(B(),1);jin();Hin=L(Mt(),1),z0r="Separator",Bin="horizontal",H0r=["horizontal","vertical"],Win=zin.forwardRef((t,e)=>{let{decorative:n,orientation:r=Bin,...o}=t,i=W0r(r)?r:Bin,a=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return(0,Hin.jsx)(Uin.div,{"data-orientation":i,...a,...o,ref:e})});Win.displayName=z0r;mQe=Win});var _xe,Lv,xxe=b(()=>{"use client";_xe=L(B());Vin();De();Lv=_xe.forwardRef(({className:t,orientation:e="horizontal",decorative:n=!0,...r},o)=>_xe.createElement(mQe,{ref:o,decorative:n,orientation:e,className:J("tw-shrink-0 tw-bg-[var(--background-modifier-border)]",e==="horizontal"?"tw-h-px tw-w-full":"tw-h-full tw-w-px",t),...r}));Lv.displayName=mQe.displayName});function Sxe({options:t,selectedIndex:e,onSelect:n,onHighlight:r,query:o="",mode:i="search",showPreview:s=!1,searchBarMode:a=!1,searchQuery:l="",onSearchChange:c,onKeyDown:u,className:d,width:f}){let p=(0,Yi.useRef)(null),m=(0,Yi.useRef)(null),[h,g]=Yi.default.useState(null),[v,y]=Yi.default.useState(e);e!==v&&(y(e),g(null)),(0,Yi.useEffect)(()=>{p.current&&p.current.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})},[e]);let w=I=>{let C=I.target.value;c?.(C)},_=I=>{(I.key==="ArrowDown"||I.key==="ArrowUp"||I.key==="Enter"||I.key==="Tab"||I.key==="Escape")&&(I.preventDefault(),u?.(I))},S=s&&t[e]?.content;return Yi.default.createElement("div",{className:J("tw-flex tw-flex-col",d)},S&&Yi.default.createElement("div",{className:"tw-mb-2 tw-overflow-hidden tw-rounded-md tw-bg-primary tw-p-3 tw-text-sm tw-shadow-xl",style:{minHeight:q0r,maxHeight:K0r,...f&&{width:f}}},Yi.default.createElement("div",{className:"tw-mb-1 tw-text-xs tw-text-muted"},"Preview"),t[e].subtitle&&Yi.default.createElement("div",{className:"tw-mb-2 tw-text-xs tw-text-muted"},t[e].subtitle),Yi.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-text-normal"},t[e].content)),Yi.default.createElement("div",{className:"tw-overflow-hidden tw-rounded-lg tw-bg-primary",style:{...f&&{width:f}}},Yi.default.createElement("div",{className:"tw-overflow-y-auto",style:{minHeight:Math.min(t.length*44+16,100),maxHeight:240}},Yi.default.createElement("div",{className:"tw-p-2 tw-text-normal"},t.map((I,C)=>{let k=C===e,T=C===h,P=I.disabled??!1,E=(k||T)&&!P,O=i==="category"&&!o&&I.icon&&!("data"in I);return Yi.default.createElement("div",{key:I.key,ref:k?p:void 0,className:J("tw-flex tw-items-center tw-rounded-md tw-px-3 tw-py-2 tw-text-sm",P?"tw-cursor-not-allowed tw-text-muted tw-opacity-50":"tw-cursor-pointer tw-text-normal",E&&"tw-bg-modifier-hover"),title:P?I.disabledReason:void 0,onMouseDown:$=>{$.preventDefault(),!P&&n(I)},onMouseEnter:()=>{P||(g(C),r(C))},onMouseLeave:()=>g(null)},O?Yi.default.createElement("div",{className:"tw-flex tw-w-full tw-items-center tw-justify-between"},Yi.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},I.icon,Yi.default.createElement("span",{className:"tw-font-medium"},I.title)),Yi.default.createElement(Vi,{className:"tw-size-4 tw-text-muted"})):Yi.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-items-center tw-gap-2"},I.icon&&Yi.default.createElement("div",{className:"tw-flex tw-h-full tw-shrink-0 tw-items-center"},I.icon),Yi.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-flex-col tw-gap-0.5"},Yi.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-1"},Yi.default.createElement("span",{className:"tw-truncate tw-font-medium tw-text-normal"},I.title),I.trailingContent),I.subtitle&&Yi.default.createElement("div",{className:"tw-truncate tw-text-xs tw-text-muted"},I.subtitle))))}))),a&&Yi.default.createElement("div",{className:"tw-border-t tw-border-solid tw-border-border tw-p-0.5"},Yi.default.createElement("input",{ref:m,type:"text",value:l,onChange:w,onKeyDown:_,placeholder:"Search...",autoFocus:!0,className:"tw-w-full tw-rounded-md !tw-border-none !tw-bg-transparent tw-px-1 tw-py-0 tw-text-sm tw-text-normal placeholder:tw-text-muted focus:!tw-shadow-none"}))))}var Yi,q0r,K0r,hQe=b(()=>{Yi=L(B());Re();De();q0r=120,K0r=240});function Kin({options:t,selectedIndex:e,onSelect:n,onHighlight:r,query:o="",mode:i="search",showPreview:s=!1,searchBarMode:a=!1,searchQuery:l="",onSearchChange:c,onKeyDown:u}){return qin.default.createElement(Sxe,{options:t,selectedIndex:e,onSelect:n,onHighlight:r,query:o,mode:i,showPreview:s,searchBarMode:a,searchQuery:l,onSearchChange:c,onKeyDown:u})}var qin,Gin=b(()=>{qin=L(B());hQe()});function Zin(t){return t.isCopilotPlus&&!t.isAgentMode}function Cxe(t=!1,e=!1){return(0,u0.useMemo)(()=>{let n=Z0r.filter(r=>r.category==="tools"?t:r.category==="webTabs"?Ln():!0);return e?[G0r,...n]:n},[t,e])}var u0,NS,G0r,Z0r,pM=b(()=>{u0=L(B());$n();Re();NS=Object.freeze([]),G0r={key:"agents",title:"Agents",subtitle:"Ask another coding agent this turn",category:"agents",icon:u0.default.createElement(gy,{className:"tw-size-4"})},Z0r=[{key:"notes",title:"Notes",subtitle:"Reference notes in your vault",category:"notes",icon:u0.default.createElement(Jo,{className:"tw-size-4"})},{key:"webTabs",title:"Web Tabs",subtitle:"Reference open browser tabs",category:"webTabs",icon:u0.default.createElement(Xo,{className:"tw-size-4"})},{key:"tools",title:"Tools",subtitle:"AI tools and commands",category:"tools",icon:u0.default.createElement(Pw,{className:"tw-size-4"})},{key:"folders",title:"Folders",subtitle:"Reference vault folders",category:"folders",icon:u0.default.createElement(Fl,{className:"tw-size-4"})},{key:"images",title:"Images",subtitle:"Attach image files",category:"images",icon:u0.default.createElement(bG,{className:"tw-size-4"}),isAction:!0}]});var zee=wi((Yin,kxe)=>{((t,e)=>{typeof define=="function"&&define.amd?define([],e):typeof kxe=="object"&&kxe.exports?kxe.exports=e():t.fuzzysort=e()})(Yin,t=>{"use strict";var e=(q,F)=>{if(!q||!F)return Q;var z=p(q);V(F)||(F=f(F));var N=z.bitflags;return(N&F._bitflags)!==N?Q:h(z,F)},n=(q,F,z)=>{if(!q)return z?.all?m(F,z):le;var N=p(q),R=N.bitflags,X=N.containsSpace,D=u(z?.threshold||0),G=z?.limit||K,ce=0,Z=0,te=F.length;function fe(Br){ce<G?(ae.add(Br),++ce):(++Z,Br._score>ae.peek()._score&&ae.replaceTop(Br))}if(z?.key)for(var de=z.key,ye=0;ye<te;++ye){var Te=F[ye],Be=U(Te,de);if(Be&&(V(Be)||(Be=f(Be)),(R&Be._bitflags)===R)){var qe=h(N,Be);qe!==Q&&(qe._score<D||(qe.obj=Te,fe(qe)))}}else if(z?.keys){var Ae=z.keys,Xt=Ae.length;e:for(var ye=0;ye<te;++ye){var Te=F[ye];{for(var Ve=0,Ee=0;Ee<Xt;++Ee){var de=Ae[Ee],Be=U(Te,de);if(!Be){O[Ee]=ne;continue}V(Be)||(Be=f(Be)),O[Ee]=Be,Ve|=Be._bitflags}if((R&Ve)!==R)continue}if(X)for(let An=0;An<N.spaceSearches.length;An++)P[An]=se;for(var Ee=0;Ee<Xt;++Ee){if(Be=O[Ee],Be===ne){$[Ee]=ne;continue}if($[Ee]=h(N,Be,!1,X),$[Ee]===Q){$[Ee]=ne;continue}if(X)for(let zn=0;zn<N.spaceSearches.length;zn++){if(E[zn]>-1e3&&P[zn]>se){var st=(P[zn]+E[zn])/4;st>P[zn]&&(P[zn]=st)}E[zn]>P[zn]&&(P[zn]=E[zn])}}if(X){for(let An=0;An<N.spaceSearches.length;An++)if(P[An]===se)continue e}else{var Ne=!1;for(let An=0;An<Xt;An++)if($[An]._score!==se){Ne=!0;break}if(!Ne)continue}var He=new a(Xt);for(let An=0;An<Xt;An++)He[An]=$[An];if(X){var et=0;for(let An=0;An<N.spaceSearches.length;An++)et+=P[An]}else{var et=se;for(let zn=0;zn<Xt;zn++){var qe=He[zn];if(qe._score>-1e3&&et>se){var st=(et+qe._score)/4;st>et&&(et=st)}qe._score>et&&(et=qe._score)}}if(He.obj=Te,He._score=et,z?.scoreFn){if(et=z.scoreFn(He),!et)continue;et=u(et),He._score=et}et<D||fe(He)}}else for(var ye=0;ye<te;++ye){var Be=F[ye];if(Be&&(V(Be)||(Be=f(Be)),(R&Be._bitflags)===R)){var qe=h(N,Be);qe!==Q&&(qe._score<D||fe(qe))}}if(ce===0)return le;for(var it=new Array(ce),ye=ce-1;ye>=0;--ye)it[ye]=ae.poll();return it.total=ce+Z,it},r=(q,F="<b>",z="</b>")=>{for(var N=typeof F=="function"?F:void 0,R=q.target,X=R.length,D=q.indexes,G="",ce=0,Z=0,te=!1,fe=[],de=0;de<X;++de){var ye=R[de];if(D[Z]===de){if(++Z,te||(te=!0,N?(fe.push(G),G=""):G+=F),Z===D.length){N?(G+=ye,fe.push(N(G,ce++)),G="",fe.push(R.substr(de+1))):G+=ye+z+R.substr(de+1);break}}else te&&(te=!1,N?(fe.push(N(G,ce++)),G=""):G+=z);G+=ye}return N?fe:G},o=q=>{typeof q=="number"?q=""+q:typeof q!="string"&&(q="");var F=y(q);return l(q,{_targetLower:F._lower,_targetLowerCodes:F.lowerCodes,_bitflags:F.bitflags})},i=()=>{S.clear(),I.clear()};class s{get indexes(){return this._indexes.slice(0,this._indexes.len).sort((F,z)=>F-z)}set indexes(F){return this._indexes=F}highlight(F,z){return r(this,F,z)}get score(){return c(this._score)}set score(F){this._score=u(F)}}class a extends Array{get score(){return c(this._score)}set score(F){this._score=u(F)}}var l=(q,F)=>{let z=new s;return z.target=q,z.obj=F.obj??Q,z._score=F._score??se,z._indexes=F._indexes??[],z._targetLower=F._targetLower??"",z._targetLowerCodes=F._targetLowerCodes??Q,z._nextBeginningIndexes=F._nextBeginningIndexes??Q,z._bitflags=F._bitflags??0,z},c=q=>q===se?0:q>1?q:Math.E**(((-q+1)**.04307-1)*-2),u=q=>q===0?se:q>1?q:1-Math.pow(Math.log(q)/-2+1,1/.04307),d=q=>{typeof q=="number"?q=""+q:typeof q!="string"&&(q=""),q=q.trim();var F=y(q),z=[];if(F.containsSpace){var N=q.split(/\s+/);N=[...new Set(N)];for(var R=0;R<N.length;R++)if(N[R]!==""){var X=y(N[R]);z.push({lowerCodes:X.lowerCodes,_lower:N[R].toLowerCase(),containsSpace:!1})}}return{lowerCodes:F.lowerCodes,_lower:F._lower,containsSpace:F.containsSpace,bitflags:F.bitflags,spaceSearches:z}},f=q=>{if(q.length>999)return o(q);var F=S.get(q);return F!==void 0||(F=o(q),S.set(q,F)),F},p=q=>{if(q.length>999)return d(q);var F=I.get(q);return F!==void 0||(F=d(q),I.set(q,F)),F},m=(q,F)=>{var z=[];z.total=q.length;var N=F?.limit||K;if(F?.key)for(var R=0;R<q.length;R++){var X=q[R],D=U(X,F.key);if(D!=Q){V(D)||(D=f(D));var G=l(D.target,{_score:D._score,obj:X});if(z.push(G),z.length>=N)return z}}else if(F?.keys)for(var R=0;R<q.length;R++){for(var X=q[R],ce=new a(F.keys.length),Z=F.keys.length-1;Z>=0;--Z){var D=U(X,F.keys[Z]);if(!D){ce[Z]=ne;continue}V(D)||(D=f(D)),D._score=se,D._indexes.len=0,ce[Z]=D}if(ce.obj=X,ce._score=se,z.push(ce),z.length>=N)return z}else for(var R=0;R<q.length;R++){var D=q[R];if(D!=Q&&(V(D)||(D=f(D)),D._score=se,D._indexes.len=0,z.push(D),z.length>=N))return z}return z},h=(q,F,z=!1,N=!1)=>{if(z===!1&&q.containsSpace)return g(q,F,N);for(var R=q._lower,X=q.lowerCodes,D=X[0],G=F._targetLowerCodes,ce=X.length,Z=G.length,ye=0,te=0,fe=0;;){var de=D===G[te];if(de){if(C[fe++]=te,++ye,ye===ce)break;D=X[ye]}if(++te,te>=Z)return Q}var ye=0,Te=!1,Be=0,qe=F._nextBeginningIndexes;qe===Q&&(qe=F._nextBeginningIndexes=_(F.target)),te=C[0]===0?0:qe[C[0]-1];var Ae=0;if(te!==Z)for(;;)if(te>=Z){if(ye<=0||(++Ae,Ae>200))break;--ye;var Xt=k[--Be];te=qe[Xt]}else{var de=X[ye]===G[te];if(de){if(k[Be++]=te,++ye,ye===ce){Te=!0;break}++te}else te=qe[te]}var Ve=ce<=1?-1:F._targetLower.indexOf(R,C[0]),Ee=!!~Ve,st=Ee?Ve===0||F._nextBeginningIndexes[Ve-1]===Ve:!1;if(Ee&&!st){for(var Ne=0;Ne<qe.length;Ne=qe[Ne])if(!(Ne<=Ve)){for(var He=0;He<ce&&X[He]===F._targetLowerCodes[Ne+He];He++);if(He===ce){Ve=Ne,st=!0;break}}}var et=An=>{for(var zn=0,Yp=0,la=1;la<ce;++la)An[la]-An[la-1]!==1&&(zn-=An[la],++Yp);var vu=An[ce-1]-An[0]-(ce-1);if(zn-=(12+vu)*Yp,An[0]!==0&&(zn-=An[0]*An[0]*.2),!Te)zn*=1e3;else{for(var Ds=1,la=qe[0];la<Z;la=qe[la])++Ds;Ds>24&&(zn*=(Ds-24)*10)}return zn-=(Z-ce)/2,Ee&&(zn/=1+ce*ce*1),st&&(zn/=1+ce*ce*1),zn-=(Z-ce)/2,zn};if(Te)if(st){for(var Ne=0;Ne<ce;++Ne)C[Ne]=Ve+Ne;var it=C,Br=et(C)}else var it=k,Br=et(k);else{if(Ee)for(var Ne=0;Ne<ce;++Ne)C[Ne]=Ve+Ne;var it=C,Br=et(it)}F._score=Br;for(var Ne=0;Ne<ce;++Ne)F._indexes[Ne]=it[Ne];F._indexes.len=ce;let Xr=new s;return Xr.target=F.target,Xr._score=F._score,Xr._indexes=F._indexes,Xr},g=(q,F,z)=>{for(var N=new Set,R=0,X=Q,D=0,G=q.spaceSearches,ce=G.length,Z=0,te=()=>{for(let st=Z-1;st>=0;st--)F._nextBeginningIndexes[T[st*2+0]]=T[st*2+1]},fe=!1,Ee=0;Ee<ce;++Ee){E[Ee]=se;var de=G[Ee];if(X=h(de,F),z){if(X===Q)continue;fe=!0}else if(X===Q)return te(),Q;var ye=Ee===ce-1;if(!ye){var Te=X._indexes,Be=!0;for(let Ne=0;Ne<Te.len-1;Ne++)if(Te[Ne+1]-Te[Ne]!==1){Be=!1;break}if(Be){var qe=Te[Te.len-1]+1,Ae=F._nextBeginningIndexes[qe-1];for(let Ne=qe-1;Ne>=0&&Ae===F._nextBeginningIndexes[Ne];Ne--)F._nextBeginningIndexes[Ne]=qe,T[Z*2+0]=Ne,T[Z*2+1]=Ae,Z++}}R+=X._score/ce,E[Ee]=X._score/ce,X._indexes[0]<D&&(R-=(D-X._indexes[0])*2),D=X._indexes[0];for(var Xt=0;Xt<X._indexes.len;++Xt)N.add(X._indexes[Xt])}if(z&&!fe)return Q;te();var Ve=h(q,F,!0);if(Ve!==Q&&Ve._score>R){if(z)for(var Ee=0;Ee<ce;++Ee)E[Ee]=Ve._score/ce;return Ve}z&&(X=F),X._score=R;var Ee=0;for(let st of N)X._indexes[Ee++]=st;return X._indexes.len=Ee,X},v=q=>q.replace(/\p{Script=Latin}+/gu,F=>F.normalize("NFD")).replace(/[\u0300-\u036f]/g,""),y=q=>{q=v(q);for(var F=q.length,z=q.toLowerCase(),N=[],R=0,X=!1,D=0;D<F;++D){var G=N[D]=z.charCodeAt(D);if(G===32){X=!0;continue}var ce=G>=97&&G<=122?G-97:G>=48&&G<=57?26:G<=127?30:31;R|=1<<ce}return{lowerCodes:N,bitflags:R,containsSpace:X,_lower:z}},w=q=>{for(var F=q.length,z=[],N=0,R=!1,X=!1,D=0;D<F;++D){var G=q.charCodeAt(D),ce=G>=65&&G<=90,Z=ce||G>=97&&G<=122||G>=48&&G<=57,te=ce&&!R||!X||!Z;R=ce,X=Z,te&&(z[N++]=D)}return z},_=q=>{q=v(q);for(var F=q.length,z=w(q),N=[],R=z[0],X=0,D=0;D<F;++D)R>D?N[D]=R:(R=z[++X],N[D]=R===void 0?F:R);return N},S=new Map,I=new Map,C=[],k=[],T=[],P=[],E=[],O=[],$=[],U=(q,F)=>{var z=q[F];if(z!==void 0)return z;if(typeof F=="function")return F(q);var N=F;Array.isArray(F)||(N=F.split("."));for(var R=N.length,X=-1;q&&++X<R;)q=q[N[X]];return q},V=q=>typeof q=="object"&&typeof q._bitflags=="number",K=1/0,se=-K,le=[];le.total=0;var Q=null,ne=o(""),ee=q=>{var F=[],z=0,N={},R=X=>{for(var D=0,G=F[D],ce=1;ce<z;){var Z=ce+1;D=ce,Z<z&&F[Z]._score<F[ce]._score&&(D=Z),F[D-1>>1]=F[D],ce=1+(D<<1)}for(var te=D-1>>1;D>0&&G._score<F[te]._score;te=(D=te)-1>>1)F[D]=F[te];F[D]=G};return N.add=X=>{var D=z;F[z++]=X;for(var G=D-1>>1;D>0&&X._score<F[G]._score;G=(D=G)-1>>1)F[D]=F[G];F[D]=X},N.poll=X=>{if(z!==0){var D=F[0];return F[0]=F[--z],R(),D}},N.peek=X=>{if(z!==0)return F[0]},N.replaceTop=X=>{F[0]=X,R()},N},ae=ee();return{single:e,go:n,prepare:o,cleanup:i}})});var gQe,d0,Ixe=b(()=>{pe();gQe=t=>{switch(t){case"@vault":return"Search through your vault for relevant information";case"@websearch":return"Search the web for information";case"@composer":return"Edit existing notes or create new notes.";case"@memory":return"Save information to user memory";default:return""}},d0=class{static async callTool(e,n){if(!e)throw new Error("Tool is undefined");let r=e,o=await r.call(n);return o??(W(`[ToolCall] Tool "${r.name}" returned null/undefined`),null)}}});var gV,Txe=b(()=>{gV=["@vault","@websearch","@composer","@memory"]});var s_,Pxe,yQe,vQe,wQe,bQe,q$,Hee,Wee=b(()=>{Us();s_=require("obsidian");AC();Se();ut();pe();Pxe=250,yQe=yo([]),vQe=yo([]),wQe=yo([]),bQe=yo([]),q$=class q${constructor(){this.initialized=!1;this.app=null;this.handleFileCreate=e=>{e instanceof s_.TFile?U_(e)&&(this.debouncedRefreshNotes(),this.debouncedRefreshTagsFrontmatter(),this.debouncedRefreshTagsAll()):e instanceof s_.TFolder&&this.debouncedRefreshFolders()};this.handleFileDelete=e=>{e instanceof s_.TFile?U_(e)&&(this.debouncedRefreshNotes(),this.debouncedRefreshTagsFrontmatter(),this.debouncedRefreshTagsAll()):e instanceof s_.TFolder&&this.debouncedRefreshFolders()};this.handleFileRename=(e,n)=>{e instanceof s_.TFile?U_(e)&&(this.debouncedRefreshNotes(),this.debouncedRefreshTagsFrontmatter(),this.debouncedRefreshTagsAll()):e instanceof s_.TFolder&&this.debouncedRefreshFolders()};this.handleFileModify=e=>{e instanceof s_.TFile&&e.extension==="md"&&this.debouncedRefreshTagsAll()};this.handleMetadataChange=e=>{e.extension==="md"&&(this.debouncedRefreshTagsFrontmatter(),this.debouncedRefreshTagsAll())};this.debouncedRefreshNotes=Ba(()=>this.refreshNotes(),Pxe,{leading:!0,trailing:!0});this.debouncedRefreshFolders=Ba(()=>this.refreshFolders(),Pxe,{leading:!0,trailing:!0});this.debouncedRefreshTagsFrontmatter=Ba(()=>this.refreshTagsFrontmatter(),Pxe,{leading:!0,trailing:!0});this.debouncedRefreshTagsAll=Ba(()=>this.refreshTagsAll(),Pxe,{leading:!0,trailing:!0});this.refreshNotes=()=>{if(!this.app?.vault)return;let n=this.app.vault.getFiles().filter(r=>r instanceof s_.TFile&&U_(r));on.set(yQe,n)};this.refreshFolders=()=>{if(!this.app?.vault)return;let e=this.app.vault.getAllLoadedFiles().filter(n=>n instanceof s_.TFolder);on.set(vQe,e)};this.refreshTagsFrontmatter=()=>{if(!this.app?.vault||!this.app?.metadataCache)return;let e=this.app,n=new Set;e.vault.getMarkdownFiles().forEach(o=>{F_(e,o,!0).forEach(s=>{let a=s.startsWith("#")?s:`#${s}`;n.add(a)})});let r=Array.from(n).sort();on.set(wQe,r)};this.refreshTagsAll=()=>{if(!this.app?.vault||!this.app?.metadataCache)return;let e=this.app,n=new Set;e.vault.getMarkdownFiles().forEach(o=>{F_(e,o,!1).forEach(s=>{let a=s.startsWith("#")?s:`#${s}`;n.add(a)})});let r=Array.from(n).sort();on.set(bQe,r)}}static getInstance(){return q$.instance||(q$.instance=new q$),q$.instance}initialize(e){if(this.initialized){j("VaultDataManager: Already initialized, skipping");return}if(!e?.vault){j("VaultDataManager: app.vault not available, deferring initialization");return}this.app=e,j("VaultDataManager: Initializing with vault event listeners"),this.refreshNotes(),this.refreshFolders(),this.refreshTagsFrontmatter(),this.refreshTagsAll(),e.vault.on("create",this.handleFileCreate),e.vault.on("delete",this.handleFileDelete),e.vault.on("rename",this.handleFileRename),e.vault.on("modify",this.handleFileModify),e.metadataCache.on("changed",this.handleMetadataChange),this.initialized=!0}cleanup(){this.initialized&&(j("VaultDataManager: Cleaning up event listeners"),this.debouncedRefreshNotes.cancel(),this.debouncedRefreshFolders.cancel(),this.debouncedRefreshTagsFrontmatter.cancel(),this.debouncedRefreshTagsAll.cancel(),this.app?.vault&&(this.app.vault.off("create",this.handleFileCreate),this.app.vault.off("delete",this.handleFileDelete),this.app.vault.off("rename",this.handleFileRename),this.app.vault.off("modify",this.handleFileModify)),this.app?.metadataCache&&this.app.metadataCache.off("changed",this.handleMetadataChange),this.initialized=!1)}unload(){this.cleanup()}};q$.instance=null;Hee=q$});function Axe(t=!1){let e=Ar(yQe,{store:on});return(0,Jin.useMemo)(()=>{let n;return t?n=[...e]:n=e.filter(r=>r.extension==="md"||r.extension==="canvas"),n.sort((r,o)=>o.stat.ctime-r.stat.ctime)},[e,t])}var Jin,_Qe=b(()=>{Jin=L(B());Us();Wee();Se()});function Xin(){return Ar(vQe,{store:on})}var Qin=b(()=>{Us();Wee();Se()});function J0r(t){try{let e=Sl(t),n=e.getLeaves(),r=[];for(let o of n){let i=e.getPageInfo(o),s=o.view,a=!!i.url?.trim(),l=!!i.title?.trim();if(!a&&!l)continue;let c=s.webviewMounted===void 0||s.webviewFirstLoadFinished===void 0?!0:!!(s.webviewMounted&&s.webviewFirstLoadFinished),u=a&&c;r.push({url:i.url||"",title:i.title||void 0,faviconUrl:i.faviconUrl||void 0,isLoaded:u})}return r.sort((o,i)=>{if(o.isLoaded!==i.isLoaded)return o.isLoaded?-1:1;let s=o.url||o.title||"",a=i.url||i.title||"";return s.localeCompare(a)}),r}catch{return[]}}function X0r(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.url!==o.url||r.title!==o.title||r.faviconUrl!==o.faviconUrl||r.isLoaded!==o.isLoaded)return!1}return!0}function esn(t={}){let e=vn(),{enabled:n=!0}=t,[r,o]=(0,yV.useState)([]),i=(0,yV.useRef)(null);return(0,yV.useEffect)(()=>{if(!n){o([]);return}if(!Ln()){o([]);return}let s=!1,a=()=>{if(s)return;let m=J0r(e);o(h=>X0r(h,m)?h:m)},l=()=>{s||i.current===null&&(i.current=window.requestAnimationFrame(()=>{i.current=null,a()}))};a();let u=Sl(e).subscribeToWebviewLoad(l),d=e.workspace.on("layout-change",l),f=e.workspace.on("active-leaf-change",l),p=window.setInterval(l,Y0r);return()=>{s=!0,i.current!==null&&(window.cancelAnimationFrame(i.current),i.current=null),window.clearInterval(p),e.workspace.offref(d),e.workspace.offref(f),u()}},[e,n]),r}var yV,Y0r,tsn=b(()=>{yV=L(B());ko();$n();T$();Y0r=6e3});function RS(){let t=vn(),[e,n]=(0,Mxe.useState)(()=>{if(!Ln())return Exe;try{return Sl(t).getActiveWebTabState()}catch{return Exe}});return(0,Mxe.useEffect)(()=>{if(!Ln()){n(Exe);return}let r;try{let o=Sl(t);n(o.getActiveWebTabState()),r=o.subscribeActiveWebTabState(n)}catch{n(Exe)}return()=>{r?.()}},[t]),e}var Mxe,Exe,vV=b(()=>{Mxe=L(B());$n();ko();T$();Exe={activeWebTabForMentions:null,activeOrLastWebTab:null}});function Oxe(t,e,n,r,o,i,s=null,a=NS){let l=Axe(r),c=Xin(),u=Ln()&&(e==="category"&&t.trim().length>0||e==="search"&&n==="webTabs"),d=esn({enabled:u}),{activeWebTabForMentions:f}=RS(),p=(0,su.useMemo)(()=>l.map((y,w)=>({key:`note-${y.basename}-${w}`,title:y.basename,subtitle:y.path,category:"notes",data:y,content:void 0,icon:su.default.createElement(Jo,{className:"tw-size-4"}),searchKeyword:y.path})),[l]),m=(0,su.useMemo)(()=>o?gV.map(y=>({key:`tool-${y}`,title:y,subtitle:gQe(y),category:"tools",data:y,content:gQe(y),icon:su.default.createElement(Pw,{className:"tw-size-4"})})):[],[o]),h=(0,su.useMemo)(()=>c.map(y=>({key:`folder-${y.path}`,title:y.name,subtitle:y.path,category:"folders",data:y,content:void 0,icon:su.default.createElement(Fl,{className:"tw-size-4"}),searchKeyword:y.path})),[c]),g=(0,su.useMemo)(()=>Ln()?d.map((y,w)=>{let _=y.isLoaded!==!1;return{key:`webtab-${y.url||y.title||w}-${w}`,title:y.title||"Untitled",subtitle:_?y.url:"Tab not loaded",category:"webTabs",data:y,content:void 0,disabled:!_,disabledReason:"Switch to this tab to load it first",icon:_?su.default.createElement(Xo,{className:"tw-size-4"}):su.default.createElement(OC,{className:"tw-size-4 tw-text-muted"}),searchKeyword:`${y.title||""} ${y.url||""}`}}):[],[d]),v=(0,su.useMemo)(()=>a.map(y=>({key:`agent-${y.id}`,title:y.displayName,subtitle:void 0,category:"agents",data:y.id,content:void 0,icon:su.default.createElement(y.Icon,{className:"tw-size-4"}),trailingContent:y.needsSelfHostWarning?su.default.createElement(Fy):void 0,searchKeyword:`${y.displayName} ${y.id}`})),[a]);return(0,su.useMemo)(()=>{if(e==="category"){if(!t){let U=i.map(K=>({...K,content:void 0})),V=[];return f&&V.push({key:"active-web-tab",title:"Active Web Tab",subtitle:void 0,category:"activeWebTab",data:f,content:void 0,icon:su.default.createElement(Xo,{className:"tw-size-4"})}),s&&V.push({key:`active-note-${s.path}`,title:"Active Note",subtitle:void 0,category:"activeNote",data:s,content:void 0,icon:su.default.createElement(DC,{className:"tw-size-4"})}),V.length>0?[...V,...U]:U}let y=t.toLowerCase(),w=m.filter(U=>U.title.toLowerCase().includes(y)),_=v.filter(U=>U.title.toLowerCase().includes(y)||typeof U.data=="string"&&U.data.toLowerCase().includes(y)),C="active note".includes(y)&&s?{key:`active-note-${s.path}`,title:"Active Note",subtitle:void 0,category:"activeNote",data:s,content:void 0,icon:su.default.createElement(DC,{className:"tw-size-4"})}:null,P="active web tab".includes(y)&&f?{key:"active-web-tab",title:"Active Web Tab",subtitle:void 0,category:"activeWebTab",data:f,content:void 0,icon:su.default.createElement(Xo,{className:"tw-size-4"})}:null,E=[...p,...h,...g],$=xQe.default.go(t,E,{keys:["searchKeyword"],limit:Vee,threshold:-1e4}).map(U=>U.obj);return[..._,...w,...P?[P]:[],...C?[C]:[],...$].slice(0,Vee)}else{let y=[];switch(n){case"agents":y=v;break;case"notes":y=p;break;case"tools":y=m;break;case"folders":y=h;break;case"webTabs":y=g;break}if(!t){if(n==="notes"){let _=E2(),S=y.filter(C=>!(typeof C.data=="object"&&"path"in C.data&&typeof C.data.path=="string"&&C.data.path.startsWith(_+"/"))),I=y.filter(C=>typeof C.data=="object"&&"path"in C.data&&typeof C.data.path=="string"&&C.data.path.startsWith(_+"/"));return[...S,...I].slice(0,Vee)}return y.slice(0,Vee)}return xQe.default.go(t,y,{keys:["title","subtitle"],limit:Vee,threshold:-1e4}).map(_=>_.obj)}},[e,t,n,p,m,h,g,v,i,f,s])}var su,xQe,Vee,SQe=b(()=>{su=L(B());$n();Re();xQe=L(zee());Ixe();Txe();_Qe();Qin();tsn();vV();pM();Is();qj();Vee=30});function Q0r(t){return"data"in t}function eTr(t){return"icon"in t&&!("data"in t)}function Nxe({isOpen:t,onClose:e,onSelect:n,isCopilotPlus:r=!1,showTools:o=!1,currentActiveFile:i=null}){let[s,a]=(0,Pg.useState)(""),[l,c]=(0,Pg.useState)(0),[u,d]=(0,Pg.useState)({mode:"category"}),[f,p]=(0,Pg.useState)(t),[m,h]=(0,Pg.useState)(0),g=Cxe(o),v=Oxe(s,u.mode,u.selectedCategory,r,o,g,i),y=(0,Pg.useCallback)(I=>{if(!I?.disabled){if(u.mode==="category"&&eTr(I)&&!s){if(I.isAction){n(I.category,null),e();return}d(C=>({...C,mode:"search",selectedCategory:I.category})),a(""),c(0);return}Q0r(I)&&(n(I.category,I.data),e())}},[u.mode,s,n,e]),w=(0,Pg.useCallback)(I=>{c(I)},[]),_=(0,Pg.useCallback)(I=>{a(I),c(0)},[]),S=(0,Pg.useCallback)(I=>{switch(I.key){case"ArrowDown":{I.preventDefault();let C=l+1;for(;C<v.length&&v[C]?.disabled;)C++;C>=v.length&&(C=l),c(C);break}case"ArrowUp":{I.preventDefault();let C=l-1;for(;C>=0&&v[C]?.disabled;)C--;C<0&&(C=l),c(C);break}case"Enter":case"Tab":{I.preventDefault();let C=v[l];if(C?.disabled)break;C&&y(C);break}case"Escape":{I.preventDefault(),e();break}case"Backspace":{u.mode==="search"&&!s&&(I.preventDefault(),d({mode:"category",selectedCategory:void 0}),c(0));break}}},[l,v,y,e,u.mode,s]);return t!==f&&(p(t),t||(a(""),c(0),d({mode:"category",selectedCategory:void 0}))),v.length!==m&&(h(v.length),c(0)),t?Pg.default.createElement(Kin,{options:v,selectedIndex:l,onSelect:y,onHighlight:w,query:s,mode:u.mode,showPreview:!1,searchBarMode:!0,searchQuery:s,onSearchChange:_,onKeyDown:S}):null}var Pg,CQe=b(()=>{Pg=L(B());Gin();pM();SQe()});var Ei,tTr,nsn,rsn=b(()=>{Re();Ei=L(B());$n();yt();MJe();xxe();es();ko();ut();I$();CQe();Gb();tTr=[],nsn=({includeActiveNote:t,currentActiveFile:e,includeActiveWebTab:n,activeWebTab:r,contextNotes:o,contextUrls:i,contextFolders:s,contextWebTabs:a,selectedTextContexts:l=tTr,onRemoveContext:c,showIndexingCard:u,onTypeaheadSelect:d,lexicalEditorRef:f,hideAddContextButton:p=!1,isAgentMode:m=!1})=>{let h=vn(),[g]=Cw(),[v]=kT(),[y,w]=(0,Ei.useState)(!1),_=(0,Ei.useRef)(null),S=sd(g),I=()=>{w(!1)},C=(K,se)=>{d(K,se),window.setTimeout(()=>{f?.current&&f.current.focus()},100)},k=K=>{Qdt(h,K)},T=Ei.default.useMemo(()=>{let K=new Map(o.map(se=>[se.path,se]));return Array.from(K.values())},[o]),P=Ei.default.useMemo(()=>Array.from(new Set(i)),[i]),E=Ei.default.useMemo(()=>UI(a),[a]),O=l.length>0,$=t&&!O&&!!e,U=n&&!O&&!!r&&Ln(),V=T.length>0||P.length>0||l.length>0||s.length>0||E.length>0||$||U;return m&&!V?null:Ei.default.createElement("div",{className:"tw-flex tw-w-full tw-items-start tw-gap-1"},!p&&Ei.default.createElement("div",{className:"tw-flex tw-h-full tw-items-start"},Ei.default.createElement(nc,{open:y,onOpenChange:w},Ei.default.createElement(Ku,{asChild:!0},Ei.default.createElement(oe,{ref:_,variant:"ghost2",size:"fit",className:"tw-ml-1 tw-rounded-sm tw-border tw-border-solid tw-border-border tw-text-muted"},Ei.default.createElement("span",{className:"tw-text-base tw-font-medium tw-leading-none"},"@"),!V&&Ei.default.createElement("span",{className:"tw-pr-1 tw-text-sm tw-leading-4"},"Add context"))),Ei.default.createElement(Cl,{className:"tw-w-[400px] tw-p-0",align:"start",side:"top",sideOffset:4},Ei.default.createElement(Nxe,{isOpen:y,onClose:I,onSelect:C,isCopilotPlus:S,currentActiveFile:e})))),Ei.default.createElement("div",{className:"tw-flex tw-flex-1 tw-flex-wrap tw-gap-1"},$&&e&&Ei.default.createElement(inn,{currentActiveFile:e,onRemove:()=>c("activeNote",""),onClick:()=>k(e)}),U&&r&&Ei.default.createElement(snn,{activeWebTab:r,onRemove:()=>c("activeWebTab","")}),T.map(K=>Ei.default.createElement(p_e,{key:K.path,note:K,onRemove:()=>c("notes",K.path),onClick:()=>k(K)})),P.map(K=>Ei.default.createElement(m_e,{key:K,url:K,onRemove:()=>c("urls",K)})),s.map(K=>Ei.default.createElement(g_e,{key:K,folder:K,onRemove:()=>c("folders",K)})),E.map(K=>Ei.default.createElement(h_e,{key:K.url,webTab:K,onRemove:()=>c("webTabs",K.url)})),l.map(K=>Ei.default.createElement(y_e,{key:K.id,selectedText:K,onRemove:()=>c("selectedText",K.id)}))),v.isActive&&u&&Ei.default.createElement(Ei.default.Fragment,null,Ei.default.createElement(Lv,{orientation:"vertical"}),Ei.default.createElement(oe,{variant:"ghost2",size:"fit",className:"tw-text-muted",onClick:u},Ei.default.createElement(Dr,{className:"tw-size-3 tw-animate-spin"}),Ei.default.createElement("span",{className:"tw-text-xs"},"Indexing..."))))}});var osn,isn,ssn=b(()=>{osn=L(B());rsn();isn=({contextNotes:t,includeActiveNote:e,activeNote:n,includeActiveWebTab:r,activeWebTab:o,contextUrls:i,contextFolders:s,contextWebTabs:a,selectedTextContexts:l,showIndexingCard:c,lexicalEditorRef:u,onAddToContext:d,onRemoveFromContext:f,hideAddContextButton:p,isAgentMode:m})=>osn.default.createElement(nsn,{includeActiveNote:e,currentActiveFile:n,includeActiveWebTab:r,activeWebTab:o,contextNotes:t,onRemoveContext:(v,y)=>{f(v,y)},contextUrls:i,contextFolders:s,contextWebTabs:a,selectedTextContexts:l,showIndexingCard:c,onTypeaheadSelect:(v,y)=>{d(v,y)},lexicalEditorRef:u,hideAddContextButton:p,isAgentMode:m})});var Ag,asn,lsn=b(()=>{Ag=L(B());Re();yt();Gb();Oc();CQe();asn=({onSelect:t,isCopilotPlus:e,showTools:n=!1,currentActiveFile:r,lexicalEditorRef:o})=>{let[i,s]=(0,Ag.useState)(!1);return Ag.default.createElement(nc,{open:i,onOpenChange:s},Ag.default.createElement(sf,{delayDuration:0},Ag.default.createElement(hr,null,Ag.default.createElement(gr,{asChild:!0},Ag.default.createElement(Ku,{asChild:!0},Ag.default.createElement(oe,{variant:"ghost2",size:"icon",className:"tw-text-muted hover:tw-text-accent","aria-label":"Add context"},Ag.default.createElement(zs,{className:"tw-size-4"})))),Ag.default.createElement(fr,{className:"tw-px-1 tw-py-0.5"},"Add context"))),Ag.default.createElement(Cl,{className:"tw-w-[400px] tw-p-0",align:"start",side:"top",sideOffset:4,onCloseAutoFocus:a=>{a.preventDefault(),o?.current?.focus()}},Ag.default.createElement(Nxe,{isOpen:i,onClose:()=>s(!1),onSelect:t,isCopilotPlus:e,showTools:n,currentActiveFile:r})))}});function csn(t,e){let n=t.body.createEl("input",{cls:"tw-hidden",attr:{type:"file",accept:"image/*",multiple:!0}}),r=()=>{n.remove(),e.onSettle?.()};n.addEventListener("change",()=>{e.onFiles(Array.from(n.files??[])),r()},{once:!0}),n.addEventListener("cancel",r,{once:!0}),n.click()}var usn=b(()=>{});function Lxe({className:t}){return Rxe.default.createElement("span",{onClick:e=>e.stopPropagation(),className:J("tw-flex tw-shrink-0 tw-items-center tw-text-warning",t)},Rxe.default.createElement(rs,{content:nTr,side:"top",delayDuration:0},Rxe.default.createElement(Wr,{className:"tw-size-3.5"})))}var Rxe,nTr,kQe=b(()=>{De();Lh();Re();Rxe=L(B()),nTr="Free model. The provider may log or train on your prompts. Review their privacy terms before sending sensitive content."});function dsn({override:t,className:e}){let{models:n,value:r,effort:o,effortOptionsByModelKey:i,commitSelection:s,disabled:a}=t,[l,c]=(0,Cn.useState)(!1),[u,d]=(0,Cn.useState)(null),[f,p]=(0,Cn.useState)(null),[m,h]=(0,Cn.useState)(null),g=(0,Cn.useRef)({model:"",effort:null}),v=(0,Cn.useMemo)(()=>n.filter(O=>(O.enabled??!0)&&!O._disabledReason).map(O=>Jn(O)),[n]),y=n.find(O=>Jn(O)===r),w=o?.options.find(O=>O.value===o.value)?.label??null,_=o?.value??null;(0,Cn.useEffect)(()=>{if(l){let O=r&&v.includes(r)?r:v[0]??null;d(O),p(O);let $=O?i[O]??[]:[],U=O===r&&_!==null?_:$.length>0?$[0]?.value??null:null;h(U),g.current={model:r,effort:_}}},[l,r,v,_,i]);let S=(0,Cn.useMemo)(()=>f?i[f]??[]:[],[f,i]),I=(0,Cn.useCallback)(O=>{if(v.length===0)return;let $=u?v.indexOf(u):-1,U=($+O+v.length)%v.length;$===-1&&(U=O===1?0:v.length-1),d(v[U])},[v,u]),C=(0,Cn.useCallback)(O=>{p(O),d(O);let $=i[O]??[];if($.length===0){h(null);return}$.some(V=>V.value===m)||h(O===r&&_!==null?_:$[0]?.value??null)},[i,m,r,_]),k=(0,Cn.useCallback)(O=>{if(S.length===0)return;let $=S.findIndex(V=>V.value===m),U=Math.max(0,Math.min(S.length-1,($===-1?0:$)+O));h(S[U]?.value??null)},[S,m]),T=O=>{switch(O.key){case"ArrowDown":O.preventDefault(),I(1);break;case"ArrowUp":O.preventDefault(),I(-1);break;case"ArrowLeft":S.length>0&&(O.preventDefault(),k(-1));break;case"ArrowRight":S.length>0&&(O.preventDefault(),k(1));break;case"Enter":u&&(O.preventDefault(),C(u));break}},P=O=>{if(O){c(!0);return}if(f){let $=g.current,U=f!==$.model,V=m!==$.effort;U?s(f,m):V&&o&&o.onChange(m)}c(!1)},E;return Cn.default.createElement(nc,{open:l,onOpenChange:P},Cn.default.createElement(Ku,{asChild:!0},Cn.default.createElement(oe,{variant:"ghost2",size:"fit",disabled:a,className:J("tw-min-w-0 tw-justify-start tw-text-muted",e),title:"Model \xB7 effort"},Cn.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-1"},y?Cn.default.createElement(Xj,{model:y,iconSize:8}):Cn.default.createElement("span",{className:"tw-truncate"},"Select Model"),w&&Cn.default.createElement(Cn.default.Fragment,null,Cn.default.createElement("span",{className:"tw-text-faint","aria-hidden":!0},"\xB7"),Cn.default.createElement("span",{className:"tw-text-xs tw-text-muted"},w)),y?._needsSelfHostWarning&&Cn.default.createElement(Fy,{stopPropagation:!1})),!a&&Cn.default.createElement(Bs,{className:"tw-mt-0.5 tw-size-4 tw-shrink-0"}))),Cn.default.createElement(Cl,{className:"tw-w-[380px] tw-p-0",align:"start",side:"top",sideOffset:4,onKeyDown:T},Cn.default.createElement("div",{className:"tw-max-h-72 tw-overflow-y-auto tw-py-1",role:"listbox","aria-label":"Model"},n.map(O=>{let $=Jn(O),U=O._disabledReason,V=!!U,K=O._needsLicense?null:U??null,se=$===u,le=$===f,Q=O._group!==void 0&&O._group!==E,ne=`__group__${O._group}__${$}`;return E=O._group,Cn.default.createElement(Cn.default.Fragment,{key:$},Q&&Cn.default.createElement("div",{key:ne,className:"tw-px-3 tw-pb-1 tw-pt-2 tw-text-xs tw-uppercase tw-tracking-wide tw-text-faint"},O._group),Cn.default.createElement("div",{role:"option","aria-selected":le,"aria-disabled":V||void 0,className:J("tw-flex tw-cursor-pointer tw-items-center tw-justify-between tw-gap-3 tw-px-3 tw-py-1.5 tw-text-sm",se&&!V&&"tw-bg-interactive-hover",V&&"tw-cursor-not-allowed tw-opacity-50"),onClick:()=>{V||C($)},title:U??void 0},Cn.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-2"},Cn.default.createElement("span",{className:"tw-flex tw-w-3 tw-shrink-0 tw-items-center tw-justify-center tw-text-xs tw-text-muted","aria-hidden":!0},le?"\u2713":se?"\u203A":""),Cn.default.createElement("div",{className:"tw-min-w-0"},Cn.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-1"},Cn.default.createElement(Xj,{model:O,iconSize:12}),O._needsLicense&&Cn.default.createElement(F6,null),O._isFree&&Cn.default.createElement(Lxe,null),O._needsSelfHostWarning&&Cn.default.createElement(Fy,null)),O._subtitle&&Cn.default.createElement("div",{className:"tw-truncate tw-text-xs tw-text-muted"},O._subtitle))),K&&Cn.default.createElement("span",{className:"tw-shrink-0 tw-text-xs tw-text-faint"},K)))})),Cn.default.createElement("div",{className:"tw-border-t tw-border-solid tw-border-border tw-bg-secondary tw-px-3 tw-py-2"},Cn.default.createElement(rTr,{options:S,value:m,onChange:h}))))}function rTr({options:t,value:e,onChange:n}){let r=t.length>0,o=r?Math.max(0,t.findIndex(s=>s.value===e)):0,i=r?t[o]?.label??"":"n/a";return Cn.default.createElement("div",{className:"tw-flex tw-h-6 tw-items-center tw-justify-between tw-gap-3"},Cn.default.createElement("span",{className:"tw-font-mono tw-text-[10px] tw-uppercase tw-tracking-wider tw-text-muted"},"Effort"),Cn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-3"},r?Cn.default.createElement(oTr,{options:t,value:e,onChange:n}):Cn.default.createElement("div",{className:"tw-h-6 tw-w-[140px]","aria-hidden":!0}),Cn.default.createElement("span",{className:J("tw-w-[72px] tw-truncate tw-rounded-md tw-px-2 tw-py-0.5 tw-text-center tw-font-mono tw-text-xs tw-font-medium",r?"tw-bg-interactive-accent-hsl/10 tw-text-accent":"tw-border tw-border-dashed tw-border-border tw-italic tw-text-faint")},i)))}function oTr({options:t,value:e,onChange:n}){let r=Math.max(0,t.findIndex(i=>i.value===e)),o=Math.max(1,t.length-1);return Cn.default.createElement(kX,{min:0,max:o,step:1,value:[r],onValueChange:([i])=>{if(typeof i!="number")return;let s=Math.max(0,Math.min(t.length-1,i));n(t[s]?.value??null)},"aria-label":"Effort",className:"tw-relative tw-flex tw-h-6 tw-w-[140px] tw-touch-none tw-select-none tw-items-center"},Cn.default.createElement(lve,{className:"tw-relative tw-mx-1.5 tw-h-0.5 tw-w-full tw-grow tw-rounded-full tw-bg-[var(--background-modifier-border)]"},Cn.default.createElement(cve,{className:"tw-absolute tw-h-full tw-rounded-full tw-bg-interactive-accent"})),Cn.default.createElement("div",{className:"tw-pointer-events-none tw-absolute tw-inset-x-1.5 tw-top-1/2 -tw-translate-y-1/2"},t.map((i,s)=>{let a=t.length===1?50:s/(t.length-1)*100,l=s<=r;return Cn.default.createElement("span",{key:String(i.value??`__default__${s}`),"aria-hidden":!0,className:J("tw-absolute tw-top-1/2 tw-size-1.5 -tw-translate-x-1/2 -tw-translate-y-1/2 tw-rounded-full",l?"tw-bg-interactive-accent":"tw-border-[1.5px] tw-border-solid tw-border-border tw-bg-primary"),style:{left:`${a}%`}})})),Cn.default.createElement(uve,{"aria-label":"Effort",className:"tw-flex tw-size-6 tw-items-center tw-justify-center tw-rounded-full tw-border-[1.5px] tw-border-solid tw-border-border tw-bg-primary tw-shadow-sm tw-transition-colors focus-visible:tw-outline-none focus-visible:tw-ring-2 focus-visible:tw-ring-ring focus-visible:tw-ring-offset-1 disabled:tw-pointer-events-none disabled:tw-opacity-50"},Cn.default.createElement("span",{"aria-hidden":!0,className:"tw-size-2 tw-rounded-full tw-bg-interactive-accent"})))}var Cn,fsn=b(()=>{Cn=L(B());Re();X9e();yt();kQe();v_e();qj();Gb();MZ();eK();De()});function iTr(t){return psn[t]?.label??t}function msn({override:t,className:e}){let{options:n,value:r,onChange:o,disabled:i}=t,s=r?iTr(r):"Mode";return Eg.default.createElement(up,null,Eg.default.createElement(dp,{asChild:!0},Eg.default.createElement(oe,{variant:"ghost2",size:"sm",disabled:i,className:J("tw-shrink-0 tw-text-muted",r==="plan"&&"tw-text-blue/70 hover:tw-text-blue/100 focus-visible:tw-text-blue/100",r==="auto"&&"tw-text-red/70 hover:tw-text-red/100 focus-visible:tw-text-red/100",e),title:"Operational mode"},Eg.default.createElement("span",{className:"tw-truncate"},s),!i&&Eg.default.createElement(Bs,{className:"tw-mt-0.5 tw-size-4 tw-shrink-0"}))),Eg.default.createElement(Ac,{align:"start",className:"tw-w-[320px]"},n.map(a=>{let l=psn[a.value],c=r===a.value;return Eg.default.createElement(co,{key:a.value,onSelect:()=>o(a.value),className:"tw-items-start tw-gap-2 tw-py-2"},Eg.default.createElement("div",{className:"tw-mt-0.5 tw-w-3 tw-shrink-0"},c&&Eg.default.createElement(Hr,{className:"tw-size-3 tw-text-muted"})),Eg.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-0.5"},Eg.default.createElement("span",{className:"tw-text-sm tw-font-medium tw-text-normal"},l?.label??a.label),l?.description&&Eg.default.createElement("span",{className:"tw-text-xs tw-leading-snug tw-text-muted"},l.description)))})))}var Eg,psn,hsn=b(()=>{Eg=L(B());Re();yt();xk();De();psn={auto:{label:"Auto",description:"Uses the agent's Auto permissions for tools and edits."},plan:{label:"Plan",description:"Drafts a plan and waits for your approval before editing."},default:{label:"Safe",description:"Asks for approval before every edit."}}});function au({children:t,className:e,...n}){return gsn.default.createElement(ei,{variant:"secondary",className:J("tw-mx-0.5 tw-inline-flex tw-items-center tw-gap-1 tw-border tw-border-solid tw-border-border tw-px-2 tw-py-0 tw-align-middle tw-text-xs",e),...n},t)}var gsn,f0=b(()=>{gsn=L(B());pm();De()});function rh(t){return t.getRootElement()?.doc??activeDocument}var ysn,ed,p0=b(()=>{ysn=L(B());$o();f0();ed=class extends hxe{constructor(e,n){super(n),this.__value=e}updateDOM(){return!1}isInline(){return!0}canInsertTextBefore(){return!0}canInsertTextAfter(){return!0}canBeEmpty(){return!1}isKeyboardSelectable(){return!0}isIsolated(){return!0}isPill(){return!0}getValue(){return this.__value}setValue(e){let n=this.getWritable();n.__value=e}getTextContent(){return this.__value}createDOM(e,n){return rh(n).win.createSpan(this.getClassName())}exportDOM(e){return{element:rh(e).win.createSpan({text:this.__value,attr:{[this.getDataAttribute()]:"","data-pill-value":this.__value}})}}exportJSON(){return{...super.exportJSON(),value:this.__value,type:this.getType(),version:1}}decorate(){return ysn.default.createElement(au,null,this.__value)}}});function LS({content:t,openBracket:e,closeBracket:n,className:r,maxWidth:o="tw-max-w-40",tooltipContent:i}){let s=(0,Mg.useRef)(null),[a,l]=(0,Mg.useState)(!1);return Mg.default.createElement(sf,{delayDuration:300},Mg.default.createElement(hr,{open:a,onOpenChange:u=>{let d=s.current?s.current.offsetWidth<s.current.scrollWidth:!1;l(u&&d)}},Mg.default.createElement(gr,{asChild:!0},Mg.default.createElement("span",{className:J("tw-inline-flex tw-items-center",o,r)},Mg.default.createElement("span",{className:"tw-shrink-0"},e),Mg.default.createElement("span",{ref:s,className:"tw-min-w-0 tw-truncate"},t),Mg.default.createElement("span",{className:"tw-shrink-0"},n))),Mg.default.createElement(fr,{className:"tw-max-w-64 tw-text-wrap tw-break-words"},i||`${e}${t}${n}`)))}var Mg,qee=b(()=>{Mg=L(B());De();Oc()});function sTr(t){let e=t.getAttribute("data-note-title"),n=t.getAttribute("data-note-path");return e&&n?{node:Kee(e,n)}:null}function aTr({node:t}){let e=t.getNoteTitle(),n=t.getNotePath(),r=n.toLowerCase(),o=r.endsWith(".pdf"),i=r.endsWith(".canvas");return mM.default.createElement(au,null,mM.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},mM.default.createElement(LS,{content:e,openBracket:"[[",closeBracket:"]]",tooltipContent:mM.default.createElement("div",{className:"tw-text-left"},n)}),o&&mM.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"pdf"),i&&mM.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"canvas")))}function Kee(t,e){return new hM(t,e)}function IQe(t){return t instanceof hM}function vsn(t){let e=ho(),n=0;function r(o){if(IQe(o)&&o.getNotePath()===t)o.remove(),n++;else if("getChildren"in o&&typeof o.getChildren=="function"){let i=o.getChildren();for(let s of i)r(s)}}return r(e),n}var mM,hM,wV=b(()=>{mM=L(B());$o();p0();qee();f0();hM=class t extends ed{static getType(){return"note-pill"}static clone(e){return new t(e.__noteTitle,e.__notePath,e.__key)}constructor(e,n,r){super(e,r),this.__noteTitle=e,this.__notePath=n}getClassName(){return"note-pill-wrapper"}getDataAttribute(){return"data-lexical-note-pill"}static importDOM(){return{span:e=>e.hasAttribute("data-lexical-note-pill")?{conversion:sTr,priority:1}:null}}static importJSON(e){let{noteTitle:n,notePath:r}=e;return Kee(n,r)}exportJSON(){return{...super.exportJSON(),noteTitle:this.__noteTitle,notePath:this.__notePath,type:"note-pill",version:1}}exportDOM(e){let n=this.__notePath.toLowerCase(),r=n.endsWith(".pdf")?`${this.__noteTitle}.pdf`:n.endsWith(".canvas")?`${this.__noteTitle}.canvas`:this.__noteTitle;return{element:rh(e).win.createSpan({text:`[[${r}]]`,attr:{"data-lexical-note-pill":"true","data-note-title":this.__noteTitle,"data-note-path":this.__notePath}})}}getTextContent(){let e=this.__notePath.toLowerCase();return`[[${e.endsWith(".pdf")?`${this.__noteTitle}.pdf`:e.endsWith(".canvas")?`${this.__noteTitle}.canvas`:this.__noteTitle}]]`}getNoteTitle(){return this.__noteTitle}getNotePath(){return this.__notePath}decorate(){return mM.default.createElement(aTr,{node:this})}}});function bsn(){let t=(0,gM.useContext)(wsn);return t===void 0?null:t.currentActiveFile}function $xe({currentActiveFile:t,children:e}){let n=(0,gM.useMemo)(()=>({currentActiveFile:t}),[t]);return gM.default.createElement(wsn.Provider,{value:n},e)}var gM,wsn,Dxe=b(()=>{gM=L(B()),wsn=(0,gM.createContext)(void 0)});function lTr(t){return{node:Gee()}}function cTr(){let t=bsn();if(!t)return $v.default.createElement(au,null,$v.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},$v.default.createElement(LS,{content:"activeNote",openBracket:"{",closeBracket:"}",tooltipContent:$v.default.createElement("div",{className:"tw-text-left"},"Will use the active note at the time the message is sent")})));let e=t.basename,n=t.path,r=n.toLowerCase().endsWith(".pdf");return $v.default.createElement(au,null,$v.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},$v.default.createElement(LS,{content:e,openBracket:"[[",closeBracket:"]]",tooltipContent:$v.default.createElement("div",{className:"tw-text-left"},n)}),$v.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"Current"),r&&$v.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"pdf")))}function Gee(){return new yM}function TQe(t){return t instanceof yM}function _sn(){let t=ho(),e=0;function n(r){if(TQe(r))r.remove(),e++;else if("getChildren"in r&&typeof r.getChildren=="function"){let o=r.getChildren();for(let i of o)n(i)}}return n(t),e}var $v,yM,bV=b(()=>{$v=L(B());$o();p0();qee();f0();Dxe();yM=class t extends ed{static getType(){return"active-note-pill"}static clone(e){return new t(e.__key)}constructor(e){super("Current Note",e)}getClassName(){return"active-note-pill-wrapper"}getDataAttribute(){return"data-lexical-active-note-pill"}static importDOM(){return{span:e=>e.hasAttribute("data-lexical-active-note-pill")?{conversion:lTr,priority:2}:null}}static importJSON(e){return Gee()}exportJSON(){return{...super.exportJSON(),type:"active-note-pill",version:1}}exportDOM(e){return{element:rh(e).win.createSpan({text:"{activeNote}",attr:{"data-lexical-active-note-pill":"true"}})}}getTextContent(){return"{activeNote}"}decorate(){return $v.default.createElement(cTr,null)}}});function uTr(t){let e=t.getAttribute("data-url"),n=t.getAttribute("data-title");return e!==null?{node:Fxe(e,n||void 0)}:null}function Fxe(t,e,n=!1){return new K$(t,e,n)}function dTr(){let t=ho(),e=[];function n(r){if(r instanceof K$&&e.push(r),"getChildren"in r&&typeof r.getChildren=="function"){let o=r.getChildren();for(let i of o)n(i)}}return n(t),e}function xsn(t){let e=dTr();for(let n of e)n.getURL()===t&&n.remove()}function Ssn(t){return t instanceof K$}var Zee,K$,Yee=b(()=>{Zee=L(B());$o();p0();f0();K$=class t extends ed{static getType(){return"url-pill"}static clone(e){return new t(e.__url,e.__title,e.__isActive,e.__key)}constructor(e,n,r=!1,o){super(e,o),this.__url=e,this.__title=n,this.__isActive=r}getClassName(){return"url-pill-wrapper"}getDataAttribute(){return"data-lexical-url-pill"}static importDOM(){return{span:e=>e.hasAttribute("data-lexical-url-pill")?{conversion:uTr,priority:1}:null}}static importJSON(e){let{url:n,title:r,isActive:o}=e;return Fxe(n,r,o)}exportJSON(){return{...super.exportJSON(),url:this.__url,title:this.__title,isActive:this.__isActive,type:"url-pill",version:1}}exportDOM(e){let n=rh(e).win.createSpan({text:this.__url,attr:{"data-lexical-url-pill":"true","data-url":this.__url}});return this.__title&&n.setAttribute("data-title",this.__title),{element:n}}getTextContent(){return this.__url}getURL(){return this.__url}setURL(e){let n=this.getWritable();n.__url=e}getTitle(){return this.__title}setTitle(e){let n=this.getWritable();n.__title=e}setActive(e){let n=this.getWritable();n.__isActive=e}getActive(){return this.__isActive}decorate(){let e=this.__title||this.__url;return Zee.default.createElement(au,{className:"tw-whitespace-nowrap"},Zee.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Zee.default.createElement("span",{className:"tw-max-w-40 tw-truncate"},e),this.__isActive&&Zee.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"Active")))}}});function fTr(t){let e=t.getAttribute("data-pill-value");return e!==null?{node:Jee(e)}:null}function Jee(t){return new m0(t)}function Csn(t){return t instanceof m0}function pTr(){let t=ho(),e=[];function n(r){if(r instanceof m0&&e.push(r),"getChildren"in r&&typeof r.getChildren=="function"){let o=r.getChildren();for(let i of o)n(i)}}return n(t),e}function ksn(t){let e=pTr();for(let n of e)n.getValue()===t&&n.remove()}var Uxe,m0,_V=b(()=>{Uxe=L(B());$o();p0();qee();f0();m0=class t extends ed{static getType(){return"folder-pill"}static clone(e){return new t(e.__value,e.__key)}constructor(e,n){super(e,n)}getClassName(){return"folder-pill-wrapper"}getDataAttribute(){return"data-lexical-folder-pill"}static importDOM(){return{span:e=>e.hasAttribute("data-lexical-folder-pill")?{conversion:fTr,priority:1}:null}}static importJSON(e){let{value:n}=e;return Jee(n)}exportJSON(){return{...super.exportJSON(),type:"folder-pill"}}decorate(){let e=Uxe.default.createElement("div",{className:"tw-text-left"},this.getFolderPath());return Uxe.default.createElement(au,null,Uxe.default.createElement(LS,{content:this.getFolderPath(),openBracket:"{",closeBracket:"}",tooltipContent:e}))}getTextContent(){return`{${this.getFolderPath()}}`}exportDOM(e){return{element:rh(e).win.createSpan({text:`{${this.getFolderPath()}}`,attr:{[this.getDataAttribute()]:"","data-pill-value":this.__value}})}}getFolderPath(){return this.getValue()}}});function mTr(t){let e=t.getAttribute("data-pill-value");return e!==null?{node:Z$(e)}:null}function Z$(t){return new G$(t)}function Isn(t){return t instanceof G$}function hTr(){let t=ho(),e=[];function n(r){if(r instanceof G$&&e.push(r),"getChildren"in r&&typeof r.getChildren=="function"){let o=r.getChildren();for(let i of o)n(i)}}return n(t),e}function Tsn(t){let e=hTr();for(let n of e)n.getValue()===t&&n.remove()}var G$,Xee=b(()=>{$o();p0();G$=class t extends ed{static getType(){return"tool-pill"}static clone(e){return new t(e.__value,e.__key)}constructor(e,n){super(e,n)}getClassName(){return"tool-pill-wrapper"}getDataAttribute(){return"data-lexical-tool-pill"}static importDOM(){return{span:e=>e.hasAttribute("data-lexical-tool-pill")?{conversion:mTr,priority:1}:null}}static importJSON(e){let{value:n}=e;return Z$(n)}exportJSON(){return{...super.exportJSON(),type:"tool-pill"}}getToolName(){return this.getValue()}}});function gTr(t){return{node:jxe()}}function yTr(){let{activeWebTabForMentions:t}=RS();return Ln()?t?Ld.default.createElement(au,null,Ld.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Ld.default.createElement(Xo,{className:"tw-size-3"}),Ld.default.createElement("span",{className:"tw-max-w-40 tw-truncate",title:t.url},t.title??"Untitled"),Ld.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"Current"))):Ld.default.createElement(au,null,Ld.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Ld.default.createElement(Xo,{className:"tw-size-3"}),Ld.default.createElement(LS,{content:"activeWebTab",openBracket:"{",closeBracket:"}",tooltipContent:Ld.default.createElement("div",{className:"tw-text-left"},"Will use the active web tab at the time the message is sent")}))):Ld.default.createElement(au,null,Ld.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Ld.default.createElement(Xo,{className:"tw-size-3"}),Ld.default.createElement(LS,{content:"activeWebTab",openBracket:"{",closeBracket:"}",tooltipContent:Ld.default.createElement("div",{className:"tw-text-left"},"Web Viewer not supported on mobile")})))}function jxe(){return new vM}function PQe(t){return t instanceof vM}function Psn(){let t=ho(),e=0;function n(r){if(PQe(r))r.remove(),e++;else if("getChildren"in r&&typeof r.getChildren=="function"){let o=r.getChildren();for(let i of o)n(i)}}return n(t),e}var Ld,vM,xV=b(()=>{Ld=L(B());$o();Re();$n();gt();p0();qee();f0();vV();vM=class t extends ed{static getType(){return"active-web-tab-pill"}static clone(e){return new t(e.__key)}constructor(e){super("Current Web Tab",e)}getClassName(){return"active-web-tab-pill-wrapper"}getDataAttribute(){return"data-lexical-active-web-tab-pill"}static importDOM(){return{span:e=>e.hasAttribute("data-lexical-active-web-tab-pill")?{conversion:gTr,priority:2}:null}}static importJSON(e){return jxe()}exportJSON(){return{...super.exportJSON(),type:"active-web-tab-pill",version:1}}exportDOM(e){return{element:rh(e).win.createSpan({text:vC,attr:{"data-lexical-active-web-tab-pill":"true"}})}}getTextContent(){return vC}decorate(){return Ld.default.createElement(yTr,null)}}});function Asn(t,e){return`[\u{1F310}: ${e?.trim()||tN(t)||"Untitled"}]`}function vTr(t){let e=t.getAttribute("data-url"),n=t.getAttribute("data-title"),r=t.getAttribute("data-favicon-url");return e!==null?{node:Bxe(e,n||void 0,r||void 0)}:null}function Bxe(t,e,n){return new h0(t,e,n)}function Esn(t){return t instanceof h0}function AQe(){let t=ho(),e=[];function n(r){if(r instanceof h0&&e.push(r),"getChildren"in r&&typeof r.getChildren=="function"){let o=r.getChildren();for(let i of o)n(i)}}return n(t),e}function Msn(t){let e=AQe();for(let n of e)n.getURL()===t&&n.remove()}var Qee,h0,SV=b(()=>{Qee=L(B());$o();Re();ut();p0();f0();h0=class t extends ed{static getType(){return"web-tab-pill"}static clone(e){return new t(e.__url,e.__title,e.__faviconUrl,e.__key)}constructor(e,n,r,o){super(e,o),this.__url=e,this.__title=n,this.__faviconUrl=r}getClassName(){return"web-tab-pill-wrapper"}getDataAttribute(){return"data-lexical-web-tab-pill"}static importDOM(){return{span:e=>e.hasAttribute("data-lexical-web-tab-pill")?{conversion:vTr,priority:1}:null}}static importJSON(e){let{url:n,title:r,faviconUrl:o}=e;return Bxe(n,r,o)}exportJSON(){return{...super.exportJSON(),url:this.__url,title:this.__title,faviconUrl:this.__faviconUrl,type:"web-tab-pill",version:1}}exportDOM(e){let n=rh(e).win.createSpan({text:Asn(this.__url,this.__title),attr:{"data-lexical-web-tab-pill":"true","data-url":this.__url}});return this.__title&&n.setAttribute("data-title",this.__title),this.__faviconUrl&&n.setAttribute("data-favicon-url",this.__faviconUrl),{element:n}}getTextContent(){return Asn(this.__url,this.__title)}getURL(){return this.__url}getTitle(){return this.__title}getFaviconUrl(){return this.__faviconUrl}setTitle(e){let n=this.getWritable();n.__title=e}setFaviconUrl(e){let n=this.getWritable();n.__faviconUrl=e}decorate(){let e=this.__title||this.__url;return Qee.default.createElement(au,{className:"tw-whitespace-nowrap"},Qee.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Qee.default.createElement(Xo,{className:"tw-size-3"}),Qee.default.createElement("span",{className:"tw-max-w-40 tw-truncate"},e)))}}});var EQe={};sr(EQe,{LexicalComposerContext:()=>Osn,createLexicalComposerContext:()=>wTr,useLexicalComposerContext:()=>bTr});function wTr(t,e){let n=null;return t!=null&&(n=t[1]),{getTheme:function(){return e??(n!=null?n.getTheme():null)}}}function bTr(){let t=(0,zxe.useContext)(Osn);return t==null&&function(e,...n){let r=new URL("https://lexical.dev/docs/error"),o=new URLSearchParams;o.append("code",e);for(let i of n)o.append("v",i);throw r.search=o.toString(),Error(`Minified Lexical error #${e}; visit ${r.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}(8),t}var zxe,Osn,Nsn=b(()=>{zxe=L(B(),1),Osn=(0,zxe.createContext)(null)});var MQe,Rsn,Lsn,go,Il=b(()=>{Nsn();MQe=EQe,Rsn=MQe.LexicalComposerContext,Lsn=MQe.createLexicalComposerContext,go=MQe.useLexicalComposerContext});var OQe={};sr(OQe,{LexicalComposer:()=>xTr});function xTr({initialConfig:t,children:e}){let n=(0,CV.useMemo)(()=>{let{theme:r,namespace:o,nodes:i,onError:s,editorState:a,html:l}=t,c=Lsn(null,r),u=Iin({editable:t.editable,html:l,namespace:o,nodes:i,onError:d=>s(d,u),theme:r});return function(d,f){if(f!==null){if(f===void 0)d.update(()=>{let p=ho();if(p.isEmpty()){let m=a0();p.append(m);let h=Dsn?document.activeElement:null;(qn()!==null||h!==null&&h===d.getRootElement())&&m.select()}},Hxe);else if(f!==null)switch(typeof f){case"string":{let p=d.parseEditorState(f);d.setEditorState(p,Hxe);break}case"object":d.setEditorState(f,Hxe);break;case"function":d.update(()=>{ho().isEmpty()&&f(d)},Hxe)}}}(u,a),[u,c]},[]);return _Tr(()=>{let r=t.editable,[o]=n;o.setEditable(r===void 0||r)},[]),(0,$sn.jsx)(Rsn.Provider,{value:n,children:e})}var CV,$sn,Dsn,_Tr,Hxe,Fsn=b(()=>{Il();$o();CV=L(B(),1),$sn=L(Mt(),1),Dsn=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0,_Tr=Dsn?CV.useLayoutEffect:CV.useEffect,Hxe={tag:pV}});var STr,Wxe,NQe=b(()=>{Fsn();STr=OQe,Wxe=STr.LexicalComposer});var RQe={};sr(RQe,{useLexicalEditable:()=>ITr});function kTr(t){return{initialValueFn:()=>t.isEditable(),subscribe:e=>t.registerEditableListener(e)}}function ITr(){return function(t){let[e]=go(),n=(0,$S.useMemo)(()=>t(e),[e,t]),[r,o]=(0,$S.useState)(()=>n.initialValueFn()),i=(0,$S.useRef)(r);return CTr(()=>{let{initialValueFn:s,subscribe:a}=n,l=s();return i.current!==l&&(i.current=l,o(l)),a(c=>{i.current=c,o(c)})},[n,t]),r}(kTr)}var $S,CTr,Usn=b(()=>{Il();$S=L(B(),1),CTr=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0?$S.useLayoutEffect:$S.useEffect});var TTr,jsn,Bsn=b(()=>{Usn();TTr=RQe,jsn=TTr.useLexicalEditable});var $Qe={};sr($Qe,{$canShowPlaceholder:()=>Hsn,$canShowPlaceholderCurry:()=>ATr,$findTextIntersectionFromCharacters:()=>ETr,$isRootTextContentEmpty:()=>LQe,$isRootTextContentEmptyCurry:()=>PTr,$rootTextContent:()=>zsn,registerLexicalTextEntity:()=>OTr});function zsn(){return ho().getTextContent()}function LQe(t,e=!0){if(t)return!1;let n=zsn();return e&&(n=n.trim()),n===""}function PTr(t,e){return()=>LQe(t,e)}function Hsn(t){if(!LQe(t,!1))return!1;let e=ho().getChildren(),n=e.length;if(n>1)return!1;for(let r=0;r<n;r++){let o=e[r];if(uxe(o))return!1;if(io(o)){if(!Kon(o)||o.__indent!==0)return!1;let i=o.getChildren(),s=i.length;for(let a=0;a<s;a++){let l=i[r];if(!Ho(l))return!1}}}return!0}function ATr(t){return()=>Hsn(t)}function ETr(t,e){let n=t.getFirstChild(),r=0;e:for(;n!==null;){if(io(n)){let s=n.getFirstChild();if(s!==null){n=s;continue}}else if(Ho(n)){let s=n.getTextContentSize();if(r+s>e)return{node:n,offset:e-r};r+=s}let o=n.getNextSibling();if(o!==null){n=o;continue}let i=n.getParent();for(;i!==null;){let s=i.getNextSibling();if(s!==null){n=s;continue e}i=i.getParent()}break}return null}function MTr(t,...e){let n=new URL("https://lexical.dev/docs/error"),r=new URLSearchParams;r.append("code",t);for(let o of e)r.append("v",o);throw n.search=r.toString(),Error(`Minified Lexical error #${t}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}function OTr(t,e,n,r){let o=s=>s instanceof n,i=s=>{let a=i_(s.getTextContent());a.setFormat(s.getFormat()),s.replace(a)};return[t.registerNodeTransform(OS,s=>{if(!s.isSimpleText())return;let a,l=s.getPreviousSibling(),c=s.getTextContent(),u=s;if(Ho(l)){let f=l.getTextContent(),p=e(f+c);if(o(l)){if(p===null||(m=>m.getLatest().__mode)(l)!==0)return void i(l);{let m=p.end-f.length;if(m>0){let h=f+c.slice(0,m);if(l.select(),l.setTextContent(h),m===c.length)s.remove();else{let g=c.slice(m);s.setTextContent(g)}return}}}else if(p===null||p.start<f.length)return}let d=0;for(;;){a=e(c);let f,p=a===null?"":c.slice(a.end);if(c=p,p===""){let h=u.getNextSibling();if(Ho(h)){p=u.getTextContent()+h.getTextContent();let g=e(p);if(g===null)return void(o(h)?i(h):h.markDirty());if(g.start!==0)return}}if(a===null)return;if(a.start===0&&Ho(l)&&l.isTextEntity()){d+=a.end;continue}a.start===0?[f,u]=u.splitText(a.end):[,f,u]=u.splitText(a.start+d,a.end+d),f===void 0&&MTr(165,"nodeToReplace");let m=r(f);if(m.setFormat(f.getFormat()),f.replace(m),u==null)return;d=0,l=m}}),t.registerNodeTransform(n,s=>{let a=s.getTextContent(),l=e(a);if(l===null||l.start!==0)return void i(s);if(a.length>l.end)return void s.splitText(l.end);let c=s.getPreviousSibling();Ho(c)&&c.isTextEntity()&&(i(c),i(s));let u=s.getNextSibling();Ho(u)&&u.isTextEntity()&&(i(u),o(s)&&i(s))})]}var Wsn=b(()=>{$o()});var Y$,PCi,Vxe,ACi,ECi,MCi,OCi,NCi,DQe=b(()=>{Wsn();Y$=$Qe,PCi=Y$.$canShowPlaceholder,Vxe=Y$.$canShowPlaceholderCurry,ACi=Y$.$findTextIntersectionFromCharacters,ECi=Y$.$isRootTextContentEmpty,MCi=Y$.$isRootTextContentEmptyCurry,OCi=Y$.$rootTextContent,NCi=Y$.registerLexicalTextEntity});var HQe={};sr(HQe,{$addNodeStyle:()=>DTr,$cloneWithProperties:()=>dM,$copyBlockFormatIndent:()=>Qsn,$ensureForwardRangeSelection:()=>Xsn,$forEachSelectedTextNode:()=>Jsn,$getSelectionStyleValueForProperty:()=>VTr,$isAtNodeEnd:()=>$Tr,$isParentElementRTL:()=>zQe,$moveCaretSelection:()=>tan,$moveCharacter:()=>HTr,$patchStyleText:()=>FTr,$selectAll:()=>fxe,$setBlocksType:()=>UTr,$shouldOverrideDefaultCharacterSelection:()=>zTr,$sliceSelectedTextNodeContent:()=>LTr,$trimTextContentFromAnchor:()=>Ysn,$wrapNodes:()=>BTr,createDOMRange:()=>NTr,createRectsFromDOMRange:()=>RTr,getCSSFromStyleObject:()=>Zsn,getStyleObjectFromCSS:()=>Kxe,trimTextContentFromAnchor:()=>qTr});function BQe(t,...e){let n=new URL("https://lexical.dev/docs/error"),r=new URLSearchParams;r.append("code",t);for(let o of e)r.append("v",o);throw n.search=r.toString(),Error(`Minified Lexical error #${t}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}function Vsn(t){let e=t;for(;e!=null;){if(e.nodeType===Node.TEXT_NODE)return e;e=e.firstChild}return null}function qsn(t){let e=t.parentNode;if(e==null)throw new Error("Should never happen");return[e,Array.from(e.childNodes).indexOf(t)]}function NTr(t,e,n,r,o){let i=e.getKey(),s=r.getKey(),a=document.createRange(),l=t.getElementByKey(i),c=t.getElementByKey(s),u=n,d=o;if(Ho(e)&&(l=Vsn(l)),Ho(r)&&(c=Vsn(c)),e===void 0||r===void 0||l===null||c===null)return null;l.nodeName==="BR"&&([l,u]=qsn(l)),c.nodeName==="BR"&&([c,d]=qsn(c));let f=l.firstChild;l===c&&f!=null&&f.nodeName==="BR"&&u===0&&d===0&&(d=1);try{a.setStart(l,u),a.setEnd(c,d)}catch{return null}return!a.collapsed||u===d&&i===s||(a.setStart(c,d),a.setEnd(l,u)),a}function RTr(t,e){let n=t.getRootElement();if(n===null)return[];let r=n.getBoundingClientRect(),o=getComputedStyle(n),i=parseFloat(o.paddingLeft)+parseFloat(o.paddingRight),s=Array.from(e.getClientRects()),a,l=s.length;s.sort((c,u)=>{let d=c.top-u.top;return Math.abs(d)<=3?c.left-u.left:d});for(let c=0;c<l;c++){let u=s[c],d=a&&a.top<=u.top&&a.top+a.height>u.top&&a.left+a.width>u.left,f=u.width+i===r.width;d||f?(s.splice(c--,1),l--):a=u}return s}function Gsn(t){let e={};if(!t)return e;let n=t.split(";");for(let r of n)if(r!==""){let[o,i]=r.split(/:([^]+)/);o&&i&&(e[o.trim()]=i.trim())}return e}function Kxe(t){let e=qxe.get(t);return e===void 0&&(e=Gsn(t),qxe.set(t,e)),e}function Zsn(t){let e="";for(let n in t)n&&(e+=`${n}: ${t[n]};`);return e}function LTr(t,e){let n=t.getStartEndPoints();if(e.isSelected(t)&&!lQe(e)&&n!==null){let[r,o]=n,i=t.isBackward(),s=r.getNode(),a=o.getNode(),l=e.is(s),c=e.is(a);if(l||c){let[u,d]=jon(t),f=s.is(a),p=e.is(i?a:s),m=e.is(i?s:a),h,g=0;f?(g=u>d?d:u,h=u>d?u:d):p?(g=i?d:u,h=void 0):m&&(g=0,h=i?u:d),e.__text=e.__text.slice(g,h)}}return e}function $Tr(t){if(t.type==="text")return t.offset===t.getNode().getTextContentSize();let e=t.getNode();return io(e)||BQe(177),t.offset===e.getChildrenSize()}function Ysn(t,e,n){let r=e.getNode(),o=n;if(io(r)){let i=r.getDescendantByIndex(e.offset);i!==null&&(r=i)}for(;o>0&&r!==null;){if(io(r)){let c=r.getLastDescendant();c!==null&&(r=c)}let i=r.getPreviousSibling(),s=0;if(i===null){let c=r.getParentOrThrow(),u=c.getPreviousSibling();for(;u===null;){if(c=c.getParent(),c===null){i=null;break}u=c.getPreviousSibling()}c!==null&&(s=c.isInline()?0:2,i=u)}let a=r.getTextContent();a===""&&io(r)&&!r.isInline()&&(a=`
`);let l=a.length;if(!Ho(r)||o>=l){let c=r.getParent();r.remove(),c==null||c.getChildrenSize()!==0||cV(c)||c.remove(),o-=l+s,r=i}else{let c=r.getKey(),u=t.getEditorState().read(()=>{let p=zon(c);return Ho(p)&&p.isSimpleText()?p.getTextContent():null}),d=l-o,f=a.slice(0,d);if(u!==null&&u!==a){let p=$ee(),m=r;if(r.isSimpleText())r.setTextContent(u);else{let h=i_(u);r.replace(h),m=h}if(gn(p)&&p.isCollapsed()){let h=p.anchor.offset;m.select(h,h)}}else if(r.isSimpleText()){let p=e.key===c,m=e.offset;m<o&&(m=l);let h=p?m-o:0,g=p?m:d;if(p&&h===0){let[v]=r.splitText(h,g);v.remove()}else{let[,v]=r.splitText(h,g);v.remove()}}else{let p=i_(f);r.replace(p)}o=0}}}function DTr(t){let e=t.getStyle(),n=Gsn(e);qxe.set(e,n)}function FQe(t,e){(gn(t)?t.isCollapsed():Ho(t)||io(t))||BQe(280);let n=Kxe(gn(t)?t.style:Ho(t)?t.getStyle():t.getTextStyle()),r=Object.entries(e).reduce((i,[s,a])=>(typeof a=="function"?i[s]=a(n[s],t):a===null?delete i[s]:i[s]=a,i),{...n}),o=Zsn(r);gn(t)||Ho(t)?t.setStyle(o):t.setTextStyle(o),qxe.set(o,r)}function FTr(t,e){if(gn(t)&&t.isCollapsed()){FQe(t,e);let n=t.anchor.getNode();io(n)&&n.isEmpty()&&FQe(n,e)}Jsn(n=>{FQe(n,e)})}function Jsn(t){let e=qn();if(!e)return;let n=new Map;if(gn(e))for(let i of $on(e).getTextSlices())i&&n.set(i.caret.origin.getKey(),i.getSliceIndices());let r=e.getNodes();for(let i of r){if(!Ho(i)||!i.canHaveFormat())continue;let[s,a]=(o=i,n.get(o.getKey())||[0,o.getTextContentSize()]);a!==s&&(lQe(i)||s===0&&a===i.getTextContentSize()?t(i):t(i.splitText(s,a)[s===0?0:1]))}var o;gn(e)&&e.anchor.type==="text"&&e.focus.type==="text"&&e.anchor.key===e.focus.key&&Xsn(e)}function Xsn(t){if(t.isBackward()){let{anchor:e,focus:n}=t,{key:r,offset:o,type:i}=e;e.set(n.key,n.offset,n.type),n.set(r,o,i)}}function Qsn(t,e){let n=t.getFormatType(),r=t.getIndent();n!==e.getFormatType()&&e.setFormat(n),r!==e.getIndent()&&e.setIndent(r)}function UTr(t,e,n=Qsn){if(t===null)return;let r=t.getStartEndPoints(),o=new Map,i=null;if(r){let[s,a]=r;i=iQe(),i.anchor.set(s.key,s.offset,s.type),i.focus.set(a.key,a.offset,a.type);let l=jQe(s.getNode(),jee),c=jQe(a.getNode(),jee);io(l)&&o.set(l.getKey(),l),io(c)&&o.set(c.getKey(),c)}for(let s of t.getNodes())if(io(s)&&jee(s))o.set(s.getKey(),s);else if(r===null){let a=jQe(s,jee);io(a)&&o.set(a.getKey(),a)}for(let[s,a]of o){let l=e();n(a,l),a.replace(l,!0),i&&(s===i.anchor.key&&i.anchor.set(l.getKey(),i.anchor.offset,i.anchor.type),s===i.focus.key&&i.focus.set(l.getKey(),i.focus.offset,i.focus.type))}i&&t.is(qn())&&uV(i)}function Ksn(t){return t.getNode().isAttached()}function jTr(t){let e=t;for(;e!==null&&!V$(e);){let n=e.getLatest(),r=e.getParent();n.getChildrenSize()===0&&e.remove(!0),e=r}}function BTr(t,e,n=null){let r=t.getStartEndPoints(),o=r?r[0]:null,i=t.getNodes(),s=i.length;if(o!==null&&(s===0||s===1&&o.type==="element"&&o.getNode().getChildrenSize()===0)){let c=o.type==="text"?o.getNode().getParentOrThrow():o.getNode(),u=c.getChildren(),d=e();return d.setFormat(c.getFormatType()),d.setIndent(c.getIndent()),u.forEach(f=>d.append(f)),n&&(d=n.append(d)),void c.replace(d)}let a=null,l=[];for(let c=0;c<s;c++){let u=i[c];V$(u)?(UQe(t,l,l.length,e,n),l=[],a=u):a===null||a!==null&&Won(u,a)?l.push(u):(UQe(t,l,l.length,e,n),l=[u])}UQe(t,l,l.length,e,n)}function UQe(t,e,n,r,o=null){if(e.length===0)return;let i=e[0],s=new Map,a=[],l=io(i)?i:i.getParentOrThrow();l.isInline()&&(l=l.getParentOrThrow());let c=!1;for(;l!==null;){let m=l.getPreviousSibling();if(m!==null){l=m,c=!0;break}if(l=l.getParentOrThrow(),V$(l))break}let u=new Set;for(let m=0;m<n;m++){let h=e[m];io(h)&&h.getChildrenSize()===0&&u.add(h.getKey())}let d=new Set;for(let m=0;m<n;m++){let h=e[m],g=h.getParent();if(g!==null&&g.isInline()&&(g=g.getParent()),g!==null&&qon(h)&&!d.has(h.getKey())){let v=g.getKey();if(s.get(v)===void 0){let y=r();y.setFormat(g.getFormatType()),y.setIndent(g.getIndent()),a.push(y),s.set(v,y),g.getChildren().forEach(w=>{y.append(w),d.add(w.getKey()),io(w)&&w.getChildrenKeys().forEach(_=>d.add(_))}),jTr(g)}}else if(u.has(h.getKey())){io(h)||BQe(179);let v=r();v.setFormat(h.getFormatType()),v.setIndent(h.getIndent()),a.push(v),h.remove(!0)}}if(o!==null)for(let m=0;m<a.length;m++){let h=a[m];o.append(h)}let f=null;if(V$(l))if(c)if(o!==null)l.insertAfter(o);else for(let m=a.length-1;m>=0;m--){let h=a[m];l.insertAfter(h)}else{let m=l.getFirstChild();if(io(m)&&(l=m),m===null)if(o)l.append(o);else for(let h=0;h<a.length;h++){let g=a[h];l.append(g),f=g}else if(o!==null)m.insertBefore(o);else for(let h=0;h<a.length;h++){let g=a[h];m.insertBefore(g),f=g}}else if(o)l.insertAfter(o);else for(let m=a.length-1;m>=0;m--){let h=a[m];l.insertAfter(h),f=h}let p=$ee();gn(p)&&Ksn(p.anchor)&&Ksn(p.focus)?uV(p.clone()):f!==null?f.selectEnd():t.dirty=!0}function ean(t){let e=t.anchor.getNode(),n=cV(e)?e:e.getParentOrThrow(),r=lxe().getElementByKey(n.getKey());if(r===null)return!1;let o=r.ownerDocument.defaultView;return o===null?!1:o.getComputedStyle(r).writingMode==="vertical-rl"}function zTr(t,e){let n=ean(t)?!e:e;zQe(t)&&(n=!n);let r=lV(t.focus,n?"previous":"next");if(Von(r))return!1;for(let o of Fon(r)){if(Dee(o))return!o.origin.isInline();if(!io(o.origin)){if(uxe(o.origin))return!0;break}}return!1}function tan(t,e,n,r){t.modify(e?"extend":"move",n,r)}function zQe(t){let e=t.anchor.getNode();return(cV(e)?e:e.getParentOrThrow()).getDirection()==="rtl"}function HTr(t,e,n){let r=zQe(t),o;o=ean(t)||r?!n:n,tan(t,e,o,"character")}function WTr(t,e,n){let r=Kxe(t.getStyle());return r!==null&&r[e]||n}function VTr(t,e,n=""){let r=null,o=t.getNodes(),i=t.anchor,s=t.focus,a=t.isBackward(),l=a?s.offset:i.offset,c=a?s.getNode():i.getNode();if(gn(t)&&t.isCollapsed()&&t.style!==""){let u=Kxe(t.style);if(u!==null&&e in u)return u[e]}for(let u=0;u<o.length;u++){let d=o[u];if((u===0||l!==0||!d.is(c))&&Ho(d)){let f=WTr(d,e,n);if(r===null)r=f;else if(r!==f){r="";break}}}return r===null?n:r}function jQe(t,e){let n=t;for(;n!==null&&n.getParent()!==null&&!e(n);)n=n.getParentOrThrow();return e(n)?n:null}var qxe,qTr,nan=b(()=>{$o();$o();qxe=new Map;qTr=Ysn});var rl,ran,DCi,FCi,UCi,jCi,BCi,zCi,HCi,WCi,WQe,VCi,qCi,KCi,VQe,Gxe,GCi,ZCi,YCi,oan,JCi,XCi,QCi,ete=b(()=>{nan();rl=HQe,ran=rl.$addNodeStyle,DCi=rl.$cloneWithProperties,FCi=rl.$copyBlockFormatIndent,UCi=rl.$ensureForwardRangeSelection,jCi=rl.$forEachSelectedTextNode,BCi=rl.$getSelectionStyleValueForProperty,zCi=rl.$isAtNodeEnd,HCi=rl.$isParentElementRTL,WCi=rl.$moveCaretSelection,WQe=rl.$moveCharacter,VCi=rl.$patchStyleText,qCi=rl.$selectAll,KCi=rl.$setBlocksType,VQe=rl.$shouldOverrideDefaultCharacterSelection,Gxe=rl.$sliceSelectedTextNodeContent,GCi=rl.$trimTextContentFromAnchor,ZCi=rl.$wrapNodes,YCi=rl.createDOMRange,oan=rl.createRectsFromDOMRange,JCi=rl.getCSSFromStyleObject,XCi=rl.getStyleObjectFromCSS,QCi=rl.trimTextContentFromAnchor});var ZQe={};sr(ZQe,{$descendantsMatching:()=>MPr,$dfs:()=>mPr,$dfsIterator:()=>man,$filter:()=>IPr,$findMatchingParent:()=>van,$firstToLastIterator:()=>OPr,$getAdjacentCaret:()=>hPr,$getAdjacentSiblingOrParentSiblingCaret:()=>tte,$getDepth:()=>gan,$getNearestBlockElementAncestorOrThrow:()=>bPr,$getNearestNodeOfType:()=>wPr,$getNextRightPreorderNode:()=>vPr,$getNextSiblingOrParentSibling:()=>yPr,$insertFirst:()=>TPr,$insertNodeToNearestRoot:()=>SPr,$insertNodeToNearestRootAtCaret:()=>wan,$isEditorIsNestedEditor:()=>APr,$lastToFirstIterator:()=>GQe,$restoreEditorState:()=>xPr,$reverseDfs:()=>gPr,$reverseDfsIterator:()=>yan,$splitNode:()=>tin,$unwrapAndFilterDescendants:()=>EPr,$unwrapNode:()=>NPr,$wrapNodeInElement:()=>CPr,CAN_USE_BEFORE_INPUT:()=>rPr,CAN_USE_DOM:()=>dan,IS_ANDROID:()=>oPr,IS_ANDROID_CHROME:()=>iPr,IS_APPLE:()=>sPr,IS_APPLE_WEBKIT:()=>aPr,IS_CHROME:()=>lPr,IS_FIREFOX:()=>fan,IS_IOS:()=>cPr,IS_SAFARI:()=>uPr,addClassNamesToElement:()=>dPr,calculateZoomLevel:()=>PPr,isBlockDomNode:()=>Ain,isHTMLAnchorElement:()=>Ein,isHTMLElement:()=>wxe,isInlineDomNode:()=>Bee,isMimeType:()=>pan,makeStateWrapper:()=>RPr,markSelection:()=>uan,mediaFileReader:()=>pPr,mergeRegister:()=>lan,objectKlassEquals:()=>kPr,positionNodeOnRange:()=>can,registerNestedElementResolver:()=>_Pr,removeClassNamesFromElement:()=>fPr,selectionAlwaysOnDisplay:()=>nPr});function Zxe(t,...e){let n=new URL("https://lexical.dev/docs/error"),r=new URLSearchParams;r.append("code",t);for(let o of e)r.append("v",o);throw n.search=r.toString(),Error(`Minified Lexical error #${t}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}function aan(...t){let e=[];for(let n of t)if(n&&typeof n=="string")for(let[r]of n.matchAll(/\S+/g))e.push(r);return e}function lan(...t){return()=>{for(let e=t.length-1;e>=0;e--)t[e]();t.length=0}}function DS(t){return`${t}px`}function can(t,e,n){let r=null,o=null,i=null,s=[],a=document.createElement("div");function l(){r===null&&Zxe(182),o===null&&Zxe(183);let{left:d,top:f}=o.getBoundingClientRect(),p=oan(t,e);var m,h;a.isConnected||(h=a,(m=o).insertBefore(h,m.firstChild));let g=!1;for(let v=0;v<p.length;v++){let y=p[v],w=s[v]||document.createElement("div"),_=w.style;_.position!=="absolute"&&(_.position="absolute",g=!0);let S=DS(y.left-d);_.left!==S&&(_.left=S,g=!0);let I=DS(y.top-f);_.top!==I&&(w.style.top=I,g=!0);let C=DS(y.width);_.width!==C&&(w.style.width=C,g=!0);let k=DS(y.height);_.height!==k&&(w.style.height=k,g=!0),w.parentNode!==a&&(a.append(w),g=!0),s[v]=w}for(;s.length>p.length;)s.pop();g&&n(s)}function c(){o=null,r=null,i!==null&&i.disconnect(),i=null,a.remove();for(let d of s)d.remove();s=[]}a.style.position="relative";let u=t.registerRootListener(function d(){let f=t.getRootElement();if(f===null)return c();let p=f.parentElement;if(!wxe(p))return c();c(),r=f,o=p,i=new MutationObserver(m=>{let h=t.getRootElement(),g=h&&h.parentElement;if(h!==r||g!==o)return d();for(let v of m)if(!a.contains(v.target))return l()}),i.observe(p,tPr),l()});return()=>{u(),c()}}function ian(t,e,n){if(t.type!=="text"&&io(e)){let r=e.getDOMSlot(n);return[r.element,r.getFirstChildOffset()+t.offset]}return[Tin(n)||n,t.offset]}function uan(t,e){let n=null,r=null,o=null,i=null,s=null,a=null,l=()=>{};function c(u){u.read(()=>{let d=qn();if(!gn(d))return n=null,o=null,i=null,a=null,l(),void(l=()=>{});let[f,p]=function(k){let T=k.getStartEndPoints();return k.isBackward()?[T[1],T[0]]:T}(d),m=f.getNode(),h=m.getKey(),g=f.offset,v=p.getNode(),y=v.getKey(),w=p.offset,_=t.getElementByKey(h),S=t.getElementByKey(y),I=n===null||_!==r||g!==o||h!==n.getKey(),C=i===null||S!==s||w!==a||y!==i.getKey();if((I||C)&&_!==null&&S!==null){let k=function(T,P,E,O,$,U,V){let K=(T._window?T._window.document:document).createRange();return K.setStart(...ian(P,E,O)),K.setEnd(...ian($,U,V)),K}(t,f,m,_,p,v,S);l(),l=can(t,k,T=>{if(e===void 0)for(let P of T){let E=P.style;E.background!=="Highlight"&&(E.background="Highlight"),E.color!=="HighlightText"&&(E.color="HighlightText"),E.marginTop!==DS(-1.5)&&(E.marginTop=DS(-1.5)),E.paddingTop!==DS(4)&&(E.paddingTop=DS(4)),E.paddingBottom!==DS(0)&&(E.paddingBottom=DS(0))}else e(T)})}n=m,r=_,o=g,i=v,s=S,a=w})}return c(t.getEditorState()),lan(t.registerUpdateListener(({editorState:u})=>c(u)),()=>{l()})}function nPr(t){let e=null,n=()=>{let r=getSelection(),o=r&&r.anchorNode,i=t.getRootElement();o!==null&&i!==null&&i.contains(o)?e!==null&&(e(),e=null):e===null&&(e=uan(t))};return document.addEventListener("selectionchange",n),()=>{e!==null&&e(),document.removeEventListener("selectionchange",n)}}function dPr(t,...e){let n=aan(...e);n.length>0&&t.classList.add(...n)}function fPr(t,...e){let n=aan(...e);n.length>0&&t.classList.remove(...n)}function pan(t,e){for(let n of e)if(t.type.startsWith(n))return!0;return!1}function pPr(t,e){let n=t[Symbol.iterator]();return new Promise((r,o)=>{let i=[],s=()=>{let{done:a,value:l}=n.next();if(a)return r(i);let c=new FileReader;c.addEventListener("error",o),c.addEventListener("load",()=>{let u=c.result;typeof u=="string"&&i.push({file:l,result:u}),s()}),pan(l,e)?c.readAsDataURL(l):s()};s()})}function mPr(t,e){return Array.from(man(t,e))}function hPr(t){return t?t.getAdjacentCaret():null}function gPr(t,e){return Array.from(yan(t,e))}function man(t,e){return han("next",t,e)}function han(t,e,n){let r=ho(),o=e||r,i=io(o)?fM(o,t):l0(o,t),s=gan(o),a=n?Lee(aQe(l0(n,t))):function(c,u){let d=tte(l0(c,u));return d&&d[0]}(o,t),l=s;return pQe({hasNext:c=>c!==null,initial:i,map:c=>({depth:l,node:c.origin}),step:c=>{if(c.isSameNodeCaret(a))return null;Dee(c)&&l++;let u=tte(c);return!u||u[0].isSameNodeCaret(a)?null:(l+=u[1],u[0])}})}function yPr(t){let e=tte(l0(t,"next"));return e&&[e[0].origin,e[1]]}function gan(t){let e=-1;for(let n=t;n!==null;n=n.getParent())e++;return e}function vPr(t){let e=tte(aQe(l0(t,"previous")),"root");return e&&e[0].origin}function yan(t,e){return han("previous",t,e)}function wPr(t,e){let n=t;for(;n!=null;){if(n instanceof e)return n;n=n.getParent()}return null}function bPr(t){let e=van(t,n=>io(n)&&!n.isInline());return io(e)||Zxe(4,t.__key),e}function _Pr(t,e,n,r){let o=i=>i instanceof e;return t.registerNodeTransform(e,i=>{let s=(a=>{let l=a.getChildren();for(let d=0;d<l.length;d++){let f=l[d];if(o(f))return null}let c=a,u=a;for(;c!==null;)if(u=c,c=c.getParent(),o(c))return{child:u,parent:c};return null})(i);if(s!==null){let{child:a,parent:l}=s;if(a.is(i)){r(l,i);let c=a.getNextSiblings(),u=c.length;if(l.insertAfter(a),u!==0){let d=n(l);a.insertAfter(d);for(let f=0;f<u;f++)d.append(c[f])}l.canBeEmpty()||l.getChildrenSize()!==0||l.remove()}}})}function xPr(t,e){let n=new Map,r=t._pendingEditorState;for(let[i,s]of e._nodeMap)n.set(i,dM(s));r&&(r._nodeMap=n),t._dirtyType=2;let o=e._selection;uV(o===null?null:o.clone())}function SPr(t){let e=qn()||$ee(),n;if(gn(e))n=lV(e.focus,"next");else{if(e!=null){let s=e.getNodes(),a=s[s.length-1];a&&(n=l0(a,"next"))}n=n||fM(ho(),"previous").getFlipped().insert(a0())}let r=wan(t,n),o=Lee(r),i=Dee(o)?Zon(o):r;return Xon(Bon(i)),t.getLatest()}function wan(t,e,n){let r=sQe(e,"next");for(let o=r;o;o=ein(o,n))r=o;return dxe(r)&&Zxe(283),r.insert(t.isInline()?a0().append(t):t),sQe(l0(t.getLatest(),"next"),e.direction)}function CPr(t,e){let n=e();return t.replace(n),n.append(t),n}function kPr(t,e){return t!==null&&Object.getPrototypeOf(t).constructor.name===e.name}function IPr(t,e){let n=[];for(let r=0;r<t.length;r++){let o=e(t[r]);o!==null&&n.push(o)}return n}function TPr(t,e){fM(t,"next").insert(e)}function PPr(t){let e=1;if(function(){if(qQe===void 0){let n=document.createElement("div");n.style.cssText="position: absolute; opacity: 0; width: 100px; left: -1000px;",document.body.appendChild(n);let r=n.getBoundingClientRect();n.style.setProperty("zoom","2"),qQe=n.getBoundingClientRect().width===r.width,document.body.removeChild(n)}return qQe}())for(;t;)e*=Number(window.getComputedStyle(t).getPropertyValue("zoom")),t=t.parentElement;return e}function APr(t){return t._parentEditor!==null}function EPr(t,e){return ban(t,e,null)}function ban(t,e,n){let r=!1;for(let o of GQe(t))e(o)?n!==null&&n(o):(r=!0,io(o)&&ban(o,e,n||(i=>o.insertAfter(i))),o.remove());return r}function MPr(t,e){let n=[],r=Array.from(t).reverse();for(let o=r.pop();o!==void 0;o=r.pop())if(e(o))n.push(o);else if(io(o))for(let i of GQe(o))r.push(i);return n}function OPr(t){return _an(fM(t,"next"))}function GQe(t){return _an(fM(t,"previous"))}function _an(t){return pQe({hasNext:Gon,initial:t.getAdjacentCaret(),map:e=>e.origin.getLatest(),step:e=>e.getAdjacentCaret()})}function NPr(t){Jon(l0(t,"next")).splice(1,t.getChildren())}function tte(t,e="root"){let n=0,r=t,o=Lee(r);for(;o===null;){if(n--,o=r.getParentCaret(e),!o)return null;r=o,o=Lee(r)}return o&&[o,n]}function RPr(t){let e=r=>Hon(r,t),n=(r,o)=>Qon(r,t,o);return{$get:e,$set:n,accessors:[e,n],makeGetterMethod:()=>function(){return e(this)},makeSetterMethod:()=>function(r){return n(this,r)},stateConfig:t}}var a_,KTr,GTr,ZTr,YTr,JTr,XTr,san,KQe,QTr,ePr,tPr,rPr,dan,oPr,iPr,sPr,aPr,lPr,fan,cPr,uPr,van,qQe,xan=b(()=>{$o();$o();ete();a_=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0,KTr=a_&&"documentMode"in document?document.documentMode:null,GTr=a_&&/Mac|iPod|iPhone|iPad/.test(navigator.platform),ZTr=a_&&/^(?!.*Seamonkey)(?=.*Firefox).*/i.test(navigator.userAgent),YTr=!(!a_||!("InputEvent"in window)||KTr)&&"getTargetRanges"in new window.InputEvent("input"),JTr=a_&&/Version\/[\d.]+.*Safari/.test(navigator.userAgent),XTr=a_&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,san=a_&&/Android/.test(navigator.userAgent),KQe=a_&&/^(?=.*Chrome).*/i.test(navigator.userAgent),QTr=a_&&san&&KQe,ePr=a_&&/AppleWebKit\/[\d.]+/.test(navigator.userAgent)&&!KQe;tPr={attributes:!0,characterData:!0,childList:!0,subtree:!0};rPr=YTr,dan=a_,oPr=san,iPr=QTr,sPr=GTr,aPr=ePr,lPr=KQe,fan=ZTr,cPr=XTr,uPr=JTr;van=(t,e)=>{let n=t;for(;n!==ho()&&n!=null;){if(e(n))return n;n=n.getParent()}return null};qQe=!(fan||!dan)&&void 0});var nr,oki,iki,ski,aki,lki,cki,uki,dki,fki,pki,mki,hki,gki,yki,vki,wki,bki,_ki,xki,Ski,Cki,kki,Iki,Tki,Pki,Aki,Eki,Mki,Oki,Nki,Rki,Lki,$ki,Dki,Fki,Uki,jki,YQe,Bki,San,zki,Hki,Wki,Vki,qki,g0,nte,Kki,Gki,Zki,Yki,J$=b(()=>{xan();nr=ZQe,oki=nr.$descendantsMatching,iki=nr.$dfs,ski=nr.$dfsIterator,aki=nr.$filter,lki=nr.$findMatchingParent,cki=nr.$firstToLastIterator,uki=nr.$getAdjacentCaret,dki=nr.$getAdjacentSiblingOrParentSiblingCaret,fki=nr.$getDepth,pki=nr.$getNearestBlockElementAncestorOrThrow,mki=nr.$getNearestNodeOfType,hki=nr.$getNextRightPreorderNode,gki=nr.$getNextSiblingOrParentSibling,yki=nr.$insertFirst,vki=nr.$insertNodeToNearestRoot,wki=nr.$insertNodeToNearestRootAtCaret,bki=nr.$isEditorIsNestedEditor,_ki=nr.$lastToFirstIterator,xki=nr.$restoreEditorState,Ski=nr.$reverseDfs,Cki=nr.$reverseDfsIterator,kki=nr.$splitNode,Iki=nr.$unwrapAndFilterDescendants,Tki=nr.$unwrapNode,Pki=nr.$wrapNodeInElement,Aki=nr.CAN_USE_BEFORE_INPUT,Eki=nr.CAN_USE_DOM,Mki=nr.IS_ANDROID,Oki=nr.IS_ANDROID_CHROME,Nki=nr.IS_APPLE,Rki=nr.IS_APPLE_WEBKIT,Lki=nr.IS_CHROME,$ki=nr.IS_FIREFOX,Dki=nr.IS_IOS,Fki=nr.IS_SAFARI,Uki=nr.addClassNamesToElement,jki=nr.calculateZoomLevel,YQe=nr.isBlockDomNode,Bki=nr.isHTMLAnchorElement,San=nr.isHTMLElement,zki=nr.isInlineDomNode,Hki=nr.isMimeType,Wki=nr.makeStateWrapper,Vki=nr.markSelection,qki=nr.mediaFileReader,g0=nr.mergeRegister,nte=nr.objectKlassEquals,Kki=nr.positionNodeOnRange,Gki=nr.registerNestedElementResolver,Zki=nr.removeClassNamesFromElement,Yki=nr.selectionAlwaysOnDisplay});var JQe={};sr(JQe,{registerDragonSupport:()=>LPr});function LPr(t){let e=window.location.origin,n=r=>{if(r.origin!==e)return;let o=t.getRootElement();if(document.activeElement!==o)return;let i=r.data;if(typeof i=="string"){let s;try{s=JSON.parse(i)}catch{return}if(s&&s.protocol==="nuanria_messaging"&&s.type==="request"){let a=s.payload;if(a&&a.functionId==="makeChanges"){let l=a.args;if(l){let[c,u,d,f,p,m]=l;t.update(()=>{let h=qn();if(gn(h)){let g=h.anchor,v=g.getNode(),y=0,w=0;if(Ho(v)&&c>=0&&u>=0&&(y=c,w=c+u,h.setTextNodeRange(v,y,v,w)),y===w&&d===""||(h.insertRawText(d),v=g.getNode()),Ho(v)){y=f,w=f+p;let _=v.getTextContentSize();y=y>_?_:y,w=w>_?_:w,h.setTextNodeRange(v,y,v,w)}r.stopImmediatePropagation()}})}}}}};return window.addEventListener("message",n,!0),()=>{window.removeEventListener("message",n,!0)}}var Can=b(()=>{$o()});var $Pr,kan,Ian=b(()=>{Can();$Pr=JQe,kan=$Pr.registerDragonSupport});var XQe={};sr(XQe,{$generateHtmlFromNodes:()=>FPr,$generateNodesFromDOM:()=>DPr});function DPr(t,e){let n=e.body?e.body.childNodes:[],r=[],o=[];for(let i=0;i<n.length;i++){let s=n[i];if(!Pan.has(s.nodeName)){let a=Aan(s,t,o,!1);a!==null&&(r=r.concat(a))}}return function(i){for(let s of i)s.getNextSibling()instanceof cQe&&s.insertAfter(oQe());for(let s of i){let a=s.getChildren();for(let l of a)s.insertBefore(l);s.remove()}}(o),r}function FPr(t,e){if(typeof document>"u"||typeof window>"u"&&window.window===void 0)throw new Error("To use $generateHtmlFromNodes in headless mode please initialize a headless browser implementation such as JSDom before calling this function.");let n=document.createElement("div"),r=ho().getChildren();for(let o=0;o<r.length;o++)Tan(t,r[o],n,e);return n.innerHTML}function Tan(t,e,n,r=null){let o=r===null||e.isSelected(r),i=io(e)&&e.excludeFromCopy("html"),s=e;if(r!==null){let p=dM(e);p=Ho(p)&&r!==null?Gxe(r,p):p,s=p}let a=io(s)?s.getChildren():[],l=Pin(t,s.getType()),c;c=l&&l.exportDOM!==void 0?l.exportDOM(t,s):s.exportDOM(t);let{element:u,after:d}=c;if(!u)return!1;let f=document.createDocumentFragment();for(let p=0;p<a.length;p++){let m=a[p],h=Tan(t,m,f,r);!o&&io(e)&&h&&e.extractWithChild(m,r,"html")&&(o=!0)}if(o&&!i){if((San(u)||fQe(u))&&u.append(f),n.append(u),d){let p=d.call(s,u);p&&(fQe(u)?u.replaceChildren(p):u.replaceWith(p))}}else n.append(f);return o}function Aan(t,e,n,r,o=new Map,i){let s=[];if(Pan.has(t.nodeName))return s;let a=null,l=function(m,h){let{nodeName:g}=m,v=h._htmlConversions.get(g.toLowerCase()),y=null;if(v!==void 0)for(let w of v){let _=w(m);_!==null&&(y===null||(y.priority||0)<=(_.priority||0))&&(y=_)}return y!==null?y.conversion:null}(t,e),c=l?l(t):null,u=null;if(c!==null){u=c.after;let m=c.node;if(a=Array.isArray(m)?m[m.length-1]:m,a!==null){for(let[,h]of o)if(a=h(a,i),!a)break;a&&s.push(...Array.isArray(m)?m:[a])}c.forChild!=null&&o.set(t.nodeName,c.forChild)}let d=t.childNodes,f=[],p=(a==null||!V$(a))&&(a!=null&&cxe(a)||r);for(let m=0;m<d.length;m++)f.push(...Aan(d[m],e,n,p,new Map(o),a));return u!=null&&(f=u(f)),YQe(t)&&(f=UPr(t,f,p?()=>{let m=new cQe;return n.push(m),m}:a0)),a==null?f.length>0?s=s.concat(f):YQe(t)&&function(m){return m.nextSibling==null||m.previousSibling==null?!1:Bee(m.nextSibling)&&Bee(m.previousSibling)}(t)&&(s=s.concat(oQe())):io(a)&&a.append(...f),s}function UPr(t,e,n){let r=t.style.textAlign,o=[],i=[];for(let s=0;s<e.length;s++){let a=e[s];if(cxe(a))r&&!a.getFormat()&&a.setFormat(r),o.push(a);else if(i.push(a),s===e.length-1||s<e.length-1&&cxe(e[s+1])){let l=n();l.setFormat(r),l.append(...i),o.push(l),i=[]}}return o}var Pan,Ean=b(()=>{ete();J$();$o();Pan=new Set(["STYLE","SCRIPT"])});var Man,Oan,Nan,Ran=b(()=>{Ean();Man=XQe,Oan=Man.$generateHtmlFromNodes,Nan=Man.$generateNodesFromDOM});var eet={};sr(eet,{$generateJSONFromSelectedNodes:()=>Uan,$generateNodesFromSerializedNodes:()=>jan,$getClipboardDataFromSelection:()=>Ban,$getHtmlContent:()=>$an,$getLexicalContent:()=>Dan,$insertDataTransferForPlainText:()=>jPr,$insertDataTransferForRichText:()=>BPr,$insertGeneratedNodes:()=>QQe,copyToClipboard:()=>zPr,setLexicalClipboardDataTransfer:()=>zan});function Yxe(t,...e){let n=new URL("https://lexical.dev/docs/error"),r=new URLSearchParams;r.append("code",t);for(let o of e)r.append("v",o);throw n.search=r.toString(),Error(`Minified Lexical error #${t}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}function $an(t,e=qn()){return e==null&&Yxe(166),gn(e)&&e.isCollapsed()||e.getNodes().length===0?"":Oan(t,e)}function Dan(t,e=qn()){return e==null&&Yxe(166),gn(e)&&e.isCollapsed()||e.getNodes().length===0?null:JSON.stringify(Uan(t,e))}function jPr(t,e){let n=t.getData("text/plain")||t.getData("text/uri-list");n!=null&&e.insertRawText(n)}function BPr(t,e,n){let r=t.getData("application/x-lexical-editor");if(r)try{let a=JSON.parse(r);if(a.namespace===n._config.namespace&&Array.isArray(a.nodes))return QQe(n,jan(a.nodes),e)}catch{}let o=t.getData("text/html"),i=t.getData("text/plain");if(o&&i!==o)try{let a=new DOMParser().parseFromString(function(l){return window.trustedTypes&&window.trustedTypes.createPolicy?window.trustedTypes.createPolicy("lexical",{createHTML:c=>c}).createHTML(l):l}(o),"text/html");return QQe(n,Nan(n,a),e)}catch{}let s=i||t.getData("text/uri-list");if(s!=null)if(gn(e)){let a=s.split(/(\r?\n|\t)/);a[a.length-1]===""&&a.pop();for(let l=0;l<a.length;l++){let c=qn();if(gn(c)){let u=a[l];u===`
`||u===`\r
`?c.insertParagraph():u===" "?c.insertNodes([Don()]):c.insertText(u)}}}else e.insertRawText(s)}function QQe(t,e,n){t.dispatchCommand(xin,{nodes:e,selection:n})||(n.insertNodes(e),function(r){if(gn(r)&&r.isCollapsed()){let o=r.anchor,i=null,s=lV(o,"previous");if(s)if(dxe(s))i=s.origin;else{let a=Uon(s,fM(ho(),"next").getFlipped());for(let l of a){if(Ho(l.origin)){i=l.origin;break}if(io(l.origin)&&!l.origin.isInline())break}}if(i&&Ho(i)){let a=i.getFormat(),l=i.getStyle();r.format===a&&r.style===l||(r.format=a,r.style=l,r.dirty=!0)}}}(n))}function Fan(t,e,n,r=[]){let o=e===null||n.isSelected(e),i=io(n)&&n.excludeFromCopy("html"),s=n;if(e!==null){let c=dM(n);c=Ho(c)&&e!==null?Gxe(e,c):c,s=c}let a=io(s)?s.getChildren():[],l=function(c){let u=c.exportJSON(),d=c.constructor;if(u.type!==d.getType()&&Yxe(58,d.name),io(c)){let f=u.children;Array.isArray(f)||Yxe(59,d.name)}return u}(s);if(Ho(s)){let c=s.__text;c.length>0?l.text=c:o=!1}for(let c=0;c<a.length;c++){let u=a[c],d=Fan(t,e,u,l.children);!o&&io(n)&&d&&n.extractWithChild(u,e,"clone")&&(o=!0)}if(o&&!i)r.push(l);else if(Array.isArray(l.children))for(let c=0;c<l.children.length;c++){let u=l.children[c];r.push(u)}return o}function Uan(t,e){let n=[],r=ho().getChildren();for(let o=0;o<r.length;o++)Fan(t,e,r[o],n);return{namespace:t._config.namespace,nodes:n}}function jan(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=Yon(r);Ho(o)&&ran(o),e.push(o)}return e}async function zPr(t,e,n){if(kV!==null)return!1;if(e!==null)return new Promise((c,u)=>{t.update(()=>{c(Lan(t,e,n))})});let r=t.getRootElement(),o=t._window||window,i=window.document,s=dQe(o);if(r===null||s===null)return!1;let a=i.createElement("span");a.style.cssText="position: fixed; top: -1000px;",a.append(i.createTextNode("#")),r.append(a);let l=new Range;return l.setStart(a,0),l.setEnd(a,1),s.removeAllRanges(),s.addRange(l),new Promise((c,u)=>{let d=t.registerCommand(mxe,f=>(nte(f,ClipboardEvent)&&(d(),kV!==null&&(window.clearTimeout(kV),kV=null),c(Lan(t,f,n))),!0),pxe);kV=window.setTimeout(()=>{d(),kV=null,c(!1)},50),i.execCommand("copy"),a.remove()})}function Lan(t,e,n){if(n===void 0){let o=dQe(t._window);if(!o)return!1;let i=o.anchorNode,s=o.focusNode;if(i!==null&&s!==null&&!Min(t,i,s))return!1;let a=qn();if(a===null)return!1;n=Ban(a)}e.preventDefault();let r=e.clipboardData;return r!==null&&(zan(r,n),!0)}function Ban(t=qn()){let e={"text/plain":t?t.getTextContent():""};if(t){let n=lxe();for(let[r,o]of HPr){let i=o(n,t);i!==null&&(e[r]=i)}}return e}function zan(t,e){for(let n in e){let r=e[n];r!==void 0&&t.setData(n,r)}}var kV,HPr,Han=b(()=>{Ran();ete();J$();$o();kV=null;HPr=[["text/html",$an],["application/x-lexical-editor",Dan]]});var FS,lIi,cIi,uIi,Wan,dIi,tet,fIi,pIi,mIi,hIi,Van=b(()=>{Han();FS=eet,lIi=FS.$generateJSONFromSelectedNodes,cIi=FS.$generateNodesFromSerializedNodes,uIi=FS.$getClipboardDataFromSelection,Wan=FS.$getHtmlContent,dIi=FS.$getLexicalContent,tet=FS.$insertDataTransferForPlainText,fIi=FS.$insertDataTransferForRichText,pIi=FS.$insertGeneratedNodes,mIi=FS.copyToClipboard,hIi=FS.setLexicalClipboardDataTransfer});var net={};sr(net,{registerPlainText:()=>ZPr});function Kan(t,e){e.update(()=>{if(t!==null){let n=nte(t,KeyboardEvent)?null:t.clipboardData,r=qn();if(r!==null&&n!=null){t.preventDefault();let o=Wan(e);o!==null&&n.setData("text/html",o),n.setData("text/plain",r.getTextContent())}}})}function ZPr(t){return g0(t.registerCommand(fV,e=>{let n=qn();return!!gn(n)&&(n.deleteCharacter(e),!0)},Rs),t.registerCommand(lin,e=>{let n=qn();return!!gn(n)&&(n.deleteWord(e),!0)},Rs),t.registerCommand(ain,e=>{let n=qn();return!!gn(n)&&(n.deleteLine(e),!0)},Rs),t.registerCommand(iin,e=>{let n=qn();if(!gn(n))return!1;if(typeof e=="string")n.insertText(e);else{let r=e.dataTransfer;if(r!=null)tet(r,n);else{let o=e.data;o&&n.insertText(o)}}return!0},Rs),t.registerCommand(_in,()=>{let e=qn();return!!gn(e)&&(e.removeText(),!0)},Rs),t.registerCommand(uQe,e=>{let n=qn();return!!gn(n)&&(n.insertLineBreak(e),!0)},Rs),t.registerCommand(fin,()=>{let e=qn();return!!gn(e)&&(e.insertLineBreak(),!0)},Rs),t.registerCommand(min,e=>{let n=qn();if(!gn(n))return!1;let r=e,o=r.shiftKey;return!!VQe(n,!0)&&(r.preventDefault(),WQe(n,o,!0),!0)},Rs),t.registerCommand(hin,e=>{let n=qn();if(!gn(n))return!1;let r=e,o=r.shiftKey;return!!VQe(n,!1)&&(r.preventDefault(),WQe(n,o,!1),!0)},Rs),t.registerCommand(yin,e=>{let n=qn();return!!gn(n)&&(!qan||navigator.language!=="ko-KR")&&(e.preventDefault(),t.dispatchCommand(fV,!0))},Rs),t.registerCommand(vin,e=>{let n=qn();return!!gn(n)&&(e.preventDefault(),t.dispatchCommand(fV,!1))},Rs),t.registerCommand(mV,e=>{let n=qn();if(!gn(n))return!1;if(e!==null){if((qan||qPr||GPr)&&VPr)return!1;e.preventDefault()}return t.dispatchCommand(uQe,!1)},Rs),t.registerCommand(Sin,()=>(fxe(),!0),Rs),t.registerCommand(mxe,e=>{let n=qn();return!!gn(n)&&(Kan(e,t),!0)},Rs),t.registerCommand(sin,e=>{let n=qn();return!!gn(n)&&(function(r,o){Kan(r,o),o.update(()=>{let i=qn();gn(i)&&i.removeText()})}(e,t),!0)},Rs),t.registerCommand(vxe,e=>{let n=qn();return!!gn(n)&&(function(r,o){r.preventDefault(),o.update(()=>{let i=qn(),s=nte(r,ClipboardEvent)?r.clipboardData:null;s!=null&&gn(i)&&tet(s,i)},{tag:win})}(e,t),!0)},Rs),t.registerCommand(uin,e=>{let n=qn();return!!gn(n)&&(e.preventDefault(),!0)},Rs),t.registerCommand(cin,e=>{let n=qn();return!!gn(n)&&(e.preventDefault(),!0)},Rs))}var IV,WPr,VPr,qPr,qan,KPr,GPr,Gan=b(()=>{Van();ete();J$();$o();IV=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0,WPr=IV&&"documentMode"in document?document.documentMode:null,VPr=!(!IV||!("InputEvent"in window)||WPr)&&"getTargetRanges"in new window.InputEvent("input"),qPr=IV&&/Version\/[\d.]+.*Safari/.test(navigator.userAgent),qan=IV&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,KPr=IV&&/^(?=.*Chrome).*/i.test(navigator.userAgent),GPr=IV&&/AppleWebKit\/[\d.]+/.test(navigator.userAgent)&&!KPr});var YPr,Zan,Yan=b(()=>{Gan();YPr=net,Zan=YPr.registerPlainText});var oet={};sr(oet,{PlainTextPlugin:()=>JPr});function Jan(t){return t.getEditorState().read(Vxe(t.isComposing()))}function JPr({contentEditable:t,placeholder:e=null,ErrorBoundary:n}){let[r]=go(),o=function(i,s){let[a,l]=(0,Dv.useState)(()=>i.getDecorators());return ret(()=>i.registerDecoratorListener(c=>{(0,Jxe.flushSync)(()=>{l(c)})}),[i]),(0,Dv.useEffect)(()=>{l(i.getDecorators())},[i]),(0,Dv.useMemo)(()=>{let c=[],u=Object.keys(a);for(let d=0;d<u.length;d++){let f=u[d],p=(0,wM.jsx)(s,{onError:h=>i._onError(h),children:(0,wM.jsx)(Dv.Suspense,{fallback:null,children:a[f]})}),m=i.getElementByKey(f);m!==null&&c.push((0,Jxe.createPortal)(p,m,f))}return c},[s,a,i])}(r,n);return function(i){ret(()=>g0(Zan(i),kan(i)),[i])}(r),(0,wM.jsxs)(wM.Fragment,{children:[t,(0,wM.jsx)(XPr,{content:e}),o]})}function XPr({content:t}){let[e]=go(),n=function(o){let[i,s]=(0,Dv.useState)(()=>Jan(o));return ret(()=>{function a(){let l=Jan(o);s(l)}return a(),g0(o.registerUpdateListener(()=>{a()}),o.registerEditableListener(()=>{a()}))},[o]),i}(e),r=jsn();return n?typeof t=="function"?t(r):t:null}var Dv,Jxe,wM,ret,Xan=b(()=>{Il();Bsn();DQe();J$();Dv=L(B(),1),Jxe=L(Es(),1),wM=L(Mt(),1);Ian();Yan();ret=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0?Dv.useLayoutEffect:Dv.useEffect});var QPr,Xxe,iet=b(()=>{Xan();QPr=oet,Xxe=QPr.PlainTextPlugin});var set={};sr(set,{ContentEditable:()=>tAr,ContentEditableElement:()=>tln});function eAr({editor:t,ariaActiveDescendant:e,ariaAutoComplete:n,ariaControls:r,ariaDescribedBy:o,ariaErrorMessage:i,ariaExpanded:s,ariaInvalid:a,ariaLabel:l,ariaLabelledBy:c,ariaMultiline:u,ariaOwns:d,ariaRequired:f,autoCapitalize:p,className:m,id:h,role:g="textbox",spellCheck:v=!0,style:y,tabIndex:w,"data-testid":_,...S},I){let[C,k]=(0,jf.useState)(t.isEditable()),T=(0,jf.useCallback)(E=>{E&&E.ownerDocument&&E.ownerDocument.defaultView?t.setRootElement(E):t.setRootElement(null)},[t]),P=(0,jf.useMemo)(()=>function(...E){return O=>{E.forEach($=>{typeof $=="function"?$(O):$!=null&&($.current=O)})}}(I,T),[T,I]);return eln(()=>(k(t.isEditable()),t.registerEditableListener(E=>{k(E)})),[t]),(0,y0.jsx)("div",{"aria-activedescendant":C?e:void 0,"aria-autocomplete":C?n:"none","aria-controls":C?r:void 0,"aria-describedby":o,...i!=null?{"aria-errormessage":i}:{},"aria-expanded":C&&g==="combobox"?!!s:void 0,...a!=null?{"aria-invalid":a}:{},"aria-label":l,"aria-labelledby":c,"aria-multiline":u,"aria-owns":C?d:void 0,"aria-readonly":!C||void 0,"aria-required":f,autoCapitalize:p,className:m,contentEditable:C,"data-testid":_,id:h,ref:P,role:g,spellCheck:v,style:y,tabIndex:w,...S})}function Qan(t){return t.getEditorState().read(Vxe(t.isComposing()))}function nAr(t,e){let{placeholder:n,...r}=t,[o]=go();return(0,y0.jsxs)(y0.Fragment,{children:[(0,y0.jsx)(tln,{editor:o,...r,ref:e}),n!=null&&(0,y0.jsx)(rAr,{editor:o,content:n})]})}function rAr({content:t,editor:e}){let n=function(s){let[a,l]=(0,jf.useState)(()=>Qan(s));return eln(()=>{function c(){let u=Qan(s);l(u)}return c(),g0(s.registerUpdateListener(()=>{c()}),s.registerEditableListener(()=>{c()}))},[s]),a}(e),[r,o]=(0,jf.useState)(e.isEditable());if((0,jf.useLayoutEffect)(()=>(o(e.isEditable()),e.registerEditableListener(s=>{o(s)})),[e]),!n)return null;let i=null;return typeof t=="function"?i=t(r):t!==null&&(i=t),i===null?null:(0,y0.jsx)("div",{"aria-hidden":!0,children:i})}var jf,y0,eln,tln,tAr,nln=b(()=>{Il();jf=L(B(),1),y0=L(Mt(),1);DQe();J$();eln=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0?jf.useLayoutEffect:jf.useEffect;tln=(0,jf.forwardRef)(eAr);tAr=(0,jf.forwardRef)(nAr)});var rln,Qxe,OIi,aet=b(()=>{nln();rln=set,Qxe=rln.ContentEditable,OIi=rln.ContentEditableElement});var det={};sr(det,{createEmptyHistoryState:()=>uAr,registerHistory:()=>cAr});function aAr(t,e,n,r,o){if(t===null||n.size===0&&r.size===0&&!o)return l_;let i=e._selection,s=t._selection;if(o)return oAr;if(!(gn(i)&&gn(s)&&s.isCollapsed()&&i.isCollapsed()))return l_;let a=function(v,y,w){let _=v._nodeMap,S=[];for(let I of y){let C=_.get(I);C!==void 0&&S.push(C)}for(let[I,C]of w){if(!C)continue;let k=_.get(I);k===void 0||cV(k)||S.push(k)}return S}(e,n,r);if(a.length===0)return l_;if(a.length>1){let v=e._nodeMap,y=v.get(i.anchor.key),w=v.get(s.anchor.key);return y&&w&&!t._nodeMap.has(y.__key)&&Ho(y)&&y.__text.length===1&&i.anchor.offset===1?oln:l_}let l=a[0],c=t._nodeMap.get(l.__key);if(!Ho(c)||!Ho(l)||c.__mode!==l.__mode)return l_;let u=c.__text,d=l.__text;if(u===d)return l_;let f=i.anchor,p=s.anchor;if(f.key!==p.key||f.type!=="text")return l_;let m=f.offset,h=p.offset,g=d.length-u.length;return g===1&&h===m-1?oln:g===-1&&h===m+1?iAr:g===-1&&h===m?sAr:l_}function lAr(t,e){let n=Date.now(),r=l_;return(o,i,s,a,l,c)=>{let u=Date.now();if(c.has(gxe))return r=l_,n=u,uet;let d=aAr(o,i,a,l,t.isComposing()),f=(()=>{let p=s===null||s.editor===t,m=c.has(din);if(!m&&p&&c.has(pV))return eSe;if(o===null)return cet;let h=i._selection;return a.size>0||l.size>0?m===!1&&d!==l_&&d===r&&u<n+e&&p||a.size===1&&function(g,v,y){let w=v._nodeMap.get(g),_=y._nodeMap.get(g),S=v._selection,I=y._selection;return!(gn(S)&&gn(I)&&S.anchor.type==="element"&&S.focus.type==="element"&&I.anchor.type==="text"&&I.focus.type==="text"||!Ho(w)||!Ho(_)||w.__parent!==_.__parent)&&JSON.stringify(v.read(()=>w.exportJSON()))===JSON.stringify(y.read(()=>_.exportJSON()))}(Array.from(a)[0],o,i)?eSe:cet:h!==null?eSe:uet})();return n=u,r=d,f}}function iln(t){t.undoStack=[],t.redoStack=[],t.current=null}function cAr(t,e,n){let r=lAr(t,n);return g0(t.registerCommand(Cin,()=>(function(i,s){let a=s.redoStack,l=s.undoStack;if(l.length!==0){let c=s.current,u=l.pop();c!==null&&(a.push(c),i.dispatchCommand(Fee,!0)),l.length===0&&i.dispatchCommand(Uee,!1),s.current=u||null,u&&u.editor.setEditorState(u.editorState,{tag:gxe})}}(t,e),!0),Rs),t.registerCommand(bin,()=>(function(i,s){let a=s.redoStack,l=s.undoStack;if(a.length!==0){let c=s.current;c!==null&&(l.push(c),i.dispatchCommand(Uee,!0));let u=a.pop();a.length===0&&i.dispatchCommand(Fee,!1),s.current=u||null,u&&u.editor.setEditorState(u.editorState,{tag:gxe})}}(t,e),!0),Rs),t.registerCommand(rin,()=>(iln(e),!1),Rs),t.registerCommand(oin,()=>(iln(e),t.dispatchCommand(Fee,!1),t.dispatchCommand(Uee,!1),!0),Rs),t.registerUpdateListener(({editorState:i,prevEditorState:s,dirtyLeaves:a,dirtyElements:l,tags:c})=>{let u=e.current,d=e.redoStack,f=e.undoStack,p=u===null?null:u.editorState;if(u!==null&&i===p)return;let m=r(s,i,u,a,l,c);if(m===cet)d.length!==0&&(e.redoStack=[],t.dispatchCommand(Fee,!1)),u!==null&&(f.push({...u}),t.dispatchCommand(Uee,!0));else if(m===uet)return;e.current={editor:t,editorState:i}}))}function uAr(){return{current:null,redoStack:[],undoStack:[]}}var eSe,cet,uet,l_,oAr,oln,iAr,sAr,sln=b(()=>{J$();$o();eSe=0,cet=1,uet=2,l_=0,oAr=1,oln=2,iAr=3,sAr=4});var aln,tSe,lln,fet=b(()=>{sln();aln=det,tSe=aln.createEmptyHistoryState,lln=aln.registerHistory});var pet={};sr(pet,{HistoryPlugin:()=>dAr,createEmptyHistoryState:()=>tSe});function dAr({delay:t,externalHistoryState:e}){let[n]=go();return function(r,o,i=1e3){let s=(0,nSe.useMemo)(()=>o||tSe(),[o]);(0,nSe.useEffect)(()=>lln(r,s,i),[i,r,s])}(n,e,t),null}var nSe,cln=b(()=>{Il();fet();fet();nSe=L(B(),1)});var uln,rSe,jIi,met=b(()=>{cln();uln=pet,rSe=uln.HistoryPlugin,jIi=uln.createEmptyHistoryState});var het={};sr(het,{OnChangePlugin:()=>pAr});function pAr({ignoreHistoryMergeTagChange:t=!0,ignoreSelectionChange:e=!1,onChange:n}){let[r]=go();return fAr(()=>{if(n)return r.registerUpdateListener(({editorState:o,dirtyElements:i,dirtyLeaves:s,prevEditorState:a,tags:l})=>{e&&i.size===0&&s.size===0||t&&l.has(pV)||a.isEmpty()||n(o,r,l)})},[r,t,e,n]),null}var oSe,fAr,dln=b(()=>{Il();$o();oSe=L(B(),1),fAr=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0?oSe.useLayoutEffect:oSe.useEffect});var mAr,iSe,get=b(()=>{dln();mAr=het,iSe=mAr.OnChangePlugin});var wet={};sr(wet,{LexicalErrorBoundary:()=>gAr});function vet(t,e){return vet=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},vet(t,e)}function gAr({children:t,onError:e}){return(0,yet.jsx)(hAr,{fallback:(0,yet.jsx)("div",{style:{border:"1px solid #f00",color:"#f00",padding:"8px"},children:"An error was thrown."}),onError:e,children:t})}var TV,yet,fln,hAr,pln=b(()=>{TV=L(B(),1),yet=L(Mt(),1);fln={error:null},hAr=function(t){var e,n;function r(){for(var i,s=arguments.length,a=new Array(s),l=0;l<s;l++)a[l]=arguments[l];return(i=t.call.apply(t,[this].concat(a))||this).state=fln,i.resetErrorBoundary=function(){for(var c,u=arguments.length,d=new Array(u),f=0;f<u;f++)d[f]=arguments[f];i.props.onReset==null||(c=i.props).onReset.apply(c,d),i.reset()},i}n=t,(e=r).prototype=Object.create(n.prototype),e.prototype.constructor=e,vet(e,n),r.getDerivedStateFromError=function(i){return{error:i}};var o=r.prototype;return o.reset=function(){this.setState(fln)},o.componentDidCatch=function(i,s){var a,l;(a=(l=this.props).onError)==null||a.call(l,i,s)},o.componentDidUpdate=function(i,s){var a,l,c,u,d=this.state.error,f=this.props.resetKeys;d!==null&&s.error!==null&&((c=i.resetKeys)===void 0&&(c=[]),(u=f)===void 0&&(u=[]),c.length!==u.length||c.some(function(p,m){return!Object.is(p,u[m])}))&&((a=(l=this.props).onResetKeysChange)==null||a.call(l,i.resetKeys,f),this.reset())},o.render=function(){var i=this.state.error,s=this.props,a=s.fallbackRender,l=s.FallbackComponent,c=s.fallback;if(i!==null){var u={error:i,resetErrorBoundary:this.resetErrorBoundary};if(TV.isValidElement(c))return c;if(typeof a=="function")return a(u);if(l)return TV.createElement(l,u);throw new Error("react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop")}return this.props.children},r}(TV.Component)});var yAr,sSe,bet=b(()=>{pln();yAr=wet,sSe=yAr.LexicalErrorBoundary});function eD(t){_et.add(t)}function tD(t){_et.delete(t)}function rte(t){return _et.has(t)}function ote(t){let e=X$.get(Q$);X$.set(Q$,e.filter(n=>n.title!==t))}function nD(t,e){let n=X$.get(Q$),r;(e?n.findIndex(i=>i.title===e):-1)!==-1?r=n.map(i=>i.title===e?t:i):r=[...n,t],X$.set(Q$,r)}function PV(t){X$.set(Q$,t)}function aSe(){return Ar(Q$,{store:X$})}function Bf(){return X$.get(Q$)}var X$,Q$,_et,c_=b(()=>{Us();Us();X$=sy(),Q$=yo([]),_et=new Set});var xet,US,v0,w0,jS,b0,_0,mln,rD=b(()=>{xet="{copilot-selection}",US={title:"",content:"",showInContextMenu:!0,showInSlashMenu:!0,order:0,modelKey:"",lastUsedMs:0},v0="copilot-command-context-menu-enabled",w0="copilot-command-slash-enabled",jS="copilot-command-context-menu-order",b0="copilot-command-model-key",_0="copilot-command-last-used",mln=[{title:"Fix grammar and spelling",content:"Fix the grammar and spelling of {}. Preserve all formatting, line breaks, and special characters. Do not add or remove any content. Return only the corrected text.",showInContextMenu:!0,showInSlashMenu:!0,order:1e3,modelKey:"",lastUsedMs:0},{title:"Translate to Chinese",content:`Translate {} into Chinese:
1. Preserve the meaning and tone
2. Maintain appropriate cultural context
3. Keep formatting and structure
Return only the translated text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1010,modelKey:"",lastUsedMs:0},{title:"Summarize",content:"Create a bullet-point summary of {}. Each bullet point should capture a key point. Return only the bullet-point summary.",showInContextMenu:!0,showInSlashMenu:!0,order:1020,modelKey:"",lastUsedMs:0},{title:"Simplify",content:"Simplify {} to a 6th-grade reading level (ages 11-12). Use simple sentences, common words, and clear explanations. Maintain the original key concepts. Return only the simplified text.",showInContextMenu:!0,showInSlashMenu:!0,order:1030,modelKey:"",lastUsedMs:0},{title:"Explain like I am 5",content:`Explain {} in simple terms that a 5-year-old would understand:
1. Use basic vocabulary
2. Include simple analogies
3. Break down complex concepts
Return only the simplified explanation.`,showInContextMenu:!0,showInSlashMenu:!0,order:1040,modelKey:"",lastUsedMs:0},{title:"Emojify",content:`Add relevant emojis to enhance {}. Follow these rules:
1. Insert emojis at natural breaks in the text
2. Never place two emojis next to each other
3. Keep all original text unchanged
4. Choose emojis that match the context and tone
Return only the emojified text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1050,modelKey:"",lastUsedMs:0},{title:"Make shorter",content:`Reduce {} to half its length while preserving these elements:
1. Main ideas and key points
2. Essential details
3. Original tone and style
Return only the shortened text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1060,modelKey:"",lastUsedMs:0},{title:"Make longer",content:`Expand {} to twice its length by:
1. Adding relevant details and examples
2. Elaborating on key points
3. Maintaining the original tone and style
Return only the expanded text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1070,modelKey:"",lastUsedMs:0},{title:"Generate table of contents",content:"Generate a hierarchical table of contents for {}. Use appropriate heading levels (H1, H2, H3, etc.). Include page numbers if present. Return only the table of contents.",showInContextMenu:!1,showInSlashMenu:!1,order:1080,modelKey:"",lastUsedMs:0},{title:"Generate glossary",content:'Create a glossary of important terms, concepts, and phrases from {}. Format each entry as "Term: Definition". Sort entries alphabetically. Return only the glossary.',showInContextMenu:!1,showInSlashMenu:!1,order:1090,modelKey:"",lastUsedMs:0},{title:"Remove URLs",content:"Remove all URLs from {}. Preserve all other content and formatting. URLs may be in various formats (http, https, www). Return only the text with URLs removed.",showInContextMenu:!1,showInSlashMenu:!1,order:1100,modelKey:"",lastUsedMs:0},{title:"Rewrite as tweet",content:`Rewrite {} as a single tweet with these requirements:
1. Maximum 280 characters
2. Use concise, impactful language
3. Maintain the core message
Return only the tweet text.`,showInContextMenu:!1,showInSlashMenu:!1,order:1110,modelKey:"",lastUsedMs:0},{title:"Rewrite as tweet thread",content:`Convert {} into a Twitter thread following these rules:
1. Each tweet must be under 240 characters
2. Start with "THREAD START" on its own line
3. Separate tweets with "
---
"
4. End with "THREAD END" on its own line
5. Make content engaging and clear
Return only the formatted thread.`,showInContextMenu:!1,showInSlashMenu:!1,order:1120,modelKey:"",lastUsedMs:0},{title:"Clip YouTube Transcript",content:`
Based on the YouTube video information and transcript provided in the context, generate a complete Obsidian note in the following format.
IMPORTANT: If no YouTube video context is found, remind the user to:
1. Open a YouTube video in Web Viewer (or use @ to select a YouTube web tab)
2. Then use this command again
Generate the note with this exact structure:
---
title: "<video title>"
description: "<first 200 chars of description>"
channel: "<channel name>"
url: "<video url>"
duration: "<duration>"
published: <upload date in YYYY-MM-DD format>
thumbnailUrl: "<YouTube thumbnail URL: i.ytimg.com/vi/VIDEO_ID/maxresdefault.jpg with https protocol>"
genre:
- "<genre>"
watched:
---
![<video title>](<video url>)
> [!summary]- Description
> <full video description, preserve line breaks>
## Summary
<Brief 2-3 paragraph summary of the video content>
## Key Takeaways
<List 5-8 key takeaways as bullet points>
## Mindmap
CRITICAL Mermaid mindmap syntax rules - MUST follow exactly:
- Root node format: root(Topic Name) - use round brackets, NO double brackets
- Child nodes: just plain text, no brackets needed
- Do NOT use quotes, parentheses, brackets, or any special characters in text
- Do NOT use icons or emojis
- Keep all node text short and simple - max 3-4 words per node
- Use only letters, numbers, and spaces
Example of CORRECT syntax:
\`\`\`mermaid
mindmap
root(Video Main Topic)
First Theme
Detail one
Detail two
Second Theme
Detail three
Third Theme
\`\`\`
## Notable Quotes
<List 5-10 notable quotes from the transcript. Format each as:>
- [<timestamp>: <quote text>](<video_url>&t=<seconds>s)
Return only the markdown content without any explanations or comments.`,showInContextMenu:!1,showInSlashMenu:!0,order:1130,modelKey:"",lastUsedMs:0},{title:"Clip Web Page",content:`
Based on the web page content provided in the context (from Obsidian Web Clipper or Web Viewer), generate a complete Obsidian note.
IMPORTANT: If no web page context is found, remind the user to:
1. Open a web page in Web Viewer (or use @ to select a web tab)
2. Or open a note clipped by Obsidian Web Clipper
3. Then use this command again
Generate the note with this exact structure:
---
title: "<page title>"
source: "<page url>"
description: "<brief description>"
tags:
- "clippings"
---
## Summary
<Brief 2-3 paragraph summary of the page content>
## Key Takeaways
<List 5-8 key takeaways as bullet points>
## Mindmap
CRITICAL Mermaid mindmap syntax rules - MUST follow exactly:
- Root node format: root(Topic Name) - use round brackets, NO double brackets
- Child nodes: just plain text, no brackets needed
- Do NOT use quotes, parentheses, brackets, or any special characters in text
- Keep all node text short and simple - max 3-4 words per node
\`\`\`mermaid
mindmap
root(Main Topic)
Theme One
Detail
Theme Two
Detail
\`\`\`
## Notable Quotes
<List 3-5 notable quotes from the content, if any>
Return only the markdown content without any explanations or comments.`,showInContextMenu:!1,showInSlashMenu:!0,order:1140,modelKey:"",lastUsedMs:0}]});function cSe(t,e,n){let r=t.trim();return r?t!==r?"Command name cannot have leading or trailing spaces":n&&t===n?null:/[#<>:"/\\|?*[\]^\x00-\x1F]/g.test(r)?'Command name contains invalid characters. Avoid using: < > : " / \\ | ? * [ ] ^':e.some(i=>i.title.toLowerCase()===r.toLowerCase())?"A command with this name already exists":null:"Command name cannot be empty"}function oD(t){return encodeURIComponent(t.toLowerCase())}function bM(){return E2()}function AV(t){return`${bM()}/${t}.md`}function EV(t){if(!(t instanceof lSe.TFile)||t.extension!=="md")return!1;let e=bM();return!(!t.path.startsWith(e+"/")||t.path.slice(e.length+1).includes("/"))}function hln(t,e){return t.metadataCache.getFileCache(e)?.frontmatter?.[jS]!=null}async function ite(t,e){let n=await t.vault.read(e),r=fy(n),o=t.metadataCache.getFileCache(e),i=o?.frontmatter?.[v0]??US.showInContextMenu,s=o?.frontmatter?.[w0]??US.showInSlashMenu,a=o?.frontmatter?.[_0]??US.lastUsedMs,l=o?.frontmatter?.[jS]??US.order,c=o?.frontmatter?.[b0]??US.modelKey;return{title:e.basename,modelKey:c,content:r,showInContextMenu:i,showInSlashMenu:s,order:l,lastUsedMs:a}}async function Cet(t){let e=t.vault.getFiles().filter(n=>EV(n));return await Promise.all(e.map(n=>ite(t,n)))}async function gln(t){let e=await Cet(t);return PV(e),e}function ste(t){return ay(t,"manual",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:()=>0,getManualOrder:e=>e.order})}function vAr(t){return ay(t,"recent",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:e=>e.lastUsedMs})}function wAr(t){return ay(t,"name",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:()=>0})}function uSe(t){switch(Y().promptSortStrategy){case"timestamp":return vAr(t);case"alphabetical":return wAr(t);case"manual":return ste(t);default:return t}}async function ate(t,e,n,r=!1){let i=(await lte(t,e,n,t.vault,t.workspace.getActiveFile())).processedPrompt;if(i.includes(`{${Xp}}`)||r)return i;let s=i.indexOf(xet);return s===-1?n.trim()?i+`
<`+Xp+">"+n+"</"+Xp+">":i:i.slice(0,s)+n+i.slice(s+xet.length)}async function _Ar(t,e,n,r){let o=new Map,i=new Set,s;for(;(s=bAr.exec(e))!==null;){let a=s[1].trim(),l={content:"",files:[]},c=a.toLowerCase();if(c==="activenote")if(r){let u=await k2(r,n);u&&(l.content=`<${FO}>
<path>${r.path}</path>
## ${Lie(r)}
${u}
</${FO}>`,l.files.push(r))}else new lSe.Notice("No active note found.");else{if(c==="activewebtab")continue;if(a.startsWith("#")){let u=a.slice(1).split(",").map(p=>p.trim()),d=Nie(t,u),f=[];for(let p of d){let m=await k2(p,n);m&&(f.push(`<${FO}>
<path>${p.path}</path>
## ${Lie(p)}
${m}
</${FO}>`),l.files.push(p))}l.content=f.join(`
`)}else{let u=Wdt(a),d=BK(n,u),f=[];for(let p of d){let m=await k2(p,n);m&&(f.push(`<${FO}>
<path>${p.path}</path>
## ${Lie(p)}
${m}
</${FO}>`),l.files.push(p))}l.content=f.join(`
`)}}l.content?(o.set(a,l.content),l.files.forEach(u=>i.add(u))):c!=="activenote"&&c!=="activewebtab"&&(a.startsWith('"')||W(`No notes found for variable: ${a}`))}return{variablesMap:o,includedFiles:i}}async function lte(t,e,n,r,o,i=!1){let s=Y(),a=new Set;if(!s.enableCustomPromptTemplating)return!i&&e.includes("{}")&&!n&&o&&a.add(o),{processedPrompt:e+`
`,includedFiles:Array.from(a)};let{variablesMap:l,includedFiles:c}=await _Ar(t,e,r,o);c.forEach(m=>a.add(m));let u=e,d="",f=null;!i&&u.includes("{}")&&(u=u.replace(/\{\}/g,`{${Xp}}`),n?d+=`<${Xp}>
${n}
</${Xp}>`:o?(f=await k2(o,r),d+=`<${Xp} type="active_note">
${f||""}
</${Xp}>`,a.add(o)):d+=`<${Xp}>
(No selected text or active note available)
</${Xp}>`);for(let[m,h]of l.entries())m.toLowerCase()==="activenote"&&f!==null||(d?d+=`
<${Z5} name="${m}">
${h}
</${Z5}>`:d+=`<${Z5} name="${m}">
${h}
</${Z5}>`);let p=Hdt(u,r);for(let m of p)if(!a.has(m)){let h=await k2(m,r);if(h){let g=await r.adapter.stat(m.path),v=g?new Date(g.ctime).toISOString():"Unknown",y=g?new Date(g.mtime).toISOString():"Unknown",w=`<${G5}>
<title>${m.basename}</title>
<path>${m.path}</path>
<ctime>${v}</ctime>
<mtime>${y}</mtime>
<content>
${h}
</content>
</${G5}>`;d&&(d+=`
`),d+=`${w}`,a.add(m)}}return{processedPrompt:d?`${u}
${d}`:`${u}
`,includedFiles:Array.from(a)}}function yln(t,e){let r=`${t} (copy)`,o=1;for(;e.some(i=>i.title.toLowerCase()===r.toLowerCase());)o++,r=`${t} (copy ${o})`;return r}function dSe(){let e=Bf().reduce((n,r)=>n>r.order?n:r.order,0);return e===Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e+10}async function ket(t,e,n){try{eD(e.path),await t.fileManager.processFrontMatter(e,r=>{r[v0]==null&&(r[v0]=n.showInContextMenu),r[w0]==null&&(r[w0]=n.showInSlashMenu),r[jS]==null&&(r[jS]=n.order),r[b0]==null&&(r[b0]=n.modelKey),r[_0]==null&&(r[_0]=n.lastUsedMs)})}finally{tD(e.path)}}var lSe,bAr,Og=b(()=>{rD();pe();lSe=require("obsidian");Se();Is();c_();W5();ut();wC();gt();bAr=/\{(?!copilot-selection\}|\[\[)([^}]+)\}/g});var cte,Fa,x0=b(()=>{cte=require("obsidian");Og();iy();rD();c_();ut();Jh();Fa=class t{constructor(e){this.app=e}static getInstance(e){if(!t.instance){if(!e)throw new Error("CustomCommandManager.getInstance() requires `app` on first call (seed it at plugin load).");t.instance=new t(e)}return t.instance}async createCommand(e,n={}){let r={skipStoreUpdate:!1,autoOrder:!0,...n},o=AV(e.title);try{eD(o);let i=e.order;r.autoOrder&&(i=dSe()),e={...e,order:i};let s=bM();await ao(this.app.vault,s);let a=this.app.vault.getAbstractFileByPath(o),l;a instanceof cte.TFile?(await this.app.vault.modify(a,e.content),l=a):l=await this.app.vault.create(o,e.content),await this.app.fileManager.processFrontMatter(l,c=>{c[v0]=e.showInContextMenu,c[w0]=e.showInSlashMenu,c[jS]=e.order,c[b0]=e.modelKey,c[_0]=e.lastUsedMs}),r.skipStoreUpdate||nD(e,e.title)}finally{tD(o)}}async recordUsage(e){await this.updateCommand({...e,lastUsedMs:Date.now()},e.title)}async updateCommand(e,n,r=!1){let o=AV(e.title),i=AV(n),s=e.title!==n;try{eD(o),s&&eD(i),r||nD(e,n);let a=this.app.vault.getAbstractFileByPath(o);if(s){if(this.app.vault.getAbstractFileByPath(o))throw new Nr("Error saving custom prompt. Please check if the title already exists.");let c=this.app.vault.getAbstractFileByPath(i);c instanceof cte.TFile&&(await this.app.vault.rename(c,o),a=this.app.vault.getAbstractFileByPath(o))}a||(await this.createCommand(e,{skipStoreUpdate:r,autoOrder:!0}),a=this.app.vault.getAbstractFileByPath(AV(e.title))),a instanceof cte.TFile&&(await this.app.vault.modify(a,e.content),await this.app.fileManager.processFrontMatter(a,l=>{l[v0]=e.showInContextMenu,l[w0]=e.showInSlashMenu,l[jS]=e.order,l[b0]=e.modelKey,l[_0]=e.lastUsedMs}))}finally{tD(o),s&&tD(i)}}async updateCommands(e){PV(e),await Promise.all(e.map(n=>this.updateCommand(n,n.title,!0)))}async reorderCommands(e){let n=[...e];for(let r=0;r<n.length;r++)n[r]={...n[r],order:r*10};await this.updateCommands(n)}async deleteCommand(e){let n=AV(e.title);try{eD(n),ote(e.title);let r=this.app.vault.getAbstractFileByPath(n);r instanceof cte.TFile&&await Bc(this.app,r)}finally{tD(n)}}}});function bln(t,e){let n=e.getSelection();if(n===null||!n.isCollapsed)return null;let r=n.anchorNode,o=t,i=n.anchorOffset;if(r==null||i==null)return null;let s=e.document.createRange();try{s.setStart(r,o),s.setEnd(r,i)}catch{return null}return s}function _M({options:t,selectedIndex:e,onSelect:n,onHighlight:r,range:o,query:i,showPreview:s=!1,mode:a="search",onKeyDown:l}){let[c,u]=(0,u_.useState)(null),d=o?.startContainer.win??window,f=(0,u_.useCallback)(h=>{let g=Math.floor(h.innerWidth*xAr);if(t.length===0)return Math.min(vln,g);let v=Math.max(...t.map(S=>S.title.length)),y=Math.max(...t.map(S=>S.subtitle?.length||0)),w=Math.max(v*8+32,y*6+32),_=Math.min(Math.max(w,300),vln);return Math.min(_,g)},[t]),p=(0,u_.useCallback)(()=>{if(!o)return;let h=o.startContainer.win,g=o.getBoundingClientRect(),v=f(h),y=g.top-4,w=8,_=h.innerWidth-v-8,S=Math.min(Math.max(g.left,w),_);u({top:y,left:S,width:v})},[o,f]);if((0,u_.useEffect)(()=>{p()},[p]),(0,u_.useEffect)(()=>{if(!o)return;let h=o.startContainer.win,g=()=>p();return h.addEventListener("resize",g),h.document.addEventListener("scroll",g,{passive:!0}),()=>{h.removeEventListener("resize",g),h.document.removeEventListener("scroll",g)}},[p,o]),!c||t.length===0)return null;let m=u_.default.createElement("div",{className:"tw-absolute tw-z-[9999] tw-flex tw-flex-col tw-items-end",style:{bottom:`calc(100vh - ${c.top}px)`,left:c.left,width:c.width}},u_.default.createElement(Sxe,{options:t,selectedIndex:e,onSelect:n,onHighlight:r,query:i,mode:a,showPreview:s,onKeyDown:l,className:"tw-shadow-lg",width:c.width}));return(0,wln.createPortal)(m,d.document.body)}var u_,wln,vln,xAr,MV=b(()=>{u_=L(B()),wln=L(Es());hQe();vln=400,xAr=.9});function xM({triggerConfig:t,options:e,onSelect:n,onStateChange:r,onHighlight:o}){let[i]=go(),[s,a]=(0,Ng.useState)({isOpen:!1,query:"",selectedIndex:0,range:null});(0,Ng.useEffect)(()=>{r?.(s)},[s,r]);let l=(0,Ng.useCallback)(()=>{a({isOpen:!1,query:"",selectedIndex:0,range:null})},[]),c=(0,Ng.useCallback)(f=>{a(p=>({...p,selectedIndex:f})),o&&e[f]&&o(f,e[f])},[o,e]),u=(0,Ng.useCallback)(f=>{if(!f||!s.isOpen)return!1;switch(f.key){case"ArrowDown":{if(e.length===0)return!1;f.preventDefault();let p=s.selectedIndex+1;for(;p<e.length&&e[p]?.disabled;)p++;return p>=e.length&&(p=s.selectedIndex),c(p),!0}case"ArrowUp":{if(e.length===0)return!1;f.preventDefault();let p=s.selectedIndex-1;for(;p>=0&&e[p]?.disabled;)p--;return p<0&&(p=s.selectedIndex),c(p),!0}case"Enter":case"Tab":return e.length===0?(l(),!1):(e[s.selectedIndex]?.disabled||(f.preventDefault(),e[s.selectedIndex]&&n(e[s.selectedIndex])),!0);case"Escape":return f.preventDefault(),l(),!0;default:return!1}},[s.isOpen,s.selectedIndex,e,n,l,c]);(0,Ng.useEffect)(()=>{let f=i.registerCommand(pin,y=>u(y),c0),p=i.registerCommand(gin,y=>u(y),c0),m=i.registerCommand(mV,y=>u(y),c0),h=i.registerCommand(hV,y=>u(y),c0),g=i.registerCommand(yxe,y=>u(y),c0),v=i.registerCommand(nin,()=>(s.isOpen&&l(),!1),c0);return()=>{f(),p(),m(),h(),g(),v()}},[i,u,s.isOpen,l]);let d=(0,Ng.useCallback)((f,p)=>{let{char:m,multiChar:h=!1,allowWhitespace:g=!1}=t;if(h){let v=m.length,y=-1;for(let w=p-1;w>=v-1;w--)if(f.slice(w-v+1,w+1)===m){if(w-v+1===0||/\s/.test(f[w-v])){y=w-v+1;break}}else if(!g&&/\s/.test(f[w]))break;if(y!==-1){let w=f.slice(y+v,p);return w.startsWith(" ")?null:{triggerIndex:y,query:w}}}else{let v=-1;for(let y=p-1;y>=0;y--){let w=f[y];if(w===m){if(y===0||/\s/.test(f[y-1])){v=y;break}}else if(!g&&/\s/.test(w))break}if(v!==-1){let y=f.slice(v+1,p);return y.startsWith(" ")?null:{triggerIndex:v,query:y}}}return null},[t]);return(0,Ng.useEffect)(()=>i.registerUpdateListener(({editorState:f})=>{f.read(()=>{let p=qn();if(!gn(p)||!p.isCollapsed()){s.isOpen&&l();return}let m=p.anchor,h=m.getNode();if(!(h instanceof OS)){s.isOpen&&l();return}let g=h.getTextContent(),v=m.offset,y=d(g,v);if(y){let{triggerIndex:w,query:_}=y,S=i._window??window,I=bln(w,S);I&&a(C=>({...C,isOpen:!0,query:_,selectedIndex:0,range:I}))}else s.isOpen&&l()})}),[i,s.isOpen,l,d]),(0,Ng.useEffect)(()=>{a(f=>({...f,selectedIndex:0}))},[e.length]),(0,Ng.useEffect)(()=>{a(f=>f.selectedIndex>=e.length&&e.length>0?{...f,selectedIndex:Math.max(0,e.length-1)}:f)},[e.length]),{state:s,setState:a,closeMenu:l,detectTrigger:d,handleHighlight:c}}var Ng,ute=b(()=>{Ng=L(B());Il();$o();MV()});function _ln(t,e,n){let r=t.filter(s=>s.userInvocable===!1?!1:n===null?!0:s.enabledAgents.includes(n)),o=new Set(r.map(s=>s.name.toLowerCase())),i=e.filter(s=>s.showInSlashMenu?!o.has(s.title.toLowerCase()):!1);return[...r.map((s,a)=>({kind:"skill",key:`skill:${s.name}:${a}`,name:s.name,description:s.description,body:s.body,skill:s})),...i.map((s,a)=>({kind:"command",key:`command:${s.title}:${a}`,name:s.title,description:"",body:s.content,command:s}))]}var xln=b(()=>{});function kAr(){let[t,e]=(0,zf.useState)(CAr);return(0,zf.useEffect)(()=>{if(!Ln())return;let n=!1,r;async function o(){let{getManagedSkills:i,SkillManager:s,listBackendDescriptors:a}=await Promise.resolve().then(()=>(Hf(),d_)),l=()=>{n||e({enabled:!0,skills:i(),backendIds:new Set(a().map(c=>c.id))})};l(),s.hasInstance()&&(r=s.getInstance().subscribeToSkillSetChange(l))}return o().catch(i=>{n||H("Failed to load Agent Mode slash commands.",i)}),()=>{n=!0,r?.()}},[]),t}function IAr(t,e){let n=xt();if(!t)return null;let r=n.agentMode?.activeBackend;return typeof r!="string"||r.length===0||!e?.has(r)?null:r}function Sln(){let[t]=go(),e=aSe(),n=kAr(),r=IAr(n.enabled,n.backendIds),[o,i]=(0,zf.useState)(""),s=(0,zf.useMemo)(()=>uSe(e),[e]),a=(0,zf.useMemo)(()=>_ln(n.skills,s,r).map(m=>({key:m.key,title:m.name,subtitle:m.description||void 0,content:m.body,item:m})),[n.skills,s,r]),l=(0,zf.useMemo)(()=>{if(!o)return a;let p=Iet.default.go(o,a,{key:"title",threshold:-1e4});return p.length>0?p.map(h=>h.obj):Iet.default.go(o,a,{key:"content",threshold:-1e4}).map(h=>h.obj)},[a,o]),c=(0,zf.useCallback)(p=>{t.update(()=>{let m=qn();if(!gn(m))return;let h=m.anchor,g=h.getNode();if(!(g instanceof OS))return;let v=g.getTextContent(),y=v.lastIndexOf("/",h.offset);if(y===-1)return;let w=v.slice(0,y),_=v.slice(h.offset),S=`/${p} `;g.setTextContent(w+S+_);let I=w.length+S.length;g.select(I,I)})},[t]),u=(0,zf.useCallback)(p=>{let m=p.item;m.kind==="command"&&Fa.getInstance().recordUsage(m.command),c(m.name)},[c]),{state:d,handleHighlight:f}=xM({triggerConfig:{char:"/",allowWhitespace:!1},options:l,onSelect:u,onStateChange:p=>{i(p.query)}});return d.isOpen?zf.default.createElement(_M,{options:l,selectedIndex:d.selectedIndex,onSelect:u,onHighlight:f,range:d.range,query:d.query,showPreview:!0}):zf.default.createElement(zf.default.Fragment,null)}var zf,Iet,SAr,CAr,Cln=b(()=>{zf=L(B());Il();$o();Iet=L(zee());c_();x0();Og();pe();Se();$n();MV();ute();xln();SAr=Object.freeze([]),CAr=Object.freeze({enabled:!1,skills:SAr,backendIds:null})});function Iln(t,e=!1,n={},r=null){let o=Axe(e),i=(0,iD.useMemo)(()=>o.map((a,l)=>({key:`${a.basename}-${l}`,title:a.basename,subtitle:a.path,content:"",icon:iD.default.createElement(Jo,{className:"tw-size-4"}),file:a})),[o]);return(0,iD.useMemo)(()=>{let a={...TAr,...n},l=E2();if(!t.trim()){let v=i.filter(_=>!_.file.path.startsWith(l+"/")),y=i.filter(_=>_.file.path.startsWith(l+"/"));if(r){let _={key:`active-note-${r.path}`,title:"Active Note",subtitle:r.path,content:"",category:"activeNote",icon:iD.default.createElement(DC,{className:"tw-size-4"}),file:r},S=[...v,...y].slice(0,a.limit-1);return[_,...S]}return[...v,...y].slice(0,a.limit)}let c=t.trim(),u=c.toLowerCase(),p="active note".includes(u)&&r?{key:`active-note-${r.path}`,title:"Active Note",subtitle:r.path,content:"",category:"activeNote",icon:iD.default.createElement(DC,{className:"tw-size-4"}),file:r}:null,m=p?a.limit-1:a.limit,g=kln.default.go(c,i,{keys:["subtitle"],limit:m,threshold:a.threshold}).map(v=>v.obj);return p?[p,...g]:g},[i,t,n,r])}var iD,kln,TAr,Tln=b(()=>{iD=L(B());Re();kln=L(zee());_Qe();Is();TAr={limit:30,threshold:-1e4}});function Aln(){return(0,SM.useContext)(Pln)}function Eln({cloudAgentIds:t,children:e}){let n=(0,SM.useMemo)(()=>t,[t]);return SM.default.createElement(Pln.Provider,{value:n},e)}var SM,dte,Pln,fSe=b(()=>{SM=L(B()),dte=Object.freeze(new Set),Pln=(0,SM.createContext)(dte)});function PAr({backendId:t,label:e}){let{enableSelfHostMode:n}=xt(),r=Aln(),o=n&&r.has(t);return fte.default.createElement(au,null,fte.default.createElement(gy,{className:"tw-size-3"}),e,o&&fte.default.createElement(Fy,null))}function AAr(t){let e=t.getAttribute("data-pill-value");return e!==null?{node:NV(e,t.getAttribute("data-pill-label")??e)}:null}function NV(t,e){return new OV(t,e)}function Mln(t){return t instanceof OV}var fte,OV,pte=b(()=>{Re();fte=L(B());Se();fSe();qj();p0();f0();OV=class t extends ed{static getType(){return"agent-pill"}static clone(e){return new t(e.__value,e.__label,e.__key)}constructor(e,n,r){super(e,r),this.__label=n}getClassName(){return"agent-pill-wrapper"}getDataAttribute(){return"data-lexical-agent-pill"}static importDOM(){return{span:e=>e.hasAttribute("data-lexical-agent-pill")?{conversion:AAr,priority:1}:null}}static importJSON(e){return NV(e.value,e.label)}exportJSON(){return{...super.exportJSON(),type:"agent-pill",label:this.__label}}getBackendId(){return this.getValue()}getTextContent(){return""}exportDOM(e){let n=super.exportDOM(e);return n.element instanceof HTMLElement&&(n.element.setAttribute("data-pill-label",this.__label),n.element.textContent=this.__label||this.__value),n}decorate(){return fte.default.createElement(PAr,{backendId:this.__value,label:this.__label||this.__value})}}});function EAr(t){let{type:e,title:n,data:r}=t;switch(e){case"active-note":return Gee();case"notes":if(r instanceof BS.TFile&&n)return Kee(n,r.path);break;case"tools":if(typeof r=="string")return Z$(r);break;case"folders":if(r instanceof BS.TFolder)return Jee(r.path);break;case"webTabs":if(r&&typeof r=="object"&&"url"in r)return Bxe(r.url,r.title,r.faviconUrl);break;case"activeWebTab":return jxe();case"agents":if(typeof r=="string")return NV(r,n??r);break}throw new Error(`Invalid pill data: ${JSON.stringify(t)}`)}function MAr(t,e,n){return{beforeText:t.slice(0,e),afterText:t.slice(n)}}function OAr(t,e,n,r,o){let i=o?r?" "+r:" ":r;e?(t.setTextContent(e),t.insertAfter(n),i&&n.insertAfter(i_(i))):(t.replace(n),i&&n.insertAfter(i_(i))),n.selectNext()}function NAr(t){try{let e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"}catch{return!1}}function RAr(t){let e=t.startsWith("@")?t:`@${t}`;return gV.includes(e)?e:null}function LAr(t,e){if(!t?.vault)return null;try{let n=t.vault.getAllLoadedFiles().filter(o=>o instanceof BS.TFolder);for(let o of n)if(o.name===e)return o;for(let o of n)if(o.path===e)return o;let r=e.toLowerCase();for(let o of n)if(o.name.toLowerCase()===r||o.path.toLowerCase()===r)return o;return null}catch(n){return j("Error resolving folder reference:",n),null}}function $Ar(t,e){if(!t?.vault||!t?.metadataCache)return null;try{let n=t.metadataCache.getFirstLinkpathDest(e,"");if(n&&n instanceof BS.TFile)return n;if(!e.endsWith(".md")){let s=t.metadataCache.getFirstLinkpathDest(e+".md","");if(s&&s instanceof BS.TFile)return s}if(!e.endsWith(".pdf")){let s=t.metadataCache.getFirstLinkpathDest(e+".pdf","");if(s&&s instanceof BS.TFile)return s}let r=t.vault.getMarkdownFiles();for(let s of r)if(s.basename===e||s.name===e)return s;let i=t.vault.getFiles().filter(s=>s instanceof BS.TFile&&s.extension==="pdf");for(let s of i)if(s.basename===e||s.name===e)return s;return null}catch(n){return j("Error resolving note reference:",n),null}}function Tet(t,e,n={}){let{includeNotes:r=!0,includeURLs:o=!1,includeTools:i=!1,includeCustomTemplates:s=!1}=n,a=[],l=[],c=[],u=1;if(r&&(l.push("(\\[\\[([^\\]]+)\\]\\])"),c.push({type:"notes",groupCount:2,startIndex:u}),u+=2),o&&(l.push(`(https?:\\/\\/[^\\s"'<>]+)`),c.push({type:"urls",groupCount:1,startIndex:u}),u+=1),i&&(l.push("(@[a-zA-Z][a-zA-Z0-9_]*)"),c.push({type:"tools",groupCount:1,startIndex:u}),u+=1),s&&(l.push("(\\{([^}]+)\\})"),c.push({type:"customTemplates",groupCount:2,startIndex:u}),u+=2),l.length===0)return[{type:"text",content:e}];let d=new RegExp(l.join("|"),"g"),f=0,p;for(;(p=d.exec(e))!==null;){if(p.index>f){let h=e.slice(f,p.index);h&&a.push({type:"text",content:h})}let m=null;for(let h of c)if(p[h.startIndex]){m=h;break}if(!m)a.push({type:"text",content:p[0]});else if(m.type==="notes"){let h=p[m.startIndex+1].trim(),g=$Ar(t,h);if(g&&g instanceof BS.TFile){let y=t.workspace.getActiveFile()?.path===g.path;a.push({type:"note-pill",content:g.basename,file:g,isActive:y})}else a.push({type:"text",content:p[0]})}else if(m.type==="urls"){let h=p[m.startIndex].replace(/,+$/,"");NAr(h)?a.push({type:"url-pill",content:h,url:h}):a.push({type:"text",content:p[0]})}else if(m.type==="tools"){let h=p[m.startIndex],g=RAr(h);g?a.push({type:"tool-pill",content:g,toolName:g}):a.push({type:"text",content:p[0]})}else if(m.type==="customTemplates"){let h=p[m.startIndex+1].trim();if(h==="activeNote")a.push({type:"active-note-pill",content:"activeNote"});else{let g=LAr(t,h);g?a.push({type:"folder-pill",content:g.path,folder:g}):a.push({type:"text",content:p[0]})}}f=d.lastIndex}if(f<e.length){let m=e.slice(f);m&&a.push({type:"text",content:m})}return a}function Pet(t){let e=[];for(let n of t)n.type==="text"&&n.content?e.push(i_(n.content)):n.type==="active-note-pill"?e.push(Gee()):n.type==="note-pill"&&n.file?e.push(Kee(n.content,n.file.path)):n.type==="url-pill"&&n.url?e.push(Fxe(n.url)):n.type==="tool-pill"&&n.toolName?e.push(Z$(n.toolName)):n.type==="folder-pill"&&n.folder&&e.push(Jee(n.folder.path));return e}function Oln(t,e,n={}){let{enableURLPills:r=!1,insertAtSelection:o=!0}=n;if(!e)return;let i=qn();if(!gn(i)){j("No range selection available for text insertion");return}let s=Tet(t,e,{includeNotes:!0,includeURLs:r}),a=Pet(s);a.length>0&&(o||i.removeText(),i.insertNodes(a))}function RV(t,e,n=!0){let r=qn();if(!gn(r))return;let o=r.anchor,i=o.getNode();if(!(i instanceof OS))return;let s=i.getTextContent(),a=o.offset,l=-1;if(t==="[["?l=s.lastIndexOf("[[",a):l=s.lastIndexOf(t,a),l===-1)return;let{beforeText:c,afterText:u}=MAr(s,l,a),d=EAr(e);OAr(i,c,d,u,n)}var BS,sD,aD=b(()=>{$o();BS=require("obsidian");wV();bV();Yee();Xee();_V();SV();xV();pte();pe();Txe();sD=kin("INSERT_TEXT_WITH_PILLS_COMMAND")});async function DAr(t,e,n=500){try{if(e.extension==="pdf"||e.extension==="canvas")return"";let o=(await t.vault.cachedRead(e)).replace(/^---\s*\n[\s\S]*?\n---\s*\n?/,"").trim();return o.length>n?o.slice(0,n)+"...":o}catch(r){return W("Failed to read note content:",r),"Failed to load content"}}var pSe,Nln=b(()=>{pe();pSe=class{constructor(e){this.app=e;this.cache=new Map}async getOrLoadContent(e,n=500){let r=this.cache.get(e.path);if(r!==void 0)return r;let o=await DAr(this.app,e,n);return this.cache.set(e.path,o),o}clear(){this.cache.clear()}remove(e){this.cache.delete(e)}has(e){return this.cache.has(e)}}});function Rln({isCopilotPlus:t=!1,currentActiveFile:e=null}){let n=vn(),[r]=go(),[o,i]=(0,Rg.useState)(""),[s]=(0,Rg.useState)(()=>new pSe(n)),[a,l]=(0,Rg.useState)(()=>new Map),c=(0,Rg.useCallback)(async h=>{try{let g=await s.getOrLoadContent(h,500);return l(v=>{let y=new Map(v);return y.set(h.path,g),y}),g}catch{let g="Failed to load content";return l(v=>{let y=new Map(v);return y.set(h.path,g),y}),g}},[s]),d=Iln(o,t,{},e).map(h=>({...h,content:a.get(h.file.path)||""})),f=(0,Rg.useCallback)(h=>{if(h.category==="activeNote")r.update(()=>{RV("[[",{type:"active-note"})});else{let g={type:"notes",title:h.title,data:h.file};r.update(()=>{RV("[[",g)})}},[r]),{state:p,handleHighlight:m}=xM({triggerConfig:{char:"[[",multiChar:!0,allowWhitespace:!0},options:d,onSelect:f,onStateChange:h=>{i(h.query)},onHighlight:(h,g)=>{g&&!a.has(g.file.path)&&c(g.file)}});return(0,Rg.useEffect)(()=>{d.length>0&&!a.has(d[0].file.path)&&c(d[0].file)},[d,a,c]),Rg.default.createElement(Rg.default.Fragment,null,p.isOpen&&Rg.default.createElement(_M,{options:d,selectedIndex:p.selectedIndex,onSelect:f,onHighlight:m,range:p.range,query:p.query,showPreview:!0}))}var Rg,Lln=b(()=>{Rg=L(B());Il();ko();MV();Tln();ute();aD();Nln()});function $ln(t=!1){let e=Ar(wQe,{store:on}),n=Ar(bQe,{store:on});return t?e:n}var Dln=b(()=>{Us();Wee();Se()});function Uln(t,e={}){let n=(0,mSe.useMemo)(()=>({...FAr,...e}),[e]),r=$ln(n.frontmatterOnly),o=(0,mSe.useMemo)(()=>r.map((s,a)=>{let l=s.startsWith("#")?s.slice(1):s;return{key:`tag-${l}-${a}`,title:s,subtitle:void 0,content:"",tag:l}}),[r]);return(0,mSe.useMemo)(()=>{if(!t.trim())return o.slice(0,n.limit);let s=t.trim();return Fln.default.go(s,o,{key:"title",limit:n.limit,threshold:n.threshold}).map(l=>l.obj)},[o,t,n])}var mSe,Fln,FAr,jln=b(()=>{mSe=L(B()),Fln=L(zee());Dln();FAr={limit:10,threshold:-1e4,frontmatterOnly:!1}});function Bln({onTagSelected:t}){let[e]=go(),[n,r]=(0,CM.useState)(""),o=Uln(n,{limit:10}),i=(0,CM.useCallback)(l=>{e.update(()=>{let c=qn();if(!gn(c))return;let u=c.anchor,d=u.getNode();if(!(d instanceof OS))return;let f=d.getTextContent(),p=u.offset,m=f.lastIndexOf("#",p);if(m===-1)return;let h=f.slice(0,m),g=f.slice(p),v=`#${l.tag} `;d.setTextContent(h+v+g);let y=h.length+v.length;d.select(y,y)}),t?.()},[e,t]),{state:s,handleHighlight:a}=xM({triggerConfig:{char:"#",multiChar:!1,allowWhitespace:!1},options:o,onSelect:i,onStateChange:l=>{r(l.query)}});return CM.default.createElement(CM.default.Fragment,null,s.isOpen&&CM.default.createElement(_M,{options:o,selectedIndex:s.selectedIndex,onSelect:i,onHighlight:a,range:s.range,query:s.query,showPreview:!1}))}var CM,zln=b(()=>{CM=L(B());Il();$o();MV();ute();jln()});function hSe({isCopilotPlus:t=!1,showTools:e=!1,currentActiveFile:n=null,agentBrands:r=NS}){let o=vn(),[i]=go(),[s,a]=(0,rc.useState)({mode:"category"}),[l,c]=(0,rc.useState)(""),u=Cxe(e,r.length>0),d=(0,rc.useMemo)(()=>u.filter(k=>!k.isAction),[u]),f=(0,rc.useCallback)(async k=>{if(!k){c("");return}try{if(k.extension==="pdf"||k.extension==="canvas"){c("");return}let P=(await o.vault.cachedRead(k)).replace(/^---\s*\n[\s\S]*?\n---\s*\n?/,"").trim(),E=P.length>300?P.slice(0,300)+"...":P;c(E)}catch{c("Failed to load content")}},[o]),[p,m]=(0,rc.useState)(""),h=Oxe(p,s.mode,s.selectedCategory,t,e,d,n,r),g=(0,rc.useCallback)(k=>"data"in k,[]),v=(0,rc.useCallback)(k=>"icon"in k&&!("data"in k),[]),y=(0,rc.useCallback)(k=>{if(s.mode==="category"&&v(k)&&!p){a(T=>({...T,mode:"search",selectedCategory:k.category}));return}if(g(k)){if(k.category==="activeNote")i.update(()=>{RV("@",{type:"active-note"})});else if(!k.isAction){let T={type:k.category,title:k.title,data:k.data};i.update(()=>{RV("@",T)})}}},[s.mode,p,v,g,i]),w=(0,rc.useCallback)(k=>{m(k.query),k.isOpen||a({mode:"category",selectedCategory:void 0})},[]),{state:_,handleHighlight:S}=xM({triggerConfig:{char:"@",allowWhitespace:!0},options:h,onSelect:y,onStateChange:w}),I=(0,rc.useMemo)(()=>{let k=h[_.selectedIndex];return k&&g(k)&&k.category==="notes"&&k.data instanceof Aet.TFile?k.data:null},[_.selectedIndex,h,g]);(0,rc.useEffect)(()=>{f(I)},[I,f]);let C=(0,rc.useMemo)(()=>h.map((k,T)=>T===_.selectedIndex&&g(k)&&k.category==="notes"&&k.data instanceof Aet.TFile?{...k,content:l}:k),[h,_.selectedIndex,l,g]);return rc.default.createElement(rc.default.Fragment,null,_.isOpen&&rc.default.createElement(_M,{options:C,selectedIndex:_.selectedIndex,onSelect:y,onHighlight:S,range:_.range,query:_.query,showPreview:h[_.selectedIndex]&&g(h[_.selectedIndex])&&h[_.selectedIndex].category==="notes",mode:s.mode}))}var rc,Aet,Eet=b(()=>{rc=L(B());Il();Aet=require("obsidian");ko();MV();ute();aD();pM();SQe()});function Met(t){if(!(t instanceof hxe))return!1;let e=t;return typeof e.isPill=="function"&&e.isPill()===!0}function gSe(){let[t]=go();return Hln.default.useEffect(()=>{let e=t.registerCommand(fV,n=>{let r=!1;return t.update(()=>{let o=qn();if(!gn(o)||!o.isCollapsed()){r=!1;return}let i=o.anchor,s=i.getNode();if(Met(s)){(n&&i.offset===1||!n&&i.offset===0)&&(s.remove(),r=!0);return}if(io(s)&&n&&i.offset>0){let l=s.getChildren()[i.offset-1];if(Met(l)){l.remove(),r=!0;return}}if(n&&i.offset===0){let a=s.getPreviousSibling();if(a&&Met(a)){a.remove(),r=!0;return}}r=!1}),r},pxe);return()=>{e()}},[t]),null}var Hln,Oet=b(()=>{Hln=L(B());Il();$o()});function UAr(t){let e=n=>{n.key==="Escape"&&n.stopPropagation()};return t.addEventListener("keydown",e),()=>t.removeEventListener("keydown",e)}function ySe({onSubmit:t,sendShortcut:e,onEscape:n,onShiftTab:r}){let[o]=go();return(0,mte.useEffect)(()=>o.registerCommand(mV,i=>i?Wln(i)?(i.preventDefault(),!0):jAr(i,e)?(i.preventDefault(),t(),!0):!1:!1,dV),[o,t,e]),(0,mte.useEffect)(()=>{let i,s=o.registerRootListener(a=>{i?.(),i=a?UAr(a):void 0});return()=>{s(),i?.()}},[o]),(0,mte.useEffect)(()=>{if(n)return o.registerCommand(yxe,i=>i?(Wln(i)||(i.preventDefault(),n()),!0):!1,dV)},[o,n]),(0,mte.useEffect)(()=>{if(r)return o.registerCommand(hV,i=>!i||!i.shiftKey||i.metaKey||i.ctrlKey||i.altKey?!1:(i.preventDefault(),r(),!0),dV)},[o,r]),null}function Wln(t){return t.isComposing||t.key==="Process"}function jAr(t,e){switch(e){case"enter":return!t.shiftKey&&!t.metaKey&&!t.ctrlKey&&!t.altKey;case"shift+enter":return t.shiftKey&&!t.metaKey&&!t.ctrlKey&&!t.altKey;default:return!1}}var mte,Net=b(()=>{mte=L(B());Il();$o();gt()});function vSe({value:t}){let[e]=go();return Vln.default.useEffect(()=>{e.update(()=>{let n=ho();if(n.getTextContent()!==t){n.clear();let o=a0();t&&o.append(i_(t)),n.append(o)}})},[e,t]),null}var Vln,Ret=b(()=>{Vln=L(B());Il();$o()});function wSe({onFocus:t,onEditorReady:e}){let[n]=go();return qln.default.useEffect(()=>{t(()=>{n.focus()}),e&&e(n)},[n,t,e]),null}var qln,Let=b(()=>{qln=L(B());Il()});function Lg({config:t,onChange:e,onRemoved:n}){let[r]=go(),o=bSe.default.useRef([]),{isPillNode:i,extractData:s,getKey:a=u=>String(u),getChangeKey:l}=t,c=bSe.default.useMemo(()=>l??a,[l,a]);return bSe.default.useEffect(()=>{if(!(!e&&!n))return r.registerUpdateListener(({editorState:u})=>{u.read(()=>{let d=[],f=ho();function p(T){if(i(T)){let E=s(T);d.push(E)}let P=T;if(typeof P.getChildren=="function"){let E=P.getChildren();for(let O of E)p(O)}}p(f);let m=new Set,g=d.filter(T=>{let P=a(T);return m.has(P)?!1:(m.add(P),!0)}).sort((T,P)=>a(T).localeCompare(a(P))),v=o.current,y=g.map(a),w=v.map(a),_=g.map(c),S=v.map(c),I=y.length!==w.length||y.some((T,P)=>T!==w[P]),C=_.length!==S.length||_.some((T,P)=>T!==S[P]);if(I||C){if(n){let T=new Set(y),P=v.filter(E=>!T.has(a(E)));P.length>0&&n(P)}o.current=g,e&&e(g)}})})},[r,e,n,i,s,a,c]),null}var bSe,lD=b(()=>{bSe=L(B());Il();$o()});function _Se({onNotesChange:t,onNotesRemoved:e}){return Kln.default.createElement(Lg,{config:BAr,onChange:t,onRemoved:e})}var Kln,BAr,$et=b(()=>{Kln=L(B());wV();lD();BAr={isPillNode:IQe,extractData:t=>{let e=t;return{path:e.getNotePath(),basename:e.getNoteTitle()}},getKey:t=>t.path}});function Zln({onURLsChange:t,onURLsRemoved:e}){return Gln.default.createElement(Lg,{config:zAr,onChange:t,onRemoved:e})}var Gln,zAr,Yln=b(()=>{Gln=L(B());Yee();lD();zAr={isPillNode:Ssn,extractData:t=>t.getURL()}});function Xln({onToolsChange:t,onToolsRemoved:e}){return Jln.default.createElement(Lg,{config:HAr,onChange:t,onRemoved:e})}var Jln,HAr,Qln=b(()=>{Jln=L(B());Xee();lD();HAr={isPillNode:Isn,extractData:t=>t.getToolName()}});function xSe({onFoldersChange:t,onFoldersRemoved:e}){return ecn.default.createElement(Lg,{config:WAr,onChange:t,onRemoved:e})}var ecn,WAr,Det=b(()=>{ecn=L(B());_V();lD();WAr={isPillNode:Csn,extractData:t=>t.getFolderPath()}});function SSe({onActiveNoteAdded:t,onActiveNoteRemoved:e}){let[n]=go();return(0,tcn.useEffect)(()=>{let r=!1,o=n.registerUpdateListener(({editorState:i})=>{i.read(()=>{let s=ho(),a=!1;function l(c){if(TQe(c)){a=!0;return}if("getChildren"in c&&typeof c.getChildren=="function"){let u=c.getChildren();for(let d of u){if(a)return;l(d)}}}l(s),a&&!r?(r=!0,t?.()):!a&&r&&(r=!1,e?.())})});return()=>{o()}},[n,t,e]),null}var tcn,Fet=b(()=>{Il();tcn=L(B());$o();bV()});function ncn({onWebTabsChange:t,onWebTabsRemoved:e,onActiveWebTabAdded:n,onActiveWebTabRemoved:r}){return kM.default.createElement(kM.default.Fragment,null,kM.default.createElement(Lg,{config:VAr,onChange:t,onRemoved:e}),(n||r)&&kM.default.createElement(qAr,{onActiveWebTabAdded:n,onActiveWebTabRemoved:r}))}function qAr({onActiveWebTabAdded:t,onActiveWebTabRemoved:e}){let n={isPillNode:PQe,extractData:()=>!0,getKey:()=>"active-web-tab"},r=kM.default.useCallback(i=>{i.length>0&&t&&t()},[t]),o=kM.default.useCallback(i=>{i.length>0&&e&&e()},[e]);return kM.default.createElement(Lg,{config:n,onChange:r,onRemoved:o})}var kM,VAr,rcn=b(()=>{kM=L(B());SV();xV();lD();VAr={isPillNode:Esn,extractData:t=>({url:t.getURL(),title:t.getTitle(),faviconUrl:t.getFaviconUrl()}),getKey:t=>t.url,getChangeKey:t=>[t.url,t.title??"",t.faviconUrl??""].join(`
`)}});function icn({onAgentsChange:t}){return ocn.default.createElement(Lg,{config:KAr,onChange:t})}var ocn,KAr,scn=b(()=>{ocn=L(B());pte();lD();KAr={isPillNode:Mln,extractData:t=>t.getBackendId()}});function lcn({enableURLPills:t=!1,onImagePaste:e}){let n=vn(),[r]=go();return acn.default.useEffect(()=>r.registerCommand(vxe,o=>{let i=o.clipboardData;if(!i)return!1;if(e){let m=i.items;if(m){let h=Array.from(m).filter(g=>g.type.indexOf("image")!==-1);if(h.length>0){o.preventDefault();let v=h.map(y=>y.getAsFile()).filter(y=>y!==null);return v.length>0&&e(v),!0}}}let s=i.getData("text/plain"),a=s.includes("[["),l=t&&s.includes("http"),c=s.includes("@"),u=s.includes("#"),d=s.includes("{")&&s.includes("}");if(!s||!a&&!l&&!c&&!u&&!d)return!1;let f=Tet(n,s,{includeNotes:!0,includeURLs:t,includeTools:!0,includeCustomTemplates:!0});return f.some(m=>m.type==="note-pill"||m.type==="active-note-pill"||t&&m.type==="url-pill"||m.type==="tool-pill"||m.type==="folder-pill")?(o.preventDefault(),r.update(()=>{let m=qn();if(!gn(m))return;let h=Pet(f);h.length>0&&m.insertNodes(h)}),!0):!1},c0),[r,t,e,n]),null}var acn,ccn=b(()=>{acn=L(B());Il();$o();ko();aD()});function kSe(t,e){return e[t.index].slice(0,t.charCount)}function ISe(t,e,n=!1){let r=e[t.index],{typeMs:o,deleteMs:i,holdMs:s,gapMs:a}=GAr;switch(t.phase){case"typing":{let l=n?r.length:Math.min(t.charCount+1,r.length),c=l>=r.length?"holding":"typing";return{state:{...t,charCount:l,phase:c},delayMs:o}}case"holding":case"deleting":{let l=n?0:Math.max(t.charCount-1,0);return{state:{...t,charCount:l,phase:l>0?"deleting":"gap"},delayMs:t.phase==="holding"?s:i}}case"gap":return{state:{index:(t.index+1)%e.length,charCount:0,phase:"typing"},delayMs:a}}}function TSe(t){let e=[...t];for(let n=e.length-1;n>0;n--){let r=Math.floor(Math.random()*(n+1));[e[n],e[r]]=[e[r],e[n]]}return e}var GAr,CSe,Uet=b(()=>{GAr=Object.freeze({typeMs:45,deleteMs:25,holdMs:5e3,gapMs:500}),CSe=()=>({index:0,charCount:0,phase:"typing"})});var oh,ucn,dcn=b(()=>{aD();Uet();Il();$o();oh=L(B()),ucn=({prompts:t,descriptionId:e})=>{let[n]=go(),r=(0,oh.useMemo)(()=>TSe(t),[t]),[o]=(0,oh.useState)(()=>window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches??!1),[i,s]=(0,oh.useState)(CSe);(0,oh.useEffect)(()=>{let{state:c,delayMs:u}=ISe(i,r,o),d=window.setTimeout(()=>s(c),u);return()=>window.clearTimeout(d)},[i,r,o]);let a=kSe(i,r),l=a.length>0?r[i.index]:null;return(0,oh.useEffect)(()=>{if(l)return n.registerCommand(hV,c=>!c||c.shiftKey||c.metaKey||c.ctrlKey||c.altKey?!1:(c.preventDefault(),n.dispatchCommand(sD,{text:l,options:{insertAtSelection:!0}}),!0),dV)},[n,l]),oh.default.createElement(oh.default.Fragment,null,oh.default.createElement("span",{"aria-hidden":"true"},a),i.phase==="holding"&&oh.default.createElement("span",{"aria-hidden":"true",className:"tw-ml-1.5 tw-whitespace-nowrap tw-text-ui-smaller tw-opacity-80"},"\u21E5 Tab"),oh.default.createElement("span",{id:e,className:"tw-sr-only"},l?`Suggested prompt: ${l}. Press Tab to insert it.`:""))}});function pcn(){let t=vn(),[e]=go();return fcn.default.useEffect(()=>e.registerCommand(sD,n=>{let{text:r,options:o={}}=n;return e.update(()=>{Oln(t,r,o)}),!0},Rs),[e,t]),null}var fcn,mcn=b(()=>{fcn=L(B());Il();$o();ko();aD()});function IM(){let t=(0,ol.useContext)(hcn);if(t===void 0)throw new Error("useChatInput must be used within a ChatInputProvider");return t}function PSe({children:t}){let[e,n]=(0,ol.useState)(null),[r,o]=(0,ol.useState)(null),i=(0,ol.useRef)(null),s=(0,ol.useRef)(!1),a=(0,ol.useCallback)(f=>{n(f)},[]),l=(0,ol.useCallback)(f=>{o(()=>f)},[]),c=(0,ol.useCallback)((f,p=!1)=>{e?e.dispatchCommand(sD,{text:f,options:{enableURLPills:p,insertAtSelection:!0}}):i.current={text:f,enableURLPills:p}},[e]);(0,ol.useEffect)(()=>{if(!e||!i.current)return;let{text:f,enableURLPills:p}=i.current;i.current=null,e.dispatchCommand(sD,{text:f,options:{enableURLPills:p,insertAtSelection:!0}})},[e]);let u=(0,ol.useCallback)(()=>{r?r():s.current=!0},[r]);(0,ol.useEffect)(()=>{r&&s.current&&(s.current=!1,r())},[r]);let d=(0,ol.useMemo)(()=>({insertTextWithPills:c,focusInput:u,registerEditor:a,registerFocusHandler:l}),[c,u,a,l]);return ol.default.createElement(hcn.Provider,{value:d},t)}var ol,hcn,hte=b(()=>{ol=L(B());aD();hcn=(0,ol.createContext)(void 0)});var Yr,ZAr,gcn,ycn=b(()=>{Yr=L(B());$o();NQe();iet();aet();met();get();bet();Cln();Lln();zln();Eet();wV();Yee();Xee();_V();bV();SV();xV();pte();Oet();Net();Ret();Let();$et();Yln();Qln();Det();Fet();rcn();scn();ccn();dcn();mcn();hte();De();pe();Dxe();fSe();mw();Se();pM();ZAr=({value:t,onChange:e,onSubmit:n,placeholder:r="Type a message...",placeholderPrompts:o,disabled:i=!1,className:s="",onNotesChange:a,onNotesRemoved:l,onURLsChange:c,onURLsRemoved:u,onToolsChange:d,onToolsRemoved:f,onFoldersChange:p,onFoldersRemoved:m,onActiveNoteAdded:h,onActiveNoteRemoved:g,onWebTabsChange:v,onWebTabsRemoved:y,onActiveWebTabAdded:w,onActiveWebTabRemoved:_,onAgentsChange:S,agentBrands:I=NS,cloudAgentIds:C=dte,onEditorReady:k,onImagePaste:T,onTagSelected:P,isCopilotPlus:E=!1,showTools:O=!1,currentActiveFile:$=null,currentChain:U,onEscape:V,onShiftTab:K})=>{let[se,le]=Yr.default.useState(null),[Q,ne]=Yr.default.useState(null),ee=IM(),ae=xt(),q=Yr.default.useCallback(G=>{le(()=>G)},[]);(0,Yr.useEffect)(()=>{Q&&ee.registerEditor(Q)},[Q,ee]),(0,Yr.useEffect)(()=>{se&&ee.registerFocusHandler(se)},[se,ee]);let F=Yr.default.useMemo(()=>({namespace:"ChatEditor",theme:{root:"tw-outline-none",paragraph:"tw-m-0"},nodes:[hM,yM,G$,m0,h0,vM,OV,...c?[K$]:[]],onError:G=>{H("Lexical error:",G)},editable:!i}),[c,i]),z=(0,Yr.useCallback)(G=>{G.read(()=>{let Z=ho().getTextContent();e(Z)})},[e]),N=(0,Yr.useId)(),R=!!o&&o.length>0,X=(0,Yr.useId)(),D=(0,Yr.useCallback)(G=>{ne(G),k?.(G)},[k]);return Yr.default.createElement(Wxe,{initialConfig:F},Yr.default.createElement($xe,{currentActiveFile:$},Yr.default.createElement(Eln,{cloudAgentIds:C},Yr.default.createElement("div",{className:J("tw-relative",s)},Yr.default.createElement("span",{id:X,className:"tw-sr-only"},"Chat input"),Yr.default.createElement(Xxe,{contentEditable:Yr.default.createElement(Qxe,{className:"tw-max-h-60 tw-min-h-[60px] tw-w-full tw-resize-none tw-overflow-y-auto tw-rounded-md tw-border-none tw-bg-transparent tw-px-2 tw-text-sm tw-text-normal tw-outline-none focus-visible:tw-ring-0","aria-labelledby":X,"aria-describedby":R?N:void 0}),placeholder:Yr.default.createElement("div",{className:"tw-pointer-events-none tw-absolute tw-left-2 tw-top-0 tw-select-none tw-text-sm tw-text-muted/60"},R?Yr.default.createElement(ucn,{prompts:o,descriptionId:N}):r),ErrorBoundary:sSe}),Yr.default.createElement(iSe,{onChange:z,ignoreSelectionChange:!0}),Yr.default.createElement(rSe,null),Yr.default.createElement(ySe,{onSubmit:n,sendShortcut:ae.defaultSendShortcut,onEscape:V,onShiftTab:K}),Yr.default.createElement(vSe,{value:t}),Yr.default.createElement(wSe,{onFocus:q,onEditorReady:D}),Yr.default.createElement(_Se,{onNotesChange:a,onNotesRemoved:l}),c&&Yr.default.createElement(Zln,{onURLsChange:c,onURLsRemoved:u}),Yr.default.createElement(Xln,{onToolsChange:d,onToolsRemoved:f}),Yr.default.createElement(xSe,{onFoldersChange:p,onFoldersRemoved:m}),Yr.default.createElement(SSe,{onActiveNoteAdded:h,onActiveNoteRemoved:g}),Yr.default.createElement(ncn,{onWebTabsChange:v,onWebTabsRemoved:y,onActiveWebTabAdded:w,onActiveWebTabRemoved:_}),Yr.default.createElement(icn,{onAgentsChange:S}),Yr.default.createElement(gSe,null),Yr.default.createElement(lcn,{enableURLPills:!!c,onImagePaste:T}),Yr.default.createElement(Sln,null),Yr.default.createElement(Rln,{isCopilotPlus:E,currentActiveFile:$}),U&&U!=="llm_chain"&&Yr.default.createElement(Bln,{onTagSelected:P}),Yr.default.createElement(hSe,{isCopilotPlus:E,showTools:O,currentActiveFile:$,agentBrands:I}),Yr.default.createElement(pcn,null)))))},gcn=ZAr});var jet,_n,vcn,YAr,JAr,ASe,Bet=b(()=>{es();yt();w_e();Se();ut();I$();ut();x_e();Re();jet=require("obsidian"),_n=L(B());$o();ssn();lsn();usn();pM();fsn();hsn();wV();bV();Yee();_V();Xee();xV();SV();ycn();De();pM();fSe();pte();vcn="tw-rounded-full tw-bg-interactive-accent tw-text-on-accent hover:tw-bg-interactive-accent-hover",YAr="Your AI assistant for Obsidian \u2022 @ to add context \u2022 / for custom prompts",JAr=_n.default.forwardRef(function({topRightAccessory:e,placeholder:n=YAr,placeholderPrompts:r,inputMessage:o,setInputMessage:i,handleSendMessage:s,isGenerating:a,onStopGenerating:l,app:c,contextNotes:u,setContextNotes:d,includeActiveNote:f,setIncludeActiveNote:p,includeActiveWebTab:m,setIncludeActiveWebTab:h,activeWebTab:g,selectedImages:v,onAddImage:y,setSelectedImages:w,disableModelSwitch:_,modelPickerOverride:S,modePickerOverride:I,selectedTextContexts:C,onRemoveSelectedText:k,showIndexingCard:T,toolControls:P,onToolPillsChange:E,onTagSelected:O,onEscape:$,onShiftTab:U,editMode:V=!1,onEditSave:K,onEditCancel:se,initialContext:le,isAgentMode:Q=!1,agentBrands:ne=NS,cloudAgentIds:ee=dte,onMentionedAgentsChange:ae},q){let[F,z]=(0,_n.useState)(le?.urls||[]),[N,R]=(0,_n.useState)(le?.folders||[]),[X,D]=(0,_n.useState)([]),G=(0,_n.useRef)(null),ce=(0,_n.useRef)(null),[Z,te]=CT(),fe=xt(),[de]=Cw(),[ye,Te]=(0,_n.useState)(()=>{let Ct=c.workspace.getActiveFile();return U_(Ct)?Ct:null}),[Be,qe]=(0,_n.useState)([]),[Ae,Xt]=(0,_n.useState)([]),[Ve,Ee]=(0,_n.useState)([]),[st,Ne]=(0,_n.useState)([]),He=sd(de),et=Zin({isCopilotPlus:He,isAgentMode:Q}),it=(0,_n.useMemo)(()=>UI([...X,...st]),[X,st]),Br=()=>{let Ct=ce.current;return Ct?Ct.read(()=>AQe().map(_t=>({url:_t.getURL(),title:_t.getTitle(),faviconUrl:_t.getFaviconUrl()}))):st},Xr=()=>{if(V&&K){K(o,{notes:u,urls:F,folders:N});return}let Ct=Br(),wt=UI([...X,...Ct]);if(!He){s({webTabs:wt});return}s({contextNotes:u,urls:F,contextFolders:N,webTabs:wt})},An=Ct=>{let wt=new Set(Ct.map(_t=>_t.path));d(_t=>_t.filter(an=>!wt.has(an.path)))},zn=(0,_n.useCallback)(Ct=>{ae?.(Ct)},[ae]),Yp=Ct=>{let wt=new Set(Ct);z(_t=>_t.filter(an=>!wt.has(an)))},la=Ct=>{ce.current&&ce.current.update(()=>{vsn(Ct)}),qe(wt=>wt.filter(_t=>_t.path!==Ct))},vu=Ct=>{ce.current&&ce.current.update(()=>{xsn(Ct)}),Xt(wt=>wt.filter(_t=>_t!==Ct))},Ds=Ct=>{ce.current&&ce.current.update(()=>{ksn(Ct)}),Ee(wt=>wt.filter(_t=>_t!==Ct))},hh=(Ct,wt)=>{switch(Ct){case"activeNote":p(!0);break;case"notes":if(wt instanceof jet.TFile){let _t=c.workspace.getActiveFile();_t&&wt.path===_t.path?(p(!0),d(an=>an.filter(Qr=>Qr.path!==wt.path))):d(an=>an.find(Vo=>Vo.path===wt.path)?an:[...an,wt])}break;case"tools":typeof wt=="string"&&ce.current&&ce.current.update(()=>{let _t=qn();if(gn(_t)){let an=Z$(wt);_t.insertNodes([an])}});break;case"agents":if(typeof wt=="string"&&ce.current){let _t=ne.find(an=>an.id===wt)?.displayName??wt;ce.current.update(()=>{let an=qn();gn(an)&&an.insertNodes([NV(wt,_t)])})}break;case"folders":if(wt&&typeof wt.path=="string"){let _t=wt.path;R(an=>an.find(Vo=>Vo===_t)?an:[...an,_t])}break;case"webTabs":if(wt&&typeof wt=="object"&&"url"in wt&&typeof wt.url=="string"){let _t=TYe(wt);if(!_t)break;let an=Lf(g?.url);if(an&&_t.url===an){h(!0),D(Qr=>Qr.filter(Vo=>Lf(Vo.url)!==an));break}D(Qr=>UI([...Qr,_t]))}break;case"activeWebTab":h(!0);{let _t=Lf(g?.url);_t&&D(an=>an.filter(Qr=>Lf(Qr.url)!==_t))}break;case"images":{let _t=G.current?.doc;if(!_t)break;csn(_t,{onFiles:y,onSettle:()=>ce.current?.focus()});break}}},N_=(Ct,wt)=>{switch(Ct){case"activeNote":p(!1),ce.current&&ce.current.update(()=>{_sn()});break;case"notes":typeof wt=="string"&&(ye?.path===wt&&f?p(!1):d(_t=>_t.filter(an=>an.path!==wt)),la(wt));break;case"urls":typeof wt=="string"&&(z(_t=>_t.filter(an=>an!==wt)),vu(wt));break;case"folders":typeof wt=="string"&&(R(_t=>_t.filter(an=>an!==wt)),Ds(wt));break;case"selectedText":typeof wt=="string"&&k?.(wt);break;case"activeWebTab":h(!1),ce.current&&ce.current.update(()=>{Psn()});break;case"webTabs":if(typeof wt=="string"){let _t=Lf(wt);if(!_t)break;D(an=>an.filter(Qr=>Lf(Qr.url)!==_t)),Ne(an=>an.filter(Qr=>Lf(Qr.url)!==_t)),ce.current&&ce.current.update(()=>{Msn(_t)})}break}},ty=Ct=>{let wt=new Set(Ct);R(_t=>_t.filter(an=>!wt.has(an)))};(0,_n.useEffect)(()=>{d(Ct=>{let wt=new Set(Ct.map(Qr=>Qr.path)),_t=Be.filter(Qr=>!wt.has(Qr.path)),an=[];return _t.forEach(Qr=>{let Vo=c.vault.getAbstractFileByPath(Qr.path);Vo instanceof jet.TFile&&an.push(Vo)}),[...Ct,...an]})},[Be,c.vault,d]),(0,_n.useEffect)(()=>{sd(de)?z(Ct=>{let wt=new Set(Ct),_t=Ae.filter(an=>!wt.has(an));return _t.length>0?Array.from(new Set([...Ct,..._t])):Ct}):z([])},[Ae,de]),(0,_n.useEffect)(()=>{R(Ct=>{let wt=new Set(Ct),_t=Ve.filter(an=>!wt.has(an));return[...Ct,..._t]})},[Ve]),(0,_n.useEffect)(()=>{let Ct,wt=()=>{window.clearTimeout(Ct),Ct=window.setTimeout(()=>{let an=c.workspace.getActiveFile();Te(U_(an)?an:null)},100)},_t=c.workspace.on("active-leaf-change",wt);return()=>{window.clearTimeout(Ct),c.workspace.offref(_t)}},[c.workspace]);let fl=(0,_n.useCallback)(Ct=>{ce.current=Ct},[]);(0,_n.useEffect)(()=>{if(!V||!se)return;let Ct=_t=>{_t.key==="Escape"&&(_t.preventDefault(),se())},wt=G.current?.doc;if(wt)return wt.addEventListener("keydown",Ct,!0),()=>wt.removeEventListener("keydown",Ct,!0)},[V,se]),(0,_n.useImperativeHandle)(q,()=>({removeToolPills(Ct){ce.current&&ce.current.update(()=>{Ct.forEach(wt=>Tsn(wt))})}}),[]);let wu=(0,_n.useCallback)(()=>{p(!0)},[p]),ct=(0,_n.useCallback)(()=>{p(!1)},[p]),Qt=(0,_n.useCallback)(()=>{h(!0)},[h]),ir=(0,_n.useCallback)(()=>{h(!1)},[h]);return _n.default.createElement("div",{className:J("tw-flex tw-w-full tw-flex-col tw-gap-0.5 tw-rounded-md tw-border tw-border-solid tw-border-border tw-px-1 tw-pb-1 tw-pt-2 tw-@container/chat-input",I?.value==="plan"&&"tw-shadow-[0_0_10px_rgba(var(--color-blue-rgb),0.18)] tw-border-blue/60",I?.value==="auto"&&"tw-shadow-[0_0_10px_rgba(var(--color-red-rgb),0.18)] tw-border-red/60"),ref:G},_n.default.createElement("div",{className:"tw-flex tw-gap-1"},_n.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-flex-col tw-gap-0.5"},!V&&_n.default.createElement(isn,{contextNotes:u,includeActiveNote:f,activeNote:ye,includeActiveWebTab:m,activeWebTab:g,contextUrls:F,contextFolders:N,contextWebTabs:it,selectedTextContexts:C,showIndexingCard:T,onAddToContext:hh,onRemoveFromContext:N_,hideAddContextButton:Q,isAgentMode:Q}),v.length>0&&_n.default.createElement("div",{className:"selected-images"},v.map((Ct,wt)=>_n.default.createElement("div",{key:b_e(Ct),className:"image-preview-container"},_n.default.createElement("img",{src:URL.createObjectURL(Ct),alt:Ct.name,className:"selected-image-preview"}),_n.default.createElement("button",{type:"button",className:"remove-image-button",onClick:()=>w(_t=>_t.filter((an,Qr)=>Qr!==wt)),title:"Remove image"},_n.default.createElement(pn,{className:"tw-size-4"}))))),_n.default.createElement("div",{className:"tw-relative"},_n.default.createElement(gcn,{value:o,onChange:Ct=>i(Ct),onSubmit:Xr,onNotesChange:qe,onNotesRemoved:An,onActiveNoteAdded:wu,onActiveNoteRemoved:ct,onURLsChange:He?Xt:void 0,onURLsRemoved:He?Yp:void 0,onToolsChange:He?E:void 0,onFoldersChange:Ee,onFoldersRemoved:ty,onWebTabsChange:Ne,onActiveWebTabAdded:Qt,onActiveWebTabRemoved:ir,agentBrands:ne,cloudAgentIds:ee,onAgentsChange:zn,onEditorReady:fl,onImagePaste:y,onTagSelected:O,placeholder:n,placeholderPrompts:r,isCopilotPlus:He,showTools:et,currentActiveFile:ye,currentChain:de,onEscape:$,onShiftTab:U}))),e&&_n.default.createElement("div",{className:"-tw-ml-4 tw-w-6 tw-shrink-0 tw-self-start"},e)),_n.default.createElement("div",{className:"tw-flex tw-h-7 tw-justify-between tw-gap-1 tw-px-1"},_n.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-items-center tw-gap-1"},!V&&_n.default.createElement(asn,{onSelect:hh,isCopilotPlus:He,showTools:et,currentActiveFile:ye,lexicalEditorRef:ce}),S?.effortOptionsByModelKey&&S.commitSelection?_n.default.createElement(dsn,{override:{models:S.models,value:S.value,disabled:S.disabled,effort:S.effort,effortOptionsByModelKey:S.effortOptionsByModelKey,commitSelection:S.commitSelection},className:"tw-min-w-0 tw-max-w-full tw-truncate"}):_n.default.createElement(U6,{variant:"ghost2",size:"fit",disabled:S?.disabled??_,value:S?.value??Z,models:S?.models??fe.activeModels,apiKeySettings:S?void 0:fe,onChange:S?.onChange??te,className:"tw-min-w-0 tw-max-w-full tw-truncate"})),_n.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},!a&&P,I&&_n.default.createElement(msn,{override:I}),a?_n.default.createElement(oe,{size:"icon",className:J(vcn),"aria-label":"Stop generating",onClick:()=>l()},_n.default.createElement(HC,{className:"tw-size-3 tw-fill-current"})):_n.default.createElement(_n.default.Fragment,null,V&&se&&_n.default.createElement(oe,{variant:"ghost2",size:"fit",className:"tw-text-muted",onClick:se},_n.default.createElement("span",null,"cancel")),V?_n.default.createElement(oe,{variant:"ghost2",size:"fit",className:"tw-text-muted",onClick:()=>Xr()},_n.default.createElement(W_,{className:"!tw-size-3"}),_n.default.createElement("span",null,"save")):_n.default.createElement(oe,{size:"icon",className:J(vcn),"aria-label":"Send",onClick:()=>Xr(),disabled:!o.trim()},_n.default.createElement(nG,{className:"tw-size-4"}))))))}),ASe=JAr});var Bt,wcn,bcn=b(()=>{Bt=L(B());Re();yt();Oc();xk();De();Se();ut();wcn=({vaultToggle:t,setVaultToggle:e,webToggle:n,setWebToggle:r,composerToggle:o,setComposerToggle:i,autonomousAgentToggle:s,setAutonomousAgentToggle:a,onVaultToggleOff:l,onWebToggleOff:c,onComposerToggleOff:u,currentChain:d})=>{let f=sd(d),p=f,m=()=>{let y=!s;a(y),At("enableAutonomousAgent",y)},h=()=>{let y=!t;e(y),!y&&l&&l()},g=()=>{let y=!n;r(y),!y&&c&&c()},v=()=>{let y=!o;i(y),!y&&u&&u()};return f?Bt.default.createElement(sf,{delayDuration:0},Bt.default.createElement("div",{className:"tw-hidden tw-items-center tw-gap-1.5 @[420px]/chat-input:tw-flex"},p&&Bt.default.createElement(hr,null,Bt.default.createElement(gr,{asChild:!0},Bt.default.createElement(oe,{variant:"ghost2",size:"fit",onClick:m,className:J("tw-text-muted hover:tw-text-accent",s&&"tw-text-accent tw-bg-accent/10")},Bt.default.createElement(H_,{className:"tw-size-4"}))),Bt.default.createElement(fr,{className:"tw-px-1 tw-py-0.5"},"Toggle autonomous agent mode")),!s&&Bt.default.createElement(Bt.default.Fragment,null,Bt.default.createElement(hr,null,Bt.default.createElement(gr,{asChild:!0},Bt.default.createElement(oe,{variant:"ghost2",size:"fit",onClick:h,className:J("tw-text-muted hover:tw-text-accent",t&&"tw-text-accent tw-bg-accent/10")},Bt.default.createElement(RC,{className:"tw-size-4"}))),Bt.default.createElement(fr,{className:"tw-px-1 tw-py-0.5"},"Toggle vault search")),Bt.default.createElement(hr,null,Bt.default.createElement(gr,{asChild:!0},Bt.default.createElement(oe,{variant:"ghost2",size:"fit",onClick:g,className:J("tw-text-muted hover:tw-text-accent",n&&"tw-text-accent tw-bg-accent/10")},Bt.default.createElement(Xo,{className:"tw-size-4"}))),Bt.default.createElement(fr,{className:"tw-px-1 tw-py-0.5"},"Toggle web search")),Bt.default.createElement(hr,null,Bt.default.createElement(gr,{asChild:!0},Bt.default.createElement(oe,{variant:"ghost2",size:"fit",onClick:v,className:J("tw-text-muted hover:tw-text-accent",o&&"tw-text-accent tw-bg-accent/10")},Bt.default.createElement("span",{className:"tw-flex tw-items-center tw-gap-0.5"},Bt.default.createElement(hc,{className:"tw-size-2"}),Bt.default.createElement(rm,{className:"tw-size-3"})))),Bt.default.createElement(fr,{className:"tw-px-1 tw-py-0.5"},"Toggle composer (note editing)")))),Bt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-0.5 @[420px]/chat-input:tw-hidden"},Bt.default.createElement(up,null,Bt.default.createElement(dp,{asChild:!0},Bt.default.createElement(oe,{variant:"ghost2",size:"fit",className:"tw-text-muted hover:tw-text-accent"},Bt.default.createElement(Pw,{className:"tw-size-4"}))),Bt.default.createElement(Ac,{align:"end",className:"tw-w-56"},p&&Bt.default.createElement(co,{onClick:m,className:"tw-flex tw-items-center tw-justify-between"},Bt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Bt.default.createElement(H_,{className:"tw-size-4"}),Bt.default.createElement("span",null,"Autonomous Agent")),s&&Bt.default.createElement(Hr,{className:"tw-size-4"})),!s&&Bt.default.createElement(Bt.default.Fragment,null,Bt.default.createElement(co,{onClick:h,className:"tw-flex tw-items-center tw-justify-between"},Bt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Bt.default.createElement(RC,{className:"tw-size-4"}),Bt.default.createElement("span",null,"Vault Search")),t&&Bt.default.createElement(Hr,{className:"tw-size-4"})),Bt.default.createElement(co,{onClick:g,className:"tw-flex tw-items-center tw-justify-between"},Bt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Bt.default.createElement(Xo,{className:"tw-size-4"}),Bt.default.createElement("span",null,"Web Search")),n&&Bt.default.createElement(Hr,{className:"tw-size-4"})),Bt.default.createElement(co,{onClick:v,className:"tw-flex tw-items-center tw-justify-between"},Bt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Bt.default.createElement("span",{className:"tw-flex tw-items-center tw-gap-0.5"},Bt.default.createElement(hc,{className:"tw-size-2"}),Bt.default.createElement(rm,{className:"tw-size-3"})),Bt.default.createElement("span",null,"Composer")),o&&Bt.default.createElement(Hr,{className:"tw-size-4"}))),s&&Bt.default.createElement(Bt.default.Fragment,null,Bt.default.createElement(co,{disabled:!0,className:"tw-flex tw-items-center tw-justify-between tw-opacity-50"},Bt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Bt.default.createElement(RC,{className:"tw-size-4"}),Bt.default.createElement("span",null,"Vault Search"))),Bt.default.createElement(co,{disabled:!0,className:"tw-flex tw-items-center tw-justify-between tw-opacity-50"},Bt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Bt.default.createElement(Xo,{className:"tw-size-4"}),Bt.default.createElement("span",null,"Web Search"))),Bt.default.createElement(co,{disabled:!0,className:"tw-flex tw-items-center tw-justify-between tw-opacity-50"},Bt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Bt.default.createElement("span",{className:"tw-flex tw-items-center tw-gap-0.5"},Bt.default.createElement(hc,{className:"tw-size-2"}),Bt.default.createElement(rm,{className:"tw-size-3"})),Bt.default.createElement("span",null,"Composer")))))))):null}});var _cn,Tl,XAr,ESe,zet=b(()=>{es();Se();ut();_cn=require("obsidian"),Tl=L(B());Bet();bcn();XAr=t=>{let{handleSendMessage:e,inputMessage:n}=t,[r]=Cw(),o=xt(),i=sd(r),[s,a]=(0,Tl.useState)(!1),[l,c]=(0,Tl.useState)(!1),[u,d]=(0,Tl.useState)(!1),[f,p]=(0,Tl.useState)(o.enableAutonomousAgent);(0,Tl.useEffect)(()=>{p(o.enableAutonomousAgent)},[o.enableAutonomousAgent]);let m=(0,Tl.useRef)(null),h=(0,Tl.useCallback)(()=>{m.current?.removeToolPills(["@vault"])},[]),g=(0,Tl.useCallback)(()=>{m.current?.removeToolPills(["@websearch","@web"])},[]),v=(0,Tl.useCallback)(()=>{m.current?.removeToolPills(["@composer"])},[]),y=(0,Tl.useCallback)(I=>{f||(a(I.includes("@vault")),c(I.includes("@websearch")||I.includes("@web")),d(I.includes("@composer")))},[f]),w=(0,Tl.useCallback)(()=>{i&&!f&&!s&&(a(!0),new _cn.Notice("Vault search enabled for tag query"))},[i,f,s]),_=(0,Tl.useCallback)(I=>{if(!i||f){e(I);return}let C=n.toLowerCase(),k=[];if(s&&!C.includes("@vault")&&k.push("@vault"),l&&!C.includes("@websearch")&&!C.includes("@web")&&k.push("@websearch"),u&&!C.includes("@composer")&&k.push("@composer"),k.length===0){e(I);return}e({...I,toolCalls:k})},[e,n,i,f,s,l,u]),S=(0,Tl.useMemo)(()=>Tl.default.createElement(wcn,{vaultToggle:s,setVaultToggle:a,webToggle:l,setWebToggle:c,composerToggle:u,setComposerToggle:d,autonomousAgentToggle:f,setAutonomousAgentToggle:p,currentChain:r,onVaultToggleOff:h,onWebToggleOff:g,onComposerToggleOff:v}),[s,l,u,f,r,h,g,v]);return Tl.default.createElement(ASe,{...t,ref:m,handleSendMessage:_,toolControls:S,onToolPillsChange:y,onTagSelected:w})},ESe=XAr});var zp,xcn,Scn,Ccn=b(()=>{zp=L(B()),xcn=require("obsidian");zet();vV();x_e();Scn=({initialValue:t,initialContext:e,onSave:n,onCancel:r,app:o})=>{let[i,s]=(0,zp.useState)(t),[a,l]=(0,zp.useState)(e?.notes?.filter(C=>C instanceof xcn.TFile)||[]),[c,u]=(0,zp.useState)(!1),[d,f]=(0,zp.useState)(!1),[p,m]=(0,zp.useState)([]),{activeWebTabForMentions:h}=RS(),g=(0,zp.useCallback)((C,k)=>{let T={notes:k.notes,urls:k.urls,tags:k.tags,folders:k.folders,selectedTextContexts:e?.selectedTextContexts||[]};n(C,T)},[n,e?.selectedTextContexts]),v=(0,zp.useCallback)(()=>{r()},[r]),y=(0,zp.useCallback)(()=>{},[]),w=(0,zp.useCallback)(()=>{},[]),_=(0,zp.useCallback)(C=>{m(k=>__e(k,C))},[]),S=(0,zp.useCallback)(C=>{},[]),I={notes:a,urls:e?.urls||[],tags:e?.tags||[],folders:e?.folders||[]};return zp.default.createElement(ESe,{inputMessage:i,setInputMessage:s,handleSendMessage:y,isGenerating:!1,onStopGenerating:w,app:o,contextNotes:a,setContextNotes:l,includeActiveNote:c,setIncludeActiveNote:u,includeActiveWebTab:d,setIncludeActiveWebTab:f,activeWebTab:h,selectedImages:p,onAddImage:_,setSelectedImages:m,disableModelSwitch:!1,selectedTextContexts:e?.selectedTextContexts,onRemoveSelectedText:S,editMode:!0,onEditSave:g,onEditCancel:v,initialContext:I})}});var MSe,kcn,Icn=b(()=>{MSe=L(B()),kcn=({errorContent:t})=>MSe.default.createElement("div",{className:"tw-my-2 tw-mb-6 tw-max-h-[180px] tw-overflow-y-scroll tw-rounded-xl tw-bg-modifier-error-rgb/5 tw-p-3"},MSe.default.createElement("div",{className:"tw-mb-2 tw-text-sm tw-font-semibold tw-text-error"},"\u26A0\uFE0F Error occurred"),MSe.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-text-xs tw-text-error"},t.trim()))});function Tcn(t){let e=t.trim();if(!e)return"note";let n=e.match(/^\[\[([\s\S]+?)\]\]$/),r=n?n[1]:e,[o="",i=""]=r.split("|"),s=i.trim();if(s.length>0)return s;let a=o.trim(),[l]=a.split("#"),c=(l||a).trim()||e,u=c.split("/").filter(Boolean),d=u.length>0?u[u.length-1]:c;return d.replace(/\.[^/.]+$/,"")||d||"note"}function QAr(t){let e=t.trim();return e.length<=Pcn?e:`${e.slice(0,Pcn)}\u2026`}function eEr(t){if(!t||typeof t!="object")return null;let e=t,n=typeof e.status=="string"?e.status:null,r=typeof e.message=="string"&&e.message.trim().length>0?QAr(e.message):null,o=typeof e.notePath=="string"?e.notePath:"",s=(typeof e.noteTitle=="string"&&e.noteTitle.trim().length>0?e.noteTitle.trim():Tcn(o))||Tcn(o);if(n==="invalid_path")return r??`\u26A0\uFE0F Invalid note path "${s}"`;if(n==="not_found")return r??`\u26A0\uFE0F Note "${s}" not found`;if(n==="not_unique"){let d=Array.isArray(e.candidates)?e.candidates.length:0;return r||(d>0?`\u26A0\uFE0F Multiple matches for "${s}" (${d} candidates)`:`\u26A0\uFE0F Multiple matches for "${s}"`)}if(n==="empty")return r??`\u26A0\uFE0F "${s}" contains no readable content`;if(n==="out_of_range"){if(r)return r;let d=typeof e.totalChunks=="number"&&Number.isFinite(e.totalChunks)?e.totalChunks:null,f=typeof e.chunkIndex=="number"&&Number.isFinite(e.chunkIndex)?e.chunkIndex:null;if(f!==null&&d!==null){let p=Math.max(d-1,0);return`\u26A0\uFE0F Chunk ${f} exceeds available range (max index ${p})`}return"\u26A0\uFE0F Requested chunk is out of range"}let a=typeof e.chunkIndex=="number"&&Number.isFinite(e.chunkIndex)?e.chunkIndex:0,l=typeof e.totalChunks=="number"&&Number.isFinite(e.totalChunks)?e.totalChunks:null,c=!!e.hasMore,u=[`\u2705 Read "${s||"note"}"`];return l&&l>0?u.push(`chunk ${a+1} of ${l}`):u.push(`chunk ${a+1}`),c&&u.push("more available"),u.join(" \xB7 ")}var Pcn,S0,OSe=b(()=>{Pcn=180;S0=class{static format(e,n){try{let r=n;if(typeof r=="string"&&r.startsWith("ENC:"))try{r=decodeURIComponent(r.slice(4))}catch{}let o;try{o=JSON.parse(r)}catch{o=r}switch(e){case"localSearch":return this.formatLocalSearch(o);case"webSearch":return this.formatWebSearch(o);case"youtubeTranscription":return this.formatYoutubeTranscription(o);case"writeFile":return this.formatWriteToFile(o);case"editFile":return this.formatReplaceInFile(o);case"readNote":return this.formatReadNote(o);default:return n}}catch{return n}}static formatLocalSearchDocuments(e){if(!Array.isArray(e)||e.length===0)return`\u{1F4DA} Found 0 relevant notes
No matching notes found.`;let n=e.length,r=e.slice(0,10),o=r.some(a=>{let l=a;return typeof l?.rerank_score=="number"||typeof l?.score=="number"||l?.source}),i=r.map((a,l)=>o?this.formatSearchItem(a,l):this.formatBasicSearchItem(a,l)).join(`
`),s=n>10?`
... and ${n-10} more results`:"";return`\u{1F4DA} Found ${n} relevant notes
Top results:
${i}${s}`}static formatLocalSearch(e){if(typeof e=="string"){let r=e.match(/<localSearch[^>]*>([\s\S]*)<\/localSearch>/);if(r){let o=r[1].trim(),i=o.match(/<document>/g);if((i?i.length:0)===0)return`\u{1F4DA} Found 0 relevant notes
No matching notes found.`;let a=[],l=/<document>([\s\S]*?)<\/document>/g,c;for(;(c=l.exec(o))!==null;){let u=c[1],d=u.match(/<title>([\s\S]*?)<\/title>/),f=u.match(/<path>([\s\S]*?)<\/path>/),p=u.match(/<modified>([\s\S]*?)<\/modified>/),m=(d?.[1]||"Untitled").trim(),h=(f?.[1]||"").trim(),g=(p?.[1]||"").trim();a.push({title:m,path:h,mtime:g||null})}return this.formatLocalSearchDocuments(a)}}let n=this.parseSearchResults(e);return Array.isArray(n)?n.length===0?typeof e=="string"&&!e.includes("<localSearch")&&!e.includes('"type":"local_search"')?e:`\u{1F4DA} Found 0 relevant notes
No matching notes found.`:this.formatLocalSearchDocuments(n):typeof e=="string"?e:JSON.stringify(e,null,2)}static parseSearchResults(e){if(typeof e=="object"&&e!==null){let n=e;return n.type==="local_search"&&Array.isArray(n.documents)?n.documents:[]}if(typeof e=="string"){try{let n=JSON.parse(e);if(n&&typeof n=="object"&&n.type==="local_search"&&Array.isArray(n.documents))return n.documents}catch{}return[]}return[]}static formatSearchItem(e,n){let r=e,o=typeof r.path=="string"?r.path:"",i=typeof r.title=="string"?r.title:"",s=o?o.split("/").pop()?.replace(/\.md$/,"")||i||"Untitled":i||"Untitled",a=r.rerank_score||r.score||0,l=typeof a=="number"?a.toFixed(4):a,c=r.source==="time-filtered"?"Recency":"Relevance",u=[`${n+1}. ${s}`];if(r.source==="time-filtered"){if(r.mtime)try{let f=r.mtime,p=new Date(f),m=isNaN(p.getTime())?typeof f=="string"||typeof f=="number"?String(f):"":p.toISOString();u.push(` \u{1F552} Modified: ${m}${r.includeInContext?" \u2713":""}`)}catch{let f=typeof r.mtime=="string"||typeof r.mtime=="number"?String(r.mtime):"";u.push(` \u{1F552} Modified: ${f}${r.includeInContext?" \u2713":""}`)}}else r.source==="title-match"?u.push(` \u{1F516} Title match${r.includeInContext?" \u2713":""}`):u.push(` \u{1F4CA} ${c}: ${l}${r.includeInContext?" \u2713":""}`);let d=this.extractContentSnippet(r.content);if(d){let f=typeof r.content=="string"?r.content.length:0;u.push(` \u{1F4AC} "${d}${f>150?"...":""}"`)}return o&&!o.endsWith(`/${s}.md`)&&u.push(` \u{1F4C1} ${o}`),u.join(`
`)}static formatBasicSearchItem(e,n){let r=e,o=r.title||r.path||`Result ${n+1}`,i=[`${n+1}. ${o}`],s=r.mtime||r.modified||r.modified_at||r.updated_at;if(s){let a=typeof s=="string"||typeof s=="number"?String(s):"";a&&i.push(` \u{1F552} Modified: ${a}`)}return typeof r.path=="string"&&r.path&&r.path!==o&&i.push(` \u{1F4C1} ${r.path}`),i.join(`
`)}static extractContentSnippet(e,n=150){return e?(e.match(/NOTE BLOCK CONTENT:\s*([\s\S]*)/)?.[1]||e).substring(0,n).replace(/\s+/g," ").trim():""}static formatWebSearch(e){let n=Array.isArray(e)&&e.length>0?e[0]:null;if(n&&n.type==="web_search"){let r=["\u{1F310} Web Search Results"];n.content&&(r.push(""),r.push(typeof n.content=="string"?n.content:""));let o=Array.isArray(n.citations)?n.citations:[];return o.length>0&&(r.push(""),r.push("Sources:"),o.forEach((i,s)=>{r.push(`[${s+1}] ${String(i)}`)})),n.instruction&&(r.push(""),r.push(`Note: ${typeof n.instruction=="string"?n.instruction:""}`)),r.join(`
`)}if(typeof e=="string"){let r=e.split(`
`),o=["\u{1F310} Web Search Results"],i=!1,s=[],a=[];for(let l of r){if(l.includes("Sources:")){i=!0;continue}i?a.push(l):l.includes("Here are the web search results")||s.push(l)}return s.length>0&&(o.push(""),o.push(...s.filter(l=>l.trim()))),a.length>0&&(o.push(""),o.push("Sources:"),a.forEach(l=>{l.trim()&&o.push(l)})),o.join(`
`)}return typeof e=="string"?e:""}static formatYoutubeTranscription(e){let n;if(typeof e=="string")try{n=JSON.parse(e)}catch{return e}else if(typeof e=="object")n=e;else return typeof e=="number"||typeof e=="boolean"?String(e):"";let r=typeof n=="object"&&n!==null?n:null;if(!r)return typeof e=="object"?JSON.stringify(e,null,2):"";if(r.success===!1)return`\u{1F4FA} YouTube Transcription Failed
${typeof r.message=="string"?r.message:""}`;if(r.results&&Array.isArray(r.results)){let o=typeof r.total_urls=="number"?r.total_urls:r.results.length,i=[`\u{1F4FA} YouTube Transcripts (${o} video${o>1?"s":""})`];i.push("");for(let s of r.results){let a=typeof s=="object"&&s!==null?s:null;if(a){if(a.success){i.push(`\u{1F4F9} Video: ${typeof a.url=="string"?a.url:""}`),i.push("");let c=(typeof a.transcript=="string"?a.transcript:"").split(`
`),u=0;for(let d of c)if(d.trim()&&(d.match(/^\[(\d+:\d+)\]/)?(u>0&&i.push(""),i.push(`\u23F0 ${d}`)):i.push(` ${d.trim()}`),u++,u>30)){i.push(""),i.push("... (transcript truncated for display)");break}a.elapsed_time_ms&&(i.push(""),i.push(`Processing time: ${(typeof a.elapsed_time_ms=="number"?a.elapsed_time_ms/1e3:0).toFixed(1)}s`))}else i.push(`\u274C Failed to transcribe: ${typeof a.url=="string"?a.url:""}`),i.push(` ${typeof a.message=="string"?a.message:""}`);i.push(""),i.push("---"),i.push("")}}return i.join(`
`).trimEnd()}if(r.transcript){let o=["\u{1F4FA} YouTube Transcript"];o.push("");let s=(typeof r.transcript=="string"?r.transcript:"").split(`
`),a=0;for(let l of s)if(l.trim()&&(l.match(/^\[(\d+:\d+)\]/)?(a>0&&o.push(""),o.push(`\u23F0 ${l}`)):o.push(` ${l.trim()}`),a++,a>50)){o.push(""),o.push("... (transcript truncated for display)");break}return r.elapsed_time_ms&&(o.push(""),o.push(`Processing time: ${(typeof r.elapsed_time_ms=="number"?r.elapsed_time_ms/1e3:0).toFixed(1)}s`)),o.join(`
`)}return typeof e=="object"?JSON.stringify(e,null,2):""}static formatWriteToFile(e){let n=typeof e=="object"&&e!==null?e:null,r=n?n.result:e,o=(typeof r=="string"?r:typeof r=="number"||typeof r=="boolean"?String(r):"").toLowerCase();return o.includes("accepted")?"\u2705 File change: accepted":o.includes("rejected")?"\u274C File change: rejected":n&&typeof n.message=="string"?n.message:typeof r=="string"?r:""}static formatReplaceInFile(e){let n=typeof e=="object"&&e!==null?e:null,r=n?n.result:void 0,o=n?typeof r=="string"||typeof r=="number"||typeof r=="boolean"?String(r):"":typeof e=="string"?e:"",i=n?n.diff:void 0,s=typeof i=="string"?i:typeof i=="number"?String(i):"";return o.toLowerCase().includes("accepted")&&s?`\u2705 Edit accepted
\`\`\`diff
${s}
\`\`\``:o.toLowerCase().includes("accepted")?"\u2705 Edit accepted":o.toLowerCase().includes("rejected")?"\u274C Edit rejected":n&&typeof n.message=="string"?n.message:o}static formatReadNote(e){let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{n=null}let r=eEr(n);return r||(typeof e=="string"?e:JSON.stringify(e,null,2))}}});var Ls,tEr,gte,nEr,Acn,Ecn=b(()=>{Sj();De();OSe();Re();Ls=L(B()),tEr="shimmer 2s ease-in-out infinite",gte=5e3,nEr=(t,e)=>{if(!e)return null;if(e.length>gte)return`Tool '${t}' returned ${e.length.toLocaleString()} characters. The full output is preserved in chat history but omitted here to keep the UI responsive.`;try{let n=S0.format(t,e);return n.length>gte?n.slice(0,gte)+`
\u2026 (truncated ${(n.length-gte).toLocaleString()} characters for display)`:n}catch{return e.length>gte?`Tool '${t}' returned ${e.length.toLocaleString()} characters. The full output is preserved in chat history but omitted here to keep the UI responsive.`:e}},Acn=({toolName:t,displayName:e,emoji:n,isExecuting:r,result:o,confirmationMessage:i,onAccept:s,onReject:a})=>{let[l,c]=(0,Ls.useState)(!1),u=(0,Ls.useMemo)(()=>nEr(t,o),[t,o]),d=r&&!o,f=!d&&u!==null;return Ls.default.createElement(dx,{open:f?l:!1,onOpenChange:c,disabled:!f,"aria-disabled":!f,className:"tw-my-3 tw-w-full sm:tw-max-w-sm"},Ls.default.createElement("div",{className:J("tw-rounded-md tw-border tw-border-border tw-bg-secondary/50",d&&"tw-relative tw-overflow-hidden")},d&&Ls.default.createElement("div",{className:"tw-absolute tw-inset-0 tw-z-[1] tw-overflow-hidden"},Ls.default.createElement("div",{className:"tw-absolute tw-inset-0 -tw-translate-x-full",style:{background:"linear-gradient(90deg, transparent 0%, rgba(255, 255, 255, 0.3) 50%, transparent 100%)",animation:tEr}})),Ls.default.createElement(fx,{className:J("tw-flex tw-w-full tw-items-center tw-justify-between tw-px-3 tw-py-2.5 tw-text-sm sm:tw-px-4 sm:tw-py-3",f&&"hover:tw-bg-secondary/70",!f&&"tw-cursor-default")},Ls.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ls.default.createElement("span",{className:"tw-text-base"},n),Ls.default.createElement("span",{className:"tw-font-medium"},t==="readNote"?`${d?"Reading":"Read"} ${e}`:`${d?"Calling":"Called"} ${e}`,d&&t!=="readNote"&&"..."),d&&i&&Ls.default.createElement("span",{className:"tw-text-xs tw-text-muted"},"\u2022 ",i,"...")),Ls.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},!d&&s&&a&&Ls.default.createElement(Ls.default.Fragment,null,Ls.default.createElement("button",{type:"button",onClick:p=>{p.stopPropagation(),s()},className:"hover:tw-bg-green-rgb/20 tw-rounded tw-p-1",title:"Accept"},Ls.default.createElement(Hr,{className:"tw-size-4 tw-text-success"})),Ls.default.createElement("button",{type:"button",onClick:p=>{p.stopPropagation(),a()},className:"hover:tw-bg-red-rgb/20 tw-rounded tw-p-1",title:"Reject"},Ls.default.createElement(pn,{className:"tw-size-4 tw-text-error"}))),f&&Ls.default.createElement(Vi,{className:J("tw-size-4 tw-text-muted tw-transition-transform",l&&"tw-rotate-90")}))),Ls.default.createElement(px,null,Ls.default.createElement("div",{className:"tw-border-t tw-border-border tw-px-3 tw-py-2.5 sm:tw-px-4 sm:tw-py-3"},Ls.default.createElement("div",{className:"tw-text-sm tw-text-muted"},Ls.default.createElement("pre",{className:"tw-overflow-x-auto tw-whitespace-pre-wrap tw-font-mono tw-text-xs"},u??"No result available"))))))}});var Het,Mcn,LV,$V,Wet,Vet,Ocn,TM,Ncn,Rcn,Lcn,$cn,Dcn,Fcn,Ucn,jcn,Bcn,zcn,Hcn,Wcn,Vcn=b(()=>{Het=L(B());Icn();Ecn();pe();Pa();Mcn=60*60*1e3,LV=()=>(window.__copilotToolCallRoots||(window.__copilotToolCallRoots=new Map),window.__copilotToolCallRoots),$V=()=>(window.__copilotErrorBlocks||(window.__copilotErrorBlocks=new Map),window.__copilotErrorBlocks),Wet=(t,e,n)=>{if(e.size>0)return;n.get(t)===e&&n.delete(t)},Vet=(t,e,n,r,o,i)=>{try{r.root.unmount()}catch(s){W(`Error unmounting tool call root during ${o}`,n,s)}r.isUnmounting=!1,e.get(n)===r&&e.delete(n),Wet(t,e,i)},Ocn=(t,e,n,r,o,i)=>{e.delete(n),r.isUnmounting=!0,window.setTimeout(()=>{try{r.root.unmount()}catch(s){W(`Error unmounting tool call root during ${o}`,n,s)}r.isUnmounting=!1,Wet(t,e,i)},0)},TM=(t,e,n,r,o,i)=>{r.isUnmounting||(r.isUnmounting=!0,window.setTimeout(()=>{let s=i.get(t),a=s?.get(n);if(!s||a!==r){r.isUnmounting=!1,Wet(t,e,i);return}Vet(t,s,n,a,o,i)},0))},Ncn=(t,e,n,r,o,i)=>{let s=n.get(r);return s?.isUnmounting&&(Vet(e,n,r,s,`${i} (finalizing stale root)`,LV()),s=void 0),s&&s.container&&s.container!==o&&(Ocn(e,n,r,s,`${i} (container changed)`,LV()),s=void 0),s||(s={root:Er(o,t),isUnmounting:!1,container:o},n.set(r,s)),s},Rcn=(t,e,n,r,o,i)=>{let s=n.get(r);return s?.isUnmounting&&(Vet(e,n,r,s,`${i} (finalizing stale error root)`,$V()),s=void 0),s&&s.container&&s.container!==o&&(Ocn(e,n,r,s,`${i} (container changed)`,$V()),s=void 0),s||(s={root:Er(o,t),isUnmounting:!1,container:o},n.set(r,s)),s},Lcn=(t,e)=>{t.root.render(Het.default.createElement(Acn,{toolName:e.toolName,displayName:e.displayName,emoji:e.emoji,isExecuting:e.isExecuting,result:e.result||null,confirmationMessage:e.confirmationMessage}))},$cn=(t,e)=>{t.root.render(Het.default.createElement(kcn,{errorContent:e.errorContent}))},Dcn=(t,e,n,r)=>{let o=e.get(n);o&&TM(t,e,n,o,r,LV())},Fcn=(t,e,n,r)=>{let o=e.get(n);o&&TM(t,e,n,o,r,$V())},Ucn=t=>{let e=LV(),n=e.get(t);return n||(n=new Map,e.set(t,n)),n},jcn=t=>{let e=$V(),n=e.get(t);return n||(n=new Map,e.set(t,n)),n},Bcn=(t=Date.now())=>{let e=LV();e.forEach((n,r)=>{n.forEach((o,i)=>{if(o.container){if(o.container.isConnected)return;TM(r,n,i,o,"stale cleanup (detached container)",e);return}let s=Number.parseInt(r,10);Number.isNaN(s)||t-s<Mcn||TM(r,n,i,o,"stale cleanup (legacy record)",e)})})},zcn=(t=Date.now())=>{let e=$V();e.forEach((n,r)=>{n.forEach((o,i)=>{if(o.container){if(o.container.isConnected)return;TM(r,n,i,o,"stale error cleanup (detached container)",e);return}let s=Number.parseInt(r,10);Number.isNaN(s)||t-s<Mcn||TM(r,n,i,o,"stale error cleanup (legacy record)",e)})})},Hcn=(t,e,n)=>{let r=LV();e.forEach((o,i)=>{TM(t,e,i,o,n,r)})},Wcn=(t,e,n)=>{let r=$V();e.forEach((o,i)=>{TM(t,e,i,o,n,r)})}});var Kcn={};sr(Kcn,{createToolCallMarker:()=>sEr,parseToolCallMarkers:()=>Ket,updateToolCallMarker:()=>aEr});function qcn(t){try{return`ENC:${encodeURIComponent(t)}`}catch{return t}}function oEr(t){if(typeof t!="string"||!t.startsWith("ENC:"))return t;try{return decodeURIComponent(t.slice(4))}catch{return t}}function iEr(t){return`Tool '${t}' ${rEr}`}function qet(t,e=0,n=""){let r=[],o=/<errorChunk>([\s\S]*?)<\/errorChunk>/g,i=0,s;for(;(s=o.exec(t))!==null;){s.index>i&&r.push({type:"text",content:t.slice(i,s.index)});let[a,l]=s,c=e+s.index,u=n?`${n}-error-${c}`:`error-${c}`;r.push({type:"error",content:l,error:{id:u,errorContent:l,startIndex:c,endIndex:e+s.index+a.length}}),i=s.index+a.length}return i<t.length&&r.push({type:"text",content:t.slice(i)}),r.length===0&&r.push({type:"text",content:t}),r}function Ket(t,e){let n=[],r=/<!--TOOL_CALL_START:([^:]+):([^:]+):([^:]+):([^:]+):([^:]*):([^:]+)-->([\s\S]*?)<!--TOOL_CALL_END:\1:([\s\S]*?)-->/g,o=0,i;for(;(i=r.exec(t))!==null;){if(i.index>o){let w=t.slice(o,i.index);qet(w,o,e).forEach(S=>{S.type==="text"&&S.content.trim()?n.push({type:"text",content:S.content}):S.type==="error"&&S.error&&n.push({type:"error",content:S.content,error:S.error})})}let[s,a,l,c,u,d,f,p,m]=i,g=oEr(typeof m=="string"?m:""),y=(typeof g=="string"?g.length:0)>5e3?iEr(l):g??void 0;n.push({type:"toolCall",content:p,toolCall:{id:a,toolName:l,displayName:c,emoji:u,confirmationMessage:d||void 0,isExecuting:f==="true",result:y,startIndex:i.index,endIndex:i.index+s.length}}),o=i.index+s.length}if(o<t.length){let s=t.slice(o);qet(s,o,e).forEach(l=>{l.type==="text"&&l.content.trim()?n.push({type:"text",content:l.content}):l.type==="error"&&l.error&&n.push({type:"error",content:l.content,error:l.error})})}return n.length===0&&qet(t,0,e).forEach(a=>{a.type==="text"?n.push({type:"text",content:a.content}):a.type==="error"&&a.error&&n.push({type:"error",content:a.content,error:a.error})}),{segments:n}}function sEr(t,e,n,r,o="",i=!0,s="",a=""){let l=a&&qcn(a);return`<!--TOOL_CALL_START:${t}:${e}:${n}:${r}:${o}:${i}-->${s}<!--TOOL_CALL_END:${t}:${l}-->`}function aEr(t,e,n){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`(<!--TOOL_CALL_START:${r}:[^:]+:[^:]+:[^:]+:[^:]*:)true(-->[\\s\\S]*?<!--TOOL_CALL_END:${r}:)[\\s\\S]*?-->`,"g"),i=qcn(n);return t.replace(o,`$1false$2${i}-->`)}var rEr,Get=b(()=>{rEr=`Result omitted to keep the UI responsive (payload exceeded ${5e3.toLocaleString()} characters).`});function Gcn(){return{status:"idle",startTime:null,elapsedSeconds:0,steps:[]}}function Zet(t){if(t.status==="idle")return"";let e=JSON.stringify(t.steps.map(n=>n.summary));return`<!--AGENT_REASONING:${t.status}:${t.elapsedSeconds}:${e}-->`}function yte(t){let e=t.match(/<!--AGENT_REASONING:(\w+):(\d+):(.+?)-->/);if(!e)return null;let[n,r,o,i]=e,s=[];try{s=JSON.parse(i)}catch{s=[]}return{hasReasoning:!0,status:r,elapsedSeconds:parseInt(o,10),steps:s,contentAfter:t.replace(n,"").trim()}}function Zcn(t,e,n,r){if(!e.success)return`${Yet(t,r)} failed`;switch(t){case"localSearch":{if(n&&n.count>0){let o=n.titles.slice(0,3),i=n.count-o.length,s=`Found ${n.count} note${n.count!==1?"s":""}: ${o.join(", ")}`;return i>0&&(s+=` +${i} more`),s}return"No matching notes found"}case"webSearch":return"Retrieved web search results";case"getTimeRangeMs":return"Calculated time range";case"readFile":return"Read file content";case"readNote":{let o=r?.notePath;return o?`Read "${o.split("/").pop()?.replace(/\.md$/i,"")||o}"`:"Read note content"}case"createNote":return"Created new note";case"appendToNote":return"Appended to note";case"editNote":return"Edited note";case"deleteNote":return"Deleted note";case"youtubeTranscript":case"youtubeTranscription":return"Fetched video transcript";case"fetchUrl":return"Fetched URL content";case"getFileTree":return"Retrieved vault file tree";case"getTagList":return"Retrieved vault tags";case"getCurrentTime":return"Got current time";case"getTimeInfoByEpoch":return"Converted timestamp";case"convertTimeBetweenTimezones":return"Converted timezone";case"obsidianDailyNote":{let o=r?.command,i=r?.vault,s=i&&i.trim().length>0?` from "${i}"`:"";return o==="daily:path"?`Got daily note path${s}`:`Loaded today's daily note${s}`}case"obsidianRandomRead":{let o=r?.vault;return o&&o.trim().length>0?`Loaded a random note from "${o}"`:"Loaded a random note"}case"obsidianProperties":{if(r?.command==="property:read"){let i=r?.name;return i?`Read property "${i}"`:"Read property"}return"Listed vault properties"}case"obsidianTasks":return"Listed vault tasks";case"obsidianLinks":{let o=r?.command;return o==="backlinks"?"Listed backlinks":o==="links"?"Listed outgoing links":o==="orphans"?"Listed orphaned notes":o==="unresolved"?"Listed unresolved links":"Queried link graph"}case"obsidianTemplates":{if(r?.command==="template:read"){let i=r?.name;return i?`Read template "${i}"`:"Read template"}return"Listed templates"}case"obsidianBases":{let o=r?.command;return o==="base:views"?"Listed base views":o==="base:query"?"Queried base data":"Listed bases"}case"indexVault":return"Indexed vault";case"updateMemory":return"Updated memory";case"writeFile":case"editFile":{let o=r?.path,i=o?o.split("/").pop()||o:"file",s=e.result||"";return s.includes('"rejected"')||s.includes("rejected")?`Edit rejected for "${i}"`:s.includes('"failed"')||s.includes("Error")?`Edit failed for "${i}"`:t==="writeFile"?`Wrote to "${i}"`:`Edited "${i}"`}default:return"Done"}}function Yet(t,e,n){switch(t){case"localSearch":{if(n&&n.recallTerms&&n.recallTerms.length>0){let o=n.recallTerms.filter(i=>typeof i=="string"&&i.trim().length>0&&!i.includes("[object ")&&i!=="[object Object]");if(o.length>0){let i=o.slice(0,6).map(l=>`"${l}"`).join(", "),s=o.length-6,a=s>0?` +${s} more`:"";return`Searching notes for ${i}${a}`}}let r=e?.query;return r?`Searching notes for "${r.length>50?r.slice(0,50)+"...":r}"`:"Searching notes"}case"webSearch":{let r=e?.query;return r?`Searching web for "${r.length>30?r.slice(0,30)+"...":r}"`:"Searching the web"}case"getTimeRangeMs":return"Calculating time range";case"readFile":{let r=e?.path;return r?`Reading "${r.split("/").pop()||r}"`:"Reading file"}case"readNote":{let r=e?.notePath;return r?`Reading "${r.split("/").pop()?.replace(/\.md$/i,"")||r}"`:"Reading note"}case"createNote":return"Creating new note";case"appendToNote":return"Appending to note";case"editNote":return"Editing note";case"deleteNote":return"Deleting note";case"youtubeTranscript":case"youtubeTranscription":return"Fetching video transcript";case"fetchUrl":return"Fetching URL content";case"getFileTree":return"Browsing vault file tree";case"getTagList":return"Loading vault tags";case"getCurrentTime":return"Getting current time";case"getTimeInfoByEpoch":return"Converting timestamp";case"convertTimeBetweenTimezones":return"Converting timezone";case"obsidianDailyNote":{let r=e?.command,o=e?.vault,i=o&&o.trim().length>0?` from "${o}"`:"";return r==="daily:path"?`Getting daily note path${i}`:`Reading today's daily note${i}`}case"obsidianRandomRead":{let r=e?.vault;return r&&r.trim().length>0?`Reading a random note from "${r}"`:"Reading a random note"}case"obsidianProperties":{if(e?.command==="property:read"){let o=e?.name;return o?`Reading property "${o}"`:"Reading property"}return"Listing vault properties"}case"obsidianTasks":return"Listing vault tasks";case"obsidianLinks":{let r=e?.command;return r==="backlinks"?"Listing backlinks":r==="links"?"Listing outgoing links":r==="orphans"?"Listing orphaned notes":r==="unresolved"?"Listing unresolved links":"Querying link graph"}case"obsidianTemplates":{if(e?.command==="template:read"){let o=e?.name;return o?`Reading template "${o}"`:"Reading template"}return"Listing templates"}case"obsidianBases":{let r=e?.command;return r==="base:views"?"Listing base views":r==="base:query"?"Querying base data":"Listing bases"}case"indexVault":return"Indexing vault";case"updateMemory":return"Saving to memory";case"writeFile":{let r=e?.path;return r?`Writing to "${r.split("/").pop()||r}"`:"Writing to file"}case"editFile":{let r=e?.path;return r?`Editing "${r.split("/").pop()||r}"`:"Editing file"}default:return"Processing"}}function lEr(t,e){return t.length>e?t.slice(0,e-3)+"...":t}function Ycn(t){if(!t||t.trim().length===0)return null;let e=t.trim().split(`
`)[0];return lEr(e,100)}var NSe=b(()=>{});function Qcn(t,e=!0){return e?`
<guidance>
${Xcn}
IMAGE INCLUSION:
When the retrieved documents contain relevant images (in formats like ![alt](image.png) or ![[image.png]]), include them in your response at appropriate locations using their exact original markdown format from the source.
Source Catalog (for reference only):
${t.join(`
`)}
</guidance>`:`
<guidance>
IMAGE INCLUSION:
When the retrieved documents contain relevant images (in formats like ![alt](image.png) or ![[image.png]]), include them in your response at appropriate locations using their exact original markdown format from the source.
Source Catalog (for reference only):
${t.join(`
`)}
</guidance>`}function eun(t,e=!0){return e?`
${Xcn}
Source Catalog (for reference only):
${t}`:""}function tun(t){return t?"REMINDER: End your response with an '#### Sources' section listing each cited source as [^n]: [[Title]], numbered sequentially from [^1].":null}function RSe(t,e,n=!0){if(!n||!e?.length||!t)return t||"";if(dEr(t))return t;let r=e.slice(0,uEr).map((o,i)=>{let s=(o.title||o.path||"Untitled").replace(/^\[\[|\]\]$/g,"");return`[^${i+1}]: [[${s}]]`}).join(`
`);return`${t}
#### Sources:
${r}`}function DV(t){if(!t)return"";let e=t.replace(/\[\^\d+\]/g,"");return e=e.replace(/\[(\d+(?:\s*,\s*\d+)*)\](?!\()/g,""),e=e.replace(/^\s*\[\^\d+\]:.*$/gm,""),e}function dEr(t){let e=t||"",n=/(^|\n)\s*#{1,6}\s*Sources\b/i.test(e),r=/(^|\n)\s*Sources\s*(?:[:-]\s*)?(\n|$)/i.test(e),o=/<summary[^>]*>\s*Sources\s*<\/summary>/i.test(e),i=/(^|\n)\s*\[\^\d+\]:\s*/.test(e);return n||r||o||i}function nun(t){let e=t||"";return/\[\^\d+\]/.test(e)}function run(t=!0){return t?`
${cEr}`:""}function fEr(t){let e=/([\s\S]*?)\n+(?:####\s*)?Sources\s*:?\s*\n+([\s\S]*)$/i,n=t.match(e);if(n)return{mainContent:n[1],sourcesBlock:(n[2]||"").trim()};let r=t.match(/([\s\S]*?)\n+---+\s*\n+([\s\S]*)$/);if(r){let i=(r[2]||"").trim();if(i.length>0&&i.split(`
`).every(a=>!a.trim()||/^\[\^\d+\]:/.test(a.trim())))return{mainContent:r[1],sourcesBlock:i}}let o=t.match(/([\s\S]*?)\n{2,}(\[\^\d+\]:[\s\S]*)$/);if(o){let i=(o[2]||"").trim();if(i.split(`
`).every(a=>!a.trim()||/^\[\^\d+\]:/.test(a.trim())))return{mainContent:o[1],sourcesBlock:i}}return null}function pEr(t){return t.includes(`
`)||(t=t.replace(/\s*\[(\d+)\]\s*/g,`
[$1] `),t=t.replace(/\s+(\d+)\.\s/g,`
$1. `),t=t.trim()),t}function mEr(t){return t.split(`
`).map(e=>e.trim()).filter(e=>/^\[\^\d+\]:/.test(e))}function hEr(t,e){let n=new Map,r=new Set,o=[],i=/\[\^(\d+)\]/g,s;for(;(s=i.exec(t))!==null;){let a=parseInt(s[1],10);r.has(a)||(r.add(a),o.push(a))}if(o.length>0)o.forEach((a,l)=>n.set(a,l+1));else{let a=1;for(let l of e){let c=l.match(/^\[\^(\d+)\]:/);if(c){let u=parseInt(c[1],10);n.has(u)||n.set(u,a++)}}}return n}function gEr(t,e){let n=t,r;do r=!1,n=n.replace(/\[\^(\d+)\]/g,(o,i)=>{let s=parseInt(i,10),l=`[${e.get(s)??s}]`;return l!==o&&(r=!0),l}),n=n.replace(/\[\^(\d+(?:\s*,\s*\^?\d+)*)\]/g,(o,i)=>{let a=`[${i.split(",").map(l=>{let c=l.trim().replace(/^\^/,""),u=parseInt(c,10);return e.get(u)??u}).sort((l,c)=>l-c).map(l=>l.toString()).join(", ")}]`;return a!==o&&(r=!0),a});while(r);return n=n.replace(/\[(\d+)\]\./g,"[$1]"),n}function yEr(t,e){let n=[];return t.split(`
`).forEach(r=>{let o=r.match(/^\[\^(\d+)\]:\s*(.*)$/);if(!o)return;let i=parseInt(o[1],10),s=e.get(i)??i,a=o[2].match(/\[([^\]]+)\]\(([^)]+)\)/),l=o[2].match(/\[\[(.*?)\]\]/),c;if(a)c=`<a href="${a[2]}">${a[1]}</a>`;else if(l)c=`[[${l[1]}]]`;else{let u=o[2].match(/^(.*?)\]\s*\(([^)]+)\)\s*$/);if(u){let d=u[1].trim();c=`<a href="${u[2].trim()}">${d}</a>`}else c=o[2].replace(/\s*\([^)]*\)\s*$/,"")}n[s-1]=c}),n}function vEr(t){let e=[],n=new Set,r=new Map;return t.forEach((o,i)=>{if(!o)return;let s=o.match(/\[\[(.*?)\]\]/),a=s?s[1].toLowerCase():o.toLowerCase();if(!n.has(a))n.add(a),e.push(o),r.set(i+1,e.length);else{let l=e.findIndex(c=>{let u=c.match(/\[\[(.*?)\]\]/);return(u?u[1].toLowerCase():c.toLowerCase())===a});l>=0&&r.set(i+1,l+1)}}),{uniqueItems:e,consolidationMap:r}}function wEr(t,e){return e.size===0?t:t.replace(/\[(\d+(?:\s*,\s*\d+)*)\]/g,(n,r)=>{let o=r.split(/\s*,\s*/),i=new Set,s=[];for(let a of o){let l=e.get(parseInt(a,10))||parseInt(a,10);i.has(l)||(i.add(l),s.push(l))}return`[${s.join(", ")}]`})}function bEr(t){let e=t,n;do n=e,e=e.replace(/\[(\d+(?:\s*,\s*\d+)*)\](?:\s*(?:and|,)\s*|\s*)\[(\d+(?:\s*,\s*\d+)*)\]/g,(r,o,i)=>{let s=new Set(o.split(/\s*,\s*/).map(l=>l.trim()));return i.split(/\s*,\s*/).map(l=>l.trim()).every(l=>s.has(l))?`[${[...s].join(", ")}]`:r});while(e!==n);return e}function _Er(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function xEr(t){return t!=null}function SEr(t){let e=t.split(`
`),n=[];return e.forEach(r=>{let o=r.trim();if(!o)return;let i=o.replace(/^<li>/i,"").replace(/<\/li>$/i,"").replace(/^[-*]\s*/,"").trim();if(!i)return;let s=i.match(/\[([^\]]+)\]\(([^)]+)\)/),a=i.match(/\[\[(.*?)\]\]/),l;s?l=`<a href="${s[2]}">${s[1]}</a>`:a?l=`[[${a[1]}]]`:l=_Er(i),n.push({index:n.length+1,html:l})}),n}function Jcn(t,e){let n=e.filter(o=>o.html.trim().length>0);if(n.length===0)return t;let r=n.map(({index:o,html:i})=>`<li class="copilot-sources__item"><span class="copilot-sources__index">[${o}]</span><span class="copilot-sources__text">${i}</span></li>`).join(`
`);return`${t}
<br/>
<details class="copilot-sources"><summary class="copilot-sources__summary">Sources</summary>
<ul class="copilot-sources__list">
${r}
</ul>
</details>`}function CEr(t){return t.replace(/\[(\d+(?:\s*,\s*\d+)*)\](?!\()/g,'<span class="copilot-citation-ref">[$1]</span>')}function oun(t,e=!0){if(!e)return t;let n=fEr(t);if(!n)return t;let{mainContent:r,sourcesBlock:o}=n;o=pEr(o);let i=mEr(o);if(i.length===0){let d=SEr(o);return Jcn(r,d)}let s=hEr(r,i);r=gEr(r,s);let a=yEr(o,s),{uniqueItems:l,consolidationMap:c}=vEr(a);c.size>0&&(r=wEr(r,c),r=bEr(r),a=l),r=CEr(r);let u=a.map((d,f)=>d?{index:f+1,html:d}:null).filter(xEr);return Jcn(r,u)}function LSe(t){return t.map(e=>{let n=e.title||e.path||"Untitled",r=e.path||n;return`- [[${n}]] (${r})`})}var Xcn,cEr,uEr,FV=b(()=>{Xcn=`CITATION RULES:
1. START with [^1] and increment sequentially ([^1], [^2], [^3], etc.) with NO gaps
2. BE SELECTIVE: ONLY cite when introducing NEW factual claims, specific data, or direct quotes from sources
3. IMPORTANT: Do NOT cite every sentence or bullet point. This creates clutter and poor readability.
4. DO NOT cite for:
- General knowledge or common facts
- Your own analysis or synthesis
- Transitional or concluding statements
- Every single sentence (AVOID CITATION CLUTTER - aim for 1-3 citations per paragraph maximum)
5. Citations are for SOURCE ATTRIBUTION, not for proving every statement
6. GOOD: One citation per key concept. BAD: Citation after every sentence.
7. Place citations immediately after the specific claim: "The study found X [^1]" not "The study found X. [^1]"
8. Do not reuse any bracketed numbers that appear inside the source content itself
9. If multiple source chunks come from the same document, cite each relevant chunk separately (e.g., [^1] and [^2] can both be from the same document title)
10. End with '#### Sources' section containing: [^n]: [[Title]] (one per line, matching citation order)`,cEr=`WEB CITATION RULES:
1. START with [^1] and increment sequentially ([^1], [^2], [^3], etc.) with NO gaps
2. Cite ONLY when introducing new factual claims, statistics, or direct quotes from the search results
3. After every cited claim, place the corresponding footnote immediately after the sentence ("The study found X [^1]")
4. End with '#### Sources' and provide definitions EXACTLY in this format: [^n]: [Short Title](URL)
IMPORTANT: Each source definition must follow this exact pattern:
- Start with [^n]: (where n is the citation number)
- Follow with [Title](URL) where Title is SHORT (2-5 words) and wrapped in square brackets
- Example: [^1]: [Paul Graham Essay](https://paulgraham.com/wealth.html)
- DO NOT write long descriptions - keep titles concise`;uEr=20});function kEr(t){return t.split(/(```[\s\S]*?```|`[^`]*`)/g).map((n,r)=>r%2===1?n:n.replace(/\\\[\s*/g,"$$").replace(/\s*\\\]/g,"$$").replace(/\\\(\s*/g,"$").replace(/\s*\\\)/g,"$")).join("")}function IEr(t){return t=t.replace(/```dataview(\s*(?:\n|$))/g,"```text$1"),t=t.replace(/```dataviewjs(\s*(?:\n|$))/g,"```javascript$1"),t}function TEr(t){return t.replace(/```tasks(\s*(?:\n|$))/g,"```text$1")}function UV(t){let e=IEr(t),n=TEr(e);return kEr(n)}var $Se=b(()=>{});var DSe,PEr,iun,Jet,sun,FSe,Xet,aun=b(()=>{DSe="copilot-collapsible",PEr=()=>(window.__copilotCollapsibleStates||(window.__copilotCollapsibleStates=new Map),window.__copilotCollapsibleStates),iun=t=>{let e=PEr(),n=e.get(t);return n||(n=new Map,e.set(t,n)),n},Jet=(t,e)=>{let n=t.replace(/[^a-zA-Z0-9_-]/g,"_");return`${DSe}-${n}-${e}`},sun=(t,e,n={})=>{let r=n.overwriteExisting??!0;t.querySelectorAll(`details[id^="${DSe}-"]`).forEach(i=>{let s=i.id;s&&(!r&&e.has(s)||e.set(s,i.open))})},FSe=(t,e)=>{let n=typeof t.composedPath=="function"?t.composedPath():[];for(let i of n)if(i instanceof HTMLElement&&i.tagName==="DETAILS"){let s=i;if(s.id.startsWith(`${DSe}-`)&&e.contains(s))return s}let r=t.target;if(!(r instanceof Element))return null;let o=r.closest(`details[id^="${DSe}-"]`);return o?.instanceOf(HTMLElement)&&o.tagName==="DETAILS"&&e.contains(o)?o:null},Xet=(t,e)=>{let n=e.querySelector("summary");if(!n)return!1;let r=t.target;return r instanceof Node?n.contains(r):(typeof t.composedPath=="function"?t.composedPath():[]).includes(n)}});function OEr({context:t}){return!t||!t.notes?.length&&!t.urls?.length&&!t.webTabs?.length&&!t.tags?.length&&!t.folders?.length&&!t.selectedTextContexts?.length?null:zt.default.createElement("div",{className:"tw-flex tw-flex-wrap tw-gap-2"},t.notes.map((e,n)=>zt.default.createElement(hr,{key:`note-${n}-${e.path}`},zt.default.createElement(gr,{asChild:!0},zt.default.createElement("div",null,zt.default.createElement(p_e,{note:e}))),zt.default.createElement(fr,{className:"tw-max-w-sm tw-break-words"},e.path))),t.urls.map((e,n)=>zt.default.createElement(hr,{key:`url-${n}-${e}`},zt.default.createElement(gr,{asChild:!0},zt.default.createElement("div",null,zt.default.createElement(m_e,{url:e}))),zt.default.createElement(fr,{className:"tw-max-w-sm tw-break-words"},e))),t.webTabs?.map((e,n)=>zt.default.createElement(hr,{key:`webTab-${n}-${e.url}`},zt.default.createElement(gr,{asChild:!0},zt.default.createElement("div",null,zt.default.createElement(h_e,{webTab:e}))),zt.default.createElement(fr,{className:"tw-max-w-sm tw-break-words"},e.title?zt.default.createElement("div",{className:"tw-text-left"},zt.default.createElement("div",{className:"tw-font-medium"},e.title),zt.default.createElement("div",null,e.url)):e.url))),t.tags?.map((e,n)=>zt.default.createElement(hr,{key:`tag-${n}-${e}`},zt.default.createElement(gr,{asChild:!0},zt.default.createElement("div",null,zt.default.createElement(ann,{tag:e}))),zt.default.createElement(fr,{className:"tw-max-w-sm tw-break-words"},e))),t.folders?.map((e,n)=>zt.default.createElement(hr,{key:`folder-${n}-${e}`},zt.default.createElement(gr,{asChild:!0},zt.default.createElement("div",null,zt.default.createElement(g_e,{folder:e}))),zt.default.createElement(fr,{className:"tw-max-w-sm tw-break-words"},e))),t.selectedTextContexts?.map((e,n)=>zt.default.createElement(hr,{key:`selectedText-${n}-${e.id}`},zt.default.createElement(gr,{asChild:!0},zt.default.createElement("div",null,zt.default.createElement(y_e,{selectedText:e}))),zt.default.createElement(fr,{className:"tw-max-w-sm tw-break-words"},e.sourceType==="web"?e.url:e.notePath))))}var lun,zt,AEr,EEr,vte,MEr,NEr,wte,Qet=b(()=>{IJe();aee();nnn();Oc();MJe();Ccn();Vcn();xJe();gt();De();Get();NSe();FV();pe();ut();$Se();lee();lun=require("obsidian"),zt=L(B());Se();aun();AEr=/^\d+-\d+$/,EEr=t=>{let e=t.querySelector(".footnotes");e?(e.querySelectorAll("hr, hr.footnotes-sep").forEach(n=>n.remove()),e.querySelectorAll("a.footnote-backref, a.footnote-link.footnote-backref").forEach(n=>n.remove())):t.querySelectorAll("a.footnote-backref, a.footnote-link.footnote-backref").forEach(n=>n.remove()),t.querySelectorAll('a.footnote-ref, sup a[href^="#fn"], sup a[href^="#fn-"], a[href^="#fn"], a[href^="#fn-"]').forEach(n=>{let r=n.textContent?.trim()??"";if(!r||!AEr.test(r))return;let[o]=r.split("-");o&&o!==r&&(n.textContent=o)})},vte=/\[(\d+(?:\s*,\s*\d+)*)\]/g,MEr=t=>{let e=t.querySelectorAll(".copilot-sources__item");if(e.length===0)return;let n=new Map;if(e.forEach(l=>{let c=l.querySelector(".copilot-sources__index"),u=l.querySelector(".copilot-sources__text");if(!c||!u)return;let d=c.textContent?.match(/\[(\d+)\]/);if(!d)return;let f=parseInt(d[1],10),p=u.querySelector("a");p&&n.set(f,p)}),n.size===0)return;let r=t.doc,o=t.querySelector(".copilot-sources"),i=[],s=r.createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(l){return o?.contains(l)||l.parentElement?.closest("code, pre")?NodeFilter.FILTER_REJECT:(vte.lastIndex=0,vte.test(l.textContent||"")?(vte.lastIndex=0,NodeFilter.FILTER_ACCEPT):NodeFilter.FILTER_REJECT)}}),a;for(;a=s.nextNode();)i.push(a);i.forEach(l=>{let c=l.textContent||"";vte.lastIndex=0;let u=r.win.createFragment(),d=0,f;for(;(f=vte.exec(c))!==null;){f.index>d&&u.appendChild(r.createTextNode(c.slice(d,f.index)));let m=f[1].split(/\s*,\s*/).map(g=>parseInt(g.trim(),10));if(m.every(g=>n.has(g))){let g=r.win.createSpan("copilot-citation-group");g.appendChild(r.createTextNode("[")),m.forEach((v,y)=>{y>0&&g.appendChild(r.createTextNode(", "));let w=n.get(v),_=r.win.createEl("a");for(let S of Array.from(w.attributes))_.setAttribute(S.name,S.value);_.className=`copilot-citation-link${w.className?` ${w.className}`:""}`,_.textContent=String(v),_.setAttribute("aria-label",`Source ${v}`),g.appendChild(_)}),g.appendChild(r.createTextNode("]")),u.appendChild(g)}else u.appendChild(r.createTextNode(f[0]));d=f.index+f[0].length}d<c.length&&u.appendChild(r.createTextNode(c.slice(d)));let p=l.parentElement?.classList.contains("copilot-citation-ref")?l.parentElement:l;p.parentNode?.replaceChild(u,p)})};NEr=({message:t,app:e,isStreaming:n,onRegenerate:r,onEdit:o,onDelete:i,footerStart:s})=>{let[a,l]=(0,zt.useState)(!1),c=(0,zt.useMemo)(()=>yte(t.message),[t.message]),u=(0,zt.useMemo)(()=>!c?.hasReasoning||c.status==="idle"?null:{status:c.status,elapsedSeconds:c.elapsedSeconds,steps:c.steps},[c]),d=(0,zt.useRef)(null),f=(0,zt.useRef)(null),p=(0,zt.useRef)(!1),m=(0,zt.useRef)(t.id||(t.timestamp?.epoch?String(t.timestamp.epoch):`temp-${Date.now()}-${Math.random()}`)),h=(0,zt.useRef)(Ucn(m.current)),g=(0,zt.useRef)(jcn(m.current)),y=(0,zt.useRef)(iun(m.current)).current,w=xt(),_=(0,zt.useCallback)(E=>{let O=e.workspace.getActiveFile(),$=O?O.path:"",U=(z,N,R,X)=>{let D="margin: 0.5rem 0 1.5rem; padding: 0.75rem; border: 1px solid var(--background-modifier-border); border-radius: 4px; background-color: var(--background-secondary)",G="cursor: pointer; color: var(--text-muted); font-size: 0.8em; margin-bottom: 0.5rem; user-select: none",ce="margin-top: 0.75rem; padding: 0.75rem; border-radius: 4px; background-color: var(--background-primary)",Z=`<${N}>`,te=0,fe=Te=>Te.trim()+`
`,de=(Te,Be,qe)=>`<details id="${qe}"${Be} style="${D}"><summary style="${G}">${R}</summary><div class="tw-text-muted" style="${ce}">${fe(Te)}</div></details>
`;if(n&&z.includes(Z)){let Te=new RegExp(`<${N}>([\\s\\S]*?)<\\/${N}>`,"g");z=z.replace(Te,(qe,Ae)=>{let Xt=`${N}-${te}`;te+=1;let Ve=Jet(m.current,Xt),Ee=y.get(Ve)?" open":"";return de(Ae,Ee,Ve)});let Be=new RegExp(`<${N}>([\\s\\S]*)$`);return z=z.replace(Be,(qe,Ae)=>`<div style="${D}"><div style="${G}">${X}</div><div class="tw-text-muted" style="${ce}">${fe(Ae)}</div></div>`),z}let ye=new RegExp(`<${N}>([\\s\\S]*?)<\\/${N}>`,"g");return z.replace(ye,(Te,Be)=>{let qe=`${N}-${te}`;te+=1;let Ae=Jet(m.current,qe),Xt=y.get(Ae)?" open":"";return de(Be,Xt,Ae)})},V=z=>U(z,"think","Thought for a while","Thinking..."),K=z=>{let N=G=>G.replace(/<(\/?)writeToFile>/g,"<$1writeFile>"),R=G=>{let ce=/```(?:xml)?\s*([\s\S]*?<writeFile>[\s\S]*?<\/writeFile>[\s\S]*?)\s*```/g;return G.replace(ce,(Z,te)=>te.trim())},X=G=>{if(!n)return G;let ce=/```xml\s*([\s\S]*?<writeFile>[\s\S]*?)$/g;return G.replace(ce,(Z,te)=>te.trim())},D=N(z);return D=R(D),D=X(D),U(D,"writeFile","Generated new content","Generating changes...")},se=(z,N,R)=>z.split(/(```[\s\S]*?```|`[^`]*`)/g).map((D,G)=>G%2===0?D.replace(N,(ce,Z)=>{let te=e.metadataCache.getFirstLinkpathDest(Z,$);return te?R(te):ce}):D).join(""),le=UV(E),Q=se(le,/!\[\[(.*?)]]/g,z=>`![](${e.vault.getResourcePath(z)})`),ne=V(Q),ee=K(ne),q=oun(ee,w.enableInlineCitations).replace(/\[\^(\d+)\](?!:)/g,'<span class="copilot-citation-ref">[$1]</span>');return(z=>{if(!n)return z;let N=/!\[([^\]]*)\]\(([^)]+)\)/g;return z.replace(N,(R,X,D)=>{let G=REe(D);if(!G)return R;let ce=X||"YouTube Video",Z=`https://i.ytimg.com/vi/${G}/hqdefault.jpg`;return`[![${ce}](${Z})](${D})`})})(q)},[e,n,w.enableInlineCitations,y]);(0,zt.useEffect)(()=>{let E=d.current;if(!E||t.sender===ar||!n)return;let O=V=>{if(V instanceof PointerEvent&&(V.button!==0||!V.isPrimary))return;let K=FSe(V,E);if(!K||!Xet(V,K))return;let se=!K.open;K.open=se,y.set(K.id,se)},$=V=>{let K=FSe(V,E);!K||!Xet(V,K)||V.preventDefault()},U=V=>{let K=FSe(V,E);K&&y.set(K.id,K.open)};return E.addEventListener("pointerdown",O,!0),E.addEventListener("click",$,!0),E.addEventListener("toggle",U,!0),()=>{E.removeEventListener("pointerdown",O,!0),E.removeEventListener("click",$,!0),E.removeEventListener("toggle",U,!0)}},[n,t.sender,y]),(0,zt.useEffect)(()=>{if(p.current=!1,d.current&&t.sender!==ar){f.current||(f.current=new lun.Component,f.current.load()),sun(d.current,y,{overwriteExisting:!n});let E=t.message,O=c?.contentAfter??E,$=_(O),U=Ket($,m.current);if(!p.current){let V=d.current.doc,K=e.workspace.getActiveFile()?.path??"",se=new Set,le=new Set;d.current.querySelectorAll('[id^="tool-call-"]').forEach(z=>{let N=z.id.replace("tool-call-","");se.add(N)}),d.current.querySelectorAll('[id^="error-block-"]').forEach(z=>{let N=z.id.replace("error-block-","");le.add(N)}),d.current.querySelectorAll(".message-segment").forEach(z=>z.remove());let ae=0;U.segments.forEach(z=>{if(z.type==="text"&&z.content.trim()){let N=d.current.children[ae],R=V.win.createDiv("message-segment markdown-rendered");N?d.current.insertBefore(R,N):d.current.appendChild(R),YE(e,z.content,R,K,f.current).then(()=>EEr(R)).catch(X=>H("renderMarkdown failed",X)),ae++}else if(z.type==="toolCall"&&z.toolCall){let N=z.toolCall.id,R=V.getElementById(`tool-call-${N}`);if(!R){let D=d.current.children[ae],G=V.win.createDiv({cls:"tool-call-container",attr:{id:`tool-call-${N}`}});D?d.current.insertBefore(G,D):d.current.appendChild(G),R=G}let X=Ncn(e,m.current,h.current,N,R,"render refresh");!p.current&&!X.isUnmounting&&Lcn(X,z.toolCall),ae++}else if(z.type==="error"&&z.error){let N=z.error.id,R=V.getElementById(`error-block-${N}`);if(!R){let D=d.current.children[ae],G=V.win.createDiv({cls:"error-block-container",attr:{id:`error-block-${N}`}});D?d.current.insertBefore(G,D):d.current.appendChild(G),R=G}let X=Rcn(e,m.current,g.current,N,R,"error render");!p.current&&!X.isUnmounting&&$cn(X,z.error),ae++}});let q=new Set(U.segments.filter(z=>z.type==="toolCall"&&z.toolCall).map(z=>z.toolCall.id));se.forEach(z=>{if(!q.has(z)){let N=V.getElementById(`tool-call-${z}`);N&&(Dcn(m.current,h.current,z,"tool call removal"),N.remove())}});let F=new Set(U.segments.filter(z=>z.type==="error"&&z.error).map(z=>z.error.id));le.forEach(z=>{if(!F.has(z)){let N=V.getElementById(`error-block-${z}`);N&&(Fcn(m.current,g.current,z,"error block removal"),N.remove())}}),d.current&&!n&&MEr(d.current)}}return()=>{p.current=!0}},[t,e,f,n,_,y,c]),(0,zt.useEffect)(()=>{let E=f,O=m.current,$=h.current,U=g.current;return(()=>{Bcn(),zcn()})(),()=>{p.current=!0,window.setTimeout(()=>{E.current&&(E.current.unload(),E.current=null),O.startsWith("temp-")&&(Hcn(O,$,"component cleanup"),Wcn(O,U,"component cleanup"))},0)}},[]);let S=()=>{l(!0)},I=()=>{l(!1)},C=E=>{l(!1),o&&o(E)},k=()=>{t.sources&&t.sources.length>0&&new d_e(e,t.sources).open()},T=()=>{I2(e,t.message)},P=()=>t.content?zt.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-3"},t.content.map((E,O)=>E.type==="text"?zt.default.createElement("div",{key:O},t.sender===ar?zt.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-break-words tw-text-[calc(var(--font-text-size)_-_2px)] tw-font-normal"},t.message):zt.default.createElement("div",{ref:d,className:t.isErrorMessage?"tw-text-error":""})):E.type==="image_url"?zt.default.createElement("div",{key:O,className:"message-image-content"},zt.default.createElement("img",{src:E.image_url.url,alt:"User uploaded image",className:"chat-message-image"})):null)):t.sender===ar?zt.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-break-words tw-text-[calc(var(--font-text-size)_-_2px)] tw-font-normal"},t.message):zt.default.createElement("div",{ref:d,className:t.isErrorMessage?"tw-text-error":""});return a&&t.sender===ar?zt.default.createElement("div",{className:"tw-my-1 tw-flex tw-w-full tw-flex-col"},zt.default.createElement(Scn,{initialValue:t.message,initialContext:t.context,onSave:C,onCancel:I,app:e})):zt.default.createElement("div",{className:"tw-my-1 tw-flex tw-w-full tw-flex-col"},zt.default.createElement("div",{className:J("tw-group tw-mx-2 tw-rounded-md tw-p-2",t.sender===ar&&"tw-border tw-border-solid tw-border-border"),style:t.sender===ar?{backgroundColor:"var(--background-modifier-hover)"}:void 0},zt.default.createElement("div",{className:"tw-flex tw-max-w-full tw-flex-col tw-gap-2 tw-overflow-hidden"},!a&&zt.default.createElement(OEr,{context:t.context}),u&&t.sender!==ar&&zt.default.createElement(s_e,{status:u.status,elapsedSeconds:u.elapsedSeconds,steps:u.steps,isStreaming:n}),zt.default.createElement("div",{className:"message-content tw-break-words !tw-leading-[1.6]"},P()),!n&&zt.default.createElement(KI,{leading:s,timestamp:t.timestamp?.display,actions:zt.default.createElement(l_e,{message:t,onInsertIntoEditor:T,onRegenerate:r,onEdit:o?S:void 0,onDelete:i,onShowSources:k,hasSources:!!(t.sources&&t.sources.length>0)})}))))},wte=NEr});var Wf,USe,ett=b(()=>{gt();Wf=L(B()),USe=({chatHistory:t})=>{let[e,n]=(0,Wf.useState)(0),r=(0,Wf.useRef)(null),o=(0,Wf.useRef)(null),i=(0,Wf.useCallback)((u,d)=>`message-${u.id||u.timestamp?.epoch||d}`,[]),s=(0,Wf.useCallback)(()=>{if(!r.current)return 0;let u=r.current,d=u.clientHeight,f=t.map((h,g)=>({msg:h,idx:g})).filter(({msg:h})=>h.isVisible&&h.sender===ar).pop()?.idx,p=0;if(f!==void 0){let h=i(t[f],f),g=u.querySelector(`[data-message-key="${h}"]`);if(g)p=g.getBoundingClientRect().height;else{let v=t[f].message.length,y=Math.ceil(v/80);p=Math.max(60,y*24)}}return Math.max(100,d-p)},[t,i]),a=(0,Wf.useCallback)(u=>{if(u!==r.current&&(o.current&&(o.current.disconnect(),o.current=null),r.current=u,u)){let d=s();n(d);let f=new ResizeObserver(()=>{if(r.current){let p=s();n(p)}});f.observe(u),o.current=f}},[s]);(0,Wf.useEffect)(()=>{if(r.current&&t.length>0){let u=s();n(u)}},[t,s]),(0,Wf.useEffect)(()=>()=>{o.current&&o.current.disconnect()},[]);let l=(0,Wf.useCallback)((u="smooth")=>{r.current&&r.current.scrollTo({top:r.current.scrollHeight,behavior:u})},[]);(0,Wf.useEffect)(()=>{l("instant")},[l]);let c=(0,Wf.useRef)(void 0);return(0,Wf.useEffect)(()=>{let u;for(let f=t.length-1;f>=0;f--){let p=t[f];if(p.isVisible&&p.sender===ar){u=p;break}}let d=u?`${u.id??u.timestamp?.epoch??""}`:void 0;if(c.current===void 0){c.current=d;return}d&&d!==c.current&&(c.current=d,l())},[t,l]),{containerMinHeight:e,scrollContainerCallbackRef:a,getMessageKey:i}}});function REr(t){return{id:t.id,sender:t.sender,message:t.message,timestamp:t.timestamp,isVisible:t.isVisible,isErrorMessage:t.isErrorMessage,content:t.content,context:t.context}}function LEr(t){for(let e=t.length-1;e>=0;e--)if(t[e].sender!==ar)return t[e]}var sa,cun,uun,dun=b(()=>{Dtn();Utn();Ztn();Qtn();tnn();r_e();Qet();gt();ett();sa=L(B());cun=(0,sa.memo)(({messages:t,app:e,currentPlan:n,pendingToolPermissions:r,pendingAskUserQuestions:o,chatBackend:i,isLoading:s})=>{let a=(0,sa.useMemo)(()=>t.filter(w=>w.isVisible),[t]),l=(0,sa.useMemo)(()=>a.map(REr),[a]),{containerMinHeight:c,scrollContainerCallbackRef:u,getMessageKey:d}=USe({chatHistory:l}),f=n!=null&&n.decision==="pending",p=f?sa.default.createElement(Xtn,{plan:n,app:e,chatBackend:i}):null,m=r.map(w=>sa.default.createElement(enn,{key:w.toolCall.toolCallId,request:w,onResolve:i.resolveToolPermission.bind(i)})),h=o.map(w=>sa.default.createElement(Ftn,{key:w.requestId,request:w,onResolve:i.resolveAskUserQuestion.bind(i)})),g=f||r.length>0||o.length>0,v=(0,sa.useMemo)(()=>LEr(a),[a]),y=s?v?.id:void 0;return a.length===0?sa.default.createElement("div",{className:"tw-flex tw-size-full tw-flex-col tw-gap-2 tw-overflow-y-auto tw-px-3 tw-pt-2"},p,m,h):sa.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-1 tw-flex-col tw-overflow-hidden"},sa.default.createElement("div",{ref:u,"data-testid":"chat-messages",className:"tw-relative tw-flex tw-w-full tw-flex-1 tw-select-text tw-flex-col tw-items-start tw-justify-start tw-overflow-y-auto tw-scroll-smooth tw-break-words tw-text-[calc(var(--font-text-size)_-_2px)]"},a.map((w,_)=>{let I=_===a.length-1&&w.sender!==ar&&!g,C=l[_],k=w.sender!==ar,T=(w.parts?.length??0)>0,P=k&&T,E=k&&w.id===v?.id,O=E?w.turnDurationMs:void 0,$=E&&w.id===y?w.timestamp?.epoch:void 0,U=O!==void 0?sa.default.createElement(ZE,{status:"complete",durationMs:O,inline:!0}):null,V=$!==void 0?sa.default.createElement(ZE,{status:"running",startedAtMs:$}):null,K=k&&w.id===y&&!T&&!w.message,se=k?w.fanout:void 0;return sa.default.createElement("div",{key:d(C,_),"data-message-key":d(C,_),className:"tw-w-full",style:{minHeight:I?`${c}px`:"auto"}},se?sa.default.createElement("div",{className:"tw-px-3 tw-pt-2"},sa.default.createElement(TJe,{message:w,turn:se,app:e,footerStart:U}),V):K?sa.default.createElement("div",{className:"tw-px-3 tw-pt-2"},V):P?sa.default.createElement("div",{className:"tw-px-3 tw-pt-2"},sa.default.createElement(Ltn,{parts:w.parts,isStreaming:w.id===y,turnStartedAtMs:$,turnDurationMs:O,timestamp:w.timestamp?.display,app:e,turnStopReason:w.turnStopReason})):sa.default.createElement(sa.default.Fragment,null,sa.default.createElement(wte,{message:C,app:e,isStreaming:!1,footerStart:U}),V?sa.default.createElement("div",{className:"tw-px-3"},V):null))}),p,m,h))});cun.displayName="AgentChatMessages";uun=cun});function jSe(t,e){if(!e)return t;let n=e.extension?.toLowerCase(),r=n==="pdf"||n==="canvas"?`${e.basename}.${n}`:e.basename;return t.replace(/\{activenote\}/gi,()=>`[[${r}]]`)}var ttt=b(()=>{});function $Er(t){let e=t.extension?.toLowerCase();return`[[${e==="pdf"||e==="canvas"?`${t.basename}.${e}`:t.basename}]]`}function fun(t,e,n){let r=e||(n?$Er(n):""),o=t.split("{copilot-selection}").join(r);return o=o.split("{}").join(r),o=jSe(o,n),o.replace(DEr,(i,s)=>{if(i===vC)return i;let a=s.trim();return a.startsWith('"')||a.toLowerCase()==="activenote"?i:a})}var DEr,pun=b(()=>{ttt();gt();DEr=/\{([^}]+)\}/g});async function mun(t,e,n,r){if(!t.startsWith("/")||t.length<2)return{text:t};let o=t.slice(1),i=o.toLowerCase(),a=[...e].sort((d,f)=>f.title.length-d.title.length).find(d=>{let f=d.title.toLowerCase();if(!i.startsWith(f))return!1;let p=o.charAt(f.length);return p===""||/\s/.test(p)});if(!a)return{text:t};let l=o.slice(a.title.length).trim(),c=l?`${a.content}
${l}`:a.content;return{text:fun(c,n,r),matched:a}}var hun=b(()=>{pun()});var gun,yun,vun=b(()=>{gun=Object.freeze(["Summarize what I worked on this week","Turn my meeting notes into a task list with links","Find notes that say contradictory things and show me","Draft a note that connects my recent reading","Rename my untitled notes based on what's in them","Pull every open question out of my notes","Find near-duplicate notes and suggest which to merge","Rewrite the current note as a step-by-step guide","Build an index note linking everything on one theme","Clean up the headings and formatting across my notes","Tell me what my notes are missing on a topic I care about","Read this note and give me three sharper questions"]),yun="Ask anything \u2022 @ to add context \u2022 / for commands"});function UEr(t){let e=ss().filter(n=>n.getInstallState(t).kind==="ready").map(n=>({id:n.id,displayName:n.displayName,Icon:n.Icon,needsSelfHostWarning:RI(n,t)}));return e.length>0?e:FEr}function wun(t){let e=xt(),n=bte.default.useCallback(i=>{let s=ss().map(a=>a.subscribeInstallState(t,i));return()=>s.forEach(a=>a())},[t]),r=bte.default.useCallback(()=>ss().filter(i=>i.getInstallState(e).kind==="ready").map(i=>i.id).join(","),[e]),o=bte.default.useSyncExternalStore(n,r,r);return bte.default.useMemo(()=>UEr(e),[e,o])}var bte,FEr,bun=b(()=>{bte=L(B());Wm();Se();EYe();FEr=Object.freeze([])});function BSe(t,e,n){let r=RXt(e);if(!n)return r;try{let s=Sl(t).getActiveWebTabState().activeWebTabForMentions,a=f6(s?.url);if(!a)return r;let l=r.map(u=>{if(u.isActive){let{isActive:d,...f}=u;return f}return u}),c=l.findIndex(u=>f6(u.url)===a);if(c>=0){let u=l[c];return l[c]={...u,url:Lf(s?.url)??u.url,title:s?.title??u.title,faviconUrl:s?.faviconUrl??u.faviconUrl,isActive:!0},l}return[...l,{url:Lf(s?.url)??a,title:s?.title,faviconUrl:s?.faviconUrl,isActive:!0}]}catch(o){return W("[ActiveWebTabSnapshot] Failed to resolve active web tab:",o),r}}var ntt=b(()=>{pe();T$();I$()});function Fv(t){return _un.Buffer.from(t).toString("base64")}var _un,jV=b(()=>{_un=L($Ae())});async function BEr(t){try{let e=await t.arrayBuffer();return e.byteLength===0?null:{type:"image",mimeType:t.type||"image/png",data:Fv(e)}}catch(e){return W("[AgentMode] failed to read attached image",e),null}}var zSe,mi,HSe,xun,jEr,Sun,zEr,Cun=b(()=>{_S();hun();ttt();vun();es();x0();c_();Bet();pM();vV();yt();gt();De();vc();ko();pe();bun();Wm();ntt();rY();Se();ut();jV();I$();Re();zSe=require("obsidian"),mi=L(B());Gf();Hl();HSe=(t,e)=>{let n=new Set,r=[];for(let o of t){let i=e(o);n.has(i)||(n.add(i),r.push(o))}return r},xun=(t,e,n=[])=>{if(!(t.length===0&&e.length===0&&n.length===0))return{notes:t,urls:[],selectedTextContexts:e.length>0?[...e]:void 0,webTabs:n.length>0?[...n]:void 0}},jEr=t=>{if(t.length===1)return t[0];let e=t.flatMap(s=>s.context?.notes??[]),n=t.flatMap(s=>s.context?.selectedTextContexts??[]),r=t.flatMap(s=>s.context?.webTabs??[]),o=t.flatMap(s=>s.promptContent??[]),i=HSe(t.flatMap(s=>s.mentionedAgents??[]),s=>s);return{id:`queued-combined-${Co()}`,text:t.map(s=>s.text).join(`
`),rawInput:t.map(s=>s.rawInput).join(`
`),context:xun(HSe(e,s=>s.path),HSe(n,s=>s.id),UI(r)),promptContent:o.length>0?o:void 0,mentionedAgents:i.length>0?i:void 0}};Sun=(0,mi.memo)(function({backend:e,plugin:n,chatInputId:r,draft:o,app:i,mainAgentId:s,updateUserMessageHistory:a,isStarting:l,hasPendingPlanPermission:c,modelPickerOverride:u,modePickerOverride:d,onCycleMode:f,activeProjectId:p,contextLoadBlocking:m=!1,disabled:h=!1,contextStatusIndicator:g,isLanding:v=!1}){let y=(0,mi.useContext)(Gd),w=m&&!!p&&p!==tr,[_]=Yie(),{activeWebTabForMentions:S}=RS(),I=(0,mi.useRef)(r),C=Ybe(),k=wun(n),T=C?k:NS,P=(0,mi.useMemo)(()=>new Set(k.map(de=>de.id)),[k]),E=(0,mi.useRef)([]),O=(0,mi.useCallback)(de=>{E.current=de},[]),{input:$,images:U,contextNotes:V,includeActiveNote:K,includeActiveWebTab:se,loading:le,queue:Q,setInput:ne,setContextNotes:ee,setSelectedImages:ae,addImages:q,setIncludeActiveNote:F,setIncludeActiveWebTab:z,setLoading:N,setQueue:R,resetCompose:X}=o,D=u?.models.find(de=>Jn(de)===u.value),G=Array.isArray(D?.capabilities)&&!Fie(D)?D.displayName||D.name:null;(0,mi.useEffect)(()=>{I.current!==r&&(I.current=r,YK(),E.current=[])},[r]);let ce=(0,mi.useCallback)(async()=>{try{await e.cancel()}catch(de){H("[AgentMode] cancel failed",de)}R([]),N(!1)},[e,N,R]),Z=(0,mi.useCallback)(async de=>{N(!0);try{let{turn:ye}=e.sendMessage(de.text,de.context,de.promptContent,de.mentionedAgents);de.rawInput&&a(de.rawInput),await ye}catch(ye){H("Error sending agent message:",ye),new zSe.Notice("Failed to send message. Please try again.")}finally{N(!1)}},[e,N,a]),te=(0,mi.useCallback)(async de=>{if(h)return;let ye=$.trim();if(!ye)return;let Te=$,Be=i.workspace.getActiveFile(),qe=[];K&&Be&&qe.push(Be),qe.push(...V);let Ae=HSe(qe,Xr=>Xr.path),Xt=_.find(iz),Ve=await mun(ye,Bf(),Xt?.content??"",Be);Ve.matched&&Fa.getInstance().recordUsage(Ve.matched);let Ee=jSe(Ve.text,Be),Ne=!(_.length>0)&&(se||Ee.includes(vC)),He=BSe(i,de??[],Ne);if(U.length>0&&G){new zSe.Notice(`${G} doesn't support images. Switch to a vision-capable model to send images.`);return}let et;if(s){let Xr=AYe({mentionedAgentIds:E.current,installedAgentIds:P});VQ(Xr,s)&&(et=Xr)}E.current=[],X(),YK();let it=[];for(let Xr of U){let An=await BEr(Xr);An&&it.push(An)}let Br={id:`queued-${Co()}`,text:Ee,rawInput:Te,context:xun(Ae,_,He),promptContent:it.length>0?it:void 0,mentionedAgents:et};if(le||l||w){R(Xr=>[...Xr,{...Br,queueReason:w?"context":"busy"}]);return}await Z(Br)},[i,$,U,V,K,se,_,le,l,G,w,h,X,Z,R,s,P]);(0,mi.useEffect)(()=>{if(h||le||l||w||Q.length===0)return;let de=jEr(Q);if(de.promptContent?.some(ye=>ye.type==="image")&&G){new zSe.Notice(`${G} doesn't support images. Switch to a vision-capable model to send images.`);return}R([]),Z(de)},[h,le,l,w,Q,Z,R,G]);let fe=(0,mi.useCallback)(de=>{R(ye=>ye.filter(Te=>Te.id!==de))},[R]);return(0,mi.useEffect)(()=>{let de=()=>{ce()};return y?.addEventListener(cs.ABORT_STREAM,de),()=>{y?.removeEventListener(cs.ABORT_STREAM,de)}},[y,ce]),mi.default.createElement(mi.default.Fragment,null,Q.length>0&&mi.default.createElement(zEr,{messages:Q,onRemove:fe}),mi.default.createElement("div",{className:c||h?"tw-pointer-events-none tw-opacity-50":void 0,"aria-disabled":c||h||void 0},mi.default.createElement(ASe,{key:r,isAgentMode:!0,placeholder:yun,placeholderPrompts:v?gun:void 0,inputMessage:$,setInputMessage:ne,handleSendMessage:xn(de=>te(de?.webTabs)),isGenerating:le,onStopGenerating:xn(ce),onEscape:le?xn(ce):void 0,onShiftTab:d?f:void 0,app:i,contextNotes:V,setContextNotes:ee,includeActiveNote:K,setIncludeActiveNote:F,includeActiveWebTab:se,setIncludeActiveWebTab:z,activeWebTab:S,selectedImages:U,onAddImage:q,setSelectedImages:ae,disableModelSwitch:!u,modelPickerOverride:u??void 0,modePickerOverride:d??void 0,selectedTextContexts:_,onRemoveSelectedText:Zie,agentBrands:T,cloudAgentIds:Hwe(),onMentionedAgentsChange:O,topRightAccessory:g})))}),zEr=({messages:t,onRemove:e})=>mi.default.createElement("div",{className:"tw-flex tw-max-h-24 tw-flex-col tw-gap-1 tw-overflow-y-auto tw-px-2 tw-pb-1"},t.map(n=>mi.default.createElement("div",{key:n.id,className:"tw-flex tw-min-w-0 tw-items-center tw-gap-2 tw-rounded-md tw-bg-secondary-alt tw-px-2 tw-py-1 tw-text-ui-smaller",title:n.text},mi.default.createElement(NC,{className:J("tw-size-3 tw-shrink-0",n.queueReason==="context"?"tw-text-warning":"tw-text-muted")}),mi.default.createElement("span",{className:"tw-min-w-0 tw-flex-1 tw-truncate tw-whitespace-nowrap tw-text-normal"},n.queueReason==="context"&&mi.default.createElement("span",{className:"tw-font-semibold tw-text-warning"},"Waiting for context \xB7 "),n.text),mi.default.createElement(oe,{variant:"ghost2",size:"fit",className:"tw-shrink-0 tw-text-muted hover:tw-text-error",onClick:()=>e(n.id),"aria-label":"Remove queued message"},mi.default.createElement(pn,{className:"tw-size-3"})))))});function kun(t){let[e,n]=(0,cD.useState)(()=>t.getPlanUsage()),r=(0,cD.useRef)(!1);return(0,cD.useEffect)(()=>(r.current=!0,()=>{r.current=!1}),[]),(0,cD.useEffect)(()=>{let o=()=>n(t.getPlanUsage());return o(),t.subscribe(()=>{r.current&&o()})},[t]),e}var cD,Iun=b(()=>{cD=L(B())});function Tun(t){let[e,n]=(0,uD.useState)(()=>t.getSessionUsage()),r=(0,uD.useRef)(!1);return(0,uD.useEffect)(()=>(r.current=!0,()=>{r.current=!1}),[]),(0,uD.useEffect)(()=>{let o=()=>n(t.getSessionUsage());return o(),t.subscribe(()=>{r.current&&o()})},[t]),e}var uD,Pun=b(()=>{uD=L(B())});var dD,WSe,rtt=b(()=>{Re();Oc();dD=L(B()),WSe=({tokenCount:t})=>t==null?null:dD.default.createElement(hr,null,dD.default.createElement(gr,{asChild:!0},dD.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1 tw-text-sm tw-text-faint"},dD.default.createElement(cG,{className:"tw-size-3"}),dD.default.createElement("span",null,(n=>n<1e3?"<1k":`${Math.floor(n/1e3)}k`)(t)))),dD.default.createElement(fr,null,"Context used: ",t.toLocaleString()))});function VSe(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:t.toLocaleString()}function HEr({fraction:t}){let e=Aun*(1-t);return ws.createElement("svg",{className:"tw-size-4 -tw-rotate-90",viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true"},ws.createElement("circle",{cx:8,cy:8,r:ott,fill:"none",stroke:"currentColor",strokeWidth:2,className:"tw-opacity-20"}),ws.createElement("circle",{cx:8,cy:8,r:ott,fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeDasharray:Aun,strokeDashoffset:e}))}function WEr(t,e){if(t===void 0)return null;let n=t-e;if(n<=0)return null;let r=Math.round(n/6e4);if(r<60)return`resets in ${r}m`;let o=Math.floor(r/60);if(o<24){let a=r%60;return a===0?`resets in ${o}h`:`resets in ${o}h ${a}m`}let i=Math.floor(o/24),s=o%24;return s===0?`resets in ${i}d`:`resets in ${i}d ${s}h`}function VEr({planUsage:t}){let e=Date.now(),n=QP(t,e);return n?ws.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},n.windows.map(r=>{let o=WEr(r.resetsAt,e),i=Math.round(r.percent),s=r.percent>=Eun*100;return ws.createElement("div",{key:r.id,className:"tw-flex tw-flex-col tw-gap-1"},ws.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-gap-3 tw-text-ui-smaller"},ws.createElement("span",{className:"tw-whitespace-nowrap tw-text-muted"},r.label,o&&ws.createElement("span",{className:"tw-text-faint"}," \xB7 ",o)),ws.createElement("span",{className:J("tw-whitespace-nowrap tw-tabular-nums",s&&"tw-text-warning")},i,"%")),ws.createElement(Op,{value:Math.min(100,i),className:"tw-h-1.5"}))})):null}function qEr({usage:t,contextWindow:e,planUsage:n}){let r=t&&Number.isFinite(t.usedTokens)?t.usedTokens:0,o=e?Math.min(1,Math.max(0,r/e)):0,i=Math.round(o*100),s=e!==null&&o>=Eun;return ws.createElement(hr,null,ws.createElement(gr,{asChild:!0},ws.createElement(oe,{variant:"ghost2",size:"icon",className:J(s?"tw-text-warning":"tw-text-accent"),"aria-label":"Usage"},e!==null?ws.createElement(HEr,{fraction:o}):VSe(r))),ws.createElement(fr,{align:"end",side:"top",className:"tw-w-80"},ws.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},t&&ws.createElement(ws.Fragment,null,ws.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-gap-3 tw-text-ui-smaller"},ws.createElement("span",{className:"tw-whitespace-nowrap tw-text-muted"},"Context window"),ws.createElement("span",{className:J("tw-whitespace-nowrap tw-tabular-nums",s&&"tw-text-warning")},e!==null?`${VSe(r)} / ${VSe(e)} (${i}%)`:VSe(r))),e!==null&&ws.createElement(Op,{value:i,className:"tw-h-1.5"})),n&&ws.createElement(VEr,{planUsage:n}))))}function itt({backend:t}){let e=Tun(t),n=kun(t),r=e?.contextWindow,o=typeof r=="number"&&Number.isFinite(r)&&r>0?r:null,i=e!==null&&e.usedTokens>0;return o!==null||n!==null?ws.createElement(qEr,{usage:i||o!==null?e:null,contextWindow:o,planUsage:n}):i?ws.createElement(WSe,{tokenCount:e.usedTokens}):null}var ws,Eun,ott,Aun,Mun=b(()=>{HR();Iun();Pun();rtt();yt();d$();Oc();De();ws=L(B()),Eun=.85,ott=6,Aun=2*Math.PI*ott});var zS,Oun,Nun=b(()=>{yt();Oc();De();zS=L(B()),Oun=(0,zS.memo)(function({id:e,icon:n,title:r,count:o,active:i,onClick:s,controlsId:a,disabled:l=!1,disabledTooltip:c}){let u=zS.default.createElement(oe,{id:e,type:"button",role:"tab",variant:"ghost2","aria-selected":i,"aria-controls":a,"aria-disabled":l||void 0,onClick:l?void 0:s,className:J("tw-h-auto tw-flex-1 tw-gap-2 tw-rounded-md tw-px-3 tw-py-1.5","tw-text-ui-small tw-font-medium tw-duration-200",l?"tw-cursor-not-allowed tw-bg-transparent tw-text-muted tw-opacity-50":i?"tw-bg-primary tw-text-normal hover:tw-bg-primary":"tw-bg-transparent tw-text-muted hover:tw-bg-modifier-hover hover:tw-text-normal")},zS.default.createElement("span",{className:"tw-flex tw-shrink-0 tw-items-center tw-text-muted"},n),zS.default.createElement("span",null,r),!l&&typeof o=="number"&&o>0&&zS.default.createElement("span",{className:J("tw-text-ui-smaller",i?"tw-text-muted":"tw-text-faint")},o));return l&&c?zS.default.createElement(hr,null,zS.default.createElement(gr,{asChild:!0},u),zS.default.createElement(fr,{side:"top"},c)):u})});function att({sections:t,className:e,activeSectionId:n,onSectionSelect:r}){let o=t.find(m=>!m.disabled)??null,[i,s]=(0,Uv.useState)(o?.id??null),a=n!==void 0,l=a?n:i,c=m=>{a||s(m),r?.(m)},u=t.find(m=>m.id===l),d=u&&!u.disabled?u:o,f=(0,Uv.useId)(),p=m=>`${f}-tab-${m}`;return d?Uv.default.createElement("div",{className:J("tw-flex tw-min-h-0 tw-flex-col tw-overflow-hidden tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary",e)},Uv.default.createElement("div",{role:"tablist",className:"tw-flex tw-shrink-0 tw-gap-1 tw-bg-secondary tw-p-1.5"},t.map(m=>Uv.default.createElement(Oun,{key:m.id,id:p(m.id),icon:m.icon,title:m.title,count:m.count,active:m.id===d.id,controlsId:f,disabled:m.disabled,disabledTooltip:m.disabledTooltip,onClick:()=>c(m.id)}))),Uv.default.createElement("div",{id:f,role:"tabpanel","aria-labelledby":p(d.id),className:"tw-min-h-0 tw-overflow-y-auto"},Uv.default.createElement("div",{className:J(stt,"tw-flex tw-flex-col tw-pb-1")},d.renderBody()))):Uv.default.createElement(Uv.default.Fragment,null)}var Uv,stt,ltt=b(()=>{Nun();De();Uv=L(B()),stt="tw-min-h-48"});var Run,qSe,Lun=b(()=>{Run=require("obsidian");ha();qSe=class extends Run.FuzzySuggestModal{constructor(n,r){super(n);this.onChooseFolder=r}getItems(){let n=new Set,r=e$(this.app);return this.app.vault.getAllLoadedFiles().forEach(o=>{o.parent?.path&&o.parent.path!=="/"&&!r.some(s=>o.parent.path===s||o.parent.path.startsWith(s+"/"))&&n.add(o.parent.path)}),Array.from(n)}getItemText(n){return n}onChooseItem(n,r){this.onChooseFolder(n)}}});function _te(t,e){return`${t}:${e}`}function KSe(t){return _te(t.cacheKind,t.id)}function $un(t){let e=new Map;for(let n of t)e.set(KSe(n),n);return e}function ctt(t,e){if(t==="ready"&&e)return"No content";switch(t){case"ready":return"Converted";case"processing":return"Converting...";case"failed":return"Failed";case"pending":return"Queued";case"unsupported":return"Unsupported"}}function KEr({item:t,className:e}){if(t.status==="ready"&&t.contentEmpty)return f_.default.createElement(xh,{className:J("tw-size-3.5 tw-text-warning",e)});switch(t.status){case"ready":return f_.default.createElement(Xf,{className:J("tw-size-3.5 tw-text-success",e)});case"processing":return f_.default.createElement(Dr,{className:J("tw-size-3.5 tw-animate-spin tw-text-loading",e)});case"failed":return f_.default.createElement(mc,{className:J("tw-size-3.5 tw-text-error",e)});case"pending":return f_.default.createElement(NC,{className:J("tw-size-3.5 tw-text-muted",e)});case"unsupported":return f_.default.createElement(xh,{className:J("tw-size-3.5 tw-text-muted",e)})}}function BV({item:t,className:e,revealReadyOnHover:n=!1,tooltip:r=!0}){let o=n&&t.status==="ready"&&!t.contentEmpty,i=f_.default.createElement("span",{className:J("tw-flex tw-size-5 tw-shrink-0 tw-items-center tw-justify-center",o&&"tw-opacity-0 group-hover:tw-opacity-100",e)},f_.default.createElement(KEr,{item:t}));if(!r)return i;let s=t.status==="failed"&&t.error?`Failed: ${t.error}`:ctt(t.status,t.contentEmpty);return f_.default.createElement(rs,{side:"top",contentClassName:"tw-z-[60]",content:f_.default.createElement("div",{className:"tw-max-w-80"},s)},i)}var f_,GSe=b(()=>{Lh();De();Re();f_=L(B())});function Fun(t,e){return`${t}:${e}`}function utt(t){let e=t.startsWith("http")?t:`https://${t}`;return zE(e)!==null?"youtube":"web"}function ZSe(t){let e=t.trim();return e.startsWith("http")?e:`https://${e}`}function dtt(t){let e=ZSe(t),n=utt(t);return{id:Fun(n,e),url:e,type:n}}function Dun(t,e){for(;e>0&&ZEr.test(t[e-1]);)e--;return e}function YEr(t){let e=Dun(t,t.length),n={"(":0,"[":0,"{":0},r={")":0,"]":0,"}":0};for(let o=0;o<e;o++){let i=t[o];i==="("||i==="["||i==="{"?n[i]++:(i===")"||i==="]"||i==="}")&&r[i]++}for(;e>0;){let o=t[e-1],i=GEr[o];if(!i||r[o]<=n[i])break;r[o]--,e=Dun(t,e-1)}return t.slice(0,e)}function YSe(t){let e=/https?:\/\/[^\s"'<>,。、!?;:)(【】「」『』《》]+/g,n=new Set,r=[];for(let o of t.match(e)??[]){let i=YEr(o);!i||n.has(i)||(n.add(i),r.push(i))}return r}function xte(t){let e=YSe(t);if(e.length>0)return e;let n=t.trim();return n&&!/\s/.test(n)&&JEr(n)?[n]:[]}function Uun(t,e=[]){let n=new Set(e.map(ZSe)),r=[];for(let o of xte(t)){let i=dtt(o);n.has(i.url)||(n.add(i.url),r.push(i))}return r}function p_(t,e){let n=new Set,r=[],o=(i,s)=>{if(!i)return;let a=i.split(`
`);for(let l of a){let c=l.trim();if(!c)continue;let u=Fun(s,c);n.has(u)||(n.add(u),r.push({id:u,url:c,type:s}))}};return o(t,"web"),o(e,"youtube"),r}function Ste(t){let e=new Set,n=new Set,r=[],o=[];for(let i of t){let s=i.url.trim();if(s)if(i.type==="youtube"){if(n.has(s))continue;n.add(s),o.push(s)}else{if(e.has(s))continue;e.add(s),r.push(s)}}return{webUrls:r.join(`
`),youtubeUrls:o.join(`
`)}}function JEr(t){let e=t.trim();if(!e)return!1;try{let n=new URL(e.startsWith("http://")||e.startsWith("https://")?e:`https://${e}`);if(n.protocol!=="http:"&&n.protocol!=="https:"||n.username)return!1;let r=n.hostname.toLowerCase();return r?!!(r==="localhost"||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(r)||r.startsWith("[")&&r.endsWith("]")||r.includes(".")):!1}catch{return!1}}var GEr,ZEr,jun=b(()=>{cbe();GEr={")":"(","]":"[","}":"{"},ZEr=/[.,;:!?,。!?;:、]/u});var HS=b(()=>{jun()});function eMr(t){let e=t.split(".").pop()?.toLowerCase()??"";return e==="pdf"?"pdf":XEr.has(e)?"image":QEr.has(e)?"audio":"other"}function tMr(t){return utt(t)}function zun(t,e){let n=t==="file"?eMr(e):t==="youtube"?"youtube":tMr(e);return{id:e,name:nMr(e),source:t==="file"?"file":"url",fileType:n,cacheKind:t}}function nMr(t){if(t.startsWith("http://")||t.startsWith("https://"))try{let n=new URL(t),r=n.hostname.replace("www.",""),o=n.pathname+n.search;if(o&&o!=="/"){let s=o.length>30?o.slice(0,30)+"...":o;return r+s}return r}catch{return t.slice(0,50)}let e=t.split("/");return e[e.length-1]||t}var XEr,QEr,Hun=b(()=>{HS();XEr=new Set(["jpg","jpeg","png","gif","bmp","webp","svg","tiff"]),QEr=new Set(["mp3","wav","m4a","ogg","flac","aac","mp4","mpeg","mpga","webm"])});function JSe(t,e){return[...t.map(n=>({kind:n.type,source:n.url})),...e.map(n=>({kind:"file",source:n.path,fingerprint:`${n.stat.mtime}:${n.stat.size}`}))]}async function rMr(t,e){let n=new Set,r=new Map,o=new Map,[i,s,a]=await Promise.all([ftt(t.remotes),ftt(t.files),ftt(t.markers)]);for(let l of i)l.endsWith(".md")&&n.add(l);for(let l of s)if(l.endsWith(".md")&&(n.add(l),e.has(l))){let c=await iMr(t.files,l);c&&o.set(l,c.fingerprint)}for(let l of a){if(!l.startsWith("failed-")||!l.endsWith(".json"))continue;let c=await oMr(t.markers,l);c&&r.set(l,c)}return{snapshotNames:n,markersByName:r,fingerprintsByName:o}}async function XSe(t,e,n){if(Ln())try{let{remotesDir:r,filesDir:o,markersDir:i}=await Promise.resolve().then(()=>(_$(),Bwe)),{createNodeContextCacheFs:s}=await Promise.resolve().then(()=>(n6(),Qwe)),a=l=>{let c=s(l);return{list:()=>c.list(""),readText:u=>c.readText(u)}};return await rMr({remotes:a(r(t)),files:a(o(t)),markers:a(i(t,e))},n)}catch{return}}async function ftt(t){try{return await t.list()}catch{return[]}}async function oMr(t,e){try{return sYe(await t.readText(e))}catch{return null}}async function iMr(t,e){try{return aYe(await t.readText(e))}catch{return null}}function sMr(t,e){return e==="file"?t.type==="nonMd":t.type===e}function QSe(t,e,n,r){let o=e!==void 0&&aMr.has(e.phase),i=e?.failedSources??[],s=e?.retryingSources??ift,a=e?.processingSources??sft;return t.map(({kind:l,source:c,fingerprint:u})=>{let d=`${l}:${c}`,f="pending",p,m=i.find(C=>C.path===c&&sMr(C,l)),h=Kb(l,c),g=n?.snapshotNames.has(h)??!1,v=n?.markersByName.get(FQ(l,c)),y=s.some(C=>C.kind===l&&C.source===c),w=a.some(C=>C.kind===l&&C.source===c),_=n?.fingerprintsByName.get(h),S=g&&(l!=="file"||_!==void 0&&_===u),I=v!==void 0&&(l!=="file"||v.fingerprint===u)?v:void 0;return(y||w)&&r.has(d)?f="processing":m&&!m.usedStaleSnapshot?(f="failed",p=m.error):m?.usedStaleSnapshot||S?f="ready":I?(f="failed",p=I.error):o&&r.has(d)&&(f="pending"),{...zun(l,c),status:f,...p!==void 0?{error:p}:{}}})}var aMr,ptt=b(()=>{es();Hun();o6();$n();aMr=new Set(["resolve","prefetch","parse"])});function eCe(t,e,n,r){let o=r?.enabled??!0,i=Ar(my,{store:on}),s=o?i[e.id]:void 0,a=o?n?.inclusions:void 0,l=o?n?.exclusions:void 0,c=(0,WS.useMemo)(()=>o?TJt(t,{inclusions:a,exclusions:l}):{candidates:[],skippedMarkdownCount:0},[t,o,a,l]),u=c.candidates,d=(0,WS.useMemo)(()=>{if(!o)return[];let y=p_(n?.webUrls||"",n?.youtubeUrls||"");return JSe(y,u)},[o,n?.webUrls,n?.youtubeUrls,u]),f=e.contextSource,p=(0,WS.useMemo)(()=>{let y=new Set;if(!o)return y;let w=p_(f?.webUrls||"",f?.youtubeUrls||"");for(let _ of w)y.add(_.id);for(let _ of QW(t,f))y.add(`file:${_.path}`);return y},[t,o,f]),m=(0,WS.useMemo)(()=>new Set(u.map(y=>Kb("file",y.path))),[u]),[h,g]=(0,WS.useState)(void 0);return(0,WS.useEffect)(()=>{if(!o){g(void 0);return}let y=!1;return XSe(t,e.id,m).then(w=>{y||g(w)}),()=>{y=!0}},[t,o,e.id,m,s]),{items:(0,WS.useMemo)(()=>o?QSe(d,s,h,p):lMr,[o,d,s,h,p]),skippedMarkdownCount:c.skippedMarkdownCount}}var WS,lMr,mtt=b(()=>{es();ptt();o6();Xwe();Se();HS();Us();WS=L(B()),lMr=Object.freeze([])});function Wun(t,e=3e4){if(t.length<=e)return{text:t,truncated:!1};let n=t.lastIndexOf(`
`,e),r=n>=e-1024&&n>0?n:e;return{text:t.slice(0,r),truncated:!0}}var Vun=b(()=>{});var $g,tCe,qun=b(()=>{pe();lee();Vun();$g=require("obsidian"),tCe=class extends $g.Modal{constructor(n,r,o){super(n);this.title=r;this.content=o;this.component=new $g.Component}onOpen(){let{contentEl:n,modalEl:r}=this;r.addClass("!tw-w-[90vw]","!tw-max-w-[800px]"),n.empty(),n.addClass("tw-flex","tw-flex-col","tw-p-0"),this.component.load();let{text:o,truncated:i}=Wun(this.content),s=n.createDiv({cls:"tw-flex tw-items-center tw-justify-between tw-px-5 tw-py-3 tw-border-b tw-border-border"}),a=s.createDiv({cls:"tw-flex tw-items-center tw-gap-2 tw-min-w-0"}),l=a.createDiv({cls:"tw-text-muted tw-shrink-0"});(0,$g.setIcon)(l,"file-text"),a.createSpan({text:this.title,cls:"tw-font-semibold tw-text-normal tw-truncate"});let c=s.createEl("button",{cls:"tw-flex tw-items-center tw-gap-1 tw-px-2 tw-py-1 tw-rounded-md tw-bg-secondary tw-border-none tw-cursor-pointer tw-text-muted hover:tw-text-normal tw-shrink-0",attr:{"aria-label":"Copy content",title:"Copy content"}}),u=c.createSpan({cls:"tw-flex tw-items-center"});if((0,$g.setIcon)(u,"copy"),this.bindCopyFullContent(c,u),i){let m=Math.round(3e4/1e3);n.createDiv({text:`Preview shows the first ${m} KB for performance. Use Copy to get the full content.`,cls:"tw-px-5 tw-py-2 tw-text-sm tw-text-muted tw-border-b tw-border-border tw-bg-secondary"})}let d=n.createDiv({cls:i?"tw-h-[50vh] tw-overflow-auto tw-p-5":"tw-max-h-[50vh] tw-overflow-auto tw-p-5"}),f=d.createDiv({cls:"markdown-rendered tw-p-4 tw-bg-primary-alt tw-rounded-lg tw-border tw-border-border"});if(i){let m=d.createDiv({cls:"tw-flex tw-items-center tw-gap-3 tw-pt-6 tw-pb-1"});m.createDiv({cls:"tw-flex-grow tw-border-t tw-border-border"});let h=m.createEl("button",{cls:"tw-flex tw-shrink-0 tw-items-center tw-gap-2 tw-px-4 tw-py-1.5 tw-rounded-full tw-bg-secondary tw-border tw-border-border tw-cursor-pointer tw-text-xs tw-font-medium tw-uppercase tw-tracking-wide tw-text-muted hover:tw-text-accent hover:tw-border-accent",attr:{"aria-label":"Copy full content",title:"Copy full content"}}),g=h.createSpan({cls:"tw-flex tw-items-center"});(0,$g.setIcon)(g,"copy"),h.createSpan({text:"Copy full content"}),this.bindCopyFullContent(h,g),m.createDiv({cls:"tw-flex-grow tw-border-t tw-border-border"})}let p=()=>{YE(this.app,o,f,"",this.component).catch(m=>{W("[CachePreviewModal] markdown render failed",m)})};if(i){let m=this.contentEl.win??window;this.renderRafWin=m,this.renderRafId=m.requestAnimationFrame(()=>{this.renderRafId=m.requestAnimationFrame(()=>{this.renderRafId=void 0,p()})})}else p()}onClose(){this.renderRafId!==void 0&&((this.renderRafWin??window).cancelAnimationFrame(this.renderRafId),this.renderRafId=void 0),this.renderRafWin=void 0,this.component.unload(),this.contentEl.empty()}bindCopyFullContent(n,r){n.addEventListener("click",()=>{navigator.clipboard.writeText(this.content).then(()=>{(0,$g.setIcon)(r,"check"),n.addClass("tw-text-accent"),new $g.Notice("Copied to clipboard"),(n.win??window).setTimeout(()=>{(0,$g.setIcon)(r,"copy"),n.removeClass("tw-text-accent")},2e3)},()=>new $g.Notice("Failed to copy"))})}}});function Kun(t){if(VW(t)==="ENOENT"||t instanceof Error&&t.name==="NotFoundError")return!0;let e=t instanceof Error?t.message:String(t);return/ENOENT|no such file|not found|does not exist/i.test(e)}var Gun=b(()=>{Ewe()});async function zV(t,e){if(!Ln()){new Cte.Notice("Converted previews are available on desktop only.");return}let n=Kb(e.cacheKind,e.id);try{let{remotesDir:r,filesDir:o}=await Promise.resolve().then(()=>(_$(),Bwe)),{createNodeContextCacheFs:i}=await Promise.resolve().then(()=>(n6(),Qwe)),s=e.cacheKind==="file"?o(t):r(t),a=await i(s).readText(n);if(!a.trim()){new Cte.Notice("No content available for this item.");return}new tCe(t,e.name,a).open()}catch(r){if(Kun(r)){new Cte.Notice("No converted content yet for this item.");return}H(`Failed to read agent cached snapshot: ${n}`,r),new Cte.Notice("Failed to read converted content.")}}var Cte,nCe=b(()=>{qun();o6();pe();$n();Gun();Cte=require("obsidian")});var oCe,rCe,Zun=b(()=>{oCe=require("obsidian");ut();mw();rCe=class extends oCe.FuzzySuggestModal{constructor(e,n="copilot_plus"){super(e),this.activeNote=e.workspace.getActiveFile(),this.chainType=n}getOrderedNotes(e=[]){let n=this.app.workspace.getLastOpenFiles().map(s=>this.app.vault.getAbstractFileByPath(s)).filter(s=>s instanceof oCe.TFile&&$ie(s,this.chainType)&&!e.includes(s.path)&&s.path!==this.activeNote?.path),o=this.app.vault.getFiles().filter(s=>$ie(s,this.chainType)).filter(s=>!n.some(a=>a.path===s.path)&&!e.includes(s.path)&&s.path!==this.activeNote?.path);return[...this.activeNote&&$ie(this.activeNote,this.chainType)?[this.activeNote]:[],...n,...o]}formatNoteTitle(e,n,r){let o=e;return n&&(o+=" (current)"),r==="pdf"?o+=" (PDF)":r==="canvas"&&(o+=" (Canvas)"),o}}});var htt,kte,Yun=b(()=>{htt=require("obsidian");Zun();kte=class extends rCe{constructor({app:e,onFileSelect:n,excludeFilePaths:r,titleOnly:o=!1}){super(e),this.onFileSelect=n,this.availableNotes=this.getOrderedProjectFiles(r),this.titleOnly=o,this.setTitle("Select File")}getOrderedProjectFiles(e=[]){let n=["mp3","mp4","m4a","wav","webm"],r=this.app.workspace.getLastOpenFiles().map(s=>this.app.vault.getAbstractFileByPath(s)).filter(s=>s instanceof htt.TFile&&!e.includes(s.path)&&s.path!==this.activeNote?.path&&!n.includes(s.extension.toLowerCase())),i=this.app.vault.getFiles().filter(s=>!n.includes(s.extension.toLowerCase())).filter(s=>!r.some(a=>a.path===s.path)&&!e.includes(s.path)&&s.path!==this.activeNote?.path);return[...this.activeNote?[this.activeNote]:[],...r,...i]}getItems(){if(this.titleOnly){let e=new Map;return this.availableNotes.forEach(n=>{e.set(n.basename,n)}),Array.from(e.values())}return this.availableNotes}getItemText(e){let n=e.path===this.activeNote?.path;return this.formatNoteTitle(e.basename,n,e.extension)}onChooseItem(e,n){this.onFileSelect(e)}renderSuggestion(e,n){let r=n.createDiv({cls:"pointer-events-none"});if(e.item instanceof htt.TFile){let o=r.createDiv(),i=e.item;o.setText(this.formatNoteTitle(i.basename,i===this.activeNote,i.extension)),this.titleOnly||r.createDiv({cls:"mt-1 text-muted text-xs"}).setText(i.path)}}formatNoteTitle(e,n,r){let o=e;return n&&(o+=" (current)"),r&&(o+=` (${r.toUpperCase()})`),o}}});function uMr(t){return t.length>0&&t!=="position"&&t===t.trim()&&!/[:[\]]/.test(t)}function Jun(t){return t.vault.getMarkdownFiles().filter(e=>ii(t,e,null,null))}function dMr(t){let e=new Set;for(let n of Jun(t)){let r=t.metadataCache.getFileCache(n)?.frontmatter;r&&Object.keys(r).forEach(o=>{uMr(o)&&e.add(o)})}return Array.from(e).sort((n,r)=>n.localeCompare(r))}function fMr(t){return t.length>0&&!/[\r\n\u2028\u2029]/.test(t)}function pMr(t,e){let n=new Set;for(let r of Jun(t))Oie(t,r,e).forEach(o=>{let i=o.trim();fMr(i)&&n.add(i)});return Array.from(n).sort((r,o)=>r.localeCompare(o))}var ytt,gtt,iCe,Xun=b(()=>{ha();ut();ytt=require("obsidian");gtt=class extends ytt.FuzzySuggestModal{constructor(n,r,o){super(n);this.key=r;this.onChoose=o;this.setPlaceholder(`Select a value for "${r}"`)}getItems(){return[null,...pMr(this.app,this.key)]}getItemText(n){return n===null?"Any value \u2014 notes that declare this key":n}onChooseItem(n){this.onChoose(A9e(this.key,n??void 0))}},iCe=class extends ytt.FuzzySuggestModal{constructor(n,r){super(n);this.onChoose=r;this.setPlaceholder("Select a property key")}getItems(){return dMr(this.app)}getItemText(n){return n}onChooseItem(n){new gtt(this.app,n,this.onChoose).open()}}});var Qun,sCe,edn=b(()=>{ut();Qun=require("obsidian"),sCe=class extends Qun.FuzzySuggestModal{constructor(n,r){super(n);this.onChooseTag=r}getItems(){let n=this.app.vault.getMarkdownFiles(),r=new Set;for(let o of n)F_(this.app,o).forEach(s=>r.add(s));return Array.from(r)}getItemText(n){return n}onChooseItem(n,r){this.onChooseTag(n)}}});function PM(t){if(t.type!=="property")return t.pattern;let e=Rye(t.pattern);return e?e.value?`${e.key}: ${e.value}`:`${e.key}: (any)`:t.pattern}function Ite(t){let e=[...new Set(yg(t||""))],n=bI(e),r=[];return mMr.forEach(o=>{n[tdn[o]].forEach(i=>r.push({pattern:i,type:o}))}),r}function vtt(t,e,n){let r=[...new Set(yg(t||""))],o=bI(r),i=tdn[n];return pE({...o,[i]:o[i].filter(s=>s!==e)})}var mMr,tdn,aCe=b(()=>{ha();mMr=["folder","tag","note","extension","property"],tdn={folder:"folderPatterns",tag:"tagPatterns",note:"notePatterns",extension:"extensionPatterns",property:"propertyPatterns"}});function Itt(t=null){let e=hMr(),n=(0,Jt.useRef)(t||e||null);return n.current===null&&(n.current=""+gMr++),t??n.current}function ddn({children:t,className:e="",collapsedSize:n,collapsible:r,defaultSize:o,forwardedRef:i,id:s,maxSize:a,minSize:l,onCollapse:c,onExpand:u,onResize:d,order:f,style:p,tagName:m="div",...h}){let g=(0,Jt.useContext)(fCe);if(g===null)throw Error("Panel components must be rendered within a PanelGroup container");let{collapsePanel:v,expandPanel:y,getPanelSize:w,getPanelStyle:_,groupId:S,isPanelCollapsed:I,reevaluatePanelConstraints:C,registerPanel:k,resizePanel:T,unregisterPanel:P}=g,E=Itt(s),O=(0,Jt.useRef)({callbacks:{onCollapse:c,onExpand:u,onResize:d},constraints:{collapsedSize:n,collapsible:r,defaultSize:o,maxSize:a,minSize:l},id:E,idIsFromProps:s!==void 0,order:f});(0,Jt.useRef)({didLogMissingDefaultSizeWarning:!1}),pD(()=>{let{callbacks:U,constraints:V}=O.current,K={...V};O.current.id=E,O.current.idIsFromProps=s!==void 0,O.current.order=f,U.onCollapse=c,U.onExpand=u,U.onResize=d,V.collapsedSize=n,V.collapsible=r,V.defaultSize=o,V.maxSize=a,V.minSize=l,(K.collapsedSize!==V.collapsedSize||K.collapsible!==V.collapsible||K.maxSize!==V.maxSize||K.minSize!==V.minSize)&&C(O.current,K)}),pD(()=>{let U=O.current;return k(U),()=>{P(U)}},[f,E,k,P]),(0,Jt.useImperativeHandle)(i,()=>({collapse:()=>{v(O.current)},expand:U=>{y(O.current,U)},getId(){return E},getSize(){return w(O.current)},isCollapsed(){return I(O.current)},isExpanded(){return!I(O.current)},resize:U=>{T(O.current,U)}}),[v,y,w,I,E,T]);let $=_(O.current,o);return(0,Jt.createElement)(m,{...h,children:t,className:e,id:E,style:{...$,...p},[il.groupId]:S,[il.panel]:"",[il.panelCollapsible]:r||void 0,[il.panelId]:E,[il.panelSize]:parseFloat(""+$.flexGrow).toFixed(1)})}function vMr(){return yMr}function bMr(t,e){if(e){let n=(e&gdn)!==0,r=(e&ydn)!==0,o=(e&vdn)!==0,i=(e&wdn)!==0;if(n)return o?"se-resize":i?"ne-resize":"e-resize";if(r)return o?"sw-resize":i?"nw-resize":"w-resize";if(o)return"s-resize";if(i)return"n-resize"}switch(t){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function _Mr(){C0!==null&&(document.head.removeChild(C0),Ctt=null,C0=null,cCe=-1)}function wtt(t,e){var n,r;if(!wMr)return;let o=bMr(t,e);if(Ctt!==o){if(Ctt=o,C0===null){C0=document.createElement("style");let s=vMr();s&&C0.setAttribute("nonce",s),document.head.appendChild(C0)}if(cCe>=0){var i;(i=C0.sheet)===null||i===void 0||i.removeRule(cCe)}cCe=(n=(r=C0.sheet)===null||r===void 0?void 0:r.insertRule(`*{cursor: ${o} !important;}`))!==null&&n!==void 0?n:-1}}function fdn(t){return t.type==="keydown"}function pdn(t){return t.type.startsWith("pointer")}function mdn(t){return t.type.startsWith("mouse")}function pCe(t){if(pdn(t)){if(t.isPrimary)return{x:t.clientX,y:t.clientY}}else if(mdn(t))return{x:t.clientX,y:t.clientY};return{x:1/0,y:1/0}}function xMr(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function SMr(t,e,n){return n?t.x<e.x+e.width&&t.x+t.width>e.x&&t.y<e.y+e.height&&t.y+t.height>e.y:t.x<=e.x+e.width&&t.x+t.width>=e.x&&t.y<=e.y+e.height&&t.y+t.height>=e.y}function CMr(t,e){if(t===e)throw new Error("Cannot compare node with itself");let n={a:idn(t),b:idn(e)},r;for(;n.a.at(-1)===n.b.at(-1);)t=n.a.pop(),e=n.b.pop(),r=t;so(r,"Stacking order can only be calculated for elements with a common ancestor");let o={a:odn(rdn(n.a)),b:odn(rdn(n.b))};if(o.a===o.b){let i=r.childNodes,s={a:n.a.at(-1),b:n.b.at(-1)},a=i.length;for(;a--;){let l=i[a];if(l===s.a)return 1;if(l===s.b)return-1}}return Math.sign(o.a-o.b)}function IMr(t){var e;let n=getComputedStyle((e=hdn(t))!==null&&e!==void 0?e:t).display;return n==="flex"||n==="inline-flex"}function TMr(t){let e=getComputedStyle(t);return!!(e.position==="fixed"||e.zIndex!=="auto"&&(e.position!=="static"||IMr(t))||+e.opacity<1||"transform"in e&&e.transform!=="none"||"webkitTransform"in e&&e.webkitTransform!=="none"||"mixBlendMode"in e&&e.mixBlendMode!=="normal"||"filter"in e&&e.filter!=="none"||"webkitFilter"in e&&e.webkitFilter!=="none"||"isolation"in e&&e.isolation==="isolate"||kMr.test(e.willChange)||e.webkitOverflowScrolling==="touch")}function rdn(t){let e=t.length;for(;e--;){let n=t[e];if(so(n,"Missing node"),TMr(n))return n}return null}function odn(t){return t&&Number(getComputedStyle(t).zIndex)||0}function idn(t){let e=[];for(;t;)e.push(t),t=hdn(t);return e}function hdn(t){let{parentNode:e}=t;return e&&e instanceof ShadowRoot?e.host:e}function AMr(t,e,n,r,o){var i;let{ownerDocument:s}=e,a={direction:n,element:e,hitAreaMargins:r,setResizeHandlerState:o},l=(i=AM.get(s))!==null&&i!==void 0?i:0;return AM.set(s,l+1),Ate.add(a),uCe(),function(){var u;mCe.delete(t),Ate.delete(a);let d=(u=AM.get(s))!==null&&u!==void 0?u:1;if(AM.set(s,d-1),uCe(),d===1&&AM.delete(s),m_.includes(a)){let f=m_.indexOf(a);f>=0&&m_.splice(f,1),Att(),o("up",!0,null)}}}function EMr(t){let{target:e}=t,{x:n,y:r}=pCe(t);qV=!0,Ptt({target:e,x:n,y:r}),uCe(),m_.length>0&&(dCe("down",t),t.preventDefault(),bdn(e)||t.stopImmediatePropagation())}function btt(t){let{x:e,y:n}=pCe(t);if(qV&&t.buttons===0&&(qV=!1,dCe("up",t)),!qV){let{target:r}=t;Ptt({target:r,x:e,y:n})}dCe("move",t),Att(),m_.length>0&&t.preventDefault()}function _tt(t){let{target:e}=t,{x:n,y:r}=pCe(t);mCe.clear(),qV=!1,m_.length>0&&(t.preventDefault(),bdn(e)||t.stopImmediatePropagation()),dCe("up",t),Ptt({target:e,x:n,y:r}),Att(),uCe()}function bdn(t){let e=t;for(;e;){if(e.hasAttribute(il.resizeHandle))return!0;e=e.parentElement}return!1}function Ptt({target:t,x:e,y:n}){m_.splice(0);let r=null;(t instanceof HTMLElement||t instanceof SVGElement)&&(r=t),Ate.forEach(o=>{let{element:i,hitAreaMargins:s}=o,a=i.getBoundingClientRect(),{bottom:l,left:c,right:u,top:d}=a,f=PMr?s.coarse:s.fine;if(e>=c-f&&e<=u+f&&n>=d-f&&n<=l+f){if(r!==null&&document.contains(r)&&i!==r&&!i.contains(r)&&!r.contains(i)&&CMr(r,i)>0){let m=r,h=!1;for(;m&&!m.contains(i);){if(SMr(m.getBoundingClientRect(),a,!0)){h=!0;break}m=m.parentElement}if(h)return}m_.push(o)}})}function xtt(t,e){mCe.set(t,e)}function Att(){let t=!1,e=!1;m_.forEach(r=>{let{direction:o}=r;o==="horizontal"?t=!0:e=!0});let n=0;mCe.forEach(r=>{n|=r}),t&&e?wtt("intersection",n):t?wtt("horizontal",n):e?wtt("vertical",n):_Mr()}function uCe(){Stt.abort(),Stt=new AbortController;let t={capture:!0,signal:Stt.signal};Ate.size&&(qV?(m_.length>0&&AM.forEach((e,n)=>{let{body:r}=n;e>0&&(r.addEventListener("contextmenu",_tt,t),r.addEventListener("pointerleave",btt,t),r.addEventListener("pointermove",btt,t))}),AM.forEach((e,n)=>{let{body:r}=n;r.addEventListener("pointerup",_tt,t),r.addEventListener("pointercancel",_tt,t)})):AM.forEach((e,n)=>{let{body:r}=n;e>0&&(r.addEventListener("pointerdown",EMr,t),r.addEventListener("pointermove",btt,t))}))}function dCe(t,e){Ate.forEach(n=>{let{setResizeHandlerState:r}=n,o=m_.includes(n);r(t,o,e)})}function MMr(){let[t,e]=(0,Jt.useState)(0);return(0,Jt.useCallback)(()=>e(n=>n+1),[])}function so(t,e){if(!t)throw console.error(e),Error(e)}function mD(t,e,n=ktt){return t.toFixed(n)===e.toFixed(n)?0:t>e?1:-1}function k0(t,e,n=ktt){return mD(t,e,n)===0}function Dg(t,e,n){return mD(t,e,n)===0}function OMr(t,e,n){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){let o=t[r],i=e[r];if(!Dg(o,i,n))return!1}return!0}function VV({panelConstraints:t,panelIndex:e,size:n}){let r=t[e];so(r!=null,`Panel constraints not found for index ${e}`);let{collapsedSize:o=0,collapsible:i,maxSize:s=100,minSize:a=0}=r;if(mD(n,a)<0)if(i){let l=(o+a)/2;mD(n,l)<0?n=o:n=a}else n=a;return n=Math.min(s,n),n=parseFloat(n.toFixed(ktt)),n}function Tte({delta:t,initialLayout:e,panelConstraints:n,pivotIndices:r,prevLayout:o,trigger:i}){if(Dg(t,0))return e;let s=[...e],[a,l]=r;so(a!=null,"Invalid first pivot index"),so(l!=null,"Invalid second pivot index");let c=0;if(i==="keyboard"){{let d=t<0?l:a,f=n[d];so(f,`Panel constraints not found for index ${d}`);let{collapsedSize:p=0,collapsible:m,minSize:h=0}=f;if(m){let g=e[d];if(so(g!=null,`Previous layout not found for panel index ${d}`),Dg(g,p)){let v=h-g;mD(v,Math.abs(t))>0&&(t=t<0?0-v:v)}}}{let d=t<0?a:l,f=n[d];so(f,`No panel constraints found for index ${d}`);let{collapsedSize:p=0,collapsible:m,minSize:h=0}=f;if(m){let g=e[d];if(so(g!=null,`Previous layout not found for panel index ${d}`),Dg(g,h)){let v=g-p;mD(v,Math.abs(t))>0&&(t=t<0?0-v:v)}}}}{let d=t<0?1:-1,f=t<0?l:a,p=0;for(;;){let h=e[f];so(h!=null,`Previous layout not found for panel index ${f}`);let v=VV({panelConstraints:n,panelIndex:f,size:100})-h;if(p+=v,f+=d,f<0||f>=n.length)break}let m=Math.min(Math.abs(t),Math.abs(p));t=t<0?0-m:m}{let f=t<0?a:l;for(;f>=0&&f<n.length;){let p=Math.abs(t)-Math.abs(c),m=e[f];so(m!=null,`Previous layout not found for panel index ${f}`);let h=m-p,g=VV({panelConstraints:n,panelIndex:f,size:h});if(!Dg(m,g)&&(c+=m-g,s[f]=g,c.toPrecision(3).localeCompare(Math.abs(t).toPrecision(3),void 0,{numeric:!0})>=0))break;t<0?f--:f++}}if(OMr(o,s))return o;{let d=t<0?l:a,f=e[d];so(f!=null,`Previous layout not found for panel index ${d}`);let p=f+c,m=VV({panelConstraints:n,panelIndex:d,size:p});if(s[d]=m,!Dg(m,p)){let h=p-m,v=t<0?l:a;for(;v>=0&&v<n.length;){let y=s[v];so(y!=null,`Previous layout not found for panel index ${v}`);let w=y+h,_=VV({panelConstraints:n,panelIndex:v,size:w});if(Dg(y,_)||(h-=_-y,s[v]=_),Dg(h,0))break;t>0?v--:v++}}}let u=s.reduce((d,f)=>f+d,0);return Dg(u,100)?s:o}function NMr({layout:t,panelsArray:e,pivotIndices:n}){let r=0,o=100,i=0,s=0,a=n[0];so(a!=null,"No pivot index found"),e.forEach((d,f)=>{let{constraints:p}=d,{maxSize:m=100,minSize:h=0}=p;f===a?(r=h,o=m):(i+=h,s+=m)});let l=Math.min(o,100-i),c=Math.max(r,100-s),u=t[a];return{valueMax:l,valueMin:c,valueNow:u}}function Ete(t,e=document){return Array.from(e.querySelectorAll(`[${il.resizeHandleId}][data-panel-group-id="${t}"]`))}function _dn(t,e,n=document){let o=Ete(t,n).findIndex(i=>i.getAttribute(il.resizeHandleId)===e);return o??null}function xdn(t,e,n){let r=_dn(t,e,n);return r!=null?[r,r+1]:[-1,-1]}function RMr(t){return t instanceof HTMLElement?!0:typeof t=="object"&&t!==null&&"tagName"in t&&"getAttribute"in t}function Sdn(t,e=document){if(RMr(e)&&e.dataset.panelGroupId==t)return e;let n=e.querySelector(`[data-panel-group][data-panel-group-id="${t}"]`);return n||null}function hCe(t,e=document){let n=e.querySelector(`[${il.resizeHandleId}="${t}"]`);return n||null}function LMr(t,e,n,r=document){var o,i,s,a;let l=hCe(e,r),c=Ete(t,r),u=l?c.indexOf(l):-1,d=(o=(i=n[u])===null||i===void 0?void 0:i.id)!==null&&o!==void 0?o:null,f=(s=(a=n[u+1])===null||a===void 0?void 0:a.id)!==null&&s!==void 0?s:null;return[d,f]}function $Mr({committedValuesRef:t,eagerValuesRef:e,groupId:n,layout:r,panelDataArray:o,panelGroupElement:i,setLayout:s}){(0,Jt.useRef)({didWarnAboutMissingResizeHandle:!1}),pD(()=>{if(!i)return;let a=Ete(n,i);for(let l=0;l<o.length-1;l++){let{valueMax:c,valueMin:u,valueNow:d}=NMr({layout:r,panelsArray:o,pivotIndices:[l,l+1]}),f=a[l];if(f!=null){let p=o[l];so(p,`No panel data found for index "${l}"`),f.setAttribute("aria-controls",p.id),f.setAttribute("aria-valuemax",""+Math.round(c)),f.setAttribute("aria-valuemin",""+Math.round(u)),f.setAttribute("aria-valuenow",d!=null?""+Math.round(d):"")}}return()=>{a.forEach((l,c)=>{l.removeAttribute("aria-controls"),l.removeAttribute("aria-valuemax"),l.removeAttribute("aria-valuemin"),l.removeAttribute("aria-valuenow")})}},[n,r,o,i]),(0,Jt.useEffect)(()=>{if(!i)return;let a=e.current;so(a,"Eager values not found");let{panelDataArray:l}=a,c=Sdn(n,i);so(c!=null,`No group found for id "${n}"`);let u=Ete(n,i);so(u,`No resize handles found for group id "${n}"`);let d=u.map(f=>{let p=f.getAttribute(il.resizeHandleId);so(p,"Resize handle element has no handle id attribute");let[m,h]=LMr(n,p,l,i);if(m==null||h==null)return()=>{};let g=v=>{if(!v.defaultPrevented)switch(v.key){case"Enter":{v.preventDefault();let y=l.findIndex(w=>w.id===m);if(y>=0){let w=l[y];so(w,`No panel data found for index ${y}`);let _=r[y],{collapsedSize:S=0,collapsible:I,minSize:C=0}=w.constraints;if(_!=null&&I){let k=Tte({delta:Dg(_,S)?C-S:S-_,initialLayout:r,panelConstraints:l.map(T=>T.constraints),pivotIndices:xdn(n,p,i),prevLayout:r,trigger:"keyboard"});r!==k&&s(k)}}break}}};return f.addEventListener("keydown",g),()=>{f.removeEventListener("keydown",g)}});return()=>{d.forEach(f=>f())}},[i,t,e,n,r,o,s])}function sdn(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function Cdn(t,e){let n=t==="horizontal",{x:r,y:o}=pCe(e);return n?r:o}function DMr(t,e,n,r,o){let i=n==="horizontal",s=hCe(e,o);so(s,`No resize handle element found for id "${e}"`);let a=s.getAttribute(il.groupId);so(a,"Resize handle element has no group id attribute");let{initialCursorPosition:l}=r,c=Cdn(n,t),u=Sdn(a,o);so(u,`No group element found for id "${a}"`);let d=u.getBoundingClientRect(),f=i?d.width:d.height;return(c-l)/f*100}function FMr(t,e,n,r,o,i){if(fdn(t)){let s=n==="horizontal",a=0;t.shiftKey?a=100:o!=null?a=o:a=10;let l=0;switch(t.key){case"ArrowDown":l=s?0:a;break;case"ArrowLeft":l=s?-a:0;break;case"ArrowRight":l=s?a:0;break;case"ArrowUp":l=s?0:-a;break;case"End":l=100;break;case"Home":l=-100;break}return l}else return r==null?0:DMr(t,e,n,r,i)}function UMr({panelDataArray:t}){let e=Array(t.length),n=t.map(i=>i.constraints),r=0,o=100;for(let i=0;i<t.length;i++){let s=n[i];so(s,`Panel constraints not found for index ${i}`);let{defaultSize:a}=s;a!=null&&(r++,e[i]=a,o-=a)}for(let i=0;i<t.length;i++){let s=n[i];so(s,`Panel constraints not found for index ${i}`);let{defaultSize:a}=s;if(a!=null)continue;let l=t.length-r,c=o/l;r++,e[i]=c,o-=c}return e}function HV(t,e,n){e.forEach((r,o)=>{let i=t[o];so(i,`Panel data not found for index ${o}`);let{callbacks:s,constraints:a,id:l}=i,{collapsedSize:c=0,collapsible:u}=a,d=n[l];if(d==null||r!==d){n[l]=r;let{onCollapse:f,onExpand:p,onResize:m}=s;m&&m(r,d),u&&(f||p)&&(p&&(d==null||k0(d,c))&&!k0(r,c)&&p(),f&&(d==null||!k0(d,c))&&k0(r,c)&&f())}})}function lCe(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!=e[n])return!1;return!0}function jMr({defaultSize:t,dragState:e,layout:n,panelData:r,panelIndex:o,precision:i=3}){let s=n[o],a;return s==null?a=t!=null?t.toPrecision(i):"1":r.length===1?a="1":a=s.toPrecision(i),{flexBasis:0,flexGrow:a,flexShrink:1,overflow:"hidden",pointerEvents:e!==null?"none":void 0}}function BMr(t,e=10){let n=null;return(...o)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{t(...o)},e)}}function adn(t){try{if(typeof localStorage<"u")t.getItem=e=>localStorage.getItem(e),t.setItem=(e,n)=>{localStorage.setItem(e,n)};else throw new Error("localStorage not supported in this environment")}catch(e){console.error(e),t.getItem=()=>null,t.setItem=()=>{}}}function kdn(t){return`react-resizable-panels:${t}`}function Idn(t){return t.map(e=>{let{constraints:n,id:r,idIsFromProps:o,order:i}=e;return o?r:i?`${i}:${JSON.stringify(n)}`:JSON.stringify(n)}).sort((e,n)=>e.localeCompare(n)).join(",")}function Tdn(t,e){try{let n=kdn(t),r=e.getItem(n);if(r){let o=JSON.parse(r);if(typeof o=="object"&&o!=null)return o}}catch{}return null}function zMr(t,e,n){var r,o;let i=(r=Tdn(t,n))!==null&&r!==void 0?r:{},s=Idn(e);return(o=i[s])!==null&&o!==void 0?o:null}function HMr(t,e,n,r,o){var i;let s=kdn(t),a=Idn(e),l=(i=Tdn(t,o))!==null&&i!==void 0?i:{};l[a]={expandToSizes:Object.fromEntries(n.entries()),layout:r};try{o.setItem(s,JSON.stringify(l))}catch(c){console.error(c)}}function ldn({layout:t,panelConstraints:e}){let n=[...t],r=n.reduce((i,s)=>i+s,0);if(n.length!==e.length)throw Error(`Invalid ${e.length} panel layout: ${n.map(i=>`${i}%`).join(", ")}`);if(!Dg(r,100)&&n.length>0)for(let i=0;i<e.length;i++){let s=n[i];so(s!=null,`No layout data found for index ${i}`);let a=100/r*s;n[i]=a}let o=0;for(let i=0;i<e.length;i++){let s=n[i];so(s!=null,`No layout data found for index ${i}`);let a=VV({panelConstraints:e,panelIndex:i,size:s});s!=a&&(o+=s-a,n[i]=a)}if(!Dg(o,0))for(let i=0;i<e.length;i++){let s=n[i];so(s!=null,`No layout data found for index ${i}`);let a=s+o,l=VV({panelConstraints:e,panelIndex:i,size:a});if(s!==l&&(o-=l-s,n[i]=l,Dg(o,0)))break}return n}function Pdn({autoSaveId:t=null,children:e,className:n="",direction:r,forwardedRef:o,id:i=null,onLayout:s=null,keyboardResizeBy:a=null,storage:l=Pte,style:c,tagName:u="div",...d}){let f=Itt(i),p=(0,Jt.useRef)(null),[m,h]=(0,Jt.useState)(null),[g,v]=(0,Jt.useState)([]),y=MMr(),w=(0,Jt.useRef)({}),_=(0,Jt.useRef)(new Map),S=(0,Jt.useRef)(0),I=(0,Jt.useRef)({autoSaveId:t,direction:r,dragState:m,id:f,keyboardResizeBy:a,onLayout:s,storage:l}),C=(0,Jt.useRef)({layout:g,panelDataArray:[],panelDataArrayChanged:!1});(0,Jt.useRef)({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),(0,Jt.useImperativeHandle)(o,()=>({getId:()=>I.current.id,getLayout:()=>{let{layout:q}=C.current;return q},setLayout:q=>{let{onLayout:F}=I.current,{layout:z,panelDataArray:N}=C.current,R=ldn({layout:q,panelConstraints:N.map(X=>X.constraints)});sdn(z,R)||(v(R),C.current.layout=R,F&&F(R),HV(N,R,w.current))}}),[]),pD(()=>{I.current.autoSaveId=t,I.current.direction=r,I.current.dragState=m,I.current.id=f,I.current.onLayout=s,I.current.storage=l}),$Mr({committedValuesRef:I,eagerValuesRef:C,groupId:f,layout:g,panelDataArray:C.current.panelDataArray,setLayout:v,panelGroupElement:p.current}),(0,Jt.useEffect)(()=>{let{panelDataArray:q}=C.current;if(t){if(g.length===0||g.length!==q.length)return;let F=cdn[t];F==null&&(F=BMr(HMr,WMr),cdn[t]=F);let z=[...q],N=new Map(_.current);F(t,z,N,g,l)}},[t,g,l]),(0,Jt.useEffect)(()=>{});let k=(0,Jt.useCallback)(q=>{let{onLayout:F}=I.current,{layout:z,panelDataArray:N}=C.current;if(q.constraints.collapsible){let R=N.map(ce=>ce.constraints),{collapsedSize:X=0,panelSize:D,pivotIndices:G}=fD(N,q,z);if(so(D!=null,`Panel size not found for panel "${q.id}"`),!k0(D,X)){_.current.set(q.id,D);let Z=WV(N,q)===N.length-1?D-X:X-D,te=Tte({delta:Z,initialLayout:z,panelConstraints:R,pivotIndices:G,prevLayout:z,trigger:"imperative-api"});lCe(z,te)||(v(te),C.current.layout=te,F&&F(te),HV(N,te,w.current))}}},[]),T=(0,Jt.useCallback)((q,F)=>{let{onLayout:z}=I.current,{layout:N,panelDataArray:R}=C.current;if(q.constraints.collapsible){let X=R.map(fe=>fe.constraints),{collapsedSize:D=0,panelSize:G=0,minSize:ce=0,pivotIndices:Z}=fD(R,q,N),te=F??ce;if(k0(G,D)){let fe=_.current.get(q.id),de=fe!=null&&fe>=te?fe:te,Te=WV(R,q)===R.length-1?G-de:de-G,Be=Tte({delta:Te,initialLayout:N,panelConstraints:X,pivotIndices:Z,prevLayout:N,trigger:"imperative-api"});lCe(N,Be)||(v(Be),C.current.layout=Be,z&&z(Be),HV(R,Be,w.current))}}},[]),P=(0,Jt.useCallback)(q=>{let{layout:F,panelDataArray:z}=C.current,{panelSize:N}=fD(z,q,F);return so(N!=null,`Panel size not found for panel "${q.id}"`),N},[]),E=(0,Jt.useCallback)((q,F)=>{let{panelDataArray:z}=C.current,N=WV(z,q);return jMr({defaultSize:F,dragState:m,layout:g,panelData:z,panelIndex:N})},[m,g]),O=(0,Jt.useCallback)(q=>{let{layout:F,panelDataArray:z}=C.current,{collapsedSize:N=0,collapsible:R,panelSize:X}=fD(z,q,F);return so(X!=null,`Panel size not found for panel "${q.id}"`),R===!0&&k0(X,N)},[]),$=(0,Jt.useCallback)(q=>{let{layout:F,panelDataArray:z}=C.current,{collapsedSize:N=0,collapsible:R,panelSize:X}=fD(z,q,F);return so(X!=null,`Panel size not found for panel "${q.id}"`),!R||mD(X,N)>0},[]),U=(0,Jt.useCallback)(q=>{let{panelDataArray:F}=C.current;F.push(q),F.sort((z,N)=>{let R=z.order,X=N.order;return R==null&&X==null?0:R==null?-1:X==null?1:R-X}),C.current.panelDataArrayChanged=!0,y()},[y]);pD(()=>{if(C.current.panelDataArrayChanged){C.current.panelDataArrayChanged=!1;let{autoSaveId:q,onLayout:F,storage:z}=I.current,{layout:N,panelDataArray:R}=C.current,X=null;if(q){let G=zMr(q,R,z);G&&(_.current=new Map(Object.entries(G.expandToSizes)),X=G.layout)}X==null&&(X=UMr({panelDataArray:R}));let D=ldn({layout:X,panelConstraints:R.map(G=>G.constraints)});sdn(N,D)||(v(D),C.current.layout=D,F&&F(D),HV(R,D,w.current))}}),pD(()=>{let q=C.current;return()=>{q.layout=[]}},[]);let V=(0,Jt.useCallback)(q=>{let F=!1,z=p.current;return z&&window.getComputedStyle(z,null).getPropertyValue("direction")==="rtl"&&(F=!0),function(R){R.preventDefault();let X=p.current;if(!X)return()=>null;let{direction:D,dragState:G,id:ce,keyboardResizeBy:Z,onLayout:te}=I.current,{layout:fe,panelDataArray:de}=C.current,{initialLayout:ye}=G??{},Te=xdn(ce,q,X),Be=FMr(R,q,D,G,Z,X),qe=D==="horizontal";qe&&F&&(Be=-Be);let Ae=de.map(Ee=>Ee.constraints),Xt=Tte({delta:Be,initialLayout:ye??fe,panelConstraints:Ae,pivotIndices:Te,prevLayout:fe,trigger:fdn(R)?"keyboard":"mouse-or-touch"}),Ve=!lCe(fe,Xt);(pdn(R)||mdn(R))&&S.current!=Be&&(S.current=Be,!Ve&&Be!==0?qe?xtt(q,Be<0?gdn:ydn):xtt(q,Be<0?vdn:wdn):xtt(q,0)),Ve&&(v(Xt),C.current.layout=Xt,te&&te(Xt),HV(de,Xt,w.current))}},[]),K=(0,Jt.useCallback)((q,F)=>{let{onLayout:z}=I.current,{layout:N,panelDataArray:R}=C.current,X=R.map(fe=>fe.constraints),{panelSize:D,pivotIndices:G}=fD(R,q,N);so(D!=null,`Panel size not found for panel "${q.id}"`);let Z=WV(R,q)===R.length-1?D-F:F-D,te=Tte({delta:Z,initialLayout:N,panelConstraints:X,pivotIndices:G,prevLayout:N,trigger:"imperative-api"});lCe(N,te)||(v(te),C.current.layout=te,z&&z(te),HV(R,te,w.current))},[]),se=(0,Jt.useCallback)((q,F)=>{let{layout:z,panelDataArray:N}=C.current,{collapsedSize:R=0,collapsible:X}=F,{collapsedSize:D=0,collapsible:G,maxSize:ce=100,minSize:Z=0}=q.constraints,{panelSize:te}=fD(N,q,z);te!=null&&(X&&G&&k0(te,R)?k0(R,D)||K(q,D):te<Z?K(q,Z):te>ce&&K(q,ce))},[K]),le=(0,Jt.useCallback)((q,F)=>{let{direction:z}=I.current,{layout:N}=C.current;if(!p.current)return;let R=hCe(q,p.current);so(R,`Drag handle element not found for id "${q}"`);let X=Cdn(z,F);h({dragHandleId:q,dragHandleRect:R.getBoundingClientRect(),initialCursorPosition:X,initialLayout:N})},[]),Q=(0,Jt.useCallback)(()=>{h(null)},[]),ne=(0,Jt.useCallback)(q=>{let{panelDataArray:F}=C.current,z=WV(F,q);z>=0&&(F.splice(z,1),delete w.current[q.id],C.current.panelDataArrayChanged=!0,y())},[y]),ee=(0,Jt.useMemo)(()=>({collapsePanel:k,direction:r,dragState:m,expandPanel:T,getPanelSize:P,getPanelStyle:E,groupId:f,isPanelCollapsed:O,isPanelExpanded:$,reevaluatePanelConstraints:se,registerPanel:U,registerResizeHandle:V,resizePanel:K,startDragging:le,stopDragging:Q,unregisterPanel:ne,panelGroupElement:p.current}),[k,m,r,T,P,E,f,O,$,se,U,V,K,le,Q,ne]),ae={display:"flex",flexDirection:r==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return(0,Jt.createElement)(fCe.Provider,{value:ee},(0,Jt.createElement)(u,{...d,children:e,className:n,id:i,ref:p,style:{...ae,...c},[il.group]:"",[il.groupDirection]:r,[il.groupId]:f}))}function WV(t,e){return t.findIndex(n=>n===e||n.id===e.id)}function fD(t,e,n){let r=WV(t,e),i=r===t.length-1?[r-1,r]:[r,r+1],s=n[r];return{...e.constraints,panelSize:s,pivotIndices:i}}function VMr({disabled:t,handleId:e,resizeHandler:n,panelGroupElement:r}){(0,Jt.useEffect)(()=>{if(t||n==null||r==null)return;let o=hCe(e,r);if(o==null)return;let i=s=>{if(!s.defaultPrevented)switch(s.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{s.preventDefault(),n(s);break}case"F6":{s.preventDefault();let a=o.getAttribute(il.groupId);so(a,`No group element found for id "${a}"`);let l=Ete(a,r),c=_dn(a,e,r);so(c!==null,`No resize element found for id "${e}"`);let u=s.shiftKey?c>0?c-1:l.length-1:c+1<l.length?c+1:0;l[u].focus();break}}};return o.addEventListener("keydown",i),()=>{o.removeEventListener("keydown",i)}},[r,t,e,n])}function Mtt({children:t=null,className:e="",disabled:n=!1,hitAreaMargins:r,id:o,onBlur:i,onClick:s,onDragging:a,onFocus:l,onPointerDown:c,onPointerUp:u,style:d={},tabIndex:f=0,tagName:p="div",...m}){var h,g;let v=(0,Jt.useRef)(null),y=(0,Jt.useRef)({onClick:s,onDragging:a,onPointerDown:c,onPointerUp:u});(0,Jt.useEffect)(()=>{y.current.onClick=s,y.current.onDragging=a,y.current.onPointerDown=c,y.current.onPointerUp=u});let w=(0,Jt.useContext)(fCe);if(w===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");let{direction:_,groupId:S,registerResizeHandle:I,startDragging:C,stopDragging:k,panelGroupElement:T}=w,P=Itt(o),[E,O]=(0,Jt.useState)("inactive"),[$,U]=(0,Jt.useState)(!1),[V,K]=(0,Jt.useState)(null),se=(0,Jt.useRef)({state:E});pD(()=>{se.current.state=E}),(0,Jt.useEffect)(()=>{if(n)K(null);else{let ee=I(P);K(()=>ee)}},[n,P,I]);let le=(h=r?.coarse)!==null&&h!==void 0?h:15,Q=(g=r?.fine)!==null&&g!==void 0?g:5;return(0,Jt.useEffect)(()=>{if(n||V==null)return;let ee=v.current;so(ee,"Element ref not attached");let ae=!1;return AMr(P,ee,_,{coarse:le,fine:Q},(F,z,N)=>{if(!z){O("inactive");return}switch(F){case"down":{O("drag"),ae=!1,so(N,'Expected event to be defined for "down" action'),C(P,N);let{onDragging:R,onPointerDown:X}=y.current;R?.(!0),X?.();break}case"move":{let{state:R}=se.current;ae=!0,R!=="drag"&&O("hover"),so(N,'Expected event to be defined for "move" action'),V(N);break}case"up":{O("hover"),k();let{onClick:R,onDragging:X,onPointerUp:D}=y.current;X?.(!1),D?.(),ae||R?.();break}}})},[le,_,n,Q,I,P,V,C,k]),VMr({disabled:n,handleId:P,resizeHandler:V,panelGroupElement:T}),(0,Jt.createElement)(p,{...m,children:t,className:e,id:o,onBlur:()=>{U(!1),i?.()},onFocus:()=>{U(!0),l?.()},ref:v,role:"separator",style:{...{touchAction:"none",userSelect:"none"},...d},tabIndex:f,[il.groupDirection]:_,[il.groupId]:S,[il.resizeHandle]:"",[il.resizeHandleActive]:E==="drag"?"pointer":$?"keyboard":void 0,[il.resizeHandleEnabled]:!n,[il.resizeHandleId]:P,[il.resizeHandleState]:E})}var udn,Jt,fCe,il,ktt,pD,ndn,hMr,gMr,Ttt,yMr,Ctt,wMr,cCe,C0,kMr,gdn,ydn,vdn,wdn,PMr,m_,qV,AM,mCe,Ate,Stt,WMr,Pte,cdn,Ett,Adn=b(()=>{udn=L(B(),1),Jt=L(B(),1),fCe=(0,Jt.createContext)(null);fCe.displayName="PanelGroupContext";il={group:"data-panel-group",groupDirection:"data-panel-group-direction",groupId:"data-panel-group-id",panel:"data-panel",panelCollapsible:"data-panel-collapsible",panelId:"data-panel-id",panelSize:"data-panel-size",resizeHandle:"data-resize-handle",resizeHandleActive:"data-resize-handle-active",resizeHandleEnabled:"data-panel-resize-handle-enabled",resizeHandleId:"data-panel-resize-handle-id",resizeHandleState:"data-resize-handle-state"},ktt=10,pD=Jt.useLayoutEffect,ndn=udn.useId,hMr=typeof ndn=="function"?ndn:()=>null,gMr=0;Ttt=(0,Jt.forwardRef)((t,e)=>(0,Jt.createElement)(ddn,{...t,forwardedRef:e}));ddn.displayName="Panel";Ttt.displayName="forwardRef(Panel)";Ctt=null,wMr=!0,cCe=-1,C0=null;kMr=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;gdn=1,ydn=2,vdn=4,wdn=8,PMr=xMr()==="coarse",m_=[],qV=!1,AM=new Map,mCe=new Map,Ate=new Set;Stt=new AbortController;WMr=100,Pte={getItem:t=>(adn(Pte),Pte.getItem(t)),setItem:(t,e)=>{adn(Pte),Pte.setItem(t,e)}},cdn={};Ett=(0,Jt.forwardRef)((t,e)=>(0,Jt.createElement)(Pdn,{...t,forwardedRef:e}));Pdn.displayName="PanelGroup";Ett.displayName="forwardRef(PanelGroup)";Mtt.displayName="PanelResizeHandle"});var Mte,Edn,Ott,Mdn,Odn=b(()=>{Mte=L(B());Re();Adn();De();Edn=({className:t,...e})=>Mte.createElement(Ett,{className:J("tw-flex tw-size-full data-[panel-group-direction=vertical]:tw-flex-col",t),...e}),Ott=Ttt,Mdn=({withHandle:t,className:e,...n})=>Mte.createElement(Mtt,{className:J("tw-relative tw-flex tw-w-px tw-items-center tw-justify-center tw-bg-[var(--background-modifier-border)] after:tw-absolute after:tw-inset-y-0 after:tw-left-1/2 after:tw-w-1 after:tw--translate-x-1/2 focus-visible:tw-outline-none focus-visible:tw-ring-1 focus-visible:tw-ring-ring focus-visible:tw-ring-offset-1 data-[panel-group-direction=vertical]:tw-h-px data-[panel-group-direction=vertical]:tw-w-full data-[panel-group-direction=vertical]:after:tw-left-0 data-[panel-group-direction=vertical]:after:tw-h-1 data-[panel-group-direction=vertical]:after:tw-w-full data-[panel-group-direction=vertical]:after:tw--translate-y-1/2 data-[panel-group-direction=vertical]:after:tw-translate-x-0 [&[data-panel-group-direction=vertical]>div]:tw-rotate-90",e),...n},t&&Mte.createElement("div",{className:"tw-z-sidedock tw-flex tw-h-4 tw-w-3 tw-items-center tw-justify-center tw-rounded-sm tw-border tw-border-solid tw-border-border"},Mte.createElement(FC,{className:"tw-size-2.5"})))});function Rdn({onSubmit:t,placeholder:e="Enter a URL\u2026",autoFocus:n}){let[r,o]=(0,Ndn.useState)(""),i=r.trim().length>0,s=c=>{t(c),o("")},a=async()=>{if(i){s(r);return}try{let c=await navigator.clipboard.readText();c&&s(c)}catch{}};return KV.createElement("div",{className:"tw-flex tw-gap-2"},KV.createElement(Ir,{autoFocus:n,value:r,onChange:c=>o(c.target.value),onPaste:c=>{let u=c.clipboardData.getData("text"),d=xte(u);d.length!==0&&(d.length===1&&i||(c.preventDefault(),s(u)))},onKeyDown:c=>{c.key==="Enter"&&i&&(c.preventDefault(),a())},placeholder:e,className:"tw-min-w-0 tw-flex-1"}),KV.createElement(oe,{variant:i?"default":"ghost2",size:"sm",className:J("tw-h-9 tw-shrink-0 tw-gap-1.5 tw-whitespace-nowrap tw-rounded-md tw-px-3 tw-font-semibold",!i&&"!tw-border !tw-border-solid !tw-border-border !tw-bg-primary !tw-text-muted !tw-shadow-none hover:!tw-bg-interactive-hover hover:!tw-text-normal"),title:i?"Add to list":"Paste from clipboard",onClick:()=>void a()},i?KV.createElement(zs,{className:"tw-size-3.5"}):KV.createElement(aG,{className:"tw-size-3.5"}),i?"Add":"Paste"))}var KV,Ndn,Ldn=b(()=>{yt();hl();De();HS();Re();KV=L(B()),Ndn=L(B())});function I0({type:t,className:e}){return t==="youtube"?Ntt.createElement(q_,{className:J("tw-text-error",e)}):Ntt.createElement(Xo,{className:J("tw-text-context-manager-cyan",e)})}var Ntt,Ote=b(()=>{De();Re();Ntt=L(B())});function gCe({existingUrls:t,onAdd:e,container:n,trigger:r}){let[o,i]=(0,Mi.useState)(!1),[s,a]=(0,Mi.useState)([]),l=(0,Mi.useMemo)(()=>new Set(t.map(ZSe)),[t]),c=s.reduce((m,h)=>h.duplicate?m:m+1,0),u=s.length-c,d=m=>{let h=xte(m);h.length!==0&&a(g=>{let v=new Set(g.map(w=>w.item.url)),y=[];for(let w of h){let _=dtt(w);v.has(_.url)||(v.add(_.url),y.push({item:_,duplicate:l.has(_.url)}))}return y.length>0?[...g,...y]:g})},f=()=>{a([]),i(!1)},p=()=>{let m=s.filter(h=>!h.duplicate).map(h=>h.item);m.length!==0&&(e(m),f())};return Mi.default.createElement(nc,{open:o,onOpenChange:m=>{i(m),m||a([])}},Mi.default.createElement(Ku,{asChild:!0},r??Mi.default.createElement(oe,{variant:"ghost2",size:"sm",className:"tw-h-auto tw-gap-1 tw-px-0 tw-text-context-manager-cyan hover:tw-text-context-manager-cyan"},Mi.default.createElement(zs,{className:"tw-size-3.5"}),"URL")),Mi.default.createElement(Cl,{align:"start",container:n,className:"tw-w-80 tw-p-0"},Mi.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2 tw-border-x-[0px] tw-border-b tw-border-t-[0px] tw-border-solid tw-border-border tw-px-3.5 tw-pb-2.5 tw-pt-3 tw-text-sm tw-font-semibold tw-text-normal"},Mi.default.createElement(MT,{className:"tw-size-3.5"}),"Add URLs",Mi.default.createElement(oe,{variant:"ghost2",size:"icon","aria-label":"Close",onClick:f,className:"tw-ml-auto"},Mi.default.createElement(pn,{className:"tw-size-3.5"}))),Mi.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2 tw-px-3.5 tw-py-3"},Mi.default.createElement(Rdn,{autoFocus:!0,onSubmit:d,placeholder:"Enter a URL\u2026"}),Mi.default.createElement("div",{className:"tw-flex tw-h-28 tw-flex-col tw-gap-1.5 tw-overflow-y-auto"},s.length===0?Mi.default.createElement("div",{className:"tw-flex tw-flex-1 tw-flex-col tw-items-center tw-justify-center tw-gap-1 tw-text-center tw-text-xs tw-text-faint"},Mi.default.createElement(MT,{className:"tw-mb-1 tw-size-5"}),"No URLs queued yet \u2014 type or paste above"):s.map(({item:m,duplicate:h})=>Mi.default.createElement("div",{key:m.id,className:J("tw-flex tw-items-center tw-gap-2 tw-rounded-lg tw-border tw-border-solid tw-px-2.5 tw-py-1.5 tw-text-sm",h?"tw-border-error tw-bg-error/10":"tw-border-border")},Mi.default.createElement(I0,{type:m.type,className:"tw-size-3.5 tw-shrink-0"}),Mi.default.createElement("span",{className:J("tw-min-w-0 tw-flex-1 tw-truncate",h?"tw-text-error":"tw-text-normal"),title:m.url},m.url.replace(/^https?:\/\//,"")),h&&Mi.default.createElement("span",{className:"tw-shrink-0 tw-rounded tw-border tw-border-solid tw-border-error tw-px-1 tw-font-mono tw-text-ui-smaller tw-text-error"},"Exists"),Mi.default.createElement(oe,{variant:"ghost2",size:"icon","aria-label":"Remove",className:"tw-shrink-0",onClick:()=>a(g=>g.filter(v=>v.item.id!==m.id))},Mi.default.createElement(pn,{className:"tw-size-3.5"})))))),Mi.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2 tw-border-x-[0px] tw-border-b-[0px] tw-border-t tw-border-solid tw-border-border tw-px-3.5 tw-py-2.5"},Mi.default.createElement("span",{className:"tw-text-xs tw-text-faint"},c," to add",u>0&&` \xB7 ${u} exist`),Mi.default.createElement("div",{className:"tw-ml-auto tw-flex tw-gap-2"},Mi.default.createElement(oe,{variant:"ghost",size:"sm",onClick:f},"Cancel"),Mi.default.createElement(oe,{size:"sm",disabled:c===0,onClick:p},"Add",c>0?` ${c}`:"")))))}var Mi,Rtt=b(()=>{yt();Gb();Ldn();Ote();De();HS();Re();Mi=L(B())});function Fdn({activeSection:t,webCount:e,youtubeCount:n,onSelect:r,existingUrls:o,onAddUrls:i,popoverContainer:s}){return as.default.createElement("div",null,as.default.createElement("div",{className:J("tw-mb-1 tw-flex tw-cursor-pointer tw-items-center tw-rounded-md tw-p-2 hover:tw-bg-secondary/50",t==="links"&&"tw-bg-secondary"),onClick:()=>r("links")},as.default.createElement(MT,{className:"tw-mr-2 tw-size-4 tw-text-context-manager-cyan"}),as.default.createElement("h3",{className:"tw-text-sm tw-font-semibold tw-text-context-manager-cyan"},"Links"),as.default.createElement(gCe,{existingUrls:o,onAdd:i,container:s,trigger:as.default.createElement(oe,{variant:"ghost",size:"fit",className:"tw-ml-auto tw-text-muted hover:tw-bg-secondary",title:"Add link",onClick:a=>a.stopPropagation()},as.default.createElement(Sh,{className:"tw-size-4 tw-text-context-manager-cyan"}))})),as.default.createElement($dn,{Icon:Xo,label:"Web",count:e,active:t==="web",onClick:()=>r("web")}),as.default.createElement($dn,{Icon:q_,label:"YouTube",count:n,active:t==="youtube",onClick:()=>r("youtube")}))}function $dn({Icon:t,label:e,count:n,active:r,onClick:o}){return as.default.createElement("div",{className:J("tw-flex tw-cursor-pointer tw-items-center tw-gap-2 tw-rounded-md tw-py-1.5 tw-pl-6 tw-pr-2 tw-text-sm hover:tw-bg-secondary/50",r&&"tw-bg-secondary tw-text-normal"),onClick:o},as.default.createElement(t,{className:"tw-size-4 tw-text-context-manager-cyan"}),as.default.createElement("span",{className:"tw-flex-1"},e),as.default.createElement("span",{className:"tw-text-xs tw-text-faint"},n))}function Udn({app:t,urlItems:e,filter:n,agentProcessingByKey:r,onRemove:o}){let i=u=>{zV(t,u)},s=e.filter(u=>u.type==="web"),a=e.filter(u=>u.type==="youtube"),l=n==="links"||n==="web",c=n==="links"||n==="youtube";return as.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},l&&s.length>0&&as.default.createElement(Ddn,{label:"Web",type:"web",items:s,agentProcessingByKey:r,onRemove:o,onPreview:i}),c&&a.length>0&&as.default.createElement(Ddn,{label:"YouTube",type:"youtube",items:a,agentProcessingByKey:r,onRemove:o,onPreview:i}),(l&&s.length>0||c&&a.length>0)===!1&&as.default.createElement("div",{className:"tw-py-6 tw-text-center tw-text-sm tw-text-muted"},"No links yet. Use the + next to Links in the sidebar to add one."))}function Ddn({label:t,type:e,items:n,agentProcessingByKey:r,onRemove:o,onPreview:i}){return as.default.createElement("div",{className:"tw-mb-2"},as.default.createElement("div",{className:"tw-mb-1.5 tw-mt-2 tw-flex tw-items-center tw-gap-1.5 tw-text-xs tw-font-bold tw-text-faint"},as.default.createElement(I0,{type:e,className:"tw-size-3.5"}),t," ",as.default.createElement("span",{className:"tw-font-medium"},"(",n.length,")")),n.map(s=>{let a=r.get(_te(e,s.url)),l=a?.status==="ready";return as.default.createElement("div",{key:s.id,className:"tw-group tw-mb-1.5 tw-flex tw-items-center tw-gap-2.5 tw-rounded-lg tw-border tw-border-solid tw-border-border tw-px-3 tw-py-2"},as.default.createElement(I0,{type:s.type,className:"tw-size-4 tw-shrink-0"}),as.default.createElement(si,{className:"tw-min-w-0 tw-flex-1 tw-text-sm",tooltipContent:s.url},s.url.replace(/^https?:\/\//,"")),l&&a&&as.default.createElement(us,{className:"tw-size-4 tw-shrink-0 tw-cursor-pointer tw-text-faint tw-opacity-0 hover:tw-text-normal group-hover:tw-opacity-100",onClick:()=>i(a),"aria-label":"View converted content"}),a&&as.default.createElement(BV,{item:a,revealReadyOnHover:!0}),as.default.createElement(pn,{className:"tw-size-4 tw-shrink-0 tw-cursor-pointer tw-text-faint tw-opacity-0 hover:tw-text-error group-hover:tw-opacity-100",onClick:()=>o(s.id)}))}))}var as,jdn=b(()=>{GSe();Rtt();Ote();kS();yt();De();nCe();Re();as=L(B())});function Bdn(t){let[e,n]=(0,T0.useState)(t.contextSource?.webUrls??""),[r,o]=(0,T0.useState)(t.contextSource?.youtubeUrls??""),i=(0,T0.useMemo)(()=>p_(e,r),[e,r]),s=(0,T0.useCallback)(c=>{let u=Ste(c);n(u.webUrls),o(u.youtubeUrls)},[]),a=(0,T0.useCallback)(c=>{let u=Uun(c,i.map(d=>d.url));u.length>0&&s([...i,...u])},[i,s]),l=(0,T0.useCallback)(c=>{s(i.filter(u=>u.id!==c))},[i,s]);return{webUrls:e,youtubeUrls:r,urlItems:i,addFromText:a,removeUrl:l}}var T0,zdn=b(()=>{HS();T0=L(B())});function KMr({extension:t,size:e="tw-size-4"}){let n=t.toLowerCase().replace("*.","");return["jpg","jpeg","png","gif","svg"].includes(n)?$e.default.createElement(oN,{className:`tw-text-context-manager-blue ${e}`}):["mp3","wav","ogg"].includes(n)?$e.default.createElement(pG,{className:`tw-text-context-manager-purple ${e}`}):["mp4","mov","avi"].includes(n)?$e.default.createElement(iN,{className:`tw-text-context-manager-orange ${e}`}):["md","txt","mdx","markdown"].includes(n)?$e.default.createElement(Jo,{className:`${e}`}):$e.default.createElement(Jo,{className:`tw-text-faint ${e}`})}function GMr({item:t,viewMode:e,agentProcessingItem:n,onDelete:r,onOpenCached:o}){let i=t.id.split(".").pop()||"",s=t.isIgnored?zs:pn,a=o&&n?.status==="ready"?$e.default.createElement(oe,{variant:"ghost2",size:"icon",className:"tw-hidden tw-size-5 group-hover:tw-block",onClick:l=>{l.stopPropagation(),o()},title:"View Parsed Content"},$e.default.createElement(us,{className:"tw-size-4"})):null;return $e.default.createElement("div",{className:"tw-group tw-flex tw-cursor-pointer tw-items-center tw-rounded-lg tw-border tw-border-solid tw-border-border tw-p-2 tw-transition-shadow hover:tw-shadow-md"},$e.default.createElement("div",{className:"tw-mr-2 tw-shrink-0"},$e.default.createElement(KMr,{extension:i,size:"tw-size-8"})),$e.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-flex-col"},$e.default.createElement(si,{className:"tw-flex-1 tw-text-sm tw-font-medium"},t.isIgnored&&$e.default.createElement("span",{className:"tw-text-sm tw-text-error"}," (Ignored files)"),t.name),t.id&&$e.default.createElement(si,{className:"tw-flex-1 tw-text-xs tw-text-faint"},t.id)),$e.default.createElement("div",{className:"tw-ml-auto tw-flex tw-min-w-[24px] tw-items-center tw-justify-end tw-gap-2"},a,n&&$e.default.createElement(BV,{item:n,revealReadyOnHover:!0}),$e.default.createElement(s,{className:"tw-hidden tw-size-4 tw-shrink-0 tw-text-muted hover:tw-text-warning group-hover:tw-block group-hover:tw-flex-none",onClick:l=>r(l,t)})))}function Hdn({item:t,onClick:e}){let n,r;switch(t.type){case"tag":n=LT,r="tw-text-context-manager-orange";break;case"property":n=OT,r="tw-text-context-manager-purple";break;case"folder":n=Fl,r="tw-text-context-manager-yellow";break;case"files":n=Jo,r="tw-text-context-manager-blue";break;case"ignoreFiles":n=pn,r="tw-text-context-manager-red";break}return $e.default.createElement("div",{className:"tw-group tw-flex tw-cursor-pointer tw-items-center tw-rounded-lg tw-border tw-border-solid tw-border-border tw-p-2 tw-transition-shadow hover:tw-shadow-md",onClick:()=>e(t)},$e.default.createElement("div",{className:"tw-mr-2 tw-shrink-0"},t.type==="web"||t.type==="youtube"?$e.default.createElement(I0,{type:t.type,className:"tw-size-6"}):n&&$e.default.createElement(n,{className:`tw-size-6 ${r}`})),$e.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-flex-col"},$e.default.createElement(si,{className:"tw-flex-1 tw-text-sm tw-font-medium"},t.type==="tag"&&$e.default.createElement("span",{className:"tw-mr-2 tw-text-faint"},"#"),t.name),$e.default.createElement(si,{className:"tw-flex-1 tw-text-xs tw-text-faint"},t.count," ",t.count===1?"item":"items")))}function $tt(t){return"type"in t}function ZMr({initialProject:t,onSave:e,onCancel:n,app:r,popoverContainer:o}){let i=h_.Platform.isMobile,s=Bdn(t),{items:a}=eCe(r,t,t.contextSource),l=(0,$e.useMemo)(()=>$un(a),[a]),{inclusions:c,exclusions:u}=(0,$e.useMemo)(()=>Fi({inclusions:t?.contextSource.inclusions,exclusions:t?.contextSource.exclusions,isProject:!0}),[t.contextSource]),d=(0,$e.useMemo)(()=>r.vault.getFiles(),[r.vault]),f=(0,$e.useCallback)((D,G,ce)=>{let Z=D.filter(qe=>ii(r,qe,G,ce,!0)),te=(qe,Ae,Xt,Ve)=>{Ae&&Ae.forEach(Ee=>{let st={[Xt]:[Ee]};ii(r,qe,st,null,!0)&&!Ve[Ee].some(Ne=>Ne.id===qe.path)&&Ve[Ee].push({id:qe.path,name:qe.basename})})},fe={},de={},ye={},Te={},Be=[];return(G?.tagPatterns??[]).forEach(qe=>{fe[qe]=[]}),(G?.folderPatterns??[]).forEach(qe=>{de[qe]=[]}),(G?.extensionPatterns??[]).forEach(qe=>{ye[qe]=[]}),(G?.propertyPatterns??[]).forEach(qe=>{Te[qe]=[]}),Z.forEach(qe=>{te(qe,G?.tagPatterns,"tagPatterns",fe),te(qe,G?.folderPatterns,"folderPatterns",de),te(qe,G?.extensionPatterns,"extensionPatterns",ye),te(qe,G?.propertyPatterns,"propertyPatterns",Te),G?.notePatterns&&ii(r,qe,{notePatterns:G.notePatterns},null,!0)&&!Be.some(Ae=>Ae.id===qe.path)&&Be.push({id:qe.path,name:qe.basename})}),{tags:fe,folders:de,extensions:ye,properties:Te,notes:Be}},[r]),[p,m]=(0,$e.useState)(()=>f(d,c,u)),[h,g]=(0,$e.useState)(()=>{let D=d.filter(G=>u&&ii(r,G,u,null,!0));return{files:new Set(D)}}),v=(0,$e.useRef)(p),y=(0,$e.useRef)(h),[w,_]=(0,$e.useState)(""),[S,I]=(0,$e.useState)(null),[C,k]=(0,$e.useState)(null),T=S==="links"||S==="web"||S==="youtube",P=(0,$e.useCallback)(D=>{if(D.isIgnored||S==="ignoreFiles")return{};let G=l.get(_te("file",D.id));return{agentProcessingItem:G,onOpenCached:G?()=>void zV(r,G):void 0}},[S,l,r]),E=(0,$e.useCallback)((D,G)=>{let ce=Object.keys(D.tags),Z=Object.keys(D.folders),te=Object.keys(D.extensions),fe=Object.keys(D.properties),de=D.notes.map(ye=>{let Te=r.vault.getAbstractFileByPath(ye.id);if(Te instanceof h_.TFile)return YH(Te)}).filter(Boolean);return pE({tagPatterns:ce,folderPatterns:Z,extensionPatterns:te,propertyPatterns:fe,notePatterns:de})},[r.vault]),O=(0,$e.useCallback)(D=>{let G=new Array(...D.files).map(ce=>YH(ce));return pE({notePatterns:G})||""},[]);(0,$e.useEffect)(()=>{v.current=p,y.current=h},[p,h]);let $=(0,$e.useMemo)(()=>{let D=[],G=(Z,te)=>{te.forEach(fe=>{Z.some(de=>de.id===fe.id)||Z.push({id:fe.id,name:fe.name})})};return[p.tags,p.folders,p.extensions,p.properties,{notes:p.notes}].forEach(Z=>{Object.values(Z).forEach(te=>{G(D,te)})}),D},[p]),U=(0,$e.useCallback)(D=>{let G=[],ce=[],Z=[];return D.split(",").map(fe=>fe.trim()).filter(fe=>fe).forEach(fe=>{fe.startsWith("#")?G.push(fe.substring(1)):fe.startsWith(".")||fe.startsWith("*.")?Z.push(fe.replace("*","")):ce.push(fe)}),{tags:G,titles:ce,extensions:Z}},[]),V=(0,$e.useCallback)(D=>[...D].sort((G,ce)=>G.name.toLowerCase().localeCompare(ce.name.toLowerCase())),[]),K=(0,$e.useMemo)(()=>{if(w){let D=U(w);return $.filter(G=>{let ce=r.vault.getAbstractFileByPath(G.id);if(!(ce instanceof h_.TFile))return!1;let Z=ce.extension==="md",te=D.tags.length>0&&Z&&D.tags.some(Te=>F_(r,ce).some(qe=>(qe.startsWith("#")?qe.substring(1):qe).toLowerCase().includes(Te.toLowerCase()))),fe=D.titles.length>0&&D.titles.some(Te=>ce.basename.toLowerCase().includes(Te.toLowerCase())),de=D.extensions.length>0&&D.extensions.some(Te=>`.${ce.extension}`.toLowerCase()===Te.toLowerCase());return D.tags.length>0||D.titles.length>0||D.extensions.length>0?te||fe||de:!1}).map(G=>({id:G.id,name:G.name}))}if(S==="tags"&&C){let D=p.tags[C];return D||[]}if(S==="tags")return V(Object.entries(p.tags).map(([D,G])=>({id:`tag:${D}`,name:D.slice(1),type:"tag",originalId:D,count:G.length})));if(S==="folders"&&C){let D=p.folders[C];return D||[]}if(S==="folders")return V(Object.entries(p.folders).map(([D,G])=>({id:`folder:${D}`,name:D,type:"folder",originalId:D,count:G.length})));if(S==="files")return p.notes;if(S==="extensions"&&C){let D=p.extensions[C];return D||[]}if(S==="properties"&&C){let D=p.properties[C];return D||[]}if(S==="properties")return V(Object.entries(p.properties).map(([D,G])=>({id:`property:${D}`,name:PM({pattern:D,type:"property"}),type:"property",originalId:D,count:G.length})));if(S==="ignoreFiles")return Array.from(h.files).map(D=>({id:D.path,name:D.basename}));if(!S){let D=V(Object.entries(p.tags).map(([Te,Be])=>({id:`tag:${Te}`,name:Te.slice(1),type:"tag",originalId:Te,count:Be.length}))),G=V(Object.entries(p.folders).map(([Te,Be])=>({id:`folder:${Te}`,name:Te,type:"folder",originalId:Te,count:Be.length}))),ce=V(Object.entries(p.properties).map(([Te,Be])=>({id:`property:${Te}`,name:PM({pattern:Te,type:"property"}),type:"property",originalId:Te,count:Be.length}))),Z=p.notes.length>0?[{id:"files:all",name:"Files",type:"files",count:p.notes.length}]:[],te=h.files.size>0?[{id:"ignoreFiles:all",name:"Ignore Files",type:"ignoreFiles",count:h.files.size}]:[],fe=s.urlItems.filter(Te=>Te.type==="web").length,de=s.urlItems.filter(Te=>Te.type==="youtube").length;return[...[...fe>0?[{id:"web:all",name:"Web",type:"web",count:fe}]:[],...de>0?[{id:"youtube:all",name:"YouTube",type:"youtube",count:de}]:[]],...D,...ce,...G,...Z,...te]}return[]},[r,w,S,C,U,$,p.tags,p.folders,p.notes,p.extensions,p.properties,h.files,V,s.urlItems]),se=(0,$e.useCallback)((D,G)=>Object.entries(D).sort(([ce],[Z])=>ce.localeCompare(Z)).map(([ce,Z])=>({id:ce,name:G?G(ce):ce,count:Z.length})),[]),le=(0,$e.useCallback)((D,G,ce)=>{let Z=de=>d.filter(ye=>ii(r,ye,de,null,!0)).map(ye=>({id:ye.path,name:ye.basename})),te=[...y.current.files],fe=Z(ce).map(de=>({...de,isIgnored:te.some(ye=>ye.path===de.id)}));m(de=>({...de,[D]:{...de[D],[G]:fe}}))},[r,d]),Q=(0,$e.useCallback)((D,G)=>{let ce={tags:{...D.tags},folders:{...D.folders},extensions:{...D.extensions},properties:{...D.properties},notes:[...D.notes]},Z=te=>{Object.keys(te).forEach(fe=>{te[fe]=te[fe].filter(de=>de.id!==G)})};return Z(ce.tags),Z(ce.folders),Z(ce.extensions),Z(ce.properties),ce.notes=ce.notes.filter(te=>te.id!==G),ce},[]),ne=(0,$e.useCallback)((D,G=null,ce=!0)=>{I(D),k(G),ce&&_("")},[]),ee=(0,$e.useMemo)(()=>{let D=G=>(ce,Z)=>{ce.stopPropagation(),m(te=>{let fe={...te[G]};return delete fe[Z.id],{...te,[G]:fe}})};return{delete:{tag:D("tags"),folder:D("folders"),extension:D("extensions"),property:D("properties")},add:{tag:()=>{new sCe(r,G=>{let ce=P9e(G);le("tags",ce,{tagPatterns:[ce]})}).open()},property:()=>{new iCe(r,G=>{le("properties",G,{propertyPatterns:[G]})}).open()},folder:()=>{new qSe(r,G=>{le("folders",G,{folderPatterns:[G]})}).open()},file:()=>{new kte({app:r,onFileSelect:G=>{p.notes.find(Z=>Z.id===G.path)||(g(Z=>{let te=new Set(Z.files);return te.delete(G),{...Z,files:te}}),m(Z=>({...Z,notes:[...Z.notes,{id:G.path,name:G.basename}]})))},excludeFilePaths:[],titleOnly:!1}).open()},extension:()=>{new h_.Notice("Adding extension is temporarily not supported.")},ignoreFile:()=>{new kte({app:r,onFileSelect:G=>{h.files.has(G)||(g(Z=>{let te=new Set(Z.files);return te.add(G),{...Z,files:te}}),m(Z=>Q(Z,G.path)))},excludeFilePaths:[],titleOnly:!1}).open()}},click:{tag:G=>{ne("tags",G)},property:G=>{ne("properties",G)},folder:G=>{ne("folders",G)},extension:G=>{ne("extensions",G)},files:()=>{ne("files")},ignoreFiles:()=>{ne("ignoreFiles")}}}},[r,p.notes,h.files,le,Q,ne]),ae=(0,$e.useCallback)(D=>{D.type==="tag"&&D.originalId?ee.click.tag(D.originalId):D.type==="property"&&D.originalId?ee.click.property(D.originalId):D.type==="folder"&&D.originalId?ee.click.folder(D.originalId):D.type==="files"?ee.click.files():D.type==="ignoreFiles"?ee.click.ignoreFiles():(D.type==="web"||D.type==="youtube")&&ne(D.type)},[ee,ne]),q=()=>w?`Search Results for: "${w}"`:S==="links"?"Links":S==="web"?"Web":S==="youtube"?"YouTube":S==="tags"&&C?`Tag: ${C}`:S==="tags"?"Tags":S==="properties"&&C?`Property: ${PM({pattern:C,type:"property"})}`:S==="properties"?"Properties":S==="folders"&&C?`Folder: ${C}`:S==="folders"?"Folders":S==="files"?"Files":S==="extensions"&&C?`Extension: ${C}`:S==="ignoreFiles"?"Ignore Files":"All Categories",F=!w&&!C&&(S==="tags"||S==="folders"||S==="properties"),z=(D,G)=>{D.stopPropagation();let ce=r.vault.getAbstractFileByPath(G.id);ce instanceof h_.TFile&&(g(Z=>{let te=new Set(Z.files);return te.add(ce),{...Z,files:te}}),m(Z=>Q(Z,G.id)))},N=(0,$e.useCallback)(()=>{let D=E(v.current,d),G=O(y.current),{inclusions:ce,exclusions:Z}=Fi({inclusions:D,exclusions:G,isProject:!0}),te=f(d,ce,Z);m(te)},[d,O,E,f]),R=(D,G)=>{D.stopPropagation();let ce=r.vault.getAbstractFileByPath(G.id);ce instanceof h_.TFile&&(g(Z=>{let te=new Set(Z.files);return te.delete(ce),{...Z,files:te}}),N())},X=()=>{let D=E(p,d),G=O(h);e({...t,contextSource:{...t.contextSource,inclusions:D,exclusions:G,webUrls:s.webUrls,youtubeUrls:s.youtubeUrls}})};return $e.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-col"},$e.default.createElement(Edn,{direction:"horizontal",className:"tw-flex-1"},$e.default.createElement(Ott,{defaultSize:i?35:30,minSize:20,maxSize:40},$e.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-col"},$e.default.createElement("div",{className:"tw-border-b tw-p-4"},$e.default.createElement("h2",{className:"tw-text-lg tw-font-semibold"},"File Context")),$e.default.createElement(Ym,{className:"tw-max-h-[500px] tw-flex-1"},$e.default.createElement("div",{className:"tw-space-y-6 tw-p-4"},$e.default.createElement(Fdn,{activeSection:S,webCount:s.urlItems.filter(D=>D.type==="web").length,youtubeCount:s.urlItems.filter(D=>D.type==="youtube").length,onSelect:D=>ne(D),existingUrls:s.urlItems.map(D=>D.url),onAddUrls:D=>s.addFromText(D.map(G=>G.url).join(`
`)),popoverContainer:o}),$e.default.createElement(Lv,null),$e.default.createElement(Ltt,{title:"Tags",IconComponent:LT,iconColorClassName:"tw-text-context-manager-orange",items:se(p.tags,D=>D.slice(1)),activeItem:C,activeSection:S,sectionType:"tags",renderIcon:D=>$e.default.createElement("span",{className:"tw-mr-2 tw-text-faint"},"#"),onItemClick:ee.click.tag,onAddClick:ee.add.tag,onDeleteItem:(D,G)=>ee.delete.tag(D,G),tooltip:"must be in note property",onSectionClick:()=>ne("tags",null)}),$e.default.createElement(Lv,null),$e.default.createElement(Ltt,{title:"Properties",IconComponent:OT,iconColorClassName:"tw-text-context-manager-purple",items:se(p.properties,D=>PM({pattern:D,type:"property"})),activeItem:C,activeSection:S,sectionType:"properties",onItemClick:ee.click.property,onAddClick:ee.add.property,onDeleteItem:(D,G)=>ee.delete.property(D,G),tooltip:"Include notes by a frontmatter property, e.g. Topics: Physics",onSectionClick:()=>ne("properties",null)}),$e.default.createElement(Lv,null),$e.default.createElement(Ltt,{title:"Folders",IconComponent:Fl,iconColorClassName:"tw-text-context-manager-yellow",items:se(p.folders),activeItem:C,activeSection:S,sectionType:"folders",onItemClick:ee.click.folder,onAddClick:ee.add.folder,onDeleteItem:(D,G)=>ee.delete.folder(D,G),onSectionClick:()=>ne("folders",null)}),$e.default.createElement(Lv,null),$e.default.createElement("div",null,$e.default.createElement(Dtt,{IconComponent:Jo,title:"Files",iconColorClassName:"tw-text-context-manager-blue",onAddClick:ee.add.file}),$e.default.createElement("div",{className:J("tw-cursor-pointer tw-rounded-md tw-p-2 tw-text-sm hover:tw-bg-secondary/50",S==="files"&&"tw-bg-secondary tw-text-normal"),onClick:ee.click.files},"Files (",p.notes.length,")")),$e.default.createElement(Lv,null),$e.default.createElement("div",null,$e.default.createElement(Dtt,{IconComponent:pn,title:"Ignore Files",iconColorClassName:"tw-text-context-manager-red",onAddClick:ee.add.ignoreFile}),$e.default.createElement("div",{className:J("tw-cursor-pointer tw-rounded-md tw-p-2 tw-text-sm hover:tw-bg-secondary/50",S==="ignoreFiles"&&"tw-bg-secondary tw-text-normal"),onClick:ee.click.ignoreFiles},"Files (",h.files.size,")")))))),$e.default.createElement(Mdn,{withHandle:!0}),$e.default.createElement(Ott,{defaultSize:i?65:70},$e.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-col"},$e.default.createElement("div",{className:"tw-border-b tw-p-4"},$e.default.createElement(rf,{placeholder:"Custom search: title, #tag1, .jpg",value:w,onChange:D=>{_(D),D&&ne("search",null,!1)}})),$e.default.createElement("div",{className:"tw-p-4"},$e.default.createElement("h3",{className:"tw-text-lg tw-font-medium tw-text-muted"},q())),$e.default.createElement(Ym,{className:"tw-max-h-[400px] tw-flex-1 tw-p-4 tw-pt-0"},T?$e.default.createElement(Udn,{app:r,urlItems:s.urlItems,filter:S,agentProcessingByKey:l,onRemove:s.removeUrl}):K.length===0?$e.default.createElement("div",{className:"tw-mt-10 tw-text-center tw-text-muted"},S?"No items found.":"No categories found. Add tags, folders, or files using the sidebar."):$e.default.createElement("div",{className:"tw-space-y-2",style:{display:"block"}},S||w?V(K).map(D=>F&&$tt(D)?$e.default.createElement(Hdn,{key:D.id,item:D,onClick:ae}):$tt(D)?null:$e.default.createElement(GMr,{key:D.id,item:D,viewMode:"list",onDelete:S==="ignoreFiles"||D.isIgnored?R:z,...P(D)})).filter(Boolean):K.map(D=>$tt(D)?$e.default.createElement(Hdn,{key:D.id,item:D,onClick:ae}):null).filter(Boolean)))))),$e.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2 tw-border-t tw-p-1"},$e.default.createElement(oe,{variant:"ghost",onClick:n},"Cancel"),$e.default.createElement(oe,{onClick:X},"Save")))}var h_,$e,Dtt,Ltt,EM,yCe=b(()=>{Lun();GSe();mtt();nCe();Yun();Xun();edn();aCe();kS();yt();Odn();M$();pk();xxe();De();ha();ut();Re();h_=require("obsidian"),$e=L(B());Lh();Pa();jdn();zdn();Ote();Dtt=({IconComponent:t,title:e,iconColorClassName:n,onAddClick:r,tooltip:o,onTitleClick:i})=>$e.default.createElement("div",{className:"tw-mb-3 tw-flex tw-items-center tw-justify-between"},$e.default.createElement("div",{className:J("tw-flex tw-items-center",i&&"tw-cursor-pointer tw-rounded-md tw-px-1 tw-py-0.5 hover:tw-bg-secondary/50"),onClick:i},$e.default.createElement(t,{className:`tw-mr-2 tw-size-4 ${n}`}),$e.default.createElement("h3",{className:`tw-text-sm tw-font-semibold ${n}`},e),o&&$e.default.createElement("span",{onClick:s=>s.stopPropagation()},$e.default.createElement(rs,{buttonClassName:"tw-ml-2 tw-size-4 tw-text-muted",content:$e.default.createElement("div",{className:"tw-max-w-80"},o)}))),$e.default.createElement(oe,{variant:"ghost",size:"fit",className:"tw-text-muted hover:tw-bg-secondary",title:`Add new ${e.toLowerCase()}`,onClick:r},$e.default.createElement(Sh,{className:`tw-size-4 ${n}`}))),Ltt=({title:t,IconComponent:e,iconColorClassName:n,items:r,activeItem:o,activeSection:i,sectionType:s,renderIcon:a,onItemClick:l,onAddClick:c,onDeleteItem:u,tooltip:d,onSectionClick:f})=>$e.default.createElement("div",null,$e.default.createElement(Dtt,{IconComponent:e,title:t,iconColorClassName:n,onAddClick:c,tooltip:d,onTitleClick:f}),$e.default.createElement("div",{className:"tw-space-y-1"},r.map(p=>$e.default.createElement("div",{key:p.id,className:J("tw-group tw-flex tw-cursor-pointer tw-items-center tw-justify-between tw-rounded-md tw-p-2 hover:tw-bg-secondary/50",i===s&&o===p.id&&"tw-bg-secondary tw-text-normal"),onClick:()=>l(p.id,p.name)},$e.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-items-center"},a?a(p):$e.default.createElement(e,{className:`tw-mr-2 tw-size-4 ${n}`}),$e.default.createElement(si,{className:"tw-flex-1 tw-text-sm"},p.name)),$e.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},$e.default.createElement("span",{className:"tw-text-xs tw-text-muted group-hover:tw-hidden"},p.count||0),$e.default.createElement(pn,{className:"tw-hidden tw-size-4 tw-shrink-0 tw-text-muted hover:tw-text-warning group-hover:tw-block group-hover:tw-flex-none",onClick:m=>u(m,p)}))))));EM=class extends h_.Modal{constructor(n,r,o){super(n);this.onSave=r;this.initialProject=o}onOpen(){let{contentEl:n,modalEl:r}=this;this.root=Er(n,this.app),r.addClass("tw-min-w-[50vw]");let o=s=>{this.onSave(s),this.close()},i=()=>{this.close()};this.root.render($e.default.createElement(ZMr,{initialProject:this.initialProject,onSave:o,onCancel:i,app:this.app,popoverContainer:n}))}onClose(){this.root&&this.root.unmount()}}});function vCe({icon:t,colorClass:e,label:n,tooltip:r,onRemove:o,dim:i}){return Nte.default.createElement("span",{className:J("tw-inline-flex tw-max-w-[175px] tw-items-center tw-gap-1.5 tw-rounded-lg tw-border tw-border-solid tw-border-border tw-bg-primary tw-px-2 tw-py-1 tw-text-xs",i&&"tw-opacity-45")},Nte.default.createElement("span",{className:J("tw-flex tw-shrink-0 tw-items-center",e)},t),Nte.default.createElement(si,{className:"tw-min-w-0",tooltipContent:r??n},n),o&&Nte.default.createElement(pn,{className:"tw-size-3.5 tw-shrink-0 tw-cursor-pointer tw-text-faint hover:tw-text-normal",onClick:s=>{s.stopPropagation(),o()}}))}var Nte,Wdn=b(()=>{kS();De();Re();Nte=L(B())});function wCe({contextSource:t,onChange:e,onManage:n,popoverContainer:r,isDragging:o,droppable:i=!0,solidManageButton:s=!1,className:a,showHelperText:l=!1}){let c=t?.inclusions,u=t?.exclusions,d=(0,Fn.useMemo)(()=>Ite(c),[c]),f=(0,Fn.useMemo)(()=>Ite(u),[u]),p=(0,Fn.useMemo)(()=>p_(t?.webUrls??"",t?.youtubeUrls??""),[t?.webUrls,t?.youtubeUrls]),h=d.length+p.length+f.length===0,g=($,U)=>{e({inclusions:vtt(c,$,U)})},v=($,U)=>{e({exclusions:vtt(u,$,U)})},y=$=>{let U=p.filter(se=>se.id!==$),{webUrls:V,youtubeUrls:K}=Ste(U);e({webUrls:V,youtubeUrls:K})},w=$=>{let{webUrls:U,youtubeUrls:V}=Ste([...p,...$]);e({webUrls:U,youtubeUrls:V})},[_,S]=(0,Fn.useState)(!1),[I,C]=(0,Fn.useState)(!0),k=(0,Fn.useRef)(null);(0,Fn.useLayoutEffect)(()=>{let $=k.current;if(!$)return;let U=()=>{S($.scrollHeight>$.clientHeight+1),C($.scrollHeight-$.scrollTop-$.clientHeight<2)};if(U(),typeof ResizeObserver>"u")return;let V=new ResizeObserver(U);return V.observe($),()=>V.disconnect()},[d,p,f]);let T=_&&!I,P=Fn.default.createElement(Fn.default.Fragment,null,d.map($=>{let{Icon:U,colorClass:V}=Vdn[$.type];return Fn.default.createElement(vCe,{key:`file:${$.type}:${$.pattern}`,icon:Fn.default.createElement(U,{className:"tw-size-3.5"}),colorClass:V,label:PM($),onRemove:()=>g($.pattern,$.type)})}),p.map($=>Fn.default.createElement(vCe,{key:$.id,icon:Fn.default.createElement(I0,{type:$.type,className:"tw-size-3.5"}),colorClass:"",label:$.url.replace(/^https?:\/\//,""),tooltip:$.url,onRemove:()=>y($.id)}))),E=f.map($=>{let{Icon:U,colorClass:V}=Vdn[$.type];return Fn.default.createElement(vCe,{key:`ex:${$.type}:${$.pattern}`,icon:Fn.default.createElement(U,{className:"tw-size-3.5"}),colorClass:V,label:PM($),dim:!0,onRemove:()=>v($.pattern,$.type)})}),O=Fn.default.createElement("div",{className:J("tw-flex tw-max-h-60 tw-min-h-[200px] tw-flex-col tw-rounded-xl tw-border tw-p-3 tw-transition-colors",o?"tw-border-solid tw-border-interactive-accent":"tw-border-dashed tw-border-border",a)},Fn.default.createElement("div",{className:"tw-relative tw-flex tw-min-h-0 tw-flex-1 tw-flex-col"},h?Fn.default.createElement("div",{className:"tw-flex tw-flex-1 tw-flex-col tw-items-center tw-justify-center tw-gap-1 tw-py-8 tw-text-center"},Fn.default.createElement(UC,{className:J("tw-mb-1 tw-size-6",o?"tw-text-accent":"tw-text-muted")}),Fn.default.createElement("div",{className:J("tw-text-sm",o?"tw-font-medium tw-text-accent":"tw-text-normal")},i?o?"Drop to add to context":"Drag files / folders here":"No context yet"),Fn.default.createElement("div",{className:"tw-text-xs tw-text-muted"},i?"or use Manage to add inclusion / tag / property / URL":"Add via + URL or Manage")):Fn.default.createElement("div",{className:"tw-relative tw-flex tw-min-h-0 tw-flex-1 tw-flex-col"},Fn.default.createElement("div",{ref:k,onScroll:$=>{let U=$.currentTarget;C(U.scrollHeight-U.scrollTop-U.clientHeight<2)},className:"tw-min-h-0 tw-flex-1 tw-overflow-y-auto"},Fn.default.createElement("div",{className:"tw-flex tw-flex-wrap tw-gap-2"},P),f.length>0&&Fn.default.createElement(Fn.default.Fragment,null,(d.length>0||p.length>0)&&Fn.default.createElement("div",{className:"tw-my-2 tw-border-t tw-border-dashed tw-border-border"}),Fn.default.createElement("div",{className:"tw-flex tw-flex-wrap tw-items-center tw-gap-2"},Fn.default.createElement("span",{className:"tw-mr-1 tw-text-xs tw-font-medium tw-text-muted"},"Excluded:"),E))),T&&Fn.default.createElement("div",{className:"copilot-fade-mask-bottom tw-pointer-events-none tw-absolute tw-inset-x-0 tw-bottom-0 tw-h-8 tw-rounded-b-md"})),i&&!h&&Fn.default.createElement("div",{"aria-hidden":!o,className:J("tw-pointer-events-none tw-absolute tw-inset-0 tw-flex tw-flex-col tw-items-center tw-justify-center tw-gap-1 tw-rounded-md tw-transition-opacity tw-duration-150 motion-reduce:tw-transition-none",o?"tw-opacity-100":"tw-opacity-0")},Fn.default.createElement("div",{className:"tw-absolute tw-inset-0 tw-rounded-md tw-bg-primary tw-opacity-80"}),Fn.default.createElement("div",{className:"tw-absolute tw-inset-0 tw-rounded-md tw-bg-interactive-accent/10"}),Fn.default.createElement(UC,{className:"tw-relative tw-size-5 tw-text-accent"}),Fn.default.createElement("div",{className:"tw-relative tw-text-sm tw-font-medium tw-text-accent"},"Drop to add to context"),Fn.default.createElement("div",{className:"tw-relative tw-text-xs tw-text-muted"},"Added as an inclusion"))),Fn.default.createElement("div",{className:"tw-mt-3 tw-flex tw-flex-wrap tw-items-center tw-gap-3 tw-text-xs tw-text-faint"},Fn.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-3"},i?Fn.default.createElement("div",{className:J("tw-flex tw-min-w-0 tw-items-center tw-gap-1.5",o&&"tw-font-medium tw-text-accent")},Fn.default.createElement(UC,{className:"tw-size-3.5 tw-shrink-0"}),Fn.default.createElement("span",{className:"tw-truncate"},o?"Drop to add to context":"Drag files / folders here")):Fn.default.createElement("span",{className:"tw-truncate"},"Add a web / YouTube link"),Fn.default.createElement(gCe,{existingUrls:p.map($=>$.url),onAdd:w,container:r})),Fn.default.createElement("div",{className:"tw-ml-auto tw-flex tw-shrink-0 tw-items-center"},s?Fn.default.createElement(oe,{size:"sm",className:"tw-gap-1.5",onClick:n},Fn.default.createElement(Ih,{className:"tw-size-3.5"}),"Manage Context"):Fn.default.createElement(oe,{variant:"ghost2",size:"sm",className:"tw-h-auto tw-gap-1.5 tw-px-0 tw-text-muted hover:tw-text-normal",onClick:n},Fn.default.createElement(Ih,{className:"tw-size-3.5"}),"Manage"))));return l?Fn.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Fn.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Define patterns to include specific files, folders, tags or properties in the project context. You can also add web pages or YouTube videos."),O):O}var Fn,Vdn,Ftt=b(()=>{Rtt();Wdn();aCe();Ote();yt();De();HS();Re();Fn=L(B()),Vdn={folder:{Icon:Fl,colorClass:"tw-text-context-manager-yellow"},tag:{Icon:LT,colorClass:"tw-text-context-manager-orange"},note:{Icon:Jo,colorClass:"tw-text-context-manager-blue"},extension:{Icon:sN,colorClass:"tw-text-context-manager-green"},property:{Icon:OT,colorClass:"tw-text-context-manager-purple"}}});function YMr(t){try{let e=new URL(t);return e.protocol!=="obsidian:"||e.hostname!=="open"?null:e.searchParams.get("file")}catch{return null}}function JMr(t,e){let n=e.trim();if(!n)return null;let r=YMr(n)??n;return t.vault.getAbstractFileByPath(r)??t.vault.getAbstractFileByPath(`${r}.md`)??null}async function XMr(t,e,n){let r=mo(e);if(!r)return new VS.Notice("Project not found \u2014 could not add to context"),0;let o=r.project,{inclusions:i}=Fi({inclusions:o.contextSource?.inclusions,isProject:!0}),s=new Set(i?.folderPatterns??[]),a=new Set(i?.notePatterns??[]),l=new Set(i?.tagPatterns??[]),c=new Set(i?.extensionPatterns??[]),u=new Set(i?.propertyPatterns??[]),d=0;for(let m of n)if(m instanceof VS.TFolder)m.path&&!s.has(m.path)&&(s.add(m.path),d++);else if(m instanceof VS.TFile){let h=YH(m);a.has(h)||(a.add(h),d++)}if(d===0)return 0;let f=pE({tagPatterns:[...l],extensionPatterns:[...c],folderPatterns:[...s],notePatterns:[...a],propertyPatterns:[...u]}),p={...o,contextSource:{...o.contextSource,inclusions:f}};return await nl.getInstance(t).updateProject(e,p),d}async function QMr(t,e){let n=await Promise.all(e.map(o=>new Promise(i=>{o.getAsString(s=>i(s))}))),r=new Map;for(let o of n)for(let i of o.split(`
`)){let s=JMr(t,i);s&&r.set(s.path,s)}return[...r.values()]}function Kdn(t){let{app:e,projectId:n,dropRef:r,enabled:o=!0}=t,[i,s]=(0,bCe.useState)(!1);return(0,bCe.useEffect)(()=>{let a=r.current;if(!a||!o)return;let l=f=>{f.dataTransfer&&(f.preventDefault(),!f.dataTransfer.types.includes(qdn)&&(f.dataTransfer.dropEffect="copy",s(!0)))},c=f=>{let p=a.getBoundingClientRect(),{clientX:m,clientY:h}=f;(m<p.left||m>=p.right||h<p.top||h>=p.bottom)&&s(!1)},u=async f=>{if(!f.dataTransfer||(f.preventDefault(),f.stopPropagation(),s(!1),f.dataTransfer.types.includes(qdn)))return;let p=Array.from(f.dataTransfer.items),m=p.filter(v=>v.kind==="string"),h=p.some(v=>v.kind==="file"),g=m.length>0?await QMr(e,m):[];if(g.length===0){h&&new VS.Notice("Only vault files or folders can be added to project context");return}try{await XMr(e,n,g)>0?new VS.Notice("Added to project context"):new VS.Notice("Already in project context")}catch(v){W("[project-context] failed to add dropped inclusion",v),new VS.Notice("Could not add to project context")}},d=f=>void u(f);return a.addEventListener("dragover",l),a.addEventListener("dragleave",c),a.addEventListener("drop",d),()=>{a.removeEventListener("dragover",l),a.removeEventListener("dragleave",c),a.removeEventListener("drop",d)}},[e,n,r,o]),{isDragging:i}}var VS,bCe,qdn,Gdn=b(()=>{pe();zI();Md();ha();VS=require("obsidian"),bCe=L(B()),qdn="copilot/internal-drag"});function Ydn(t){if(!t)return Zdn;let e=Ite(t.contextSource?.inclusions),n={files:0,folders:0,tags:0,extensions:0};for(let i of e)i.type==="note"?n.files++:i.type==="folder"?n.folders++:i.type==="tag"?n.tags++:n.extensions++;let r=p_(t.contextSource?.webUrls??"",t.contextSource?.youtubeUrls??"").length,o=e.length+r;return o===0?Zdn:{totalItems:o,isEmpty:!1,...n,urls:r}}function _Ce({app:t,projectId:e,popoverContainer:n}){let r=Zwe(),o=(0,ih.useMemo)(()=>r.find(h=>h.id===e),[r,e]),i=o?.contextSource,[s,a]=(0,ih.useState)(i),l=(0,ih.useRef)(null),c=(0,ih.useRef)(!1);(0,ih.useEffect)(()=>{!l.current&&!c.current&&a(i)},[i]);let u=(0,ih.useCallback)(()=>{if(c.current)return;let h=l.current;if(!h)return;l.current=null,c.current=!0;let g=mo(e)?.project;if(!g){c.current=!1;return}nl.getInstance(t).updateProject(e,{...g,contextSource:{...g.contextSource,...h}}).catch(v=>{W("[project-context] failed to save context changes",v),l.current||a(mo(e)?.project.contextSource)}).finally(()=>{c.current=!1,l.current&&u()})},[t,e]),d=(0,ih.useCallback)(h=>{a(g=>({...g??{},...h})),l.current={...l.current??{},...h},u()},[u]),f=(0,ih.useRef)(null),{isDragging:p}=Kdn({app:t,projectId:e,dropRef:f}),m=(0,ih.useCallback)(()=>{if(!o)return;new EM(t,g=>{nl.getInstance(t).updateProject(e,g).catch(v=>W("[project-context] failed to save context changes",v))},o).open()},[t,o,e]);return o?Utt.createElement("div",{ref:f,"data-copilot-drop-zone":!0,className:J(stt,"tw-flex tw-grow tw-flex-col tw-p-2")},Utt.createElement(wCe,{contextSource:s,onChange:d,onManage:m,popoverContainer:n,isDragging:p,className:"tw-grow"})):null}var Utt,ih,Zdn,Jdn=b(()=>{ltt();yCe();aCe();Ftt();De();pe();zI();Md();HS();Utt=L(B()),ih=L(B());Gdn();Zdn=Object.freeze({totalItems:0,isEmpty:!0,files:0,folders:0,tags:0,extensions:0,urls:0})});function eOr({fileType:t}){switch(t){case"pdf":return Pt.default.createElement(Jo,{className:"tw-size-3.5 tw-text-error"});case"image":return Pt.default.createElement(oN,{className:"tw-size-3.5 tw-text-accent"});case"web":case"youtube":return Pt.default.createElement(Xo,{className:"tw-size-3.5 tw-text-accent"});case"audio":return Pt.default.createElement(iN,{className:"tw-size-3.5 tw-text-warning"});default:return Pt.default.createElement(Jo,{className:"tw-size-3.5 tw-text-muted"})}}function tOr(t){return{ready:t.filter(e=>e.status==="ready").length,processing:t.filter(e=>e.status==="processing").length,failed:t.filter(e=>e.status==="failed").length,pending:t.filter(e=>e.status==="pending").length,unsupported:t.filter(e=>e.status==="unsupported").length,total:t.length}}function Qdn(t){return[...t].sort((e,n)=>(Xdn[e.status]??99)-(Xdn[n.status]??99))}function nfn({items:t,onRetry:e,onOpenCachedItem:n,onRemoveUrl:r,defaultExpanded:o=!1,maxHeight:i,showHeader:s=!0,onRetryItem:a,skippedMarkdownCount:l=0,hideSummaryBar:c=!1}){let[u,d]=(0,Pt.useState)(o),f=tOr(t),p=Qdn(t.filter(g=>g.source==="file")),m=Qdn(t.filter(g=>g.source==="url")),h=Pt.default.createElement("div",{className:"tw-space-y-3 tw-p-3"},p.length>0&&Pt.default.createElement("div",{className:"tw-space-y-2"},Pt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5 tw-px-1"},Pt.default.createElement(gG,{className:"tw-size-3.5 tw-text-accent"}),Pt.default.createElement("span",{className:"tw-text-ui-smaller tw-font-medium tw-text-muted"},"From Files (",p.length,")")),Pt.default.createElement(efn,{maxHeight:i||"200px"},p.map(g=>Pt.default.createElement(tfn,{key:KSe(g),item:g,onRetry:e,onRetryItem:a,onOpenCached:n?()=>n(g):void 0}))),l>0&&Pt.default.createElement("div",{className:"tw-px-1 tw-text-ui-smaller tw-text-faint"},l," markdown ",l===1?"file":"files"," \u2014 no conversion needed")),m.length>0&&Pt.default.createElement("div",{className:"tw-space-y-2"},Pt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5 tw-px-1"},Pt.default.createElement(Xo,{className:"tw-size-3.5 tw-text-accent"}),Pt.default.createElement("span",{className:"tw-text-ui-smaller tw-font-medium tw-text-muted"},"From URLs (",m.length,")")),Pt.default.createElement(efn,{maxHeight:i||"200px"},m.map(g=>Pt.default.createElement(tfn,{key:KSe(g),item:g,onRetry:e,onRetryItem:a,onOpenCached:n?()=>n(g):void 0,onRemove:r?()=>r(g):void 0})))));return Pt.default.createElement("div",{className:"tw-space-y-2"},s&&Pt.default.createElement("div",{className:"tw-space-y-1"},Pt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Pt.default.createElement("h4",{className:"tw-text-sm tw-font-medium tw-text-normal"},"Content Conversion")),Pt.default.createElement("p",{className:"tw-text-ui-smaller tw-text-muted"},"Non-markdown files (PDF, images, web pages, ...) are converted to text for AI.")),t.length===0&&Pt.default.createElement("div",{className:"tw-rounded-lg tw-border tw-border-border tw-p-3 tw-bg-muted/10"},Pt.default.createElement("div",{className:"tw-text-ui-smaller tw-text-muted"},"No non-markdown files or URLs need conversion for this project.")),t.length>0&&(c?Pt.default.createElement("div",{className:"tw-rounded-lg tw-border tw-border-border"},h):Pt.default.createElement("div",{className:"tw-rounded-lg tw-border tw-border-border"},Pt.default.createElement(dx,{open:u,onOpenChange:d},Pt.default.createElement(fx,{asChild:!0},Pt.default.createElement(oe,{variant:"secondary",className:" tw-flex tw-h-auto tw-w-full tw-items-center tw-justify-between tw-rounded-lg tw-p-3 tw-text-left tw-transition-colors hover:tw-bg-modifier-hover"},Pt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Pt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},f.ready>0&&Pt.default.createElement(ei,{variant:"secondary",className:"tw-h-5 tw-gap-1 tw-bg-success tw-px-1.5 tw-text-ui-smaller tw-text-success"},Pt.default.createElement(Xf,{className:"tw-size-3"}),f.ready),f.processing>0&&Pt.default.createElement(ei,{variant:"secondary",className:"tw-h-5 tw-gap-1 tw-px-1.5 tw-text-ui-smaller"},Pt.default.createElement(Dr,{className:"tw-size-3 tw-animate-spin"}),f.processing),f.pending>0&&Pt.default.createElement(ei,{variant:"secondary",className:"tw-h-5 tw-gap-1 tw-px-1.5 tw-text-ui-smaller"},Pt.default.createElement(NC,{className:"tw-size-3"}),f.pending),f.failed>0&&Pt.default.createElement(ei,{variant:"secondary",className:"tw-h-5 tw-gap-1 tw-bg-error tw-px-1.5 tw-text-ui-smaller tw-text-error"},Pt.default.createElement(mc,{className:"tw-size-3"}),f.failed),f.unsupported>0&&Pt.default.createElement(ei,{variant:"secondary",className:"tw-h-5 tw-gap-1 tw-px-1.5 tw-text-ui-smaller tw-text-muted"},Pt.default.createElement(xh,{className:"tw-size-3"}),f.unsupported)),Pt.default.createElement("span",{className:"tw-text-ui-smaller tw-text-muted"},f.total," items")),u?Pt.default.createElement(Bs,{className:"tw-size-4 tw-text-muted"}):Pt.default.createElement(Vi,{className:"tw-size-4 tw-text-muted"}))),Pt.default.createElement(px,null,Pt.default.createElement("div",{className:"tw-border-t tw-border-border"},h))))))}function efn({maxHeight:t,children:e}){let n=(0,Pt.useRef)(null),[r,o]=(0,Pt.useState)(!1),i=(0,Pt.useCallback)(a=>{n.current=a,a&&o(a.scrollHeight>a.clientHeight)},[]),s=(0,Pt.useCallback)(()=>{let a=n.current;if(!a)return;let l=a.scrollHeight-a.scrollTop-a.clientHeight<4;o(!l)},[]);return Pt.default.createElement("div",{className:"tw-relative"},Pt.default.createElement("div",{ref:i,className:"tw-space-y-1 tw-overflow-y-auto",style:{maxHeight:t},onScroll:s},e),r&&Pt.default.createElement("div",{className:"copilot-fade-mask-bottom tw-pointer-events-none tw-absolute tw-inset-x-0 tw-bottom-0 tw-h-8 tw-rounded-b-md"}))}function tfn({item:t,onRetry:e,onRetryItem:n,onOpenCached:r,onRemove:o}){let i=t.status==="processing",s=t.status==="failed",a=r&&t.status==="ready"&&!t.contentEmpty;return Pt.default.createElement("div",{className:"tw-group tw-rounded-md tw-border tw-border-border tw-bg-primary tw-p-2.5"},Pt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Pt.default.createElement(eOr,{fileType:t.fileType}),Pt.default.createElement("div",{className:"tw-min-w-0 tw-flex-1"},Pt.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-gap-2"},Pt.default.createElement(si,{className:"tw-text-sm tw-text-normal"},t.source==="url"?t.id:t.name),Pt.default.createElement("div",{className:"tw-flex tw-shrink-0 tw-items-center tw-gap-1.5"},a&&Pt.default.createElement(oe,{variant:"ghost2",size:"icon","aria-label":"View Parsed Content",onClick:l=>{l.stopPropagation(),r()},title:"View Parsed Content",className:"tw-size-5"},Pt.default.createElement(us,{className:"tw-size-4"})),(t.status!=="ready"||t.contentEmpty)&&Pt.default.createElement("span",{className:"tw-text-ui-smaller tw-text-muted"},ctt(t.status,t.contentEmpty)),Pt.default.createElement(BV,{item:t,tooltip:!1}))))),i&&t.progress!==void 0&&Pt.default.createElement("div",{className:"tw-mt-2 tw-flex tw-items-center tw-gap-2"},Pt.default.createElement(Op,{value:t.progress,className:"tw-h-1.5 tw-flex-1"}),Pt.default.createElement("span",{className:"tw-w-8 tw-text-ui-smaller tw-text-muted"},t.progress,"%")),s&&Pt.default.createElement("div",{className:"tw-mt-2 tw-flex tw-items-center tw-justify-between"},Pt.default.createElement(si,{className:"tw-flex-1 tw-text-ui-smaller tw-text-error"},t.error||"Conversion failed"),Pt.default.createElement("div",{className:"tw-flex tw-shrink-0 tw-items-center tw-gap-1"},(e||n)&&Pt.default.createElement(oe,{variant:"ghost2",size:"icon","aria-label":"Retry",onClick:l=>{l.stopPropagation(),n?n(t):e?.(t.id)},title:"Retry",className:"tw-size-5 tw-text-muted hover:tw-text-accent"},Pt.default.createElement(kh,{className:"tw-size-3.5"})),o&&Pt.default.createElement(oe,{variant:"ghost2",size:"icon","aria-label":"Remove URL from project",onClick:l=>{l.stopPropagation(),o()},title:"Remove URL from project",className:"tw-size-5 tw-text-muted hover:tw-text-error"},Pt.default.createElement(pn,{className:"tw-size-3.5"})))))}var Pt,Xdn,rfn=b(()=>{pm();yt();Sj();d$();kS();GSe();Re();Pt=L(B());Xdn={processing:0,failed:1,pending:2,unsupported:3,ready:4}});function ofn({items:t,hasConfiguredContextSource:e,skippedMarkdownCount:n,onRetryItem:r,onRetryAll:o,onEditContext:i,onOpenCachedItem:s}){let a=t.length,l=t.filter(w=>w.status==="failed").length,c=t.filter(w=>w.status==="processing"||w.status==="pending").length,u=a-c,d=a===0?0:t.filter(w=>w.status==="ready").length/a*100,f=a===0?0:l/a*100,p=a===0?0:u/a*100,m=c>0?"processing":l>0?"failed":"success",[h,g]=(0,Jr.useState)(()=>t.some(w=>w.status==="failed")?"failed":"all"),v=h==="failed"&&l===0||h==="processing"&&c===0?"all":h,y=(0,Jr.useMemo)(()=>v==="failed"?t.filter(w=>w.status==="failed"):v==="processing"?t.filter(w=>w.status==="processing"||w.status==="pending"):t,[t,v]);if(a===0){let w=e||n>0;return Jr.default.createElement("div",{className:"tw-flex tw-w-[368px] tw-max-w-full tw-flex-col"},Jr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2 tw-border-x-[0px] tw-border-b tw-border-t-[0px] tw-border-solid tw-border-border tw-px-3.5 tw-py-3 tw-text-sm tw-font-semibold tw-text-normal"},w?Jr.default.createElement(Xf,{className:"tw-size-4 tw-text-success"}):Jr.default.createElement(UC,{className:"tw-size-4 tw-text-muted"}),w?"No conversion needed":"No context loaded"),Jr.default.createElement("div",{className:"tw-px-3.5 tw-py-6 tw-text-center tw-text-sm tw-text-muted"},w?Jr.default.createElement(Jr.default.Fragment,null,"Context sources are configured and ready to use.",n>0&&Jr.default.createElement("div",{className:"tw-mt-1 tw-text-xs tw-text-faint"},n," markdown ",n===1?"file":"files"," \u2014 no conversion needed")):"This project has no context sources yet."),Jr.default.createElement("div",{className:"tw-flex tw-justify-end tw-border-x-[0px] tw-border-b-[0px] tw-border-t tw-border-solid tw-border-border tw-px-3.5 tw-py-2.5"},Jr.default.createElement(oe,{variant:"ghost",size:"sm",className:"tw-gap-1.5 tw-text-muted",onClick:i},Jr.default.createElement(ld,{className:"tw-size-3.5"}),"Edit context")))}return Jr.default.createElement("div",{className:"tw-flex tw-min-h-0 tw-w-[368px] tw-max-w-full tw-flex-col"},Jr.default.createElement("div",{className:"tw-flex tw-shrink-0 tw-items-center tw-gap-2 tw-border-x-[0px] tw-border-b tw-border-t-[0px] tw-border-solid tw-border-border tw-px-3.5 tw-py-3 tw-text-sm tw-font-semibold tw-text-normal"},m==="success"&&Jr.default.createElement(Xf,{className:"tw-size-4 tw-text-success"}),m==="processing"&&Jr.default.createElement(Dr,{className:"tw-size-4 tw-animate-spin tw-text-accent"}),m==="failed"&&Jr.default.createElement(nm,{className:"tw-size-4 tw-text-error"}),Jr.default.createElement("span",null,m==="success"&&"Context ready",m==="processing"&&"Processing\u2026",m==="failed"&&`${l} failed`),Jr.default.createElement("span",{className:J("tw-ml-auto tw-font-mono tw-text-xs tw-font-medium",m==="processing"?"tw-text-accent":"tw-text-faint")},m==="processing"?`${u} / ${a}`:`${a} ${m==="failed"?"total":"items"}`)),Jr.default.createElement("div",{className:"tw-flex tw-h-1 tw-w-full tw-shrink-0 tw-overflow-hidden tw-bg-secondary"},m==="success"&&Jr.default.createElement("div",{className:"tw-size-full tw-bg-success"}),m==="processing"&&Jr.default.createElement("div",{className:"tw-h-full tw-bg-interactive-accent tw-transition-all",style:{width:`${p}%`}}),m==="failed"&&Jr.default.createElement(Jr.default.Fragment,null,Jr.default.createElement("div",{className:"tw-h-full tw-bg-success",style:{width:`${d}%`}}),Jr.default.createElement("div",{className:"tw-h-full tw-bg-error",style:{width:`${f}%`}}))),Jr.default.createElement("div",{className:"tw-flex tw-shrink-0 tw-gap-1.5 tw-px-3.5 tw-pb-1 tw-pt-2"},Jr.default.createElement(jtt,{label:"All",active:v==="all",onClick:()=>g("all")}),l>0&&Jr.default.createElement(jtt,{label:`Failed (${l})`,active:v==="failed",onClick:()=>g("failed")}),c>0&&Jr.default.createElement(jtt,{label:"Processing",active:v==="processing",onClick:()=>g("processing")})),Jr.default.createElement("div",{className:"tw-max-h-[280px] tw-min-h-0 tw-overflow-y-auto tw-px-3.5 tw-pb-2 tw-pt-1"},Jr.default.createElement(nfn,{items:y,hideSummaryBar:!0,showHeader:!1,onRetryItem:r,skippedMarkdownCount:n,maxHeight:"none",onOpenCachedItem:s})),Jr.default.createElement("div",{className:"tw-flex tw-shrink-0 tw-gap-1.5 tw-border-x-[0px] tw-border-b-[0px] tw-border-t tw-border-solid tw-border-border tw-px-3.5 tw-py-2.5"},Jr.default.createElement(oe,{variant:"ghost",size:"sm",className:"tw-gap-1.5 tw-text-muted",onClick:o},Jr.default.createElement(uN,{className:"tw-size-3.5"}),l>0?"Retry failed":"Retry all"),Jr.default.createElement(oe,{variant:"ghost",size:"sm",className:"tw-gap-1.5 tw-text-muted",onClick:i},Jr.default.createElement(ld,{className:"tw-size-3.5"}),"Edit context")))}function jtt({label:t,active:e,onClick:n}){return Jr.default.createElement(oe,{variant:"ghost2",size:"sm",className:J("tw-h-auto tw-rounded-full tw-bg-secondary tw-px-2.5 tw-py-0.5 tw-text-xs tw-font-medium tw-text-muted hover:tw-bg-secondary hover:tw-text-normal",e&&"tw-text-accent tw-bg-interactive-accent/10 hover:tw-text-accent hover:tw-bg-interactive-accent/10"),onClick:n},t)}var Jr,ifn=b(()=>{rfn();yt();De();Re();Jr=L(B())});function sfn(t,e,n,r){let o=r&&(n===void 0||n.phase==="done")&&(n?.retryingSources?.length??0)===0&&(n?.processingSources?.length??0)===0,i=(0,P0.useMemo)(()=>{if(!o)return nOr;let f=e.contextSource,p=p_(f?.webUrls||"",f?.youtubeUrls||"");return JSe(p,QW(t,f))},[t,e.contextSource,o]),s=(0,P0.useMemo)(()=>{let f;for(let p of i)p.kind==="file"&&(f??(f=new Set)).add(Kb("file",p.source));return f??oOr},[i]),a=(0,P0.useMemo)(()=>i.length===0?rOr:new Set(i.map(f=>`${f.kind}:${f.source}`)),[i]),l=(0,P0.useMemo)(()=>i.map(f=>`${f.kind}:${f.source}:${f.fingerprint??""}`).join(`
`),[i]),[c,u]=(0,P0.useState)(void 0);return(0,P0.useEffect)(()=>{if(!o||i.length===0)return;let f=!1;return XSe(t,e.id,s).then(p=>{if(f)return;let m=p?QSe(i,void 0,p,a).filter(h=>h.status==="failed").length:0;u({projectId:e.id,sourceKey:l,liveEntry:n,count:m})}),()=>{f=!0}},[t,e.id,i,a,l,n,o,s]),o&&i.length>0&&c?.projectId===e.id&&c.sourceKey===l&&c.liveEntry===n?c.count:0}var P0,nOr,rOr,oOr,afn=b(()=>{ptt();o6();Xwe();HS();P0=L(B());nOr=Object.freeze([]),rOr=new Set,oOr=new Set});function Btt(t,e,n){if(t==="done"||n)return"done";let r=lfn[t],o=lfn[e];return r>o?"done":r===o?"active":"pending"}function sOr(t,e,n=0){let r=Math.max(0,n);if(!t||t.phase==="idle")return r>0?{kind:"failed",headline:cfn(r),steps:[],failures:[]}:{kind:"idle",headline:"No context loaded",steps:[],failures:[]};let o=t.failedSources??[],i=o.filter(u=>!u.usedStaleSnapshot),s=t.phase==="done",a=(t.retryingSources?.length??0)>0||(t.processingSources?.length??0)>0,l=[];if(t.resolved!==void 0&&t.resolved>0&&l.push({label:`Resolve files (${t.resolved})`,status:Btt(t.phase,"resolve",!0)}),t.prefetch){let{done:u,total:d}=t.prefetch;l.push({label:`Prefetch ${d} ${d===1?"URL":"URLs"} \xB7 ${u}/${d}`,status:Btt(t.phase,"prefetch",u>=d)})}if(t.parsed){let{done:u,total:d}=t.parsed;l.push({label:`Parse ${d} ${d===1?"file":"files"} \xB7 ${u}/${d}`,status:Btt(t.phase,"parse",u>=d)})}if(!s||a){let u=(t.prefetch?.total??0)+(t.parsed?.total??0),d=(t.prefetch?.done??0)+(t.parsed?.done??0);return{kind:"working",headline:!s&&u>0?`Indexing context \xB7 ${d}/${u}`:"Indexing context",steps:l,failures:o}}let c=i.length>0?i.length:r;return c>0?{kind:"failed",headline:cfn(c),steps:l,failures:o}:!e&&o.length===0?{kind:"idle",headline:"No context loaded",steps:[],failures:[]}:{kind:"ready",headline:"Context ready",steps:l,failures:o}}function cfn(t){return t===1?"1 source failed":`${t} sources failed`}function aOr(t,e,n,r){let o=Ar(my,{store:on}),i=e===tr?void 0:o[e],s=sfn(t,n,i,e!==tr&&n.id===e),a=sOr(i,r,s),[l,c]=(0,Pl.useState)(!1),u=i?.phase==="done"&&((i.retryingSources?.length??0)>0||(i.processingSources?.length??0)>0),d=`${e}\0${i?.phase??"none"}\0${u?"retry":""}`,f=(0,Pl.useRef)(d);f.current!==d&&(f.current=d,l&&c(!1)),(0,Pl.useEffect)(()=>{if(a.kind!=="working")return;let m=window.setTimeout(()=>c(!0),iOr);return()=>window.clearTimeout(m)},[a.kind,d]);let p=a.kind==="working"&&!l&&!u;return{view:a,triggerKind:p?"idle":a.kind}}function lOr({kind:t}){return t==="failed"?jv.createElement(mc,{className:"tw-size-4 tw-text-error"}):t==="ready"?jv.createElement(yy,{className:"tw-size-4 tw-text-success"}):t==="idle"?jv.createElement(OC,{className:"tw-size-4 tw-text-faint"}):jv.createElement(Dr,{className:"tw-size-4 tw-animate-spin tw-text-loading"})}function ztt({app:t,activeProjectId:e,project:n,hasConfiguredContextSource:r,landing:o,onReindex:i,onRetryItem:s,onRefreshLanding:a,onEditContext:l}){let{triggerKind:c}=aOr(t,e,n,r),[u,d]=(0,Pl.useState)(!1),f=(0,Pl.useRef)(u),p=(0,Pl.useRef)(null),m=(0,Pl.useRef)(e);(0,Pl.useEffect)(()=>{m.current=e},[e]);let h=(0,Pl.useRef)(a);(0,Pl.useEffect)(()=>{h.current=a},[a]);let g=(0,Pl.useRef)(!0);(0,Pl.useEffect)(()=>()=>{g.current=!1},[]);let v=(0,Pl.useCallback)(I=>{I===m.current&&h.current()},[]),y=(0,Pl.useCallback)(I=>{f.current?p.current=I:v(I)},[v]),w=(0,Pl.useCallback)(I=>{if(f.current=I,d(I),!I&&p.current!==null){let C=p.current;p.current=null,v(C)}},[v]),_=(0,Pl.useCallback)(async I=>{let C=m.current;await s(I)&&g.current&&y(C)},[s,y]),S=(0,Pl.useCallback)(()=>{let I=m.current;i()&&y(I)},[i,y]);return jv.createElement(nc,{open:u,onOpenChange:w},jv.createElement(Ku,{asChild:!0},jv.createElement(oe,{variant:"ghost2",size:"fit",className:"tw-text-muted","aria-label":"Project context status"},jv.createElement(lOr,{kind:c}))),jv.createElement(Cl,{align:"end",side:o?"bottom":"top",className:"tw-flex tw-max-h-[var(--radix-popover-content-available-height)] tw-w-[368px] tw-max-w-[calc(100vw-24px)] tw-flex-col tw-overflow-hidden tw-p-0"},u&&jv.createElement(cOr,{app:t,project:n,hasConfiguredContextSource:r,onRetryItem:xn(_),onRetryAll:S,onEditContext:()=>{w(!1),l()}})))}function cOr({app:t,project:e,hasConfiguredContextSource:n,onRetryItem:r,onRetryAll:o,onEditContext:i}){let{items:s,skippedMarkdownCount:a}=eCe(t,e,e.contextSource);return jv.createElement(ofn,{items:s,hasConfiguredContextSource:n,skippedMarkdownCount:a,onRetryItem:r,onRetryAll:o,onEditContext:i,onOpenCachedItem:c=>{zV(t,c)}})}var jv,Pl,iOr,lfn,ufn=b(()=>{_S();es();ifn();afn();mtt();yt();Gb();Se();nCe();Us();Re();jv=L(B()),Pl=L(B());Hl();iOr=300,lfn={idle:-1,resolve:0,prefetch:1,parse:2,done:3}});function dfn({hero:t,composer:e,floating:n,context:r,shelf:o}){return A0.default.createElement(A0.default.Fragment,null,A0.default.createElement("div",{className:"tw-h-1/4 tw-shrink-0"}),A0.default.createElement("div",{className:"tw-shrink-0 tw-pb-7"},t),A0.default.createElement("div",{className:"tw-shrink-0"},e),n?A0.default.createElement("div",{className:"tw-shrink-0"},n):null,r?A0.default.createElement("div",{className:"tw-shrink-0"},r):null,o?A0.default.createElement("div",{className:"tw-flex tw-min-h-0 tw-flex-1 tw-flex-col tw-pt-6"},o):null)}var A0,ffn=b(()=>{A0=L(B())});function mfn({title:t,subtitle:e,onSave:n,onCancel:r}){let[o,i]=(0,Fg.useState)(""),[s,a]=(0,Fg.useState)(!1),l=o.trim().length>0&&!s,c=async()=>{if(!(o.trim().length===0||s)){a(!0);try{await n({name:o.trim()})}catch(d){new pfn.Notice(kt(d))}finally{a(!1)}}},u=Fg.default.createElement(Ir,{type:"text",value:o,onChange:d=>i(d.target.value),placeholder:"Project name",autoFocus:!0,onKeyDown:d=>{d.key==="Enter"&&(d.preventDefault(),c())},className:"tw-w-full"});return Fg.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},t&&Fg.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1"},Fg.default.createElement("div",{className:"tw-text-base tw-font-semibold tw-text-normal"},t),e&&Fg.default.createElement("div",{className:"tw-text-sm tw-text-muted"},e)),t?u:Fg.default.createElement(Dh,{label:"Name",required:!0},u),Fg.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},Fg.default.createElement(oe,{variant:"secondary",onClick:r,disabled:s},"Cancel"),Fg.default.createElement(oe,{variant:"default",onClick:()=>void c(),disabled:!l},s?"Saving...":"Create")))}function hfn(t){let e=Date.now();return{id:jie(),name:t,systemPrompt:"",projectModelKey:"",modelConfigs:{},contextSource:{inclusions:"",exclusions:"",webUrls:"",youtubeUrls:""},created:e,UsageTimestamps:e}}var pfn,Fg,Htt=b(()=>{yt();Zj();hl();ut();pfn=require("obsidian"),Fg=L(B())});function xCe(t){let{scrollRect:e,visibleBottom:n,visibleTop:r,panelHeight:o,margin:i,gap:s,viewportHeight:a}=t,l=(e.top+e.bottom)/2-o/2,c=o+i,u,d;if(n&&r){let f=e.bottom-n.bottom-s,p=r.top-e.top-s;f>=c?u=n.bottom+s:p>=c?(d=r.top-s,u=d-o):u=l}else n?e.bottom-n.bottom-s>=c?u=n.bottom+s:u=l:r&&r.top-e.top-s>=c?(d=r.top-s,u=d-o):u=l;return u=Math.max(i,Math.min(u,a-i-o)),d!==void 0?{top:u,anchorBottomY:d}:{top:u}}var Wtt=b(()=>{});function wfn({anchorEl:t,onClose:e,onSave:n}){let r=(0,qS.useRef)(null),o=t.ownerDocument,i=o.defaultView??window,s=(0,qS.useCallback)(c=>{let u=t.getBoundingClientRect(),{top:d}=xCe({scrollRect:{top:0,bottom:i.innerHeight},visibleBottom:u,visibleTop:u,panelHeight:c,margin:Vtt,gap:uOr,viewportHeight:i.innerHeight}),f=u.left+u.width/2-gfn/2,p=Math.max(Vtt,Math.min(f,i.innerWidth-gfn-Vtt));return{top:d,left:p}},[t,i]),[a,l]=(0,qS.useState)(()=>s(yfn));return(0,qS.useLayoutEffect)(()=>{let c=()=>l(s(r.current?.offsetHeight??yfn));return c(),i.addEventListener("resize",c),()=>i.removeEventListener("resize",c)},[s,i]),(0,qS.useEffect)(()=>{let c=d=>{d.key==="Escape"&&!d.defaultPrevented&&(d.preventDefault(),e())},u=d=>{let f=d.target;f&&!r.current?.contains(f)&&!t.contains(f)&&e()};return i.addEventListener("keydown",c),o.addEventListener("mousedown",u,!0),()=>{i.removeEventListener("keydown",c),o.removeEventListener("mousedown",u,!0)}},[t,o,i,e]),(0,vfn.createPortal)(qtt.createElement("div",{ref:r,role:"dialog","aria-label":"New project",className:"tw-fixed tw-z-popover tw-w-[260px] tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-3 tw-shadow-lg",style:{top:a.top,left:a.left}},qtt.createElement(mfn,{title:"New project",subtitle:"Create a new project in your vault",onSave:n,onCancel:e})),o.body)}var qtt,qS,vfn,Vtt,uOr,gfn,yfn,bfn=b(()=>{Htt();Wtt();qtt=L(B()),qS=L(B()),vfn=L(Es()),Vtt=12,uOr=6,gfn=260,yfn=140});var sh,hD,Rte,Ktt,dOr,Lte,fOr,SCe=b(()=>{sh=L(B());De();hD=sh.forwardRef(({className:t,...e},n)=>sh.createElement("div",{ref:n,className:J("tw-rounded-xl tw-border tw-border-border tw-bg-primary tw-text-normal tw-shadow",t),...e}));hD.displayName="Card";Rte=sh.forwardRef(({className:t,...e},n)=>sh.createElement("div",{ref:n,className:J("tw-flex tw-flex-col tw-space-y-1.5 tw-p-6",t),...e}));Rte.displayName="CardHeader";Ktt=sh.forwardRef(({className:t,...e},n)=>sh.createElement("div",{ref:n,className:J("tw-font-semibold tw-leading-none tw-tracking-tight",t),...e}));Ktt.displayName="CardTitle";dOr=sh.forwardRef(({className:t,...e},n)=>sh.createElement("div",{ref:n,className:J("tw-text-sm tw-text-muted",t),...e}));dOr.displayName="CardDescription";Lte=sh.forwardRef(({className:t,...e},n)=>sh.createElement("div",{ref:n,className:J("tw-p-6 tw-pt-0",t),...e}));Lte.displayName="CardContent";fOr=sh.forwardRef(({className:t,...e},n)=>sh.createElement("div",{ref:n,className:J("tw-flex tw-items-center tw-p-6 tw-pt-0",t),...e}));fOr.displayName="CardFooter"});var E0,gD,_fn=b(()=>{yt();SCe();De();Re();E0=L(B()),gD=({message:t,tone:e="neutral",action:n})=>E0.default.createElement(hD,{className:J("tw-flex tw-w-full tw-flex-wrap tw-items-center tw-justify-between tw-gap-2 tw-rounded-md tw-border-solid tw-border-border tw-bg-secondary tw-px-3 tw-py-2 tw-text-xs tw-shadow-none",e==="warning"&&"tw-bg-callout-warning/20 tw-border-warning/40",e==="error"&&"tw-border-error/50"),role:e==="neutral"?void 0:"alert"},E0.default.createElement("span",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-items-start tw-gap-2"},e==="warning"&&E0.default.createElement(Wr,{"aria-hidden":"true",className:"tw-size-4 tw-shrink-0 tw-text-warning"}),e==="error"&&E0.default.createElement(mc,{"aria-hidden":"true",className:"tw-size-4 tw-shrink-0 tw-text-error"}),E0.default.createElement("span",{className:"tw-min-w-0 tw-break-words tw-text-normal"},t)),n&&("href"in n?E0.default.createElement(oe,{asChild:!0,className:"tw-h-auto tw-min-h-6 tw-max-w-full tw-whitespace-normal tw-break-words tw-py-1",variant:"secondary",size:"sm"},E0.default.createElement("a",{href:n.href,target:"_blank",rel:"noopener noreferrer"},n.label)):E0.default.createElement(oe,{className:"tw-h-auto tw-min-h-6 tw-max-w-full tw-whitespace-normal tw-break-words tw-py-1 disabled:tw-opacity-100",variant:e==="error"?"ghost":"secondary",size:"sm",disabled:n.disabled,onClick:n.onClick},n.label)))});function xfn(t){switch(t.kind){case"absent":return"absent";case"checking":case"ready":return`${t.kind}:${t.source}`;case"incompatible":return JSON.stringify([t.kind,t.source,t.currentVersion,t.minVersion,t.message]);case"error":return JSON.stringify([t.kind,t.message])}}function Sfn(){return MQ(xt())}function KS(t){let e=xt(),n=Bv.default.useCallback(i=>t?.subscribe(i)??(()=>{}),[t]),r=Bv.default.useCallback(()=>t?.getStartingBackendId()??t?.getActiveSession()?.backendId??null,[t]),o=Bv.default.useSyncExternalStore(n,r,r);if(o){let i=$a[o];if(i)return i}return MQ(e)}function MM(t,e){let n=xt(),r=Bv.default.useCallback(s=>t.subscribeInstallState(e,s),[t,e]),o=Bv.default.useCallback(()=>xfn(t.getInstallState(n)),[t,n]),i=Bv.default.useSyncExternalStore(r,o,o);return Bv.default.useMemo(()=>t.getInstallState(n),[t,n,i])}function CCe(t){let e=xt(),n=Bv.default.useCallback(i=>{let s=ss().map(a=>a.subscribeInstallState(t,i));return()=>{for(let a of s)a()}},[t]),r=Bv.default.useCallback(()=>ss().map(i=>`${i.id}=${xfn(i.getInstallState(e))}`).join("|"),[e]),o=Bv.default.useSyncExternalStore(n,r,r);return Bv.default.useMemo(()=>{let i=ss();if(i.length===0)return pOr;let s={};for(let a of i)s[a.id]=a.getInstallState(e);return s},[e,o])}var Bv,pOr,yD=b(()=>{Wm();Se();Bv=L(B()),pOr=Object.freeze({})});var kCe,g_,ICe,Gtt=b(()=>{_fn();U9e();yD();pe();kCe=require("obsidian"),g_=L(B()),ICe=({manager:t,plugin:e,onInstallClick:n})=>{let r=KS(t),o=MM(r,e),i=Xye(r),[s,a]=g_.default.useState(!1),[,l]=g_.default.useState(0);g_.default.useEffect(()=>{if(t)return t.subscribe(()=>l(f=>f+1))},[t]);let c=g_.default.useCallback(()=>{!r.upgrade||s||(a(!0),new kCe.Notice(`Upgrading ${r.displayName}\u2026`),r.upgrade(e).then(()=>new kCe.Notice(`${r.displayName} upgraded.`)).catch(f=>{H("[AgentMode] upgrade failed",f),new kCe.Notice(`Failed to upgrade ${r.displayName}. See console for details.`)}).finally(()=>a(!1)))},[r,e,s]);if(o.kind==="absent")return g_.default.createElement(gD,{message:`${r.displayName} not installed`,action:{label:`Install ${r.displayName}`,onClick:n}});if(o.kind==="checking")return g_.default.createElement(gD,{message:`Checking ${r.displayName} version\u2026`});if(o.kind==="incompatible"){let f=r.upgrade!==void 0;return g_.default.createElement(gD,{tone:"warning",message:o.message,action:{label:f?s?"Upgrading\u2026":"Upgrade":`Configure ${r.displayName}`,disabled:f&&s,onClick:f?c:()=>r.openInstallUI(e)}})}if(o.kind==="error")return g_.default.createElement(gD,{tone:"error",message:o.message,action:{label:`Configure ${r.displayName}`,onClick:()=>r.openInstallUI(e)}});if(r.auth&&i.status&&!i.status.signedIn)return g_.default.createElement(gD,{message:i.signingIn?`Signing in to ${r.displayName}\u2026`:`${r.displayName} not signed in`,action:i.signingIn?i.url?{label:"Open sign-in page",href:i.url}:void 0:{label:`Sign in to ${r.displayName}`,onClick:i.signIn}});if(!t)return null;let u=t.getLastError();return u?g_.default.createElement(gD,{tone:"error",message:u,action:{label:"Retry",onClick:()=>{t.getOrCreateActiveSession().catch(f=>{H("[AgentMode] retry failed",f)})}}}):null}});function TCe({className:t}){return Cfn.default.createElement(Fl,{"aria-hidden":"true",className:J("tw-size-4 tw-shrink-0 tw-text-muted",t)})}var Cfn,Ztt=b(()=>{De();Re();Cfn=L(B())});var y_,Ytt,kfn=b(()=>{kS();yt();Ztt();De();Re();y_=L(B()),Ytt=(0,y_.memo)(({projectName:t,onExit:e,menu:n,orphaned:r=!1,className:o})=>y_.default.createElement("div",{className:J("tw-flex tw-w-full tw-items-center tw-gap-1 tw-px-2 tw-py-1.5",o)},y_.default.createElement(oe,{variant:"ghost2",size:"sm",onClick:e,"aria-label":"Leave project",title:"Leave project",className:"tw-flex tw-shrink-0 tw-items-center tw-px-1.5 tw-text-muted hover:tw-text-normal"},y_.default.createElement(oG,{className:"tw-size-4"})),r?y_.default.createElement("span",{className:"tw-min-w-0 tw-flex-1 tw-text-ui-small tw-text-muted"},"This project no longer exists"):y_.default.createElement(y_.default.Fragment,null,y_.default.createElement(TCe,null),y_.default.createElement(si,{className:"tw-min-w-0 tw-flex-1 tw-text-ui-small tw-font-medium tw-text-normal",tooltipContent:t},t),n)));Ytt.displayName="AgentProjectHeader"});var M0,mOr,PCe,Jtt=b(()=>{Uet();xI();De();M0=L(B()),mOr=Object.freeze(["e.g. Put new notes you create in Inbox/ and link them to a related note.","e.g. Always have prefix YYYY-MM-DD in filenames."]),PCe=({value:t,onChange:e,label:n,examples:r=mOr,className:o})=>{let i=(0,M0.useMemo)(()=>TSe(r),[r]),[s]=(0,M0.useState)(()=>window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches??!1),[a,l]=(0,M0.useState)(CSe),c=t.length>0;return(0,M0.useEffect)(()=>{if(c)return;let{state:u,delayMs:d}=ISe(a,i,s),f=window.setTimeout(()=>l(u),d);return()=>window.clearTimeout(f)},[c,a,i,s]),M0.default.createElement(If,{value:t,onChange:u=>e(u.target.value),"aria-label":n,placeholder:kSe(a,i),className:J("tw-min-h-32 tw-w-full",o)})}});var Xtt,Ifn,Tfn,Pfn=b(()=>{Zj();Jtt();Xtt=L(B()),Ifn="Project instructions",Tfn=({value:t,onChange:e})=>Xtt.default.createElement(Dh,{label:Ifn,description:"Your custom instructions for the agent to follow for every interaction in this project. They take precedence over your vault instructions wherever the two conflict. Saved to AGENTS.md in the project folder, which you can also edit as a note."},Xtt.default.createElement(PCe,{label:Ifn,value:t,onChange:e}))});function hOr({initialProject:t,onSave:e,onCancel:n,plugin:r,popoverContainer:o}){let i=vn(),[s,a]=(0,Go.useState)(!1),[l,c]=(0,Go.useState)({name:!1,inclusions:!1}),[u,d]=(0,Go.useState)(()=>t?{...t}:{id:jie(),name:"",description:"",systemPrompt:"",projectModelKey:"",modelConfigs:{temperature:V5.TEMPERATURE},contextSource:{inclusions:"",exclusions:"",webUrls:"",youtubeUrls:""},created:Date.now(),UsageTimestamps:Date.now()}),f=(0,Go.useMemo)(()=>t?.id?mo(t.id):void 0,[t?.id]),p=(0,Go.useMemo)(()=>f?Nd(f.filePath).projectFolderPath:null,[f]),[m,h]=(0,Go.useState)(null),[g,v]=(0,Go.useState)(!1),y=t?.systemPrompt??"";(0,Go.useEffect)(()=>{if(p===null)return;let k=!1;return Promise.all([mme(i,p),pme(i,p)]).then(([T,P])=>{if(k)return;let E=P&&y.trim().length>0;h(E?y:T),v(E)}).catch(T=>{H("Failed to read project instructions.",T)}),()=>{k=!0}},[i,p,y]);let w=k=>{new EM(i,P=>{d(E=>({...E,contextSource:{...E.contextSource,inclusions:P.contextSource?.inclusions,exclusions:P.contextSource?.exclusions,webUrls:P.contextSource?.webUrls,youtubeUrls:P.contextSource?.youtubeUrls}}))},k).open()},_=()=>!!u.name,S=(k,T)=>{d(P=>{if(Array.isArray(T)&&T.every(E=>typeof E=="string")&&(T=T.map(E=>E.trim()).filter(Boolean)),k.includes(".")){let[E,O]=k.split("."),U=P[E];if(typeof U=="object"&&U!==null)return{...P,[E]:{...U,[O]:T}}}return{...P,[k]:T}})},I=k=>{d(T=>({...T,contextSource:{...T.contextSource,...k}}))},C=async()=>{let k=u.name?.trim()??"",T=t?{...u,name:k,projectModelKey:t.projectModelKey,modelConfigs:t.modelConfigs,...g?{systemPrompt:""}:{}}:{...u,name:k};if(!T.name){c(E=>({...E,name:!0})),new $te.Notice("Please fill in all required fields");return}let P=p!==null&&m!==null?{folder:p,text:m}:null;try{a(!0);let E=P?await jUt(i,P.folder):null;P&&await hme(i,P.folder,P.text);try{await e(T)}catch(O){throw P&&E&&await BUt(i,P.folder,E),O}}catch(E){new $te.Notice(kt(E)),c(O=>({...O,name:!0}))}finally{a(!1)}};return Go.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-col"},Go.default.createElement("div",{className:"tw-shrink-0 tw-px-4 tw-pb-2 tw-pt-4"},Go.default.createElement("div",{className:"tw-text-xl tw-font-bold tw-text-normal"},t?"Edit Project":"New Project"),Go.default.createElement("p",{className:"tw-mt-1 tw-text-sm tw-text-muted"},"Configure your project settings and context sources")),Go.default.createElement(Ym,{className:"tw-min-h-0 tw-flex-1"},Go.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-6 tw-p-4"},Go.default.createElement("div",{className:"tw-rounded-lg tw-border tw-border-border tw-p-4 tw-bg-secondary/50"},Go.default.createElement("h3",{className:"tw-mb-3 tw-text-sm tw-font-medium tw-text-normal"},"Basic Info"),Go.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-3"},Go.default.createElement(Dh,{label:"Project Name",required:!0,error:l.name&&!u.name,errorMessage:"Project name is required"},Go.default.createElement(Ir,{type:"text",value:u.name,onChange:k=>S("name",k.target.value),onBlur:()=>c(k=>({...k,name:!0})),className:"tw-w-full"})),Go.default.createElement(Dh,{label:"Description",description:"Briefly describe the purpose and goals of the project"},Go.default.createElement(Ir,{type:"text",value:u.description,onChange:k=>S("description",k.target.value),className:"tw-w-full"})),m!==null&&Go.default.createElement(Tfn,{value:m,onChange:h}))),Go.default.createElement("div",{className:"tw-rounded-lg tw-border tw-border-border tw-p-4 tw-bg-secondary/50"},Go.default.createElement("h3",{className:"tw-mb-3 tw-text-sm tw-font-medium tw-text-normal"},"Context Sources"),Go.default.createElement(wCe,{contextSource:u.contextSource,onChange:I,onManage:()=>w(u),popoverContainer:o,droppable:!1,solidManageButton:!0,showHelperText:!0})))),Go.default.createElement("div",{className:"tw-shrink-0 tw-border-t tw-border-border tw-px-4 tw-py-3"},Go.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-end tw-gap-2"},Go.default.createElement(oe,{variant:"ghost",onClick:n,disabled:s},"Cancel"),Go.default.createElement(oe,{onClick:xn(C),disabled:s||!_()},s?"Saving...":"Save"))))}var $te,Go,GV,Qtt=b(()=>{ko();yCe();yt();Zj();hl();M$();gt();Ftt();db();pe();Pfn();Mv();Md();ut();Pa();$te=require("obsidian"),Go=L(B());Hl();GV=class extends $te.Modal{constructor(n,r,o,i){super(n);this.onSave=r;this.initialProject=o;this.plugin=i}onOpen(){let{contentEl:n,modalEl:r}=this;r.addClass("!tw-max-h-[85vh]","tw-min-w-[50vw]"),this.root=Er(n,this.app);let o=async s=>{await this.onSave(s),this.close()},i=()=>{this.close()};this.root.render(Go.default.createElement(hOr,{initialProject:this.initialProject,onSave:o,onCancel:i,plugin:this.plugin,popoverContainer:n}))}onClose(){this.root.unmount()}}});function ACe(t,e){let n=mo(e.id),r=n?$Q(n.folderName):null,o=r?t.vault.getAbstractFileByPath(r):null;if(o instanceof Dte.TFolder){let i=t.internalPlugins?.getPluginById?.("file-explorer");if(i?.enabled&&i.instance?.revealInFolder){i.instance.revealInFolder(o);return}}new Dte.Notice(`Can't reveal "${e.name}" \u2014 its folder isn't visible in the file explorer.`)}var Dte,GS,ent,tnt=b(()=>{Qtt();fm();yt();De();pe();Mv();zI();Md();Re();Dte=require("obsidian"),GS=L(B());ent=(0,GS.memo)(({app:t,project:e,onEdited:n,onDeleted:r,className:o})=>{let i=()=>{new GV(t,async a=>{let l=await nl.getInstance(t).updateProject(e.id,a);n?.(l.project)},e).open()},s=()=>{new _i(t,async()=>{try{await nl.getInstance(t).deleteProject(e.id),r?.(e.id)}catch(a){H("[AgentProjectRowActions] deleteProject failed",a),new Dte.Notice(`Failed to delete project "${e.name}".`)}},`Delete project "${e.name}"? This removes its configuration; your notes stay in the vault.`,"Delete project","Delete","Cancel").open()};return GS.default.createElement("div",{className:J("tw-flex tw-items-center tw-gap-1.5",o)},GS.default.createElement(oe,{size:"sm",variant:"ghost","aria-label":`Reveal ${e.name} in vault`,title:"Reveal in vault",className:"tw-size-5 tw-p-0",onClick:a=>{a.stopPropagation(),ACe(t,e)}},GS.default.createElement(kw,{className:"tw-size-3.5"})),GS.default.createElement(oe,{size:"sm",variant:"ghost","aria-label":`Edit project ${e.name}`,title:"Edit project",className:"tw-size-5 tw-p-0",onClick:a=>{a.stopPropagation(),i()}},GS.default.createElement(wy,{className:"tw-size-3.5"})),GS.default.createElement(oe,{size:"sm",variant:"ghost","aria-label":`Delete project ${e.name}`,title:"Delete",className:"tw-size-5 tw-p-0 tw-text-error hover:tw-text-error",onClick:a=>{a.stopPropagation(),s()}},GS.default.createElement(Ts,{className:"tw-size-3.5"})))});ent.displayName="AgentProjectRowActions"});function Afn({ext:t}){return rr.default.createElement("span",{"aria-hidden":"true",className:J("tw-flex tw-h-4 tw-w-7 tw-shrink-0 tw-items-center tw-justify-center tw-rounded tw-text-smallest tw-font-bold tw-uppercase",yOr[t]??"tw-bg-secondary tw-text-muted")},t.slice(0,4)||"file")}function vOr({todoList:t}){if(!t||t.length===0)return null;let e=t.filter(n=>n.status==="completed").length;return rr.default.createElement("div",{className:"tw-px-3 tw-py-2.5"},rr.default.createElement("div",{className:"tw-mb-1.5 tw-flex tw-items-baseline tw-justify-between"},rr.default.createElement("span",{className:"tw-text-ui-smaller tw-font-semibold tw-text-faint"},"Progress"),rr.default.createElement("span",{className:"tw-text-ui-smaller tw-text-faint"},e,"/",t.length)),rr.default.createElement("ul",{className:"tw-m-0 tw-flex tw-list-none tw-flex-col tw-gap-1 tw-p-0"},t.map((n,r)=>rr.default.createElement("li",{key:`todo-${r}`,className:"tw-flex tw-items-center tw-gap-2"},rr.default.createElement("span",{"aria-hidden":"true",className:J("tw-flex tw-size-5 tw-shrink-0 tw-items-center tw-justify-center tw-rounded-full tw-text-xs tw-font-semibold",n.status==="completed"?"tw-bg-interactive-accent tw-text-on-accent":n.status==="in_progress"?"tw-border-[1.5px] tw-border-solid tw-border-interactive-accent tw-text-accent":"tw-border-[1.5px] tw-border-solid tw-border-border tw-text-faint")},n.status==="completed"?rr.default.createElement(Hr,{className:"tw-size-3"}):r+1),rr.default.createElement("span",{className:J("tw-min-w-0 tw-truncate tw-text-ui-small",n.status==="completed"?"tw-text-faint tw-line-through":"tw-text-normal"),title:n.content},n.content)))))}function wOr({files:t,onOpenInstructions:e,onOpenFile:n,onReveal:r}){let[o,i]=(0,rr.useState)(!1);return rr.default.createElement("div",{className:"tw-px-3 tw-py-2.5"},rr.default.createElement("div",{className:"tw-mb-1 tw-flex tw-items-center tw-justify-between"},rr.default.createElement("span",{className:"tw-text-ui-smaller tw-font-semibold tw-text-faint"},"Project files"),rr.default.createElement(oe,{variant:"ghost2",size:"icon","aria-label":"Reveal project files in vault",className:"tw-size-5 tw-text-faint hover:tw-text-normal",onClick:r},rr.default.createElement(kw,{className:"tw-size-3.5"}))),rr.default.createElement("div",{role:"button",tabIndex:0,className:"tw-flex tw-cursor-pointer tw-items-center tw-gap-2 tw-rounded tw-p-1 hover:tw-bg-secondary",onClick:e,onKeyDown:s=>{(s.key==="Enter"||s.key===" ")&&e()}},rr.default.createElement(Afn,{ext:"md"}),rr.default.createElement("span",{className:"tw-min-w-0 tw-flex-1 tw-truncate tw-text-ui-small"},"AGENTS.md"),rr.default.createElement(us,{"aria-hidden":"true",className:"tw-size-3.5 tw-shrink-0 tw-text-faint"})),t.map(s=>rr.default.createElement("div",{key:s.path,role:"button",tabIndex:0,className:"tw-flex tw-cursor-pointer tw-items-center tw-gap-2 tw-rounded tw-p-1 hover:tw-bg-secondary",onClick:()=>n(s.path),onKeyDown:a=>{(a.key==="Enter"||a.key===" ")&&n(s.path)}},rr.default.createElement(Afn,{ext:s.extension.toLowerCase()}),rr.default.createElement("span",{className:"tw-min-w-0 tw-flex-1 tw-truncate tw-text-ui-small",title:s.name},s.name))),rr.default.createElement("div",{role:"button",tabIndex:0,className:"tw-flex tw-cursor-pointer tw-items-center tw-gap-1 tw-rounded tw-p-1 tw-text-muted hover:tw-bg-secondary",onClick:()=>i(s=>!s),onKeyDown:s=>{(s.key==="Enter"||s.key===" ")&&i(a=>!a)},"aria-expanded":o},o?rr.default.createElement(Bs,{className:"tw-size-3.5","aria-hidden":"true"}):rr.default.createElement(Vi,{className:"tw-size-3.5","aria-hidden":"true"}),rr.default.createElement("span",{className:"tw-text-ui-small tw-font-medium"},"Outputs"),rr.default.createElement("span",{className:"tw-text-ui-smaller tw-text-faint"},"(0)")),o&&rr.default.createElement("div",{className:"tw-py-1 tw-pl-6 tw-text-ui-smaller tw-text-faint"},"No outputs yet"))}function bOr({app:t,project:e,onClose:n}){let[r,o]=(0,rr.useState)([]);return(0,rr.useEffect)(()=>{let a=mo(e.id),l=a?Nd(a.filePath).projectFolderPath:null,c=l?t.vault.getAbstractFileByPath(l):null,u=!1;return(async()=>{if(!(c instanceof vD.TFolder)){u||o([]);return}let d=c.children.filter(p=>p instanceof vD.TFile&&!p.name.startsWith(".")&&!gOr.has(p.name.toLowerCase())&&p.name.toLowerCase()!=="claude.md"),f=c.children.find(p=>p instanceof vD.TFile&&p.name.toLowerCase()==="claude.md");if(f){let p=await t.vault.read(f).catch(()=>"");FUt(p)||d.push(f)}u||o(d.sort((p,m)=>p.name.localeCompare(m.name)))})(),()=>{u=!0}},[t,e.id]),rr.default.createElement(wOr,{files:r,onOpenInstructions:()=>{let a=mo(e.id);a&&(n(),kbe(t,a).then(()=>yme(t,Nd(a.filePath).projectFolderPath,"",!0)).catch(l=>{H("[ProjectInfoPopover] Failed to open project AGENTS.md",l),new vD.Notice("Failed to open project AGENTS.md.")}))},onOpenFile:a=>{let l=r.find(c=>c.path===a);l&&(n(),t.workspace.getLeaf(!1).openFile(l).catch(c=>H("[ProjectInfoPopover] openFile failed",c)))},onReveal:()=>{n(),ACe(t,e)}})}var vD,rr,gOr,yOr,nnt,Efn=b(()=>{tnt();Qtt();yt();Gb();db();DYe();De();pe();Mv();zI();Md();Re();vD=require("obsidian"),rr=L(B()),gOr=new Set(["project.md","agents.md"]),yOr={pdf:"tw-bg-project-red tw-text-project-red",md:"tw-bg-project-blue tw-text-project-blue",html:"tw-bg-project-orange tw-text-project-orange",png:"tw-bg-project-green tw-text-project-green"};nnt=(0,rr.memo)(({app:t,project:e,todoList:n,onEdited:r,container:o,className:i})=>{let[s,a]=(0,rr.useState)(!1),l=()=>{a(!1),new GV(t,async c=>{try{let u=await nl.getInstance(t).updateProject(e.id,c);r?.(u.project)}catch(u){throw H("[ProjectInfoPopover] updateProject failed",u),u}},e).open()};return rr.default.createElement(nc,{open:s,onOpenChange:a},rr.default.createElement(Ku,{asChild:!0},rr.default.createElement(oe,{variant:"ghost2",size:"icon","aria-label":`Project info for ${e.name}`,className:J("tw-size-7 tw-text-muted hover:tw-text-normal",i)},rr.default.createElement(IG,{className:"tw-size-4"}))),rr.default.createElement(Cl,{align:"end",container:o,className:"tw-w-72 tw-p-0",onOpenAutoFocus:c=>c.preventDefault()},rr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1 tw-px-3 tw-py-2.5"},rr.default.createElement("span",{className:"tw-min-w-0 tw-flex-1 tw-truncate tw-text-ui-small tw-font-semibold",title:e.name},e.name),rr.default.createElement(oe,{variant:"ghost2",size:"icon","aria-label":`Edit project ${e.name}`,className:"tw-size-6 tw-text-muted hover:tw-text-normal",onClick:l},rr.default.createElement(Ih,{className:"tw-size-3.5"})),rr.default.createElement(oe,{variant:"ghost2",size:"icon","aria-label":"Reveal project folder in vault",className:"tw-size-6 tw-text-muted hover:tw-text-normal",onClick:()=>{a(!1),ACe(t,e)}},rr.default.createElement(kw,{className:"tw-size-3.5"}))),rr.default.createElement(vOr,{todoList:n}),rr.default.createElement(bOr,{app:t,project:e,onClose:()=>a(!1)})))});nnt.displayName="ProjectInfoPopover"});function SOr(t,e){if(e===0)return 0;let n=s=>s<Mfn?0:Math.min(e,Math.floor((s+ECe)/(Mfn+ECe))),r=t-_Or;if(n(r)>=e)return e;let i=r-xOr;return Math.max(1,n(i))}function COr({sessions:t,visibleCount:e,activeId:n}){if(t.length===0)return{visibleSessions:[],overflowSessions:[]};let r=t.slice(0,e),o=t.slice(e);if(n&&o.some(i=>i.internalId===n)){let i=o.find(c=>c.internalId===n),s=o.filter(c=>c.internalId!==n),a=r[r.length-1];return{visibleSessions:[...r.slice(0,-1),i],overflowSessions:a?[a,...s]:s}}return{visibleSessions:r,overflowSessions:o}}function Ofn(t){let[,e]=Bn.default.useState(0);Bn.default.useEffect(()=>t.subscribe({onMessagesChanged:()=>{},onStatusChanged:()=>e(o=>o+1),onLabelChanged:()=>e(o=>o+1),onNeedsAttentionChanged:()=>e(o=>o+1)}),[t]);let n=t.getLabel(),r=$a[t.backendId];return{status:t.getStatus(),label:n,needsAttention:t.getNeedsAttention(),descriptor:r,displayLabel:n??r?.displayName??"Session"}}var Bn,ECe,Mfn,_Or,xOr,Nfn,kOr,IOr,Rfn,TOr,POr,Lfn=b(()=>{Wm();kS();yt();xk();hl();Oc();De();pe();Re();Bn=L(B()),ECe=4,Mfn=128,_Or=28+ECe,xOr=28+ECe;Nfn=({manager:t})=>{let[,e]=Bn.default.useState(0);Bn.default.useEffect(()=>t.subscribe(()=>e(g=>g+1)),[t]);let n=t.getSessionsForScope(t.getActiveProjectId()),r=n.length,o=t.getActiveSession()?.internalId??null,i=t.getIsStarting(),[s,a]=Bn.default.useState(null),l=Bn.default.useRef(null),[c,u]=Bn.default.useState(0);Bn.default.useLayoutEffect(()=>{if(r===0)return;let g=l.current;if(!g)return;let v=()=>{let w=g.clientWidth;u(_=>_===w?_:w)};if(v(),typeof ResizeObserver>"u")return;let y=new ResizeObserver(v);return y.observe(g),()=>y.disconnect()},[r]);let d=Bn.default.useMemo(()=>SOr(c,r),[c,r]),{visibleSessions:f,overflowSessions:p}=Bn.default.useMemo(()=>COr({sessions:n,visibleCount:d,activeId:o}),[n,d,o]),m=Bn.default.useCallback(()=>{t.getIsStarting()||t.createSession().catch(g=>H("[AgentMode] createSession failed",g))},[t]),h=Bn.default.useCallback(g=>{t.closeSession(g).catch(v=>H("[AgentMode] closeSession failed",v))},[t]);return r===0?null:Bn.default.createElement("div",{ref:l,className:"tw-relative tw-flex tw-w-full tw-items-stretch tw-gap-1 tw-overflow-hidden tw-px-2"},Bn.default.createElement("div",{role:"tablist",className:"tw-flex tw-min-w-0 tw-items-stretch tw-gap-1"},f.map(g=>Bn.default.createElement(kOr,{key:g.internalId,session:g,isActive:g.internalId===o,isRenaming:s===g.internalId,onActivate:()=>t.setActiveSession(g.internalId),onClose:()=>h(g.internalId),onStartRename:()=>a(g.internalId),onSubmitRename:v=>{t.renameSession(g.internalId,v),a(null)},onCancelRename:()=>a(null)}))),p.length>0&&Bn.default.createElement(TOr,{sessions:p,activeId:o,onActivate:g=>t.setActiveSession(g),onClose:h}),Bn.default.createElement(hr,null,Bn.default.createElement(gr,{asChild:!0},Bn.default.createElement(oe,{variant:"ghost2",size:"icon",onClick:m,disabled:i,"aria-label":"New agent session",className:"tw-my-1 tw-shrink-0"},Bn.default.createElement(zs,{className:"tw-size-4"}))),Bn.default.createElement(fr,null,"New agent session")))},kOr=({session:t,isActive:e,isRenaming:n,onActivate:r,onClose:o,onStartRename:i,onSubmitRename:s,onCancelRename:a})=>{let{status:l,label:c,needsAttention:u,descriptor:d,displayLabel:f}=Ofn(t),[p,m]=Bn.default.useState(!1);return n?Bn.default.createElement(IOr,{key:t.internalId,initialValue:c??"",onSubmit:s,onCancel:a}):Bn.default.createElement(up,{open:p,onOpenChange:m,modal:!1},Bn.default.createElement(dp,{asChild:!0},Bn.default.createElement("div",{role:"tab","aria-selected":e,tabIndex:0,onPointerDown:h=>{h.button!==2&&h.preventDefault()},onClick:r,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),r())},onContextMenu:h=>{h.preventDefault(),m(!0)},className:J("tw-group tw-flex tw-h-7 tw-w-32 tw-min-w-0 tw-shrink-0 tw-cursor-pointer tw-items-center tw-gap-1.5","tw-my-1 tw-rounded-sm tw-px-2 tw-text-xs tw-transition-colors","focus-visible:tw-outline-none focus-visible:tw-ring-1 focus-visible:tw-ring-ring",e?"tw-border-interactive-accent tw-text-normal tw-bg-interactive-accent/10":"tw-border-transparent tw-text-faint hover:tw-bg-modifier-hover hover:tw-text-normal")},Bn.default.createElement(Rfn,{descriptor:d,status:l,needsAttention:u,onCloseOnHover:o}),Bn.default.createElement(si,{className:"tw-min-w-0 tw-flex-1 !tw-text-current",tooltipContent:f},f))),Bn.default.createElement(Ac,{align:"start",className:"tw-w-32"},Bn.default.createElement(co,{onSelect:i},"Rename"),Bn.default.createElement(co,{onSelect:o},"Close")))},IOr=({initialValue:t,onSubmit:e,onCancel:n})=>{let[r,o]=Bn.default.useState(t),i=Bn.default.useRef(!1);return Bn.default.createElement(Ir,{autoFocus:!0,value:r,onChange:s=>o(s.target.value),onBlur:()=>{i.current||e(r)},onKeyDown:s=>{s.key==="Enter"?(s.preventDefault(),e(r)):s.key==="Escape"&&(s.preventDefault(),i.current=!0,n())},className:"tw-my-1 tw-h-6 tw-w-32 tw-text-xs"})},Rfn=({descriptor:t,status:e,needsAttention:n,onCloseOnHover:r})=>{let o=t?.Icon,i=e==="running",a=!i&&(n||e==="error"),l=n?"tw-bg-interactive-accent":"tw-bg-red";return Bn.default.createElement("span",{className:"tw-relative tw-flex tw-size-4 tw-shrink-0 tw-items-center tw-justify-center"},i?Bn.default.createElement(Dr,{className:J("tw-size-4 tw-animate-spin tw-text-loading",r&&"group-hover:tw-hidden")}):o?Bn.default.createElement(o,{className:J("tw-size-4",r&&"group-hover:tw-hidden")}):Bn.default.createElement("span",{className:J("tw-size-3 tw-rounded-full tw-bg-faint/40",r&&"group-hover:tw-hidden")}),r&&Bn.default.createElement(oe,{variant:"ghost2",size:"icon","aria-label":"Close session",onClick:c=>{c.stopPropagation(),r()},className:"tw-hidden tw-size-5 tw-cursor-pointer tw-rounded-sm tw-p-0 group-hover:tw-flex"},Bn.default.createElement(pn,{className:"tw-size-4"})),a&&Bn.default.createElement("span",{"aria-hidden":!0,className:J("tw-absolute -tw-right-0.5 -tw-top-0.5 tw-size-1.5 tw-rounded-full tw-ring-1 tw-ring-[var(--background-primary)]",r&&"group-hover:tw-hidden",l)}))},TOr=({sessions:t,activeId:e,onActivate:n,onClose:r})=>{let[o,i]=Bn.default.useState(!1);return Bn.default.createElement(up,{open:o,onOpenChange:i},Bn.default.createElement(dp,{asChild:!0},Bn.default.createElement(oe,{variant:"ghost2",size:"icon",className:"tw-my-1 tw-shrink-0","aria-label":`Show ${t.length} more session${t.length===1?"":"s"}`},Bn.default.createElement(V_,{className:"tw-size-4"}))),Bn.default.createElement(Ac,{align:"end",className:"tw-w-64"},t.map(s=>Bn.default.createElement(POr,{key:s.internalId,session:s,isActive:s.internalId===e,onActivate:()=>{n(s.internalId),i(!1)},onClose:()=>r(s.internalId)}))))},POr=({session:t,isActive:e,onActivate:n,onClose:r})=>{let{status:o,needsAttention:i,descriptor:s,displayLabel:a}=Ofn(t);return Bn.default.createElement("div",{role:"menuitem",tabIndex:-1,onClick:n,className:J("tw-group tw-flex tw-cursor-pointer tw-select-none tw-items-center tw-gap-2 tw-rounded-sm tw-px-2 tw-py-1.5 tw-text-sm tw-outline-none tw-transition-colors hover:tw-bg-modifier-hover hover:tw-text-normal",e&&"tw-bg-interactive-accent/10")},Bn.default.createElement(Rfn,{descriptor:s,status:o,needsAttention:i}),Bn.default.createElement(si,{className:"tw-min-w-0 tw-flex-1 !tw-text-current",tooltipContent:a},a),Bn.default.createElement(oe,{variant:"ghost2",size:"icon","aria-label":"Close session",onClick:l=>{l.stopPropagation(),r()},className:"tw-size-5 tw-shrink-0 tw-cursor-pointer tw-rounded-sm tw-p-0"},Bn.default.createElement(pn,{className:"tw-size-4"})))}});var zv,rnt,$fn=b(()=>{yt();De();Re();zv=L(B()),rnt=(0,zv.memo)(({onCreate:t,onDismiss:e,className:n})=>zv.default.createElement("div",{className:J("tw-relative tw-flex tw-flex-col tw-gap-2 tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-secondary tw-p-3",n)},zv.default.createElement(oe,{variant:"ghost2",size:"icon",onClick:e,"aria-label":"Dismiss",className:"tw-absolute tw-right-1 tw-top-1 tw-size-6 tw-text-muted hover:tw-text-normal"},zv.default.createElement(pn,{className:"tw-size-4"})),zv.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5 tw-pr-6 tw-text-ui-small tw-font-semibold tw-text-normal"},zv.default.createElement(hc,{className:"tw-size-4 tw-shrink-0 tw-text-accent"}),zv.default.createElement("span",null,"Try a project")),zv.default.createElement("p",{className:"tw-m-0 tw-text-ui-smaller tw-text-muted"},"Group notes, URLs, PDFs, and folders into a focused context. The agent answers only within those materials, and each project keeps its own chat history."),zv.default.createElement(oe,{variant:"default",size:"sm",onClick:r=>t(r.currentTarget),className:"tw-mt-1 tw-w-full tw-gap-2"},zv.default.createElement(yG,{className:"tw-size-4"}),"New project")));rnt.displayName="AgentWelcomeCard"});var MCe,OCe,ont=b(()=>{gt();De();MCe=L(B()),OCe=({className:t})=>MCe.default.createElement("svg",{viewBox:"0 0 100 100",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",className:J("tw-shrink-0",t)},MCe.default.createElement("g",{transform:GPe},MCe.default.createElement("path",{fill:"currentColor",d:ZPe})))});function NCe(t,e=Date.now()){let n=e-t;return!Number.isFinite(n)||n<6e4?"now":n<36e5?`${Math.floor(n/6e4)}m`:n<864e5?`${Math.floor(n/36e5)}h`:n<6048e5?`${Math.floor(n/864e5)}d`:n<2592e6?`${Math.floor(n/6048e5)}w`:`${Math.floor(n/2592e6)}mo`}var int=b(()=>{});function Ufn({items:t,total:e,label:n,popoverTitle:r,searchValue:o,onSearch:i,filter:s,searchPlaceholder:a,emptyMessage:l,renderRow:c}){let[u,d]=(0,Sr.useState)(!1),[f,p]=(0,Sr.useState)(RCe),m=(0,Sr.useRef)(null),h=(0,Sr.useMemo)(()=>s(t,o),[s,t,o]),g=(0,Sr.useMemo)(()=>h.slice(0,f),[h,f]);(0,Sr.useLayoutEffect)(()=>{u&&p(RCe)},[u,o]);let v=(0,Sr.useRef)({displayCount:RCe,total:0});(0,Sr.useEffect)(()=>{v.current={displayCount:f,total:h.length}},[f,h.length]);let y=(0,Sr.useCallback)(S=>{if(m.current?.disconnect(),m.current=null,!S)return;let I=new IntersectionObserver(C=>{if(!C[0].isIntersecting)return;let{displayCount:k,total:T}=v.current;k<T&&p(P=>Math.min(P+RCe,T))},{threshold:.1});I.observe(S),m.current=I},[]),w=S=>{d(S),S||i("")},_=()=>w(!1);return Sr.default.createElement(nc,{open:u,onOpenChange:w},Sr.default.createElement(Ku,{asChild:!0},Sr.default.createElement("div",{role:"button",tabIndex:0,className:J("tw-flex tw-cursor-pointer tw-items-center tw-justify-between tw-rounded-md tw-px-2 tw-py-1.5","tw-text-xs tw-text-accent tw-transition-colors hover:tw-bg-modifier-hover hover:tw-text-accent-hover"),onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),d(!0))}},Sr.default.createElement("span",null,"View all ",n),Sr.default.createElement(Vi,{className:"tw-size-3 tw-shrink-0"}))),Sr.default.createElement(Cl,{align:"start",side:"bottom",className:"tw-w-72 tw-p-0"},Sr.default.createElement("div",{className:"tw-flex tw-max-h-80 tw-flex-col"},Sr.default.createElement("div",{className:"tw-flex tw-shrink-0 tw-items-center tw-gap-2 tw-border-b tw-border-solid tw-border-border tw-p-2"},Sr.default.createElement("span",{className:"tw-text-ui-small tw-font-medium tw-text-normal"},r),Sr.default.createElement("span",{className:"tw-text-xs tw-text-muted"},e)),Sr.default.createElement("div",{className:"tw-shrink-0 tw-p-2"},Sr.default.createElement(rf,{value:o,onChange:i,placeholder:a})),Sr.default.createElement(Ym,{className:"tw-min-h-32 tw-flex-1 tw-overflow-y-auto"},Sr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-0.5 tw-p-2 tw-pt-0"},h.length===0?Sr.default.createElement("div",{className:"tw-py-6 tw-text-center tw-text-xs tw-text-muted"},l):Sr.default.createElement(Sr.default.Fragment,null,g.map(S=>c(S,_)),Sr.default.createElement("div",{ref:y,className:"tw-h-1"}),f<h.length&&Sr.default.createElement("div",{className:"tw-py-1 tw-text-center tw-text-xs tw-text-muted"},"Showing ",f," of ",h.length," \u2014 scroll for more")))))))}var Sr,ZV,RCe,Dfn,Ffn,snt=b(()=>{Gb();M$();pk();yt();De();int();Re();Sr=L(B()),ZV=5,RCe=50,Dfn=(0,Sr.memo)(function({label:e,onClick:n}){return Sr.default.createElement(oe,{type:"button",variant:"ghost2",onClick:r=>n(r.currentTarget),"aria-label":e,className:"tw-h-auto tw-min-h-9 tw-w-full tw-justify-start tw-gap-2 tw-rounded-md tw-px-2 tw-py-1.5 hover:tw-bg-modifier-hover"},Sr.default.createElement("span",{className:"tw-flex tw-size-6 tw-shrink-0 tw-items-center tw-justify-center tw-rounded-md tw-bg-interactive-accent-hsl/10"},Sr.default.createElement(zs,{className:"tw-size-4 tw-text-accent"})),Sr.default.createElement("span",{className:"tw-text-ui-small tw-font-medium tw-text-accent"},e))}),Ffn=(0,Sr.memo)(function({label:e,timeMs:n,onClick:r,indent:o=!1,icon:i,leading:s,trailing:a}){return Sr.default.createElement("div",{role:"button",tabIndex:0,className:J("tw-group tw-flex tw-min-h-9 tw-w-full tw-cursor-pointer tw-items-center tw-gap-2 tw-rounded-md tw-px-2 tw-py-1.5","tw-text-left tw-transition-colors hover:tw-bg-modifier-hover"),onClick:r,onKeyDown:l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),r())}},s??(i&&Sr.default.createElement("span",{className:"tw-flex tw-size-6 tw-shrink-0 tw-items-center tw-justify-center"},Sr.default.createElement(i,{className:"tw-size-4 tw-text-muted"}))),Sr.default.createElement("span",{className:J("tw-min-w-0 tw-flex-1 tw-truncate tw-text-ui-small tw-text-normal",o&&!i&&!s&&"tw-pl-6"),title:e},e),Sr.default.createElement("span",{className:J("tw-shrink-0 tw-whitespace-nowrap tw-text-xs tw-text-muted",a&&"group-focus-within:tw-hidden group-hover:tw-hidden"),title:new Date(n).toLocaleString()},NCe(n)),a&&Sr.default.createElement("span",{className:"tw-hidden tw-shrink-0 tw-items-center group-focus-within:tw-flex group-hover:tw-flex",onClick:l=>l.stopPropagation(),onKeyDown:l=>l.stopPropagation()},a))})});function ant({name:t}){return LCe.default.createElement(ei,{variant:"secondary","aria-label":`Project: ${t}`,title:t,className:"tw-min-w-0 tw-max-w-24 tw-shrink-0 tw-px-1.5 tw-py-0 tw-font-normal tw-text-muted"},LCe.default.createElement("span",{className:"tw-truncate"},t))}function jfn({title:t,className:e}){return LCe.default.createElement("span",{className:J("tw-block tw-min-w-0 tw-flex-1 tw-truncate tw-text-ui-small tw-text-normal",e),title:t},t)}var LCe,Bfn=b(()=>{pm();De();LCe=L(B())});function zfn(t){return t.backendId?$a[t.backendId]?.Icon:void 0}function EOr(t){return ay(t,"recent",{getName:e=>e.title,getCreatedAtMs:e=>e.createdAt.getTime(),getLastUsedAtMs:e=>e.lastAccessedAt.getTime()})}var Gt,AOr,lnt,MOr,$Ce,Hfn=b(()=>{Wm();snt();Bfn();yt();hl();M$();pk();Zbe();oJe();De();H5();int();wC();Re();Gt=L(B());Hl();AOr=()=>{};lnt=(0,Gt.memo)(({Icon:t,needsAttention:e})=>Gt.default.createElement("span",{"aria-hidden":"true",className:"tw-flex tw-size-6 tw-shrink-0 tw-items-center tw-justify-center tw-rounded-md tw-bg-secondary tw-text-muted"},Gt.default.createElement(tee,{icon:t,needsAttention:e,iconClassName:"tw-size-4"})));lnt.displayName="ChatIconTile";MOr=(0,Gt.memo)(function({item:e,projectName:n,isEditing:r,editingTitle:o,confirmingDelete:i,onOpen:s,onStartEdit:a,onEditingTitleChange:l,onSaveEdit:c,onCancelEdit:u,onStartDelete:d,onConfirmDelete:f,onCancelDelete:p,canOpenSourceFile:m,onOpenSourceFile:h,isRunning:g,hasAttention:v}){let y=zfn(e)??BC;return r?Gt.default.createElement("div",{className:"tw-flex tw-min-h-9 tw-items-center tw-gap-2 tw-rounded-md tw-px-2 tw-py-1.5"},Gt.default.createElement(lnt,{Icon:y,needsAttention:v}),Gt.default.createElement(Ir,{value:o,onChange:w=>l(w.target.value),className:"!tw-h-6 tw-flex-1",autoFocus:!0,onKeyDown:w=>{w.key==="Enter"?c():w.key==="Escape"&&u()}}),Gt.default.createElement(oe,{size:"sm",variant:"ghost",onClick:c,className:"tw-size-5 tw-p-0"},Gt.default.createElement(Hr,{className:"tw-size-3"})),Gt.default.createElement(oe,{size:"sm",variant:"ghost",onClick:u,className:"tw-size-5 tw-p-0"},Gt.default.createElement(pn,{className:"tw-size-3"}))):Gt.default.createElement("div",{role:"button",tabIndex:0,className:J("tw-group tw-flex tw-min-h-9 tw-cursor-pointer tw-items-center tw-gap-2 tw-rounded-md tw-px-2 tw-py-1.5","tw-text-left tw-transition-colors hover:tw-bg-modifier-hover"),onClick:()=>s(e.id),onKeyDown:w=>{w.target===w.currentTarget&&(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),s(e.id))}},Gt.default.createElement(lnt,{Icon:y,needsAttention:v}),Gt.default.createElement(jfn,{title:e.title}),Gt.default.createElement("div",{className:"tw-flex tw-shrink-0 tw-items-center tw-gap-1.5"},n&&Gt.default.createElement(ant,{name:n}),g?Gt.default.createElement(Dr,{className:J("tw-size-3.5 tw-shrink-0 tw-animate-spin tw-text-accent","group-focus-within:tw-hidden group-hover:tw-hidden"),"aria-label":"Running"}):Gt.default.createElement("span",{className:"tw-shrink-0 tw-whitespace-nowrap tw-text-xs tw-text-muted group-focus-within:tw-hidden group-hover:tw-hidden",title:new Date(e.lastAccessedAt).toLocaleString()},NCe(e.lastAccessedAt.getTime())),Gt.default.createElement("div",{className:"tw-hidden tw-shrink-0 tw-items-center tw-gap-1.5 group-focus-within:tw-flex group-hover:tw-flex"},i?Gt.default.createElement(Gt.default.Fragment,null,Gt.default.createElement(oe,{size:"sm",variant:"ghost",onClick:w=>{w.stopPropagation(),f(e.id)},className:"tw-size-5 tw-p-0 tw-text-error hover:tw-text-error",title:"Confirm delete"},Gt.default.createElement(Hr,{className:"tw-size-3"})),Gt.default.createElement(oe,{size:"sm",variant:"ghost",onClick:w=>{w.stopPropagation(),p()},className:"tw-size-5 tw-p-0",title:"Cancel"},Gt.default.createElement(pn,{className:"tw-size-3"}))):Gt.default.createElement(Gt.default.Fragment,null,m&&Gt.default.createElement(oe,{size:"sm",variant:"ghost",onClick:w=>{w.stopPropagation(),h(e.id)},className:"tw-size-5 tw-p-0",title:"Open source note"},Gt.default.createElement(us,{className:"tw-size-4"})),Gt.default.createElement(oe,{size:"sm",variant:"ghost",onClick:w=>{w.stopPropagation(),a(e.id,e.title)},className:"tw-size-5 tw-p-0",title:"Rename"},Gt.default.createElement(rm,{className:"tw-size-3"})),Gt.default.createElement(oe,{size:"sm",variant:"ghost",onClick:w=>{w.stopPropagation(),d(e.id)},className:"tw-size-5 tw-p-0 tw-text-error hover:tw-text-error",title:"Delete"},Gt.default.createElement(Ts,{className:"tw-size-3"}))))))}),$Ce=(0,Gt.memo)(function({items:e,variant:n="global",title:r,onLoadChat:o,onUpdateTitle:i,onDeleteChat:s,onOpenSourceFile:a,onLoadHistory:l,runningChatIds:c,attentionChatIds:u,projectNamesById:d,className:f}){let[p,m]=(0,Gt.useState)(""),[h,g]=(0,Gt.useState)(null),[v,y]=(0,Gt.useState)(""),[w,_]=(0,Gt.useState)(null);(0,Gt.useEffect)(()=>{l?.()},[l]);let S=(0,Gt.useMemo)(()=>EOr(e),[e]),I=p.trim().length>0,C=(0,Gt.useMemo)(()=>{let Q=p.trim().toLowerCase();return Q?S.filter(ne=>ne.title.toLowerCase().includes(Q)):S},[S,p]),k=(0,Gt.useMemo)(()=>I?C:C.slice(0,ZV),[C,I]),T=!I&&C.length>ZV,P=(0,Gt.useCallback)((Q,ne)=>{_(null),g(Q),y(ne)},[]),E=(0,Gt.useCallback)(()=>{let Q=v.trim(),ne=h;g(null),!(!ne||!Q)&&i(ne,Q)},[h,v,i]),O=(0,Gt.useCallback)(Q=>{_(null),s(Q)},[s]),$=(0,Gt.useCallback)(Q=>{a(Q)},[a]),U=xn(o),V=(0,Gt.useCallback)(()=>g(null),[]),K=(0,Gt.useCallback)(()=>_(null),[]),se=(0,Gt.useCallback)(Q=>n==="global"&&Q.projectId?d?.[Q.projectId]:void 0,[d,n]),le=(0,Gt.useCallback)(Q=>{let ne=se(Q);return ne?Gt.default.createElement(ant,{name:ne}):null},[se]);return Gt.default.createElement("div",{role:r?"group":void 0,"aria-label":r,className:J("tw-flex tw-grow tw-flex-col tw-gap-2",f)},e.length>0&&Gt.default.createElement("div",{className:"tw-p-1"},Gt.default.createElement(rf,{value:p,onChange:m,placeholder:"Search chats...",inputClassName:"!tw-h-7"})),C.length===0?Gt.default.createElement("div",{className:"tw-flex tw-flex-1 tw-items-center tw-justify-center tw-px-2 tw-py-1.5 tw-text-xs tw-text-muted"},e.length>0?"No matching chats":n==="project"?"No chats in this project yet":"No recent chats"):Gt.default.createElement("div",{className:"tw-flex tw-flex-col tw-divide-y tw-divide-border"},Gt.default.createElement(Ym,{className:"tw-max-h-56 tw-overflow-y-auto"},Gt.default.createElement("div",{className:"tw-flex tw-flex-col tw-divide-y tw-divide-border"},k.map(Q=>Gt.default.createElement(MOr,{key:Q.id,item:Q,projectName:se(Q),isEditing:h===Q.id,editingTitle:h===Q.id?v:"",confirmingDelete:w===Q.id,onOpen:U,onStartEdit:P,onEditingTitleChange:y,onSaveEdit:h===Q.id?E:AOr,onCancelEdit:V,onStartDelete:_,onConfirmDelete:O,onCancelDelete:K,canOpenSourceFile:!HF(Q.id),onOpenSourceFile:$,isRunning:c?.has(Q.id)??!1,hasAttention:!!Q.needsAttention||(u?.has(Q.id)??!1)})))),T&&Gt.default.createElement(C6,{chatHistory:e,onUpdateTitle:i,onDeleteChat:s,onLoadChat:o,onOpenSourceFile:a,getIcon:zfn,getBadge:le,side:"bottom",align:"start"},Gt.default.createElement("div",{role:"button",tabIndex:0,className:J("tw-flex tw-cursor-pointer tw-items-center tw-justify-between tw-rounded-md tw-px-2 tw-py-1.5","tw-text-xs tw-text-accent tw-transition-colors hover:tw-bg-modifier-hover hover:tw-text-accent-hover"),onClick:()=>l?.(),onKeyDown:Q=>{(Q.key==="Enter"||Q.key===" ")&&(Q.preventDefault(),Q.currentTarget.click())}},Gt.default.createElement("span",null,"View all chats"),Gt.default.createElement(Vi,{className:"tw-size-3 tw-shrink-0"})))))});$Ce.displayName="GlobalRecentChatsSection"});function Vfn(t,e){try{let n=t.loadLocalStorage(e);return typeof n=="string"&&n.length>0?n:null}catch{return null}}function qfn(t,e){return Vfn(t,e)}function Kfn(t,e,n){try{t.saveLocalStorage(e,n)}catch(r){W("Failed to persist home shelf tab",r)}}function Gfn(t){return Vfn(t,Wfn)==="true"}function Zfn(t){try{t.saveLocalStorage(Wfn,"true")}catch(e){W("Failed to persist pop-out hint dismissal",e)}}var cnt,Wfn,unt=b(()=>{pe();cnt="copilot:home-shelf-tab:v1",Wfn="copilot:relevant-notes-popout-hint-dismissed:v1"});function Yfn(t){let e=(0,Fte.useCallback)(r=>t?.subscribe(r)??(()=>{}),[t]),n=(0,Fte.useCallback)(()=>t?.getRevision()??0,[t]);return(0,Fte.useSyncExternalStore)(e,n)}var Fte,Jfn=b(()=>{Fte=L(B())});function OOr(t,e,n={}){let{caseSensitive:r=!1,searchInName:o=!0,searchInDescription:i=!0}=n;if(!e.trim())return!0;let s=r?e:e.toLowerCase();return!!(o&&(r?t.name:t.name.toLowerCase()).includes(s)||i&&t.description&&(r?t.description:t.description.toLowerCase()).includes(s))}function Xfn(t,e,n={}){return!t||t.length===0?[]:e.trim()?t.filter(r=>OOr(r,e,n)):t}var Qfn=b(()=>{});function epn(t,e){return e?.getEffectiveLastUsedAt(t.id,t.UsageTimestamps)||t.UsageTimestamps||t.created}function ROr(t,e){let n=Yfn(e);return(0,lu.useMemo)(()=>ay(t,NOr,{getName:r=>r.name,getCreatedAtMs:r=>r.created,getLastUsedAtMs:r=>e?.getEffectiveLastUsedAt(r.id,r.UsageTimestamps)??r.UsageTimestamps}),[t,e,n])}var lu,NOr,dnt,fnt,tpn=b(()=>{snt();tnt();Ztt();Jfn();De();Qfn();wC();lu=L(B()),NOr="recent";dnt=(0,lu.memo)(({project:t,timeMs:e,onSelect:n,app:r,onDeleted:o})=>lu.default.createElement(Ffn,{label:t.name,timeMs:e,onClick:()=>n(t),icon:TCe,trailing:lu.default.createElement(ent,{app:r,project:t,onDeleted:o})}));dnt.displayName="ProjectRow";fnt=(0,lu.memo)(({projects:t,onSelect:e,onCreate:n,app:r,onProjectDeleted:o,projectUsageTimestampsManager:i,className:s})=>{let[a,l]=(0,lu.useState)(""),c=ROr(t,i),u=(0,lu.useMemo)(()=>c.slice(0,ZV),[c]),d=t.length,f=d>ZV;return lu.default.createElement("div",{className:J("tw-flex tw-grow tw-flex-col tw-divide-y tw-divide-border",s)},n&&lu.default.createElement(Dfn,{label:"New project",onClick:n}),d===0?lu.default.createElement("div",{className:"tw-flex tw-flex-1 tw-items-center tw-justify-center tw-px-2 tw-py-1.5 tw-text-xs tw-text-muted"},"No projects available"):lu.default.createElement(lu.default.Fragment,null,u.map(p=>lu.default.createElement(dnt,{key:p.id,project:p,timeMs:epn(p,i),onSelect:e,app:r,onDeleted:o})),f&&lu.default.createElement(Ufn,{items:c,total:d,label:"projects",popoverTitle:"All projects",searchValue:a,onSearch:l,filter:Xfn,searchPlaceholder:"Search projects",emptyMessage:"No matching projects",renderRow:(p,m)=>lu.default.createElement(dnt,{key:p.id,project:p,timeMs:epn(p,i),onSelect:h=>{e(h),m()},app:r,onDeleted:o})})))});fnt.displayName="ProjectPickerList"});var YV,pnt=b(()=>{fm();YV=class extends _i{constructor(e,n,r){let o=r?`Semantic search requires building an embedding index for your vault.
Use 'Refresh Vault Index' or 'Force Reindex Vault' commands to build the index after enabling.`:`Disabling semantic search will fall back to index-free lexical search (less resource-intensive, could be less accurate).
Your existing index will be preserved but not used.`,i=r?"Enable Semantic Search":"Disable Semantic Search",s=r?"Enable":"Disable";super(e,n,o,i,s,"Cancel")}}});function mnt(){let t=vn(),[e,n]=(0,JV.useState)(()=>t.workspace.getActiveFile()),r=(0,JV.useContext)(Gd);return(0,JV.useEffect)(()=>{let o=()=>{let i=t.workspace.getActiveFile();n(i)};return r?.addEventListener(cs.ACTIVE_LEAF_CHANGE,o),()=>{r?.removeEventListener(cs.ACTIVE_LEAF_CHANGE,o)}},[t,r]),e}var JV,npn=b(()=>{gt();ko();JV=L(B())});function opn(){let t=vn();return(0,rpn.useCallback)((n,r)=>{let o=t.dragManager;if(!o)return;n.dataTransfer.setData("copilot/internal-drag","true");let i=t.metadataCache.fileToLinktext(r,""),s=o.dragLink(n.nativeEvent,i);o.onDragStart(n.nativeEvent,s)},[t])}var rpn,ipn=b(()=>{rpn=L(B());ko()});function apn(t,e,n=20){let r=t.metadataCache.getFileCache(e),o=[];if(r?.links)for(let i of r.links){let s=t.metadataCache.getFirstLinkpathDest(i.link,e.path);if(s&&(o.push(s),o.length>=n))break}if(r?.embeds&&o.length<n)for(let i of r.embeds){let s=t.metadataCache.getFirstLinkpathDest(i.link,e.path);if(s&&(o.push(s),o.length>=n))break}return[...new Set(o)]}function lpn(t,e,n=20){let r=[],o=t.metadataCache.getBacklinksForFile(e);if(o?.data)for(let[i]of o.data){let s=t.vault.getAbstractFileByPath(i);if(s instanceof spn.TFile&&(r.push(s),r.length>=n))break}return r}var spn,cpn=b(()=>{W5();spn=require("obsidian")});function fpn(t){return t!==void 0&&Ute.includes(t)?upn[t]:void 0}var upn,dpn,Ute,DCe=b(()=>{upn={arabic:"ar",armenian:"am",bulgarian:"bg",danish:"dk",dutch:"nl",english:"en",finnish:"fi",french:"fr",german:"de",greek:"gr",hungarian:"hu",indian:"in",indonesian:"id",irish:"ie",italian:"it",lithuanian:"lt",nepali:"np",norwegian:"no",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"rs",slovenian:"ru",spanish:"es",swedish:"se",tamil:"ta",turkish:"tr",ukrainian:"uk",sanskrit:"sk"},dpn={dutch:/[^A-Za-zàèéìòóù0-9_'-]+/gim,english:/[^A-Za-zàèéìòóù0-9_'-]+/gim,french:/[^a-z0-9äâàéèëêïîöôùüûœç-]+/gim,italian:/[^A-Za-zàèéìòóù0-9_'-]+/gim,norwegian:/[^a-z0-9_æøåÆØÅäÄöÖüÜ]+/gim,portuguese:/[^a-z0-9à-úÀ-Ú]/gim,russian:/[^a-z0-9а-яА-ЯёЁ]+/gim,spanish:/[^a-z0-9A-Zá-úÁ-ÚñÑüÜ]+/gim,swedish:/[^a-z0-9_åÅäÄöÖüÜ-]+/gim,german:/[^a-z0-9A-ZäöüÄÖÜß]+/gim,finnish:/[^a-z0-9äöÄÖ]+/gim,danish:/[^a-z0-9æøåÆØÅ]+/gim,hungarian:/[^a-z0-9áéíóöőúüűÁÉÍÓÖŐÚÜŰ]+/gim,romanian:/[^a-z0-9ăâîșțĂÂÎȘȚ]+/gim,serbian:/[^a-z0-9čćžšđČĆŽŠĐ]+/gim,turkish:/[^a-z0-9çÇğĞıİöÖşŞüÜ]+/gim,lithuanian:/[^a-z0-9ąčęėįšųūžĄČĘĖĮŠŲŪŽ]+/gim,arabic:/[^a-z0-9أ-ي]+/gim,nepali:/[^a-z0-9अ-ह]+/gim,irish:/[^a-z0-9áéíóúÁÉÍÓÚ]+/gim,indian:/[^a-z0-9अ-ह]+/gim,armenian:/[^a-z0-9ա-ֆ]+/gim,greek:/[^a-z0-9α-ωά-ώ]+/gim,indonesian:/[^a-z0-9]+/gim,ukrainian:/[^a-z0-9а-яА-ЯіїєІЇЄ]+/gim,slovenian:/[^a-z0-9螚ȎŠ]+/gim,bulgarian:/[^a-z0-9а-яА-Я]+/gim,tamil:/[^a-z0-9அ-ஹ]+/gim,sanskrit:/[^a-z0-9A-Zāīūṛḷṃṁḥśṣṭḍṇṅñḻḹṝ]+/gim},Ute=Object.keys(upn)});function bs(t,e){if(e.length<hnt)Array.prototype.push.apply(t,e);else{let n=e.length;for(let r=0;r<n;r+=hnt)Array.prototype.push.apply(t,e.slice(r,r+hnt))}}function ypn(t,...e){return t.replace(/%(?:(?<position>\d+)\$)?(?<width>-?\d*\.?\d*)(?<type>[dfs])/g,function(...n){let r=n[n.length-1],{width:o,type:i,position:s}=r,a=s?e[Number.parseInt(s)-1]:e.shift(),l=o===""?0:Number.parseInt(o);switch(i){case"d":return a.toString().padStart(l,"0");case"f":{let c=a,[u,d]=o.split(".").map(f=>Number.parseFloat(f));return typeof d=="number"&&d>=0&&(c=c.toFixed(d)),typeof u=="number"&&u>=0?c.toString().padStart(l,"0"):c.toString()}case"s":return l<0?a.toString().padEnd(-l," "):a.toString().padStart(l," ");default:return a}})}function DOr(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function FOr(){return typeof process<"u"&&process.release&&process.release.name==="node"}function gpn(){return BigInt(Math.floor(performance.now()*1e6))}function wD(t){return typeof t=="number"&&(t=BigInt(t)),t<ppn?`${t}ns`:t<mpn?`${t/ppn}\u03BCs`:t<hpn?`${t/mpn}ms`:`${t/hpn}s`}function v_(){return DOr()?gpn():FOr()||typeof process<"u"&&typeof process?.hrtime?.bigint=="function"?process.hrtime.bigint():typeof performance<"u"?gpn():BigInt(0)}function jte(){return`${LOr}-${$Or++}`}function XV(t,e){return Object.hasOwn===void 0?Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0:Object.hasOwn(t,e)?t[e]:void 0}function vpn(t,e){return e[1]===t[1]?t[0]-e[0]:e[1]-t[1]}function QV(t){if(t.length===0)return[];if(t.length===1)return t[0];for(let n=1;n<t.length;n++)if(t[n].length<t[0].length){let r=t[0];t[0]=t[n],t[n]=r}let e=new Map;for(let n of t[0])e.set(n,1);for(let n=1;n<t.length;n++){let r=0;for(let o of t[n]){let i=e.get(o);i===n&&(e.set(o,i+1),r++)}if(r===0)return[]}return t[0].filter(n=>{let r=e.get(n);return r!==void 0&&e.set(n,0),r===t.length})}function FCe(t,e){let n={},r=e.length;for(let o=0;o<r;o++){let i=e[o],s=i.split("."),a=t,l=s.length;for(let c=0;c<l;c++)if(a=a[s[c]],typeof a=="object"){if(a!==null&&"lat"in a&&"lon"in a&&typeof a.lat=="number"&&typeof a.lon=="number"){a=n[i]=a;break}else if(!Array.isArray(a)&&a!==null&&c===l-1){a=void 0;break}}else if((a===null||typeof a!="object")&&c<l-1){a=void 0;break}typeof a<"u"&&(n[i]=a)}return n}function e3(t,e){return FCe(t,[e])[e]}function gnt(t,e){let n=UOr[e];if(n===void 0)throw new Error(Pn("INVALID_DISTANCE_SUFFIX",t).message);return t*n}function UCe(t,e){t.hits=t.hits.map(n=>({...n,document:{...n.document,...e.reduce((r,o)=>{let i=o.split("."),s=i.pop(),a=r;for(let l of i)a[l]=a[l]??{},a=a[l];return a[s]=null,r},n.document)}}))}function oc(t){return t?.constructor?.name==="AsyncFunction"}var LOr,$Or,ppn,mpn,hpn,hnt,UOr,Al=b(()=>{td();LOr=Date.now().toString().slice(5),$Or=0,ppn=BigInt(1e3),mpn=BigInt(1e6),hpn=BigInt(1e9),hnt=65535;UOr={cm:.01,m:1,km:1e3,ft:.3048,yd:.9144,mi:1609.344}});function Pn(t,...e){let n=new Error(ypn(BOr[t]??`Unsupported Orama Error code: ${t}`,...e));return n.code=t,"captureStackTrace"in Error.prototype&&Error.captureStackTrace(n),n}var jOr,BOr,td=b(()=>{DCe();Al();jOr=Ute.join(`
- `),BOr={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported.
Supported languages are:
- ${jOr}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.oramasearch.com/open-source/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.oramasearch for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facet doens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.',INVALID_SEARCH_MODE:'Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".',MISSING_VECTOR_AND_SECURE_PROXY:"No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.",MISSING_TERM:'"term" is a required parameter when performing hybrid search. Please provide a search term.',INVALID_VECTOR_INPUT:'Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.',PLUGIN_CRASHED:"A plugin crashed during initialization. Please check the error message for more information:",PLUGIN_SECURE_PROXY_NOT_FOUND:`Could not find '@orama/secure-proxy-plugin' installed in your Orama instance.
Please install it before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL:`Could not find a chat model defined in the secure proxy plugin configuration.
Please provide a chat model before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages."}});function wpn(t){return{raw:Number(t),formatted:wD(t)}}function bpn(t){if(t.id){if(typeof t.id!="string")throw Pn("DOCUMENT_ID_MUST_BE_STRING",typeof t.id);return t.id}return jte()}function ynt(t,e){for(let[n,r]of Object.entries(e)){let o=t[n];if(!(typeof o>"u")&&!(r==="geopoint"&&typeof o=="object"&&typeof o.lon=="number"&&typeof o.lat=="number")&&!(r==="enum"&&(typeof o=="string"||typeof o=="number"))){if(r==="enum[]"&&Array.isArray(o)){let i=o.length;for(let s=0;s<i;s++)if(typeof o[s]!="string"&&typeof o[s]!="number")return n+"."+s;continue}if(O0(r)){let i=wnt(r);if(!Array.isArray(o)||o.length!==i)throw Pn("INVALID_INPUT_VECTOR",n,i,o.length);continue}if(t3(r)){if(!Array.isArray(o))return n;let i=vnt(r),s=o.length;for(let a=0;a<s;a++)if(typeof o[a]!==i)return n+"."+a;continue}if(typeof r=="object"){if(!o||typeof o!="object")return n;let i=ynt(o,r);if(i)return n+"."+i;continue}if(typeof o!==r)return n}}}function _pn(t){return t==="geopoint"}function O0(t){return typeof t=="string"&&/^vector\[\d+\]$/.test(t)}function t3(t){return typeof t=="string"&&zOr[t]}function vnt(t){return HOr[t]}function wnt(t){let e=Number(t.slice(7,-1));switch(!0){case isNaN(e):throw Pn("INVALID_VECTOR_VALUE",t);case e<=0:throw Pn("INVALID_VECTOR_SIZE",t);default:return e}}var zOr,HOr,Bte=b(()=>{td();Al();Al();zOr={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},HOr={"string[]":"string","number[]":"number","boolean[]":"boolean","enum[]":"enum"}});function xpn(){return{idToInternalId:new Map,internalIdToId:[],save:WOr,load:VOr}}function WOr(t){return{internalIdToId:t.internalIdToId}}function VOr(t,e){let{internalIdToId:n}=e;t.internalDocumentIDStore.idToInternalId.clear(),t.internalDocumentIDStore.internalIdToId=[];let r=n.length;for(let o=0;o<r;o++){let i=n[o];t.internalDocumentIDStore.idToInternalId.set(i,o+1),t.internalDocumentIDStore.internalIdToId.push(i)}}function Ji(t,e){if(typeof e=="string"){let n=t.idToInternalId.get(e);if(n)return n;let r=t.idToInternalId.size+1;return t.idToInternalId.set(e,r),t.internalIdToId.push(e),r}return e>t.internalIdToId.length?Ji(t,e.toString()):e}function Hv(t,e){if(t.internalIdToId.length<e)throw new Error(`Invalid internalId ${e}`);return t.internalIdToId[e-1]}var Wv=b(()=>{});function KOr(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}function GOr(t,e){let n=Ji(t.sharedInternalDocumentStore,e);return t.docs[n]}function ZOr(t,e){let n=e.length,r=Array.from({length:n});for(let o=0;o<n;o++){let i=Ji(t.sharedInternalDocumentStore,e[o]);r[o]=t.docs[i]}return r}function YOr(t){return t.docs}function JOr(t,e,n){let r=Ji(t.sharedInternalDocumentStore,e);return typeof t.docs[r]<"u"?!1:(t.docs[r]=n,t.count++,!0)}function XOr(t,e){let n=Ji(t.sharedInternalDocumentStore,e);return typeof t.docs[n]>"u"?!1:(delete t.docs[n],t.count--,!0)}function QOr(t){return t.count}function eNr(t,e){let n=e;return{docs:n.docs,count:n.count,sharedInternalDocumentStore:t}}function tNr(t){return{docs:t.docs,count:t.count}}function Spn(){return{create:KOr,get:GOr,getMultiple:ZOr,getAll:YOr,store:JOr,remove:XOr,count:QOr,load:eNr,save:tNr}}var bnt=b(()=>{Wv()});function kpn(t,e){let n=[],r=t.plugins?.length;if(!r)return n;for(let o=0;o<r;o++)try{let i=t.plugins[o];typeof i[e]=="function"&&n.push(i[e])}catch(i){throw console.error("Caught error in getAllPluginsByHook:",i),Pn("PLUGIN_CRASHED")}return n}var Cpn,Ipn=b(()=>{td();Cpn=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeLoad","afterLoad","afterCreate"]});function w_(t,e,n,r){if(t.some(oc))return(async()=>{for(let i of t)await i(e,n,r)})();for(let i of t)i(e,n,r)}function bD(t,e,n){if(t.some(oc))return(async()=>{for(let o of t)await o(e,n)})();for(let o of t)o(e,n)}function n3(t,e,n,r,o){if(t.some(oc))return(async()=>{for(let s of t)await s(e,n,r,o)})();for(let s of t)s(e,n,r,o)}function r3(t,e,n,r){if(t.some(oc))return(async()=>{for(let i of t)await i(e,n,r)})();for(let i of t)i(e,n,r)}function Ppn(t,e){if(t.some(oc))return(async()=>{for(let r of t)await r(e)})();for(let r of t)r(e)}var Tpn,_nt,OM=b(()=>{Al();Tpn=["tokenizer","index","documentsStore","sorter"],_nt=["validateSchema","getDocumentIndexId","getDocumentProperties","formatElapsedTime"]});function xnt(t){let e=t.r;return t.r=e.l,e.l=t,t.h=Math.max(Vv(t.l),Vv(t.r))+1,e.h=Math.max(Vv(e.l),Vv(e.r))+1,e}function Snt(t){let e=t.l;return t.l=e.r,e.r=t,t.h=Math.max(Vv(t.l),Vv(t.r))+1,e.h=Math.max(Vv(e.l),Vv(e.r))+1,e}function Epn(t,e,n){let r=[];function o(i){i!==null&&(e<i.k&&o(i.l),i.k>=e&&i.k<=n&&bs(r,i.v),n>i.k&&o(i.r))}return o(t.root),r}function Cnt(t,e,n=!1){let r=[];if(t===null)return r;let o=[t.root];for(;o.length>0;){let i=o.pop();i&&(n&&i.k>=e&&bs(r,i.v),!n&&i.k>e&&bs(r,i.v),o.push(i.r),o.push(i.l))}return r}function knt(t,e,n=!1){let r=[];if(t===null)return r;let o=[t.root];for(;o.length>0;){let i=o.pop();i&&(n&&i.k<=e&&bs(r,i.v),!n&&i.k<e&&bs(r,i.v),o.push(i.r),o.push(i.l))}return r}function Mpn(t,e){for(;t!==null;)if(e<t.k)t=t.l;else if(e>t.k)t=t.r;else return t;return null}function Opn(t,e){return{root:{k:t,v:e,l:null,r:null,h:0}}}function Npn(t,e,n,r=500){function o(i,s,a){if(i===null)return Apn++,{k:s,v:a,l:null,r:null,h:0};if(s<i.k)i.l=o(i.l,s,a);else if(s>i.k)i.r=o(i.r,s,a);else return i.v.push(...a),i;return Apn%r===0?rNr(i,s):i}t.root=o(t.root,e,n)}function rNr(t,e){t.h=1+Math.max(Vv(t.l),Vv(t.r));let n=Vv(t.l)-Vv(t.r);return n>1&&e<t.l.k?Snt(t):n<-1&&e>t.r.k?xnt(t):n>1&&e>t.l.k?(t.l=xnt(t.l),Snt(t)):n<-1&&e<t.r.k?(t.r=Snt(t.r),xnt(t)):t}function Vv(t){return t!==null?t.h:-1}function Rpn(t,e){let n=Mpn(t.root,e);return n===null?null:n.v}function oNr(t,e){if(t===null||t.root===null)return;let n=t.root,r=null;for(;n!=null&&n.k!==e;)r=n,e<n.k?n=n.l:n=n.r;if(n===null)return;(()=>{if(n.l===null&&n.r===null)r===null?t.root=null:r.l===n?r.l=null:r.r=null;else if(n.l!=null&&n.r!=null){let i=n.r,s=n;for(;i.l!=null;)s=i,i=i.l;n.k=i.k,s===n?s.r=i.r:s.l=i.r}else{let i=n.l!=null?n.l:n.r;r===null?t.root=i:r.l===n?r.l=i:r.r=i}})()}function Lpn(t,e,n){let r=Mpn(t.root,n);if(r){if(r.v.length===1){oNr(t,n);return}r.v.splice(r.v.indexOf(e),1)}}var Apn,$pn=b(()=>{Al();Apn=0});function Dpn(){return{numberToDocumentId:new Map}}function Fpn(t,e,n){return t.numberToDocumentId.has(e)?(t.numberToDocumentId.get(e).push(n),t):(t.numberToDocumentId.set(e,[n]),t)}function Upn(t,e,n){t?.numberToDocumentId.set(n,t?.numberToDocumentId.get(n)?.filter(r=>r!==e)??[]),t?.numberToDocumentId.get(n)?.length===0&&t?.numberToDocumentId.delete(n)}function jpn(t,e){let n=Object.keys(e);if(n.length!==1)throw new Error("Invalid operation");let r=n[0];switch(r){case"eq":{let o=e[r];return t.numberToDocumentId.get(o)??[]}case"in":{let o=e[r],i=[];for(let s of o){let a=t.numberToDocumentId.get(s);a!=null&&bs(i,a)}return i}case"nin":{let o=e[r],i=[],s=t.numberToDocumentId.keys();for(let a of s){if(o.includes(a))continue;let l=t.numberToDocumentId.get(a);l!=null&&bs(i,l)}return i}}throw new Error("Invalid operation")}function Bpn(t,e){let n=Object.keys(e);if(n.length!==1)throw new Error("Invalid operation");let r=n[0];switch(r){case"containsAll":{let i=e[r].map(s=>t.numberToDocumentId.get(s)??[]);return QV(i)}}throw new Error("Invalid operation")}var zpn=b(()=>{Al()});function iNr(t,e,n){if(n<0)return-1;if(t===e)return 0;let r=t.length,o=e.length;if(r===0)return o<=n?o:-1;if(o===0)return r<=n?r:-1;if(t=t.toLowerCase(),e=e.toLowerCase(),e.startsWith(t)||t.startsWith(e))return 0;if(Math.abs(r-o)>n)return-1;let i=[];for(let s=0;s<=r;s++){i[s]=[s];for(let a=1;a<=o;a++)i[s][a]=s===0?a:0}for(let s=1;s<=r;s++){let a=1/0;for(let l=1;l<=o;l++)t[s-1]===e[l-1]?i[s][l]=i[s-1][l-1]:i[s][l]=Math.min(i[s-1][l]+1,i[s][l-1]+1,i[s-1][l-1]+1),a=Math.min(a,i[s][l]);if(a>n)return-1}return i[r][o]<=n?i[r][o]:-1}function Int(t,e,n){let r=iNr(t,e,n);return{distance:r,isBounded:r>=0}}var Tnt=b(()=>{});function o3(t,e){t.w=e.w+t.s}function jCe(t,e){t.d.push(e)}function sNr(t,e){let n=t.d.indexOf(e);return n===-1?!1:(t.d.splice(n,1),!0)}function Ant(t,e,n,r,o){if(t.e){let{w:i,d:s}=t;if(r&&i!==n)return{};if(XV(e,i)==null&&(o?Math.abs(n.length-i.length)<=o&&Int(n,i,o).isBounded&&(e[i]=[]):e[i]=[]),XV(e,i)!=null&&s.length>0){let a=new Set(e[i]),l=s.length;for(let c=0;c<l;c++)a.add(s[c]);e[i]=Array.from(a)}}for(let i of Object.keys(t.c))Ant(t.c[i],e,n,r,o);return e}function Hpn(t,e){let n="",r=Math.min(t.length,e.length);for(let o=0;o<r;o++){if(t[o]!==e[o])return n;n+=t[o]}return n}function _D(t=!1,e="",n=""){return new Pnt(n,e,t)}function Wpn(t,e,n){let r=e.length;for(let o=0;o<r;o++){let i=e[o],s=e.substring(o),a=t.c[i];if(a){let l=a.s,c=l.length,u=Hpn(l,s),d=u.length;if(l===s){jCe(a,n),a.e=!0;return}let f=l[d];if(d<c&&d===s.length){let p=_D(!0,s,i);p.c[f]=a;let m=p.c[f];m.s=l.substring(d),m.k=f,t.c[i]=p,o3(p,t),o3(m,p),jCe(p,n);return}if(d<c&&d<s.length){let p=_D(!1,u,i);p.c[f]=a,t.c[i]=p;let m=p.c[f];m.s=l.substring(d),m.k=f;let h=s[d],g=_D(!0,e.substring(o+d),h);jCe(g,n),p.c[h]=g,o3(p,t),o3(g,p),o3(m,p);return}o+=c-1,t=a}else{let l=_D(!0,s,i);jCe(l,n),t.c[i]=l,o3(l,t);return}}}function zte(t,e,n,r,o,i){if(!(r<0)){if(t.w.startsWith(e)){Ant(t,i,e,!1,0);return}if(t.e){let{w:s,d:a}=t;if(s&&(Int(e,s,o).isBounded&&(i[s]=[]),XV(i,s)!=null&&a.length>0)){let l=new Set(i[s]),c=a.length;for(let u=0;u<c;u++)l.add(a[u]);i[s]=Array.from(l)}}if(!(n>=e.length)){e[n]in t.c&&zte(t.c[e[n]],e,n+1,r,o,i),zte(t,e,n+1,r-1,o,i);for(let s in t.c)zte(t.c[s],e,n,r-1,o,i);for(let s in t.c)s!==e[n]&&zte(t.c[s],e,n+1,r-1,o,i)}}}function Ent(t,{term:e,exact:n,tolerance:r}){if(r&&!n){let o={};return r=r||0,zte(t,e,0,r||0,r,o),o}else{let o=e.length;for(let s=0;s<o;s++){let a=e[s];if(a in t.c){let l=t.c[a],c=l.s,u=e.substring(s),f=Hpn(c,u).length;if(f!==c.length&&f!==u.length){if(r)break;return{}}s+=l.s.length-1,t=l}else return{}}let i={};return Ant(t,i,e,n,r),i}}function Vpn(t,e,n,r=!0){if(!e)return!0;let o=e.length;for(let i=0;i<o;i++){let s=e[i];if(s in t.c){let a=t.c[s];i+=a.s.length-1,t=a,r&&t.w!==e||sNr(t,n)}else return!1}return!0}var Pnt,qpn=b(()=>{Tnt();Al();Pnt=class{constructor(e,n,r){M(this,"k");M(this,"s");M(this,"c",{});M(this,"d",[]);M(this,"e");M(this,"w","");this.k=e,this.s=n,this.e=r}toJSON(){return{w:this.w,s:this.s,c:this.c,d:this.d,e:this.e}}}});function Kpn(){return{root:null}}function Gpn(t,e,n){let r={point:e,docIDs:n};if(t.root==null){t.root=r;return}let o=t.root,i=0;for(;o!==null;){if(o.point.lon===e.lon&&o.point.lat===e.lat){let a=o.docIDs??[];o.docIDs=Array.from(new Set([...a,...n||[]]));return}if(i%2===0)if(e.lon<o.point.lon){if(o.left==null){o.left=r;return}o=o.left}else{if(o.right==null){o.right=r;return}o=o.right}else if(e.lat<o.point.lat){if(o.left==null){o.left=r;return}o=o.left}else{if(o.right==null){o.right=r;return}o=o.right}i++}}function Zpn(t,e,n){let r=t.root,o=0,i=null,s=null;for(;r!==null;){if(r?.point.lon===e.lon&&r.point.lat===e.lat){let l=r.docIDs?.indexOf(n);if(l!==void 0&&l>-1){r.docIDs?.splice(l,1),(r.docIDs==null||r.docIDs.length===0)&&(i!=null?s==="left"?i.left=r.left!==null?r.left:r.right:s==="right"&&(i.right=r.right!==null?r.right:r.left):t.root=r.left!==null?r.left:r.right);return}}let a=o%2;i=r,a===0?e.lon<r.point.lon?(r=r?.left,s="left"):(r=r?.right,s="right"):e.lat<r.point.lat?(r=r?.left,s="left"):(r=r?.right,s="right"),o++}}function Ypn(t,e,n,r=!0,o="asc",i=!1){let s=i?Qpn:Xpn,a=[{node:t,depth:0}],l=[];for(;a.length>0;){let{node:c,depth:u}=a.pop();if(c===null)continue;let d=s(e,c.point);(r?d<=n:d>n)&&l.push({point:c.point,docIDs:c.docIDs??[]}),c.left!=null&&a.push({node:c.left,depth:u+1}),c.right!=null&&a.push({node:c.right,depth:u+1})}return o&&l.sort((c,u)=>{let d=s(e,c.point),f=s(e,u.point);return o.toLowerCase()==="asc"?d-f:f-d}),l}function Jpn(t,e,n=!0,r=null,o=!1){let i=[{node:t,depth:0}],s=[];for(;i.length>0;){let l=i.pop();if(l==null||l.node==null)continue;let{node:c,depth:u}=l,d=u+1;c.left!=null&&i.push({node:c.left,depth:d}),c.right!=null&&i.push({node:c.right,depth:d});let f=lNr(e,c.point);f&&n?s.push({point:c.point,docIDs:c.docIDs??[]}):!f&&!n&&s.push({point:c.point,docIDs:c.docIDs??[]})}let a=aNr(e);if(r){let l=o?Qpn:Xpn;s.sort((c,u)=>{let d=l(a,c.point),f=l(a,u.point);return r.toLowerCase()==="asc"?d-f:f-d})}return s}function aNr(t){let e=0,n=0,r=0,o=t.length;for(let s=0,a=o-1;s<o;a=s++){let l=t[s].lon,c=t[s].lat,u=t[a].lon,d=t[a].lat,f=l*d-u*c;e+=f,n+=(l+u)*f,r+=(c+d)*f}e/=2;let i=6*e;return n/=i,r/=i,{lon:n,lat:r}}function lNr(t,e){let n=!1,r=e.lon,o=e.lat,i=t.length;for(let s=0,a=i-1;s<i;a=s++){let l=t[s].lon,c=t[s].lat,u=t[a].lon,d=t[a].lat;c>o!=d>o&&r<(u-l)*(o-c)/(d-c)+l&&(n=!n)}return n}function Xpn(t,e){let n=Math.PI/180,r=t.lat*n,o=e.lat*n,i=(e.lat-t.lat)*n,s=(e.lon-t.lon)*n,a=Math.sin(i/2)*Math.sin(i/2)+Math.cos(r)*Math.cos(o)*Math.sin(s/2)*Math.sin(s/2);return 6371e3*(2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a)))}function Qpn(t,e){let r=.0033528106647474805,o=(1-r)*6378137,i=Math.PI/180,s=t.lat*i,a=e.lat*i,l=(e.lon-t.lon)*i,c=Math.atan((1-r)*Math.tan(s)),u=Math.atan((1-r)*Math.tan(a)),d=Math.sin(c),f=Math.cos(c),p=Math.sin(u),m=Math.cos(u),h=l,g,v=1e3,y,w,_,S,I;do{let O=Math.sin(h),$=Math.cos(h);_=Math.sqrt(m*O*(m*O)+(f*p-d*m*$)*(f*p-d*m*$)),S=d*p+f*m*$,I=Math.atan2(_,S),y=f*m*O/_,w=1-y*y;let U=S-2*d*p/w,V=r/16*w*(4+r*(4-3*w));g=h,h=l+(1-V)*r*y*(I+V*_*(U+V*S*(-1+2*U*U)))}while(Math.abs(h-g)>1e-12&&--v>0);let C=w*(6378137*6378137-o*o)/(o*o),k=1+C/16384*(4096+C*(-768+C*(320-175*C))),T=C/1024*(256+C*(-128+C*(74-47*C))),P=T*_*(S-2*d*p/w+T/4*(S*(-1+2*_*_)-T/6*I*(-3+4*_*_)*(-3+4*I*I)));return o*k*(I-P)}var emn=b(()=>{});function BCe(t,e,n=0,r){if(e===0)throw Pn("INVALID_BOOST_VALUE");let o=new Map,i=t.length;for(let h=0;h<i;h++){let g=t[h],v=g.length;for(let y=0;y<v;y++){let[w,_]=g[y],S=_*e,I=o.get(w)?.[0];I!==void 0?o.set(w,[I*1.5+S,(o?.get(w)?.[1]||0)+1]):o.set(w,[S,1])}}let s=[];for(let h of o.entries())s.push([h[0],h[1][0]]);let a=s.sort((h,g)=>g[1]-h[1]);if(n===1)return a;let l=a.length,c=[];for(let h of o.entries())c.push([h[0],h[1][0],h[1][1]]);let u=c.sort((h,g)=>h[2]>g[2]?-1:h[2]<g[2]?1:h[1]>g[1]?-1:h[1]<g[1]?1:0),d;for(let h=0;h<l&&u[h][2]===r;h++)d=h;if(typeof d>"u"){if(n===0)return[];d=0}let f=u.length,p=new Array(f);for(let h=0;h<f;h++)p[h]=[u[h][0],u[h][1]];if(n===0)return p.slice(0,d+1);let m=d+Math.ceil(n*100*(l-d)/100);return p.slice(0,l+m)}function Mnt(t,e,n,r,o,{k:i,b:s,d:a}){return Math.log(1+(n-e+.5)/(e+.5))*(a+t*(i+1))/(t+i*(1-s+s*r/o))}var Hte=b(()=>{td()});function Ont(t,e){let n=0;for(let r=0;r<e;r++)n+=t[r]*t[r];return Math.sqrt(n)}function zCe(t,e,n,r=.8){let o=Ont(t,n),i=[];for(let[s,[a,l]]of Object.entries(e)){let c=0;for(let d=0;d<n;d++)c+=t[d]*l[d];let u=c/(o*a);u>=r&&i.push([s,u])}return i.sort((s,a)=>a[1]-s[1])}var HCe=b(()=>{});function cNr(t,e,n,r,o){let i=Ji(t.sharedInternalDocumentStore,n);t.avgFieldLength[e]=((t.avgFieldLength[e]??0)*(o-1)+r.length)/o,t.fieldLengths[e][i]=r.length,t.frequencies[e][i]={}}function uNr(t,e,n,r,o){let i=0;for(let l of r)l===o&&i++;let s=Ji(t.sharedInternalDocumentStore,n),a=i/r.length;t.frequencies[e][s][o]=a,o in t.tokenOccurrences[e]||(t.tokenOccurrences[e][o]=0),t.tokenOccurrences[e][o]=(t.tokenOccurrences[e][o]??0)+1}function dNr(t,e,n,r){let o=Ji(t.sharedInternalDocumentStore,n);r>1?t.avgFieldLength[e]=(t.avgFieldLength[e]*r-t.fieldLengths[e][o])/(r-1):t.avgFieldLength[e]=void 0,t.fieldLengths[e][o]=void 0,t.frequencies[e][o]=void 0}function fNr(t,e,n){t.tokenOccurrences[e][n]--}function pNr(t,e,n,r,o){let i=Array.from(o),s=e.avgFieldLength[n],a=e.fieldLengths[n],l=e.tokenOccurrences[n],c=e.frequencies[n],u=typeof l[r]=="number"?l[r]??0:0,d=[],f=i.length;for(let p=0;p<f;p++){let m=Ji(e.sharedInternalDocumentStore,i[p]),h=c?.[m]?.[r]??0,g=Mnt(h,u,t.docsCount,a[m],s,t.params.relevance);d.push([m,g])}return d}function nmn(t,e,n,r,o=""){r||(r={sharedInternalDocumentStore:e,indexes:{},vectorIndexes:{},searchableProperties:[],searchablePropertiesWithTypes:{},frequencies:{},tokenOccurrences:{},avgFieldLength:{},fieldLengths:{}});for(let[i,s]of Object.entries(n)){let a=`${o}${o?".":""}${i}`;if(typeof s=="object"&&!Array.isArray(s)){nmn(t,e,s,r,a);continue}if(O0(s))r.searchableProperties.push(a),r.searchablePropertiesWithTypes[a]=s,r.vectorIndexes[a]={size:wnt(s),vectors:{}};else{let l=/\[/.test(s);switch(s){case"boolean":case"boolean[]":r.indexes[a]={type:"Bool",node:{true:[],false:[]},isArray:l};break;case"number":case"number[]":r.indexes[a]={type:"AVL",node:Opn(0,[]),isArray:l};break;case"string":case"string[]":r.indexes[a]={type:"Radix",node:_D(),isArray:l},r.avgFieldLength[a]=0,r.frequencies[a]={},r.tokenOccurrences[a]={},r.fieldLengths[a]={};break;case"enum":case"enum[]":r.indexes[a]={type:"Flat",node:Dpn(),isArray:l};break;case"geopoint":r.indexes[a]={type:"BKD",node:Kpn(),isArray:l};break;default:throw Pn("INVALID_SCHEMA_TYPE",Array.isArray(s)?"array":s,a)}r.searchableProperties.push(a),r.searchablePropertiesWithTypes[a]=s}}return r}function mNr(t,e,n,r,o,i,s,a){return l=>{let c=Ji(e.sharedInternalDocumentStore,r),{type:u,node:d}=e.indexes[n];switch(u){case"Bool":{d[l?"true":"false"].push(c);break}case"AVL":{let f=a?.avlRebalanceThreshold??1;Npn(d,l,[c],f);break}case"Radix":{let f=i.tokenize(l,o,n);t.insertDocumentScoreParameters(e,n,c,f,s);for(let p of f)t.insertTokenScoreParameters(e,n,c,f,p),Wpn(d,p,c);break}case"Flat":{Fpn(d,l,c);break}case"BKD":{Gpn(d,l,[c]);break}}}}function hNr(t,e,n,r,o,i,s,a,l,c){if(O0(i))return gNr(e,n,o,r);let u=mNr(t,e,n,r,s,a,l,c);if(!t3(i))return u(o);let d=o,f=d.length;for(let p=0;p<f;p++)u(d[p])}function gNr(t,e,n,r){n instanceof Float32Array||(n=new Float32Array(n));let o=t.vectorIndexes[e].size,i=Ont(n,o);t.vectorIndexes[e].vectors[r]=[i,n]}function tmn(t,e,n,r,o,i,s,a,l){let c=Ji(e.sharedInternalDocumentStore,r);if(O0(i))return delete e.vectorIndexes[n].vectors[r],!0;let{type:u,node:d}=e.indexes[n];switch(u){case"AVL":return Lpn(d,c,o),!0;case"Bool":{let p=d[o?"true":"false"].indexOf(c);return d[o?"true":"false"].splice(p,1),!0}case"Radix":{let f=a.tokenize(o,s,n);t.removeDocumentScoreParameters(e,n,r,l);for(let p of f)t.removeTokenScoreParameters(e,n,p),Vpn(d,p,c);return!0}case"Flat":return Upn(d,c,o),!0;case"BKD":return Zpn(d,o,c),!1}}function yNr(t,e,n,r,o,i,s,a,l){if(!t3(i))return tmn(t,e,n,r,o,i,s,a,l);let c=vnt(i),u=o,d=u.length;for(let f=0;f<d;f++)tmn(t,e,n,r,u[f],c,s,a,l);return!0}function vNr(t,e,n,r){if(!(n in e.tokenOccurrences))return[];let{node:o,type:i}=e.indexes[n];if(i!=="Radix")throw Pn("WRONG_SEARCH_PROPERTY_TYPE",n);let{exact:s,tolerance:a}=t.params,l=Ent(o,{term:r,exact:s,tolerance:a}),c=new Set;for(let u in l)if(XV(l,u))for(let f of l[u])c.add(f);return t.index.calculateResultScores(t,e,n,r,Array.from(c))}function wNr(t,e,n){let r=Object.keys(n),o=r.reduce((i,s)=>({[s]:[],...i}),{});for(let i of r){let s=n[i];if(typeof e.indexes[i]>"u")throw Pn("UNKNOWN_FILTER_PROPERTY",i);let{node:a,type:l,isArray:c}=e.indexes[i];if(l==="Bool"){let f=a[s.toString()];bs(o[i],f);continue}if(l==="BKD"){let d;if("radius"in s)d="radius";else if("polygon"in s)d="polygon";else throw new Error(`Invalid operation ${s}`);if(d==="radius"){let{value:f,coordinates:p,unit:m="m",inside:h=!0,highPrecision:g=!1}=s[d],v=gnt(f,m),y=Ypn(a.root,p,v,h,void 0,g);bs(o[i],y.flatMap(({docIDs:w})=>w))}else{let{coordinates:f,inside:p=!0,highPrecision:m=!1}=s[d],h=Jpn(a.root,f,p,void 0,m);bs(o[i],h.flatMap(({docIDs:g})=>g))}continue}if(l==="Radix"&&(typeof s=="string"||Array.isArray(s))){for(let d of[s].flat()){let f=t.tokenizer.tokenize(d,t.language,i);for(let p of f){let m=Ent(a,{term:p,exact:!0});bs(o[i],Object.values(m).flat())}}continue}let u=Object.keys(s);if(u.length>1)throw Pn("INVALID_FILTER_OPERATION",u.length);if(l==="Flat"){let d=c?Bpn:jpn;bs(o[i],d(a,s));continue}if(l==="AVL"){let d=u[0],f=s[d],p=[];switch(d){case"gt":{p=Cnt(a,f,!1);break}case"gte":{p=Cnt(a,f,!0);break}case"lt":{p=knt(a,f,!1);break}case"lte":{p=knt(a,f,!0);break}case"eq":{p=Rpn(a,f)??[];break}case"between":{let[m,h]=f;p=Epn(a,m,h);break}}bs(o[i],p)}}return QV(Object.values(o))}function bNr(t){return t.searchableProperties}function _Nr(t){return t.searchablePropertiesWithTypes}function rmn(t){let e=_D(t.e,t.s,t.k);e.d=t.d,e.w=t.w;for(let n of Object.keys(t.c))e.c[n]=rmn(t.c[n]);return e}function xNr(t){return{numberToDocumentId:new Map(t)}}function SNr(t){return Array.from(t.numberToDocumentId.entries())}function CNr(t,e){let{indexes:n,vectorIndexes:r,searchableProperties:o,searchablePropertiesWithTypes:i,frequencies:s,tokenOccurrences:a,avgFieldLength:l,fieldLengths:c}=e,u={},d={};for(let f of Object.keys(n)){let{node:p,type:m,isArray:h}=n[f];switch(m){case"Radix":u[f]={type:"Radix",node:rmn(p),isArray:h};break;case"Flat":u[f]={type:"Flat",node:xNr(p),isArray:h};break;default:u[f]=n[f]}}for(let f of Object.keys(r)){let p=r[f].vectors;for(let m in p)p[m]=[p[m][0],new Float32Array(p[m][1])];d[f]={size:r[f].size,vectors:p}}return{sharedInternalDocumentStore:t,indexes:u,vectorIndexes:d,searchableProperties:o,searchablePropertiesWithTypes:i,frequencies:s,tokenOccurrences:a,avgFieldLength:l,fieldLengths:c}}function kNr(t){let{indexes:e,vectorIndexes:n,searchableProperties:r,searchablePropertiesWithTypes:o,frequencies:i,tokenOccurrences:s,avgFieldLength:a,fieldLengths:l}=t,c={};for(let d of Object.keys(n)){let f=n[d].vectors;for(let p in f)f[p]=[f[p][0],Array.from(f[p][1])];c[d]={size:n[d].size,vectors:f}}let u={};for(let d of Object.keys(e)){let{type:f,node:p,isArray:m}=e[d];if(f!=="Flat"){u[d]=e[d];continue}u[d]={type:"Flat",node:SNr(p),isArray:m}}return{indexes:u,vectorIndexes:c,searchableProperties:r,searchablePropertiesWithTypes:o,frequencies:i,tokenOccurrences:s,avgFieldLength:a,fieldLengths:l}}function omn(){return{create:nmn,insert:hNr,remove:yNr,insertDocumentScoreParameters:cNr,insertTokenScoreParameters:uNr,removeDocumentScoreParameters:dNr,removeTokenScoreParameters:fNr,calculateResultScores:pNr,search:vNr,searchByWhereClause:wNr,getSearchableProperties:bNr,getSearchablePropertiesWithTypes:_Nr,load:CNr,save:kNr}}var Nnt=b(()=>{td();$pn();zpn();qpn();emn();Al();Hte();HCe();Bte();Wv()});function imn(t,e,n,r,o){let i={language:t.tokenizer.language,sharedInternalDocumentStore:e,enabled:!0,isSorted:!0,sortableProperties:[],sortablePropertiesWithTypes:{},sorts:{}};for(let[s,a]of Object.entries(n)){let l=`${o}${o?".":""}${s}`;if(!r.includes(l)){if(typeof a=="object"&&!Array.isArray(a)){let c=imn(t,e,a,r,l);bs(i.sortableProperties,c.sortableProperties),i.sorts={...i.sorts,...c.sorts},i.sortablePropertiesWithTypes={...i.sortablePropertiesWithTypes,...c.sortablePropertiesWithTypes};continue}if(!O0(a))switch(a){case"boolean":case"number":case"string":i.sortableProperties.push(l),i.sortablePropertiesWithTypes[l]=a,i.sorts[l]={docs:new Map,orderedDocsToRemove:new Map,orderedDocs:[],type:a};break;case"geopoint":case"enum":continue;case"enum[]":case"boolean[]":case"number[]":case"string[]":continue;default:throw Pn("INVALID_SORT_SCHEMA_TYPE",Array.isArray(a)?"array":a,l)}}}return i}function TNr(t,e,n,r){return r?.enabled!==!1?imn(t,e,n,(r||{}).unsortableProperties||[],""):{disabled:!0}}function PNr(t,e,n,r){if(!t.enabled)return;t.isSorted=!1;let o=Ji(t.sharedInternalDocumentStore,n),i=t.sorts[e];i.orderedDocsToRemove.has(o)&&Rnt(t,e),i.docs.set(o,i.orderedDocs.length),i.orderedDocs.push([o,r])}function smn(t){if(t.isSorted||!t.enabled)return;let e=Object.keys(t.sorts);for(let n of e)ONr(t,n);t.isSorted=!0}function ANr(t,e,n){return e[1].localeCompare(n[1],fpn(t))}function ENr(t,e){return t[1]-e[1]}function MNr(t,e){return e[1]?-1:1}function ONr(t,e){let n=t.sorts[e],r;switch(n.type){case"string":r=ANr.bind(null,t.language);break;case"number":r=ENr.bind(null);break;case"boolean":r=MNr.bind(null);break}n.orderedDocs.sort(r);let o=n.orderedDocs.length;for(let i=0;i<o;i++){let s=n.orderedDocs[i][0];n.docs.set(s,i)}}function NNr(t){let e=Object.keys(t.sorts);for(let n of e)Rnt(t,n)}function Rnt(t,e){let n=t.sorts[e];n.orderedDocsToRemove.size&&(n.orderedDocs=n.orderedDocs.filter(r=>!n.orderedDocsToRemove.has(r[0])),n.orderedDocsToRemove.clear())}function RNr(t,e,n){if(!t.enabled)return;let r=t.sorts[e],o=Ji(t.sharedInternalDocumentStore,n);r.docs.get(o)&&(r.docs.delete(o),r.orderedDocsToRemove.set(o,!0))}function LNr(t,e,n){if(!t.enabled)throw Pn("SORT_DISABLED");let r=n.property,o=n.order==="DESC",i=t.sorts[r];if(!i)throw Pn("UNABLE_TO_SORT_ON_UNKNOWN_FIELD",r,t.sortableProperties.join(", "));return Rnt(t,r),smn(t),e.sort((s,a)=>{let l=i.docs.get(Ji(t.sharedInternalDocumentStore,s[0])),c=i.docs.get(Ji(t.sharedInternalDocumentStore,a[0])),u=typeof l<"u",d=typeof c<"u";return!u&&!d?0:u?d?o?c-l:l-c:-1:1}),e}function $Nr(t){return t.enabled?t.sortableProperties:[]}function DNr(t){return t.enabled?t.sortablePropertiesWithTypes:{}}function FNr(t,e){let n=e;if(!n.enabled)return{enabled:!1};let r=Object.keys(n.sorts).reduce((o,i)=>{let{docs:s,orderedDocs:a,type:l}=n.sorts[i];return o[i]={docs:new Map(Object.entries(s).map(([c,u])=>[+c,u])),orderedDocsToRemove:new Map,orderedDocs:a,type:l},o},{});return{sharedInternalDocumentStore:t,language:n.language,sortableProperties:n.sortableProperties,sortablePropertiesWithTypes:n.sortablePropertiesWithTypes,sorts:r,enabled:!0,isSorted:n.isSorted}}function UNr(t){if(!t.enabled)return{enabled:!1};NNr(t),smn(t);let e=Object.keys(t.sorts).reduce((n,r)=>{let{docs:o,orderedDocs:i,type:s}=t.sorts[r];return n[r]={docs:Object.fromEntries(o.entries()),orderedDocs:i,type:s},n},{});return{language:t.language,sortableProperties:t.sortableProperties,sortablePropertiesWithTypes:t.sortablePropertiesWithTypes,sorts:e,enabled:t.enabled,isSorted:t.isSorted}}function amn(){return{create:TNr,insert:PNr,remove:RNr,save:UNr,load:FNr,sortBy:LNr,getSortableProperties:$Nr,getSortablePropertiesWithTypes:DNr}}var Lnt=b(()=>{td();Bte();Wv();Al();DCe()});function zNr(t){return t<192||t>383?t:BNr[t-192]||t}function lmn(t){let e=[];for(let n=0;n<t.length;n++)e[n]=zNr(t.charCodeAt(n));return String.fromCharCode(...e)}var BNr,cmn=b(()=>{BNr=[65,65,65,65,65,65,65,67,69,69,69,69,73,73,73,73,69,78,79,79,79,79,79,null,79,85,85,85,85,89,80,115,97,97,97,97,97,97,97,99,101,101,101,101,105,105,105,105,101,110,111,111,111,111,111,null,111,117,117,117,117,121,112,121,65,97,65,97,65,97,67,99,67,99,67,99,67,99,68,100,68,100,69,101,69,101,69,101,69,101,69,101,71,103,71,103,71,103,71,103,72,104,72,104,73,105,73,105,73,105,73,105,73,105,73,105,74,106,75,107,107,76,108,76,108,76,108,76,108,76,108,78,110,78,110,78,110,110,78,110,79,111,79,111,79,111,79,111,82,114,82,114,82,114,83,115,83,115,83,115,83,115,84,116,84,116,84,116,85,117,85,117,85,117,85,117,85,117,85,117,87,119,89,121,89,90,122,90,122,90,122,115]});function dmn(t){let e,n,r,o,i,s;if(t.length<3)return t;let a=t.substring(0,1);if(a=="y"&&(t=a.toUpperCase()+t.substring(1)),r=/^(.+?)(ss|i)es$/,o=/^(.+?)([^s])s$/,r.test(t)?t=t.replace(r,"$1$2"):o.test(t)&&(t=t.replace(o,"$1$2")),r=/^(.+?)eed$/,o=/^(.+?)(ed|ing)$/,r.test(t)){let l=r.exec(t);r=new RegExp($nt),r.test(l[1])&&(r=/.$/,t=t.replace(r,""))}else o.test(t)&&(e=o.exec(t)[1],o=new RegExp(umn),o.test(e)&&(t=e,o=/(at|bl|iz)$/,i=new RegExp("([^aeiouylsz])\\1$"),s=new RegExp("^"+ZS+VCe+"[^aeiouwxy]$"),o.test(t)?t=t+"e":i.test(t)?(r=/.$/,t=t.replace(r,"")):s.test(t)&&(t=t+"e")));if(r=/^(.+?)y$/,r.test(t)&&(e=r.exec(t)?.[1],r=new RegExp(umn),e&&r.test(e)&&(t=e+"i")),r=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,r.test(t)){let l=r.exec(t);e=l?.[1],n=l?.[2],r=new RegExp($nt),e&&r.test(e)&&(t=e+HNr[n])}if(r=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,r.test(t)){let l=r.exec(t);e=l?.[1],n=l?.[2],r=new RegExp($nt),e&&r.test(e)&&(t=e+WNr[n])}if(r=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/,o=/^(.+?)(s|t)(ion)$/,r.test(t))e=r.exec(t)?.[1],r=new RegExp(WCe),e&&r.test(e)&&(t=e);else if(o.test(t)){let l=o.exec(t);e=l?.[1]??""+l?.[2]??"",o=new RegExp(WCe),o.test(e)&&(t=e)}return r=/^(.+?)e$/,r.test(t)&&(e=r.exec(t)?.[1],r=new RegExp(WCe),o=new RegExp(qNr),i=new RegExp("^"+ZS+VCe+"[^aeiouwxy]$"),e&&(r.test(e)||o.test(e)&&!i.test(e))&&(t=e)),r=/ll$/,o=new RegExp(WCe),r.test(t)&&o.test(t)&&(r=/.$/,t=t.replace(r,"")),a=="y"&&(t=a.toLowerCase()+t.substring(1)),t}var HNr,WNr,VNr,VCe,ZS,Wte,$nt,qNr,WCe,umn,fmn=b(()=>{HNr={ational:"ate",tional:"tion",enci:"ence",anci:"ance",izer:"ize",bli:"ble",alli:"al",entli:"ent",eli:"e",ousli:"ous",ization:"ize",ation:"ate",ator:"ate",alism:"al",iveness:"ive",fulness:"ful",ousness:"ous",aliti:"al",iviti:"ive",biliti:"ble",logi:"log"},WNr={icate:"ic",ative:"",alize:"al",iciti:"ic",ical:"ic",ful:"",ness:""},VNr="[^aeiou]",VCe="[aeiouy]",ZS=VNr+"[^aeiouy]*",Wte=VCe+"[aeiou]*",$nt="^("+ZS+")?"+Wte+ZS,qNr="^("+ZS+")?"+Wte+ZS+"("+Wte+")?$",WCe="^("+ZS+")?"+Wte+ZS+Wte+ZS,umn="^("+ZS+")?"+VCe});function Dnt(t,e){let n=`${this.language}:${t}:${e}`;return this.normalizationCache.has(n)?this.normalizationCache.get(n):this.stopWords?.includes(e)?(this.normalizationCache.set(n,""),""):(this.stemmer&&!this.stemmerSkipProperties.has(t)&&(e=this.stemmer(e)),e=lmn(e),this.normalizationCache.set(n,e),e)}function KNr(t){for(;t[t.length-1]==="";)t.pop();for(;t[0]==="";)t.shift();return t}function pmn(t,e,n){if(e&&e!==this.language)throw Pn("LANGUAGE_NOT_SUPPORTED",e);if(typeof t!="string")return[t];let r;if(n&&this.tokenizeSkipProperties.has(n))r=[this.normalizeToken.bind(this,n??"")(t)];else{let i=dpn[this.language];r=t.toLowerCase().split(i).map(this.normalizeToken.bind(this,n??"")).filter(Boolean)}let o=KNr(r);return this.allowDuplicates?o:Array.from(new Set(o))}function Fnt(t={}){if(!t.language)t.language="english";else if(!Ute.includes(t.language))throw Pn("LANGUAGE_NOT_SUPPORTED",t.language);let e;if(t.stemming||t.stemmer&&!("stemming"in t))if(t.stemmer){if(typeof t.stemmer!="function")throw Pn("INVALID_STEMMER_FUNCTION_TYPE");e=t.stemmer}else if(t.language==="english")e=dmn;else throw Pn("MISSING_STEMMER",t.language);let n;if(t.stopWords!==!1){if(n=[],Array.isArray(t.stopWords))n=t.stopWords;else if(typeof t.stopWords=="function")n=t.stopWords(n);else if(t.stopWords)throw Pn("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");if(!Array.isArray(n))throw Pn("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");for(let o of n)if(typeof o!="string")throw Pn("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY")}let r={tokenize:pmn,language:t.language,stemmer:e,stemmerSkipProperties:new Set(t.stemmerSkipProperties?[t.stemmerSkipProperties].flat():[]),tokenizeSkipProperties:new Set(t.tokenizeSkipProperties?[t.tokenizeSkipProperties].flat():[]),stopWords:n,allowDuplicates:!!t.allowDuplicates,normalizeToken:Dnt,normalizationCache:new Map};return r.tokenize=pmn.bind(r),r.normalizeToken=Dnt,r}var qCe=b(()=>{td();cmn();DCe();fmn()});function ZNr(t){let e={formatElapsedTime:wpn,getDocumentIndexId:bpn,getDocumentProperties:FCe,validateSchema:ynt};for(let n of _nt){let r=n;if(t[r]){if(typeof t[r]!="function")throw Pn("COMPONENT_MUST_BE_FUNCTION",r)}else t[r]=e[r]}for(let n of Object.keys(t))if(!Tpn.includes(n)&&!_nt.includes(n))throw Pn("UNSUPPORTED_COMPONENT",n)}function i3({schema:t,sort:e,language:n,components:r,id:o,plugins:i}){r||(r={}),o||(o=jte());let s=r.tokenizer,a=r.index,l=r.documentsStore,c=r.sorter;if(s?s.tokenize?s=s:s=Fnt(s):s=Fnt({language:n??"english"}),r.tokenizer&&n)throw Pn("NO_LANGUAGE_WITH_CUSTOM_TOKENIZER");let u=xpn();a||(a=omn()),c||(c=amn()),l||(l=Spn()),ZNr(r);let{getDocumentProperties:d,getDocumentIndexId:f,validateSchema:p,formatElapsedTime:m}=r,h={data:{},caches:{},schema:t,tokenizer:s,index:a,sorter:c,documentsStore:l,internalDocumentIDStore:u,getDocumentProperties:d,getDocumentIndexId:f,validateSchema:p,beforeInsert:[],afterInsert:[],beforeRemove:[],afterRemove:[],beforeUpdate:[],afterUpdate:[],beforeSearch:[],afterSearch:[],beforeInsertMultiple:[],afterInsertMultiple:[],beforeRemoveMultiple:[],afterRemoveMultiple:[],afterUpdateMultiple:[],beforeUpdateMultiple:[],afterCreate:[],formatElapsedTime:m,id:o,plugins:i,version:YNr()};h.data={index:h.index.create(h,u,t),docs:h.documentsStore.create(h,u),sorting:h.sorter.create(h,u,t,e)};for(let v of Cpn)h[v]=(h[v]??[]).concat(kpn(h,v));let g=h.afterCreate;return g&&Ppn(g,h),h}function YNr(){return"{{VERSION}}"}var mmn=b(()=>{Bte();bnt();Ipn();OM();Nnt();Wv();Lnt();qCe();td();Al()});var hmn=b(()=>{});var Unt=b(()=>{Bte();bnt();Nnt();qCe();Lnt();Wv()});var KCe,jnt,Bnt,znt=b(()=>{KCe="fulltext",jnt="hybrid",Bnt="vector"});var NM,RM,Hnt=b(()=>{znt();NM=Symbol("orama.insertions"),RM=Symbol("orama.removals")});function Wnt(t){typeof t[NM]!="number"&&(queueMicrotask(()=>{t[NM]=void 0}),t[NM]=0),t[NM]>1e3?(gmn("Orama's insert operation is synchronous. Please avoid inserting a large number of document in a single operation in order not to block the main thread or, in alternative, please use insertMultiple.",{code:"ORAMA0001"}),t[NM]=-1):t[NM]>=0&&t[NM]++}function Vnt(t){typeof t[RM]!="number"&&(queueMicrotask(()=>{t[RM]=void 0}),t[RM]=0),t[RM]>1e3?(gmn("Orama's remove operation is synchronous. Please avoid removing a large number of document in a single operation in order not to block the main thread, in alternative, please use updateMultiple.",{code:"ORAMA0002"}),t[RM]=-1):t[RM]>=0&&t[RM]++}var gmn,qnt=b(()=>{Hnt();gmn=globalThis.process?.emitWarning??function(e,n){console.warn(`[WARNING] [${n.code}] ${e}`)}});function Vte(t,e,n,r,o){let i=t.validateSchema(e,t.schema);if(i)throw Pn("SCHEMA_VALIDATION_FAILURE",i);return oc(t.index.beforeInsert)||oc(t.index.insert)||oc(t.index.afterInsert)?eRr(t,e,n,r,o):tRr(t,e,n,r,o)}async function eRr(t,e,n,r,o){let{index:i,docs:s}=t.data,a=t.getDocumentIndexId(e);if(typeof a!="string")throw Pn("DOCUMENT_ID_MUST_BE_STRING",typeof a);if(!t.documentsStore.store(s,a,e))throw Pn("DOCUMENT_ALREADY_EXISTS",a);let l=t.documentsStore.count(s);r||await w_(t.beforeInsert,t,a,e);let c=t.index.getSearchableProperties(i),u=t.index.getSearchablePropertiesWithTypes(i),d=t.getDocumentProperties(e,c);for(let[f,p]of Object.entries(d)){if(typeof p>"u")continue;let m=typeof p,h=u[f];ymn(m,h,f,p)}return await nRr(t,a,c,d,l,n,e,o),r||await w_(t.afterInsert,t,a,e),Wnt(t),a}function tRr(t,e,n,r,o){let{index:i,docs:s}=t.data,a=t.getDocumentIndexId(e);if(typeof a!="string")throw Pn("DOCUMENT_ID_MUST_BE_STRING",typeof a);if(!t.documentsStore.store(s,a,e))throw Pn("DOCUMENT_ALREADY_EXISTS",a);let l=t.documentsStore.count(s);r||w_(t.beforeInsert,t,a,e);let c=t.index.getSearchableProperties(i),u=t.index.getSearchablePropertiesWithTypes(i),d=t.getDocumentProperties(e,c);for(let[f,p]of Object.entries(d)){if(typeof p>"u")continue;let m=typeof p,h=u[f];ymn(m,h,f,p)}return rRr(t,a,c,d,l,n,e,o),r||w_(t.afterInsert,t,a,e),Wnt(t),a}function ymn(t,e,n,r){if(!(_pn(e)&&typeof r=="object"&&typeof r.lon=="number"&&typeof r.lat=="number")&&!(O0(e)&&Array.isArray(r))&&!(t3(e)&&Array.isArray(r))&&!(XNr.has(e)&&QNr.has(t))&&t!==e)throw Pn("INVALID_DOCUMENT_PROPERTY",n,e,t)}async function nRr(t,e,n,r,o,i,s,a){for(let u of n){let d=r[u];if(typeof d>"u")continue;let f=t.index.getSearchablePropertiesWithTypes(t.data.index)[u];await t.index.beforeInsert?.(t.data.index,u,e,d,f,i,t.tokenizer,o),await t.index.insert(t.index,t.data.index,u,e,d,f,i,t.tokenizer,o,a),await t.index.afterInsert?.(t.data.index,u,e,d,f,i,t.tokenizer,o)}let l=t.sorter.getSortableProperties(t.data.sorting),c=t.getDocumentProperties(s,l);for(let u of l){let d=c[u];if(typeof d>"u")continue;let f=t.sorter.getSortablePropertiesWithTypes(t.data.sorting)[u];t.sorter.insert(t.data.sorting,u,e,d,f,i)}}function rRr(t,e,n,r,o,i,s,a){for(let u of n){let d=r[u];if(typeof d>"u")continue;let f=t.index.getSearchablePropertiesWithTypes(t.data.index)[u];t.index.beforeInsert?.(t.data.index,u,e,d,f,i,t.tokenizer,o),t.index.insert(t.index,t.data.index,u,e,d,f,i,t.tokenizer,o,a),t.index.afterInsert?.(t.data.index,u,e,d,f,i,t.tokenizer,o)}let l=t.sorter.getSortableProperties(t.data.sorting),c=t.getDocumentProperties(s,l);for(let u of l){let d=c[u];if(typeof d>"u")continue;let f=t.sorter.getSortablePropertiesWithTypes(t.data.sorting)[u];t.sorter.insert(t.data.sorting,u,e,d,f,i)}}var XNr,QNr,Knt=b(()=>{Unt();Al();OM();qnt();td();XNr=new Set(["enum","enum[]"]),QNr=new Set(["string","number"])});function xD(t,e,n,r){return oc(t.index.beforeRemove)||oc(t.index.remove)||oc(t.index.afterRemove)?oRr(t,e,n,r):iRr(t,e,n,r)}async function oRr(t,e,n,r){let o=!0,{index:i,docs:s}=t.data,a=t.documentsStore.get(s,e);if(!a)return!1;let l=Hv(t.internalDocumentIDStore,Ji(t.internalDocumentIDStore,e)),c=t.documentsStore.count(s);r||await w_(t.beforeRemove,t,l);let u=t.index.getSearchableProperties(i),d=t.index.getSearchablePropertiesWithTypes(i),f=t.getDocumentProperties(a,u);for(let h of u){let g=f[h];if(typeof g>"u")continue;let v=d[h];await t.index.beforeRemove?.(t.data.index,h,l,g,v,n,t.tokenizer,c),await t.index.remove(t.index,t.data.index,h,e,g,v,n,t.tokenizer,c)||(o=!1),await t.index.afterRemove?.(t.data.index,h,l,g,v,n,t.tokenizer,c)}let p=await t.sorter.getSortableProperties(t.data.sorting),m=await t.getDocumentProperties(a,p);for(let h of p)typeof m[h]>"u"||t.sorter.remove(t.data.sorting,h,e);return r||await w_(t.afterRemove,t,l),t.documentsStore.remove(t.data.docs,e),Vnt(t),o}function iRr(t,e,n,r){let o=!0,{index:i,docs:s}=t.data,a=t.documentsStore.get(s,e);if(!a)return!1;let l=Hv(t.internalDocumentIDStore,Ji(t.internalDocumentIDStore,e)),c=t.documentsStore.count(s);r||w_(t.beforeRemove,t,l);let u=t.index.getSearchableProperties(i),d=t.index.getSearchablePropertiesWithTypes(i),f=t.getDocumentProperties(a,u);for(let h of u){let g=f[h];if(typeof g>"u")continue;let v=d[h];t.index.beforeRemove?.(t.data.index,h,l,g,v,n,t.tokenizer,c),t.index.remove(t.index,t.data.index,h,e,g,v,n,t.tokenizer,c)||(o=!1),t.index.afterRemove?.(t.data.index,h,l,g,v,n,t.tokenizer,c)}let p=t.sorter.getSortableProperties(t.data.sorting),m=t.getDocumentProperties(a,p);for(let h of p)typeof m[h]>"u"||t.sorter.remove(t.data.sorting,h,e);return r||w_(t.afterRemove,t,l),t.documentsStore.remove(t.data.docs,e),Vnt(t),o}function qte(t,e,n,r,o){return oc(t.index.beforeRemove)||oc(t.index.remove)||oc(t.index.afterRemove)||oc(t.beforeRemoveMultiple)||oc(t.afterRemoveMultiple)?sRr(t,e,n,r,o):aRr(t,e,n,r,o)}async function sRr(t,e,n,r,o){let i=0;n||(n=1e3);let s=o?[]:e.map(a=>Hv(t.internalDocumentIDStore,Ji(t.internalDocumentIDStore,a)));return o||await bD(t.beforeRemoveMultiple,t,s),await new Promise((a,l)=>{let c=0;async function u(){let d=e.slice(c*n,++c*n);if(!d.length)return a();for(let f of d)try{await xD(t,f,r,o)&&i++}catch(p){l(p)}setTimeout(u,0)}setTimeout(u,0)}),o||await bD(t.afterRemoveMultiple,t,s),i}function aRr(t,e,n,r,o){let i=0;n||(n=1e3);let s=o?[]:e.map(c=>Hv(t.internalDocumentIDStore,Ji(t.internalDocumentIDStore,c)));o||bD(t.beforeRemoveMultiple,t,s);let a=0;function l(){let c=e.slice(a*n,++a*n);if(c.length){for(let u of c)xD(t,u,r,o)&&i++;setTimeout(l,0)}}return l(),o||bD(t.afterRemoveMultiple,t,s),i}var Gnt=b(()=>{OM();Wv();qnt();Al()});function lRr(t,e){return t[1]-e[1]}function cRr(t,e){return e[1]-t[1]}function uRr(t="desc"){return t.toLowerCase()==="asc"?lRr:cRr}function s3(t,e,n){let r={},o=e.map(([c])=>c),i=t.documentsStore.getMultiple(t.data.docs,o),s=Object.keys(n),a=t.index.getSearchablePropertiesWithTypes(t.data.index);for(let c of s){let u;if(a[c]==="number"){let{ranges:d}=n[c],f=d.length,p=Array.from({length:f});for(let m=0;m<f;m++){let h=d[m];p[m]=[`${h.from}-${h.to}`,0]}u=Object.fromEntries(p)}r[c]={count:0,values:u??{}}}let l=i.length;for(let c=0;c<l;c++){let u=i[c];for(let d of s){let f=d.includes(".")?e3(u,d):u[d],p=a[d],m=r[d].values;switch(p){case"number":{let h=n[d].ranges;vmn(h,m)(f);break}case"number[]":{let h=new Set,g=n[d].ranges,v=vmn(g,m,h);for(let y of f)v(y);break}case"boolean":case"enum":case"string":{wmn(m,p)(f);break}case"boolean[]":case"enum[]":case"string[]":{let v=wmn(m,p==="boolean[]"?"boolean":"string",new Set);for(let y of f)v(y);break}default:throw Pn("FACET_NOT_SUPPORTED",p)}}}for(let c of s){let u=r[c];if(u.count=Object.keys(u.values).length,a[c]==="string"){let d=n[c],f=uRr(d.sort);u.values=Object.fromEntries(Object.entries(u.values).sort(f).slice(d.offset??0,d.limit??10))}}return r}function vmn(t,e,n){return r=>{for(let o of t){let i=`${o.from}-${o.to}`;n?.has(i)||r>=o.from&&r<=o.to&&(e[i]===void 0?e[i]=1:(e[i]++,n?.add(i)))}}}function wmn(t,e,n){let r=e==="boolean"?"false":"";return o=>{let i=o?.toString()??r;n?.has(i)||(t[i]=(t[i]??0)+1,n?.add(i))}}var GCe=b(()=>{td();Al()});function a3(t,e){let n=new Map,r=[];for(let o of t)n.set(o,!0);for(let o of e){let[i]=o;n.has(i)&&(r.push(o),n.delete(i))}return r}var ZCe=b(()=>{});function l3(t,e,n){let r=n.properties,o=r.length,i=t.index.getSearchablePropertiesWithTypes(t.data.index);for(let v=0;v<o;v++){let y=r[v];if(typeof i[y]>"u")throw Pn("UNKNOWN_GROUP_BY_PROPERTY",y);if(!bmn.includes(i[y]))throw Pn("INVALID_GROUP_BY_PROPERTY",y,bmn.join(", "),i[y])}let s=e.map(([v])=>Hv(t.internalDocumentIDStore,v)),a=t.documentsStore.getMultiple(t.data.docs,s),l=a.length,c=n.maxResult||Number.MAX_SAFE_INTEGER,u=[],d={};for(let v=0;v<o;v++){let y=r[v],w={property:y,perValue:{}},_=new Set;for(let S=0;S<l;S++){let I=a[S],C=e3(I,y);if(typeof C>"u")continue;let k=typeof C!="boolean"?C:""+C,T=w.perValue[k]??{indexes:[],count:0};T.count>=c||(T.indexes.push(S),T.count++,w.perValue[k]=T,_.add(C))}u.push(Array.from(_)),d[y]=w}let f=_mn(u),p=f.length,m=[];for(let v=0;v<p;v++){let y=f[v],w=y.length,_={values:[],indexes:[]},S=[];for(let I=0;I<w;I++){let C=y[I],k=r[I];S.push(d[k].perValue[typeof C!="boolean"?C:""+C].indexes),_.values.push(C)}_.indexes=QV(S).sort((I,C)=>I-C),_.indexes.length!==0&&m.push(_)}let h=m.length,g=Array.from({length:h});for(let v=0;v<h;v++){let y=m[v],w=n.reduce||dRr,_=y.indexes.map(k=>({id:s[k],score:e[k][1],document:a[k]})),S=w.reducer.bind(null,y.values),I=w.getInitialValue(y.indexes.length),C=_.reduce(S,I);g[v]={values:y.values,result:C}}return g}function _mn(t,e=0){if(e+1===t.length)return t[e].map(i=>[i]);let n=t[e],r=_mn(t,e+1),o=[];for(let i of n)for(let s of r){let a=[i];bs(a,s),o.push(a)}return o}var dRr,bmn,YCe=b(()=>{td();Al();Wv();dRr={reducer:(t,e,n,r)=>(e[r]=n,e),getInitialValue:t=>Array.from({length:t})},bmn=["string","number","boolean"]});function xmn(t,e,n){let r=v_(),o=t.beforeSearch?.length||t.afterSearch?.length;function i(){e.relevance=Object.assign(JCe,e.relevance??{});let a=Object.keys(t.data.index.vectorIndexes),l=e.facets&&Object.keys(e.facets).length>0,{limit:c=10,offset:u=0,term:d,properties:f,threshold:p=0,distinctOn:m,includeVectors:h=!1}=e,g=e.preflight===!0,{index:v,docs:y}=t.data,w=t.tokenizer.tokenize(d??"",n),_=t.caches.propertiesToSearch;if(!_){let O=t.index.getSearchablePropertiesWithTypes(v);_=t.index.getSearchableProperties(v),_=_.filter($=>O[$].startsWith("string")),t.caches.propertiesToSearch=_}if(f&&f!=="*"){for(let O of f)if(!_.includes(O))throw Pn("UNKNOWN_INDEX",O,_.join(", "));_=_.filter(O=>f.includes(O))}let S=SD(t.tokenizer,t.index,t.documentsStore,n,e,_,w,t.documentsStore.count(y),r),I=Object.keys(e.where??{}).length>0,C=[];I&&(C=t.index.searchByWhereClause(S,v,e.where));let k=w.length;if(k||f?.length){let O=_.length;for(let $=0;$<O;$++){let U=_[$],V=S.indexMap[U];if(k!==0)for(let Q=0;Q<k;Q++){let ne=w[Q],ee=t.index.search(S,v,U,ne);bs(V[ne],ee)}else{V[""]=[];let Q=t.index.search(S,v,U,"");bs(V[""],Q)}let K=Object.values(V);S.docsIntersection[U]=BCe(K,e?.boost?.[U]??1,p,k);let se=S.docsIntersection[U],le=se.length;for(let Q=0;Q<le;Q++){let[ne,ee]=se[Q],ae=S.uniqueDocsIDs[ne];ae?S.uniqueDocsIDs[ne]=ae+ee+.5:S.uniqueDocsIDs[ne]=ee}}}else w.length===0&&d?S.uniqueDocsIDs={}:S.uniqueDocsIDs=Object.fromEntries(Object.keys(t.documentsStore.getAll(t.data.docs)).map(O=>[O,0]));let T=Object.entries(S.uniqueDocsIDs).map(([O,$])=>[+O,$]);if(I&&(T=a3(C,T)),e.sortBy)if(typeof e.sortBy=="function"){let O=T.map(([V])=>V),U=t.documentsStore.getMultiple(t.data.docs,O).map((V,K)=>[T[K][0],T[K][1],V]);U.sort(e.sortBy),T=U.map(([V,K])=>[V,K])}else T=t.sorter.sortBy(t.data.sorting,T,e.sortBy).map(([O,$])=>[Ji(t.internalDocumentIDStore,O),$]);else T=T.sort(vpn);let P;g||(P=m?Cmn(t,T,u,c,m):XCe(t,T,u,c));let E={elapsed:{formatted:"",raw:0},hits:[],count:T.length};if(typeof P<"u"&&(E.hits=P.filter(Boolean),h||UCe(E,a)),l){let O=s3(t,T,e.facets);E.facets=O}return e.groupBy&&(E.groups=l3(t,T,e.groupBy)),E.elapsed=t.formatElapsedTime(v_()-S.timeStart),E}async function s(){t.beforeSearch&&await r3(t.beforeSearch,t,e,n);let a=i();return t.afterSearch&&await n3(t.afterSearch,t,e,n,a),a}return o?s():i()}var Smn=b(()=>{Hte();GCe();ZCe();YCe();OM();Wv();td();Al();CD()});function Znt(t,e,n="english"){let r=v_(),o=t.beforeSearch?.length||t.afterSearch?.length;function i(){let{vector:a}=e;if(a&&(!("value"in a)||!("property"in a)))throw Pn("INVALID_VECTOR_INPUT",Object.keys(a).join(", "));let{limit:l=10,offset:c=0,includeVectors:u=!1}=e,d=t.data.index.vectorIndexes[a.property],f=d.size,p=d.vectors,m=e.facets&&Object.keys(e.facets).length>0,h=Object.keys(e.where??{}).length>0,{index:g,docs:v}=t.data;if(a?.value.length!==f)throw a?.property===void 0||a?.value.length===void 0?Pn("INVALID_INPUT_VECTOR","undefined",f,"undefined"):Pn("INVALID_INPUT_VECTOR",a.property,f,a.value.length);a instanceof Float32Array||(a.value=new Float32Array(a.value));let y=zCe(a.value,p,f,e.similarity).map(([O,$])=>[Ji(t.internalDocumentIDStore,O),$]),w=t.caches.propertiesToSearch;if(!w){let O=t.index.getSearchablePropertiesWithTypes(g);w=t.index.getSearchableProperties(g),w=w.filter($=>O[$].startsWith("string")),t.caches.propertiesToSearch=w}let _=[],S=SD(t.tokenizer,t.index,t.documentsStore,n,e,w,_,t.documentsStore.count(v),r),I=[];h&&(I=t.index.searchByWhereClause(S,g,e.where),y=a3(I,y));let C=[];m&&(C=s3(t,y,e.facets));let k=Array.from({length:l});for(let O=0;O<l;O++){let $=y[O+c];if(!$)break;let U=t.data.docs.docs[$[0]];if(U){u||(U[a.property]=null);let V={id:Hv(t.internalDocumentIDStore,$[0]),score:$[1],document:U};k[O]=V}}let T=[];e.groupBy&&(T=l3(t,y,e.groupBy));let E=v_()-r;return{count:y.length,hits:k.filter(Boolean),elapsed:{raw:Number(E),formatted:wD(E)},...C?{facets:C}:{},...T?{groups:T}:{}}}async function s(){t.beforeSearch&&await r3(t.beforeSearch,t,e,n);let a=i();return t.afterSearch&&await n3(t.afterSearch,t,e,n,a),a}return o?s():i()}var Ynt=b(()=>{CD();Al();GCe();td();HCe();ZCe();YCe();Wv();OM()});function Imn(t,e,n){let r=v_(),o=t.beforeSearch?.length||t.afterSearch?.length;function i(){let{offset:a=0,limit:l=10,includeVectors:c=!1}=e,u=e.facets&&Object.keys(e.facets).length>0,d=fRr(t,e,n),f=pRr(t,e),{index:p,docs:m}=t.data,h=e.hybridWeights,g=hRr(d,f,e.term??"",h),v=t.tokenizer.tokenize(e.term??"",n),y=t.caches.propertiesToSearch;if(!y){let E=t.index.getSearchablePropertiesWithTypes(p);y=t.index.getSearchableProperties(p),y=y.filter(O=>E[O].startsWith("string")),t.caches.propertiesToSearch=y}if(e.properties&&e.properties!=="*"){for(let E of e.properties)if(!y.includes(E))throw Pn("UNKNOWN_INDEX",E,y.join(", "));y=y.filter(E=>e.properties.includes(E))}let w=SD(t.tokenizer,t.index,t.documentsStore,n,e,y,v,t.documentsStore.count(m),r),_=Object.keys(e.where??{}).length>0,S=[];_&&(S=t.index.searchByWhereClause(w,p,e.where),g=a3(S,g));let I;u&&(I=s3(t,g,e.facets));let C;e.groupBy&&(C=l3(t,g,e.groupBy));let k=XCe(t,g,a,l).filter(Boolean),T=v_(),P={count:g.length,elapsed:{raw:Number(T-r),formatted:wD(T-r)},hits:k,...I?{facets:I}:{},...C?{groups:C}:{}};if(!c){let E=Object.keys(t.data.index.vectorIndexes);UCe(P,E)}return P}async function s(){t.beforeSearch&&await r3(t.beforeSearch,t,e,n);let a=i();return t.afterSearch&&await n3(t.afterSearch,t,e,n,a),a}return o?s():i()}function fRr(t,e,n){let r=v_();e.relevance=Object.assign(JCe,e.relevance??{});let{term:o="",properties:i,threshold:s=0}=e,{index:a,docs:l}=t.data,c=t.tokenizer.tokenize(o,n),u=t.caches.propertiesToSearch;if(!u){let m=t.index.getSearchablePropertiesWithTypes(a);u=t.index.getSearchableProperties(a),u=u.filter(h=>m[h].startsWith("string")),t.caches.propertiesToSearch=u}if(i&&i!=="*"){let m=new Set(u),h=new Set(i);for(let g of i)if(!m.has(g))throw Pn("UNKNOWN_INDEX",g,u.join(", "));u=u.filter(g=>h.has(g))}let d=SD(t.tokenizer,t.index,t.documentsStore,n,e,u,c,t.documentsStore.count(l),r),f=c.length;if(f||i&&i.length>0){let m=u.length;for(let h=0;h<m;h++){let g=u[h];if(f!==0)for(let S=0;S<f;S++){let I=c[S],C=t.index.search(d,a,g,I);bs(d.indexMap[g][I],C)}else{let S=[];d.indexMap[g][""]=S;let I=t.index.search(d,a,g,"");bs(S,I)}let v=d.indexMap[g],y=Object.values(v);d.docsIntersection[g]=BCe(y,e?.boost?.[g]??1,s,f);let w=d.docsIntersection[g],_=w.length;for(let S=0;S<_;S++){let[I,C]=w[S],k=d.uniqueDocsIDs[I];d.uniqueDocsIDs[I]=k?k+C+.5:C}}}else c.length===0&&o?d.uniqueDocsIDs={}:d.uniqueDocsIDs=Object.fromEntries(Object.keys(t.documentsStore.getAll(t.data.docs)).map(m=>[m,0]));let p=Object.entries(d.uniqueDocsIDs).map(([m,h])=>[+m,h]).sort((m,h)=>h[1]-m[1]);return Tmn(p)}function pRr(t,e){let n=e.vector,r=t.data.index.vectorIndexes[n?.property],o=r.size,i=r.vectors;if(n&&(!n.value||!n.property))throw Pn("INVALID_VECTOR_INPUT",Object.keys(n).join(", "));if(n.value.length!==o)throw Pn("INVALID_INPUT_VECTOR",n.property,o,n.value.length);n instanceof Float32Array||(n.value=new Float32Array(n.value));let s=zCe(n.value,i,o,e.similarity).map(([a,l])=>[Ji(t.internalDocumentIDStore,a),l]);return Tmn(s)}function Jnt([,t]){return t}function Tmn(t){let e=Math.max.apply(Math,t.map(Jnt));return t.map(([n,r])=>[n,r/e])}function kmn(t,e){return t/e}function mRr(t,e){return(n,r)=>n*t+r*e}function hRr(t,e,n,r){let o=Math.max.apply(Math,t.map(Jnt)),i=Math.max.apply(Math,e.map(Jnt)),s=r&&r.text&&r.vector,{text:a,vector:l}=s?r:gRr(n),c=new Map,u=t.length,d=mRr(a,l);for(let p=0;p<u;p++){let[m,h]=t[p],g=kmn(h,o),v=d(g,0);c.set(m,v)}let f=e.length;for(let p=0;p<f;p++){let[m,h]=e[p],g=kmn(h,i),v=c.get(m)??0;c.set(m,v+d(0,g))}return[...c].sort((p,m)=>m[1]-p[1])}function gRr(t){return{text:.5,vector:.5}}var Pmn=b(()=>{Al();ZCe();Hte();td();CD();GCe();YCe();HCe();Wv();CD();OM()});function SD(t,e,n,r,o,i,s,a,l){let c={},u={};for(let d of i){let f={};for(let p of s)f[p]=[];c[d]=f,u[d]=[]}return{timeStart:l,tokenizer:t,index:e,documentsStore:n,language:r,params:o,docsCount:a,uniqueDocsIDs:{},indexMap:c,docsIntersection:u}}function ah(t,e,n){let r=e.mode??KCe;if(r===KCe)return xmn(t,e,n);if(r===Bnt)return Znt(t,e);if(r===jnt)return Imn(t,e);throw Pn("INVALID_SEARCH_MODE",r)}function Cmn(t,e,n,r,o){let i=t.data.docs,s=new Map,a=[],l=new Set,c=e.length,u=0;for(let d=0;d<c;d++){let f=e[d];if(typeof f>"u")continue;let[p,m]=f;if(l.has(p))continue;let h=t.documentsStore.get(i,p),g=e3(h,o);if(!(typeof g>"u"||s.has(g))&&(s.set(g,!0),u++,!(u<=n)&&(a.push({id:Hv(t.internalDocumentIDStore,p),score:m,document:h}),l.add(p),u>=n+r)))break}return a}function XCe(t,e,n,r){let o=t.data.docs,i=Array.from({length:r}),s=new Set;for(let a=n;a<r+n;a++){let l=e[a];if(typeof l>"u")break;let[c,u]=l;if(!s.has(c)){let d=t.documentsStore.get(o,c);i[a]={id:Hv(t.internalDocumentIDStore,c),score:u,document:d},s.add(c)}}return i}var JCe,CD=b(()=>{Wv();td();Al();znt();Smn();Ynt();Pmn();JCe={k:1.2,b:.75,d:.5}});function QCe(t,e){t.internalDocumentIDStore.load(t,e.internalDocumentIDStore),t.data.index=t.index.load(t.internalDocumentIDStore,e.index),t.data.docs=t.documentsStore.load(t.internalDocumentIDStore,e.docs),t.data.sorting=t.sorter.load(t.internalDocumentIDStore,e.sorting),t.tokenizer.language=e.language}function Xnt(t){return{internalDocumentIDStore:t.internalDocumentIDStore.save(t.internalDocumentIDStore),index:t.index.save(t.data.index),docs:t.documentsStore.save(t.data.docs),sorting:t.sorter.save(t.data.sorting),language:t.tokenizer.language}}var Amn=b(()=>{});var Emn=b(()=>{OM();td();Knt();Gnt();Al()});var Mmn=b(()=>{td();CD()});var Omn=b(()=>{Tnt();Al();Hte();qCe()});var eke=b(()=>{mmn();hmn();Knt();Gnt();CD();Ynt();Amn();Emn();Mmn();Hnt();Unt();Omn()});var Qnt,vRr,tke,Nmn=b(()=>{iy();pe();Se();eke();Qnt="copilot-index-chunk-",vRr=".json",tke=class{constructor(e,n,r){this.app=e;this.baseDir=n;this.identifier=r}getChunkPath(e){return`${this.baseDir}/${Qnt}${this.identifier}-${e}.json`}getMetadataPath(){return`${this.baseDir}/${Qnt}${this.identifier}-metadata.json`}getLegacyPath(){return`${this.baseDir}/copilot-index-${this.identifier}${vRr}`}assignDocumentToPartition(e,n){let o=Array.from(e).reduce((i,s)=>(i<<5)-i+s.charCodeAt(0),0);return Math.abs(o)%n}distributeDocumentsToPartitions(e,n){let r=new Map,o={};for(let s=0;s<n;s++)r.set(s,[]);Y().debug&&j(`Total documents to distribute: ${e.length}`);for(let s of e){let a=String(s.id),l=this.assignDocumentToPartition(a,n),c=r.get(l);if(!c)throw new Error(`Invalid partition index: ${l}`);c.push(s),o[a]=l}let i=0;return r.forEach((s,a)=>{i+=s.length,Y().debug&&j(`Partition ${a+1}: ${s.length} documents`)}),Y().debug&&(j(`Total documents distributed: ${i}`),i!==e.length&&H(`Document count mismatch! Original: ${e.length}, Distributed: ${i}`)),r}async ensureDirectoryExists(e){let n=e.substring(0,e.lastIndexOf("/"));await this.app.vault.adapter.exists(n)||await this.app.vault.adapter.mkdir(n)}async saveDatabase(e){try{let n=Xnt(e),r=Y().numPartitions;if(r===1){let c=this.getLegacyPath();await this.ensureDirectoryExists(c),await this.app.vault.adapter.write(c,JSON.stringify({...n,schema:e.schema}));return}let o=n.docs?.docs,i=Array.isArray(o)?o:Object.values(o||{});if(Y().debug&&j(`Starting save with ${i.length??0} total documents`),!i||i.length===0){let c={numPartitions:r,schema:e.schema,lastModified:Date.now(),documentPartitions:{}},u=this.getMetadataPath();await this.ensureDirectoryExists(u),await this.app.vault.adapter.write(u,JSON.stringify(c)),Y().debug&&j("Saved empty database state");return}let s=this.distributeDocumentsToPartitions(i,r),a={numPartitions:r,schema:e.schema,lastModified:Date.now(),documentPartitions:Object.fromEntries(i.map(c=>[c.id,this.assignDocumentToPartition(String(c.id),r)]))};await this.saveMetadata(a);let l={...n,docs:{docs:{},count:0},index:{...n.index,vectorIndexes:void 0}};for(let[c,u]of s.entries()){let d={index:{vectorIndexes:{embedding:{size:n.index.vectorIndexes.embedding.size,vectors:Object.fromEntries(Object.entries(n.index.vectorIndexes.embedding.vectors).filter(([m])=>u.some(h=>h.id===m)))}}},docs:{docs:Object.fromEntries(u.map((m,h)=>[(h+1).toString(),m])),count:u.length}},f=c===0?{...l,docs:d.docs,index:{...l.index,vectorIndexes:d.index.vectorIndexes}}:d,p=this.getChunkPath(c);await this.ensureDirectoryExists(p),await this.app.vault.adapter.write(p,JSON.stringify(f)),Y().debug&&j(`Saved partition ${c+1}/${r}`)}Y().debug&&j("Saved all partitions")}catch(n){throw H("Error saving database:",n),new Nr(`Failed to save database: ${n.message}`)}}async loadDatabase(){try{let e=this.getLegacyPath();if(await this.app.vault.adapter.exists(e)){let l=JSON.parse(await this.app.vault.adapter.read(e));if(!l?.schema)throw new Nr("Invalid legacy database format");let c=i3({schema:l.schema,components:{tokenizer:{stemmer:void 0,stopWords:void 0}}});return QCe(c,l),c}let n=await this.loadMetadata(),r=i3({schema:n.schema,components:{tokenizer:{stemmer:void 0,stopWords:void 0}}}),o=null,i=[];for(let l=0;l<n.numPartitions;l++){let c=this.getChunkPath(l);if(await this.app.vault.adapter.exists(c)){let u=JSON.parse(await this.app.vault.adapter.read(c));i.push(u),l===0&&(o=u)}}if(!o)throw new Nr("No data found in chunks");let s={},a=1;for(let l of o.internalDocumentIDStore.internalIdToId){let c=i.flatMap(u=>Object.values(u.docs.docs)).find(u=>u.id===l);c?(s[a.toString()]=c,a++):Y().debug&&W(`Document ${l} not found in any chunk`)}return o.docs.docs=s,o.docs.count=Object.keys(s).length,o.internalDocumentIDStore.internalIdToId=Object.values(s).map(l=>l.id),o.index.vectorIndexes.embedding.vectors=Object.assign({},...i.map(l=>l.index?.vectorIndexes?.embedding?.vectors||{})),QCe(r,o),r}catch(e){throw H("Error loading database:",e),new Nr(`Failed to load database: ${e.message}`)}}async clearStorage(){try{let e=this.getLegacyPath();await this.app.vault.adapter.exists(e)&&await this.app.vault.adapter.remove(e);let n=await this.app.vault.adapter.list(this.baseDir);for(let r of n.files)r.startsWith(`${this.baseDir}/${Qnt}${this.identifier}`)&&await this.app.vault.adapter.remove(r)}catch(e){throw H("Error clearing storage:",e),new Nr(`Failed to clear storage: ${e.message}`)}}async exists(){let e=this.getLegacyPath();if(Y().numPartitions===1)return await this.app.vault.adapter.exists(e);let n=this.getMetadataPath();return await this.app.vault.adapter.exists(n)||await this.app.vault.adapter.exists(e)}async loadMetadata(){let e=this.getMetadataPath();if(!await this.app.vault.adapter.exists(e))throw new Nr("No existing database found");let n=JSON.parse(await this.app.vault.adapter.read(e));if(!n?.schema)throw new Nr("Invalid metadata file: missing schema");return n}async saveMetadata(e){let n=this.getMetadataPath();await this.ensureDirectoryExists(n),await this.app.vault.adapter.write(n,JSON.stringify(e))}}});var Lmn={};sr(Lmn,{DBOperations:()=>LM});var YS,Rmn,LM,nke=b(()=>{GH();iy();pe();Se();ut();eke();oYe();Py();YS=require("obsidian");Nmn();ha();Rmn=25,LM=class t{constructor(e){this.app=e;this.isInitialized=!1;this.isIndexLoaded=!1;this.hasUnsavedChanges=!1;this.filesWithoutEmbeddings=new Set;this.upsertMutex=new e6;zr(()=>{(async()=>{try{let n=Y();YS.Platform.isMobile&&n.disableIndexOnMobile?(this.isIndexLoaded=!1,this.oramaDb=void 0):YS.Platform.isMobile&&!n.disableIndexOnMobile&&!this.oramaDb&&await this.initializeDB(await Gc.getInstance().getEmbeddingsAPI());let r=await this.getDbPath();this.dbPath&&r!==this.dbPath&&(j("Path change detected, reinitializing database..."),this.dbPath=r,await this.initializeChunkedStorage(),await this.initializeDB(await Gc.getInstance().getEmbeddingsAPI()),j("Database reinitialized with new path:",r))}catch(n){H("DBOperations settings change handler failed",n)}})()})}async initializeChunkedStorage(){if(!this.app.vault.adapter)throw new Nr("Vault adapter not available. Please try again later.");let e=await this.getDbPath();this.chunkedStorage=new tke(this.app,e,this.getVaultIdentifier()),this.isInitialized=!0}async initializeDB(e){try{if(this.isInitialized||(this.dbPath=await this.getDbPath(),await this.initializeChunkedStorage()),YS.Platform.isMobile&&Y().disableIndexOnMobile){this.isIndexLoaded=!1,this.oramaDb=void 0;return}if(!this.chunkedStorage)throw new Nr("Storage not initialized properly");try{if(await this.chunkedStorage.exists())return this.oramaDb=await this.chunkedStorage.loadDatabase(),j("Loaded existing chunked semantic index database from disk."),this.oramaDb}catch(r){H("Failed to load existing semantic index database, creating new one:",r)}let n=await this.createNewDb(e);return this.oramaDb=n,n}catch(n){H("Error initializing semantic index database:",n),new YS.Notice("Failed to initialize Copilot database. Some features may be limited.");return}}async saveDB(){if(!(YS.Platform.isMobile&&Y().disableIndexOnMobile)){if(!this.oramaDb||!this.chunkedStorage)try{if(await this.initializeDB(await Gc.getInstance().getEmbeddingsAPI()),!this.oramaDb||!this.chunkedStorage)throw new Nr("Semantic index database not found.")}catch(e){throw H("Failed to initialize database during save:",e),new Nr("Failed to initialize and save database.")}try{await this.chunkedStorage.saveDatabase(this.oramaDb),this.hasUnsavedChanges=!1,Y().debug&&j("Semantic index database saved successfully at:",this.dbPath)}catch(e){throw H("Error saving semantic index database:",e),e}}}async clearIndex(e){try{this.oramaDb||await this.initializeDB(e),await this.chunkedStorage?.clearStorage(),await new Promise(n=>window.setTimeout(n,100)),this.oramaDb=await this.createNewDb(e),await this.saveDB(),new YS.Notice("Local Copilot index cleared successfully."),j("Local Copilot index cleared successfully, new instance created.")}catch(n){throw H("Error clearing the local Copilot index:",n),new YS.Notice("An error occurred while clearing the local Copilot index."),n}}async removeDocs(e){if(!this.oramaDb)throw new Nr("Semantic index database not found.");try{let n=await ah(this.oramaDb,{term:e,properties:["path"]});n.hits.length>0&&(await qte(this.oramaDb,n.hits.map(r=>r.id),500),Y().debug&&j(`Deleted document from local Copilot index: ${e}`)),this.markUnsavedChanges()}catch(n){H("Error deleting document from local Copilotindex:",n)}}getDb(){return this.oramaDb||W("Database not initialized. Some features may be limited."),this.oramaDb}async getIsIndexLoaded(){return this.isIndexLoaded}async waitForInitialization(){await this.initializationPromise}onunload(){this.hasUnsavedChanges&&this.saveDB().catch(e=>H("saveDB on unload failed",e))}getCurrentDbPath(){return this.dbPath}async getDbPath(){let e=this.app.vault.getRoot().path,n;if(Y().enableIndexSync)n=this.app.vault.configDir;else{let r=e==="/"?"":e;n=`${r===""||r.startsWith("/")?"":"/"}${r}/.copilot-index`,await this.app.vault.adapter.exists(n)||(await this.app.vault.adapter.mkdir(n),j("Created directory:",n))}return n}getVaultIdentifier(){let e=this.app.vault.getName();return jl(e)}markUnsavedChanges(){this.hasUnsavedChanges=!0}async createNewDb(e){if(!e)throw new Nr("Embedding instance not found.");let n=await I9e(e);if(!n||n===0)throw new Nr("Invalid vector length detected. Please check if your embedding model is working.");let r=this.createDynamicSchema(n),o=i3({schema:r,components:{tokenizer:{stemmer:void 0,stopWords:void 0}}});return j(`Created new semantic index database for ${this.dbPath}. Embedding model: ${Gc.getModelName(e)} with vector length ${n}.`),this.isIndexLoaded=!0,o}static async getDocsByPath(e,n){if(!e)throw new Error("DB not initialized");return n?(await t.getAllDocuments(e)).filter(i=>i.path===n).map(i=>({document:i,score:1})):void 0}static async getDocsByEmbedding(e,n,r){return(await ah(e,{mode:"vector",vector:{value:n,property:"embedding"},limit:r.limit,similarity:r.similarity,includeVectors:!0})).hits}static async getLatestFileMtime(e){if(!e)throw new Error("DB not initialized");try{let n=await ah(e,{term:"",limit:1,sortBy:{property:"mtime",order:"DESC"}});return n.hits.length>0?n.hits[0].document.mtime:0}catch(n){return H("Error getting latest file mtime from VectorDB:",n),0}}createDynamicSchema(e){return{id:"string",title:"string",path:"string",content:"string",embedding:`vector[${e}]`,embeddingModel:"string",created_at:"number",ctime:"number",mtime:"number",tags:"string[]",extension:"string",nchars:"number"}}async upsert(e){if(!this.oramaDb)throw new Error("DB not initialized");let n=this.oramaDb;return await this.upsertMutex.runExclusive(async()=>{try{let r=this.chunkedStorage?.assignDocumentToPartition(String(e.id),Y().numPartitions),o=await ah(n,{term:String(e.id),properties:["id"],limit:1});o.hits.length>0&&await xD(n,o.hits[0].id);try{return await Vte(n,e),j(`${o.hits.length>0?"Updated":"Inserted"} document ${String(e.id)} in partition ${r}`),this.markUnsavedChanges(),e}catch(i){if(H(`Failed to ${o.hits.length>0?"update":"insert"} document ${String(e.id)}:`,i),o.hits.length>0)try{await Vte(n,o.hits[0].document)}catch(s){H("Failed to restore previous document version:",s)}return}}catch(r){H(`Error upserting document ${String(e.id)}:`,r);return}})}async getLatestFileMtime(){if(!this.oramaDb)throw new Error("DB not initialized");try{let e=await ah(this.oramaDb,{term:"",limit:1,sortBy:{property:"mtime",order:"DESC"}});return e.hits.length>0?e.hits[0].document.mtime:0}catch(e){return H("Error getting latest file mtime from VectorDB:",e),0}}async checkAndHandleEmbeddingModelChange(e){if(!this.oramaDb){j("Semantic index database not loaded in memory. Checking for existing index...");try{await this.initializeDB(e)}catch(o){throw H("Failed to initialize database:",o),new Nr("Failed to initialize semantic index database. Please check your embedding model settings.")}if(!this.oramaDb)return j("No existing index found. Will create new index."),!1}let n=await ah(this.oramaDb,{term:"",limit:1}),r;if(n.hits.length>0){let o=n.hits[0];typeof o=="object"&&o!==null&&"document"in o&&(r=o.document.embeddingModel)}if(r){let o=Gc.getModelName(e);if(!Bdt(r,o))return new YS.Notice("New embedding model detected. Rebuilding Copilot index from scratch."),j(`Detected change in embedding model from "${r}" to "${o}". Rebuilding Copilot index from scratch.`),this.oramaDb=await this.createNewDb(e),await this.saveDB(),!0}else j("No previous embedding model found in the database.");return!1}static async getAllDocuments(e){return(await ah(e,{term:"",limit:1e5,includeVectors:!0})).hits.map(r=>r.document)}async garbageCollect(){if(!this.oramaDb){j("Semantic index database not found during garbage collection. Attempting to initialize...");try{let e=await Gc.getInstance().getEmbeddingsAPI();if(!e)throw new Nr("No embedding model available.");if(await this.initializeDB(e),!this.oramaDb)throw new Nr("Failed to initialize database after attempt.")}catch(e){throw H("Failed to initialize database during garbage collection:",e),new Nr("Failed to initialize database. Please check your embedding model settings.")}}try{let e=this.app.vault.getMarkdownFiles(),n=new Set(e.map(l=>l.path)),{inclusions:r,exclusions:o}=Fi(),i=new Set(e.filter(l=>ii(this.app,l,r,o)).map(l=>l.path)),a=(await t.getAllDocuments(this.oramaDb)).filter(l=>!n.has(l.path)||!i.has(l.path));return a.length===0?0:(j("Copilot index: Docs to remove during garbage collection:",Array.from(new Set(a.map(l=>l.path))).join(", ")),a.length===1?await xD(this.oramaDb,a[0].id):await qte(this.oramaDb,a.map(l=>l.id),500),await this.saveDB(),a.length)}catch(e){throw H("Error garbage collecting the Copilot index:",e),new Nr("Failed to garbage collect the Copilot index.")}}async getIndexedFiles(){if(!this.oramaDb)throw new Nr("Semantic index database not found.");try{let e=await t.getAllDocuments(this.oramaDb),n=new Set;return e.forEach(r=>{n.add(r.path)}),Array.from(n).sort()}catch(e){throw H("Error getting indexed files:",e),new Nr("Failed to retrieve indexed files.")}}async isIndexEmpty(){if(!this.oramaDb)return!0;try{return(await ah(this.oramaDb,{term:"",limit:1})).hits.length===0}catch(e){throw H("Error checking if database is empty:",e),new Nr("Failed to check if database is empty.")}}async hasIndex(e){if(!this.oramaDb)return!1;let n=await t.getDocsByPath(this.oramaDb,e);return n!==void 0&&n.length>0}async hasEmbeddings(e){if(!this.oramaDb)return!1;let n=await t.getDocsByPath(this.oramaDb,e);return!n||n.length===0?!1:n.every(r=>r?.document?.embedding&&Array.isArray(r.document.embedding)&&r.document.embedding.length>0)}async getDocsJsonByPaths(e){if(!this.oramaDb)throw new Nr("Semantic index database not found.");let n={};for(let r of e){let o=await t.getDocsByPath(this.oramaDb,r);o&&o.length>0&&(n[r]=o.map(i=>i.document))}return n}markFileMissingEmbeddings(e){this.filesWithoutEmbeddings.add(e)}clearFilesMissingEmbeddings(){this.filesWithoutEmbeddings.clear()}getFilesMissingEmbeddings(){return Array.from(this.filesWithoutEmbeddings)}isFileMissingEmbeddings(e){return this.filesWithoutEmbeddings.has(e)}async checkIndexIntegrity(){if(!this.oramaDb)throw new Nr("Orama database not found.");try{let e=await this.getIndexedFiles(),n=[];for(let r=0;r<e.length;r+=1){let o=e[r];await this.hasEmbeddings(o)||(n.push(o),this.filesWithoutEmbeddings.add(o)),(r+1)%Rmn===0&&await this.yieldToEventLoop()}e.length%Rmn!==0&&await this.yieldToEventLoop(),n.length>0?j(`Integrity check: ${n.length} file(s) missing embeddings, marked for re-indexing:`,n.join(", ")):j("Index integrity check completed. All documents have embeddings.")}catch(e){throw H("Error checking index integrity:",e),new Nr("Failed to check index integrity.")}}async yieldToEventLoop(){await new Promise(e=>{if(typeof window<"u"){let n=window;if(n.requestIdleCallback){n.requestIdleCallback(()=>e());return}}window.setTimeout(e,0)})}}});var $mn,rke,Dmn=b(()=>{$mn=require("obsidian");pe();nA();zu();Se();rke=class{constructor(e){this.app=e;this.client=new jc}async initialize(e){try{let n=await this.getBaseUrl();await this.client.getFolder(n,this.getFolderName())}catch(n){W(`Miyo backend initialization failed: ${n}`);let r=this.getFolderName(),o=r?` ("${r}")`:"";new $mn.Notice(`Miyo isn't available for this vault${o}. Make sure Miyo is running and this vault is added to it.`)}}async clearIndex(e){W("Miyo clearIndex requested from Copilot, but folder lifecycle is managed in Miyo.")}requiresEmbeddings(){return!1}async upsert(e){j(`Skipping direct Miyo upsert for ${e.path}; Miyo manages indexing itself.`)}async upsertBatch(e){return e.length>0&&j(`Skipping direct Miyo batch upsert for ${e.length} documents.`),0}async removeByPath(e){j(`Skipping direct Miyo delete for ${e}; Miyo manages file lifecycle itself.`)}async getIndexedFiles(){let e=await this.getAllIndexedFiles();return Array.from(new Set(e.map(n=>this.toVaultPath(n.path)))).sort()}async getLatestFileMtime(){return(await this.getAllIndexedFiles()).reduce((n,r)=>Math.max(n,r.mtime??0),0)}async isIndexEmpty(){return(await this.getAllIndexedFiles()).length===0}async hasIndex(e){return(await this.getDocumentsByPath(e)).length>0}async getDocumentsByPath(e){let n=await this.getBaseUrl(),r=Dye(this.app,e);return((await this.client.getDocumentsByPath(n,this.getFolderName(),r)).documents??[]).map(s=>this.fromMiyoDocument(e,s))}async checkAndHandleEmbeddingModelChange(e){return!1}async save(){}async checkIndexIntegrity(){}async garbageCollect(){return j("Skipping Miyo garbage collection; folder lifecycle is managed in Miyo."),0}markFileMissingEmbeddings(e){}clearFilesMissingEmbeddings(){}getFilesMissingEmbeddings(){return[]}markUnsavedChanges(){}onunload(){}isRemoteBackend(){return!0}async requestIndexRefresh(e=!1){let n=await this.getBaseUrl();await this.client.scanFolder(n,this.getFolderName(),e)}async getBaseUrl(){let e=Ci(Y());return this.client.resolveBaseUrl(e)}getFolderName(){return Mp(this.app)}async getAllIndexedFiles(){let e=await this.getBaseUrl(),n=200,r=0,o=null,i=[];do{let s=await this.client.listFolderFiles(e,{folderName:this.getFolderName(),offset:r,limit:n}),a=s.files??[];if(i.push(...a),o===null&&(o=s.total??a.length),r+=a.length,a.length===0)break}while(r<o);return i}toVaultPath(e){return o$(this.app,e)}fromMiyoDocument(e,n){let r=n.path?this.toVaultPath(n.path):e,o=n.chunk_text??"",i={...n.metadata??{}};return!i.chunkId&&n.chunk_index!==void 0&&(i.chunkId=`${r}#${n.chunk_index}`),n.chunk_index!==void 0&&i.chunkIndex===void 0&&(i.chunkIndex=n.chunk_index),{id:n.id,title:n.title??"",content:o,embedding:[],path:r,embeddingModel:n.embedding_model??"",created_at:typeof n.created_at=="number"?n.created_at:0,ctime:n.ctime??0,mtime:n.mtime??0,tags:n.tags??[],extension:n.extension??"",nchars:n.nchars??o.length,metadata:i}}}});var oke,Fmn=b(()=>{nke();oke=class{constructor(e){this.dbOps=new LM(e)}async initialize(e){await this.dbOps.initializeDB(e)}async clearIndex(e){await this.dbOps.clearIndex(e)}requiresEmbeddings(){return!0}async upsert(e){return await this.dbOps.upsert(e)}async upsertBatch(e){let n=0;for(let r of e)await this.dbOps.upsert(r)&&(n+=1);return n}async removeByPath(e){await this.dbOps.removeDocs(e)}async getIndexedFiles(){return this.dbOps.getIndexedFiles()}async getLatestFileMtime(){return this.dbOps.getLatestFileMtime()}async isIndexEmpty(){return this.dbOps.isIndexEmpty()}async hasIndex(e){return this.dbOps.hasIndex(e)}async getDocumentsByPath(e){let n=this.dbOps.getDb();if(!n)throw new Error("Database is not loaded. Please restart the plugin.");let r=await LM.getDocsByPath(n,e);return r?r.map(o=>o.document):[]}async checkAndHandleEmbeddingModelChange(e){if(!e)throw new Error("Embedding instance is required to check Orama embedding model changes.");return this.dbOps.checkAndHandleEmbeddingModelChange(e)}async save(){await this.dbOps.saveDB()}async checkIndexIntegrity(){await this.dbOps.checkIndexIntegrity()}async garbageCollect(){return this.dbOps.garbageCollect()}markFileMissingEmbeddings(e){this.dbOps.markFileMissingEmbeddings(e)}clearFilesMissingEmbeddings(){this.dbOps.clearFilesMissingEmbeddings()}getFilesMissingEmbeddings(){return this.dbOps.getFilesMissingEmbeddings()}markUnsavedChanges(){this.dbOps.markUnsavedChanges()}onunload(){this.dbOps.onunload()}isRemoteBackend(){return!1}getDb(){return this.dbOps.getDb()}async reinitializeForIndexSyncChange(e){let n=await this.dbOps.getDbPath();this.dbOps.getCurrentDbPath()!==n&&await this.dbOps.initializeDB(e)}getDbOperations(){return this.dbOps}}});var c3,wRr,Kte,Umn=b(()=>{es();mw();pe();Se();c3=require("obsidian");ha();wRr=5e3,Kte=class{constructor(e,n,r){this.app=e;this.indexOps=n;this.indexBackend=r;this.debounceTimer=null;this.lastActiveFile=null;this.lastActiveFileMtime=null;this.listenersActive=!1;this.handleActiveLeafChange=async e=>{if(!this.shouldHandleEvents()||c3.Platform.isMobile&&Y().disableIndexOnMobile&&!this.indexBackend.isRemoteBackend()||B_()!=="copilot_plus")return;let r=this.lastActiveFile,o=this.lastActiveFileMtime,i=e?.view;if(this.lastActiveFile=i instanceof c3.MarkdownView?i.file:null,this.lastActiveFileMtime=this.lastActiveFile?.stat?.mtime??null,!(!r||r===this.lastActiveFile)&&!(!r?.stat?.mtime||o===null)&&r.extension==="md"){let{inclusions:s,exclusions:a}=Fi(),l=ii(this.app,r,s,a),c=o!==null&&r.stat.mtime>o;l&&c&&this.debouncedReindexFile(r)}};this.debouncedReindexFile=e=>{this.shouldHandleEvents()&&(this.debounceTimer!==null&&window.clearTimeout(this.debounceTimer),this.debounceTimer=window.setTimeout(()=>{Y().debug&&j("Copilot Plus: Triggering reindex for file ",e.path),this.indexOps.reindexFile(e).catch(n=>H("reindexFile failed",n)),this.debounceTimer=null},wRr))};this.handleFileDelete=async e=>{this.shouldHandleEvents()&&e instanceof c3.TFile&&await this.indexBackend.removeByPath(e.path)};this.syncEventListeners(),zr(()=>{this.syncEventListeners()})}shouldHandleEvents(){return Y().enableSemanticSearchV3?!(this.indexBackend.isRemoteBackend()&&!this.indexBackend.requiresEmbeddings()):!1}syncEventListeners(){let e=this.shouldHandleEvents();e&&!this.listenersActive?(j("Copilot Plus: Initializing semantic index event listeners"),this.app.workspace.on("active-leaf-change",this.handleActiveLeafChange),this.app.vault.on("delete",this.handleFileDelete),this.listenersActive=!0):!e&&this.listenersActive&&this.teardownEventListeners()}teardownEventListeners(){this.listenersActive&&(this.app.workspace.off("active-leaf-change",this.handleActiveLeafChange),this.app.vault.off("delete",this.handleFileDelete),this.debounceTimer!==null&&(window.clearTimeout(this.debounceTimer),this.debounceTimer=null),this.lastActiveFile=null,this.lastActiveFileMtime=null,this.listenersActive=!1)}cleanup(){this.teardownEventListeners()}unload(){this.teardownEventListeners()}}});function trt(t){return ert.add(t),()=>{ert.delete(t)}}function Gte(){ert.forEach(t=>t())}var ert,nrt=b(()=>{ert=new Set});var ike,jmn=b(()=>{ike=class{constructor(e){this.lastRequestTime=0;this.requestsPerMin=e}setRequestsPerMin(e){this.requestsPerMin=e}getRequestsPerMin(){return this.requestsPerMin}async wait(){let n=Date.now()-this.lastRequestTime,r=Math.max(0,6e4/this.requestsPerMin-n);r>0&&await new Promise(o=>window.setTimeout(o,r)),this.lastRequestTime=Date.now()}}});var cu,Bmn=b(()=>{cu=class{constructor(t){M(this,"pageContent");M(this,"metadata");M(this,"id");this.pageContent=t.pageContent!==void 0?t.pageContent.toString():"",this.metadata=t.metadata??{},this.id=t.id}}});var rrt,zmn=b(()=>{Lu();rrt=class extends Uo{constructor(){super(...arguments);M(this,"lc_namespace",["langchain_core","documents","transformers"])}invoke(e,n){return this.transformDocuments(e)}}});var $M=b(()=>{br();Bmn();zmn()});var Hmn,irt,Wmn=b(()=>{$M();J3e();Hmn=class extends rrt{constructor(e){super(e);M(this,"lc_namespace",["langchain","document_transformers","text_splitters"]);M(this,"chunkSize",1e3);M(this,"chunkOverlap",200);M(this,"keepSeparator",!1);M(this,"lengthFunction");if(this.chunkSize=e?.chunkSize??this.chunkSize,this.chunkOverlap=e?.chunkOverlap??this.chunkOverlap,this.keepSeparator=e?.keepSeparator??this.keepSeparator,this.lengthFunction=e?.lengthFunction??(n=>n.length),this.chunkOverlap>=this.chunkSize)throw new Error("Cannot have chunkOverlap >= chunkSize")}async transformDocuments(e,n={}){return this.splitDocuments(e,n)}splitOnSeparator(e,n){let r;if(n)if(this.keepSeparator){let o=n.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&");r=e.split(new RegExp(`(?=${o})`))}else r=e.split(n);else r=e.split("");return r.filter(o=>o!=="")}async createDocuments(e,n=[],r={}){let o=n.length>0?n:[...Array(e.length)].map(()=>({})),{chunkHeader:i="",chunkOverlapHeader:s="(cont'd) ",appendChunkOverlapHeader:a=!1}=r,l=new Array;for(let c=0;c<e.length;c+=1){let u=e[c],d=1,f=null,p=-1;for(let m of await this.splitText(u)){let h=i,g=u.indexOf(m,p+1);if(f===null){let _=this.numberOfNewLines(u,0,g);d+=_}else{let _=p+await this.lengthFunction(f);if(_<g){let S=this.numberOfNewLines(u,_,g);d+=S}else if(_>g){let S=this.numberOfNewLines(u,g,_);d-=S}a&&(h+=s)}let v=this.numberOfNewLines(m),y=o[c].loc&&typeof o[c].loc=="object"?{...o[c].loc}:{};y.lines={from:d,to:d+v};let w={...o[c],loc:y};h+=m,l.push(new cu({pageContent:h,metadata:w})),d+=v,f=m,p=g}}return l}numberOfNewLines(e,n,r){return(e.slice(n,r).match(/\n/g)||[]).length}async splitDocuments(e,n={}){let r=e.filter(s=>s.pageContent!==void 0),o=r.map(s=>s.pageContent),i=r.map(s=>s.metadata);return this.createDocuments(o,i,n)}joinDocs(e,n){let r=e.join(n).trim();return r===""?null:r}async mergeSplits(e,n){let r=[],o=[],i=0;for(let a of e){let l=await this.lengthFunction(a);if(i+l+o.length*n.length>this.chunkSize&&(i>this.chunkSize&&console.warn(`Created a chunk of size ${i}, +
which is longer than the specified ${this.chunkSize}`),o.length>0)){let c=this.joinDocs(o,n);for(c!==null&&r.push(c);i>this.chunkOverlap||i+l+o.length*n.length>this.chunkSize&&i>0;)i-=await this.lengthFunction(o[0]),o.shift()}o.push(a),i+=l}let s=this.joinDocs(o,n);return s!==null&&r.push(s),r}},irt=class ort extends Hmn{constructor(n){super(n);M(this,"separators",[`
`,`
`," ",""]);this.separators=n?.separators??this.separators,this.keepSeparator=n?.keepSeparator??!0}static lc_name(){return"RecursiveCharacterTextSplitter"}async _splitText(n,r){let o=[],i=r[r.length-1],s;for(let u=0;u<r.length;u+=1){let d=r[u];if(d===""){i=d;break}if(n.includes(d)){i=d,s=r.slice(u+1);break}}let a=this.splitOnSeparator(n,i),l=[],c=this.keepSeparator?"":i;for(let u of a)if(await this.lengthFunction(u)<this.chunkSize)l.push(u);else{if(l.length){let d=await this.mergeSplits(l,c);o.push(...d),l=[]}if(!s)o.push(u);else{let d=await this._splitText(u,s);o.push(...d)}}if(l.length){let u=await this.mergeSplits(l,c);o.push(...u)}return o}async splitText(n){return this._splitText(n,this.separators)}static fromLanguage(n,r){return new ort({...r,separators:ort.getSeparatorsForLanguage(n)})}static getSeparatorsForLanguage(n){if(n==="cpp")return[`
class `,`
void `,`
int `,`
float `,`
double `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
`,`
`," ",""];if(n==="go")return[`
func `,`
var `,`
const `,`
type `,`
if `,`
for `,`
switch `,`
case `,`
`,`
`," ",""];if(n==="java")return[`
class `,`
public `,`
protected `,`
private `,`
static `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
`,`
`," ",""];if(n==="js")return[`
function `,`
const `,`
let `,`
var `,`
class `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
default `,`
`,`
`," ",""];if(n==="php")return[`
function `,`
class `,`
if `,`
foreach `,`
while `,`
do `,`
switch `,`
case `,`
`,`
`," ",""];if(n==="proto")return[`
message `,`
service `,`
enum `,`
option `,`
import `,`
syntax `,`
`,`
`," ",""];if(n==="python")return[`
class `,`
def `,`
def `,`
`,`
`," ",""];if(n==="rst")return[`
===
`,`
---
`,`
***
`,`
.. `,`
`,`
`," ",""];if(n==="ruby")return[`
def `,`
class `,`
if `,`
unless `,`
while `,`
for `,`
do `,`
begin `,`
rescue `,`
`,`
`," ",""];if(n==="rust")return[`
fn `,`
const `,`
let `,`
if `,`
while `,`
for `,`
loop `,`
match `,`
const `,`
`,`
`," ",""];if(n==="scala")return[`
class `,`
object `,`
def `,`
val `,`
var `,`
if `,`
for `,`
while `,`
match `,`
case `,`
`,`
`," ",""];if(n==="swift")return[`
func `,`
class `,`
struct `,`
enum `,`
if `,`
for `,`
while `,`
do `,`
switch `,`
case `,`
`,`
`," ",""];if(n==="markdown")return[`
## `,`
### `,`
#### `,`
##### `,`
###### `,"```\n\n",`
***
`,`
---
`,`
___
`,`
`,`
`," ",""];if(n==="latex")return[`
\\chapter{`,`
\\section{`,`
\\subsection{`,`
\\subsubsection{`,`
\\begin{enumerate}`,`
\\begin{itemize}`,`
\\begin{description}`,`
\\begin{list}`,`
\\begin{quote}`,`
\\begin{quotation}`,`
\\begin{verse}`,`
\\begin{verbatim}`,`
\\begin{align}`,"$$","$",`
`,`
`," ",""];if(n==="html")return["<body>","<div>","<p>","<br>","<li>","<h1>","<h2>","<h3>","<h4>","<h5>","<h6>","<span>","<table>","<tr>","<td>","<th>","<ul>","<ol>","<header>","<footer>","<nav>","<head>","<style>","<script>","<meta>","<title>"," ",""];if(n==="sol")return[`
pragma `,`
using `,`
contract `,`
interface `,`
library `,`
constructor `,`
type `,`
function `,`
event `,`
modifier `,`
error `,`
struct `,`
enum `,`
if `,`
for `,`
while `,`
do while `,`
assembly `,`
`,`
`," ",""];throw new Error(`Language ${n} is not supported.`)}}});var Vmn=b(()=>{Wmn()});var u3,kD,srt=b(()=>{pe();Se();u3=class u3{constructor(){this.bytesUsed=0;let e=Y(),n=Math.min(1e3,Math.max(20,e.lexicalSearchRamLimit||100));this.maxBytes=n*u3.MB_TO_BYTES,this.candidateLimit=Math.min(u3.DEFAULT_CANDIDATE_LIMIT,Math.floor(n*5))}getMaxBytes(){return this.maxBytes}getCandidateLimit(){return this.candidateLimit}getBytesUsed(){return this.bytesUsed}canAddContent(e){return this.bytesUsed+e<=this.maxBytes}addBytes(e){this.bytesUsed+=e}reset(){let e=this.bytesUsed;this.bytesUsed=0,j(`MemoryManager: Reset memory tracking (was using ${e} bytes, max: ${this.maxBytes} bytes)`)}getUsagePercent(){return Math.round(this.bytesUsed/this.maxBytes*100)}static getByteSize(e){return new TextEncoder().encode(e).length}};u3.DEFAULT_CANDIDATE_LIMIT=500,u3.MB_TO_BYTES=1024*1024;kD=u3});function DM(t){return art||(art=new lrt(t)),art}var ake,ske,lrt,art,Zte=b(()=>{pe();gt();ake=require("obsidian");Vmn();srt();ske={maxChars:qoe,overlap:0,maxBytesTotal:10*1024*1024},lrt=class{constructor(e){this.app=e;this.cache=new Map;this.memoryUsage=0}getCacheKey(e,n){return`${e}:${n.maxChars}:${n.overlap}`}createSplitter(e){return irt.fromLanguage("markdown",{chunkSize:e.maxChars,chunkOverlap:e.overlap,separators:[`
`,`
`,". "," ",""],keepSeparator:!1})}async getChunks(e,n={}){try{if(!Array.isArray(e))return W("ChunkManager: Invalid notePaths provided"),[];if(e.length===0)return[];e.length>1e3&&(W("ChunkManager: Too many note paths, limiting to 1000"),e=e.slice(0,1e3));let r=e.filter(l=>!(!l||typeof l!="string"||l.startsWith("/")||l.startsWith("../")||l.includes("/../")||l.endsWith("/..")));if(r.length===0)return W("ChunkManager: No valid note paths provided"),[];let o={...ske,...n},i=[],s=0,a=0;for(let l of r){let c=this.getCacheKey(l,o),u=this.cache.get(c);if(u&&u.length>0){let d=this.app.vault.getAbstractFileByPath(l);if(d&&d instanceof ake.TFile&&d.stat.mtime>u[0].mtime){let f=this.calculateChunkBytes(u);this.cache.delete(c),this.memoryUsage-=f,u=void 0}}if(!u&&(u=await this.generateChunksForNote(l,o),u.length>0)){let d=this.calculateChunkBytes(u);this.memoryUsage+d<=o.maxBytesTotal?(this.cache.set(c,u),this.memoryUsage+=d):(s+=1,a+=d)}i.push(...u)}if(s>0){let l=(a/1024/1024).toFixed(1);j(`ChunkManager: Cache budget reached, skipped caching ${s} notes (${l}MB total)`)}return j(`ChunkManager: Retrieved ${i.length} chunks from ${r.length} notes (${this.formatMemoryUsage()})`),i}catch(r){return W("ChunkManager: Failed to get chunks",r),[]}}async getChunkText(e){return(await this.ensureChunkExists(e))?.content||""}async ensureChunkExists(e){let[n]=e.split("#"),o=(await this.getValidatedChunks(n)).find(i=>i.id===e);return o||W(`ChunkManager: Chunk ${e} not found after regeneration`),o||null}async getValidatedChunks(e){let n;for(let[o,i]of this.cache.entries())if(o.startsWith(e+":")){n=i;break}if(!n&&(j(`ChunkManager: Cache miss for ${e}, regenerating...`),n=await this.regenerateChunks(e),!n||n.length===0))return W(`ChunkManager: Failed to regenerate chunks for ${e}`),[];let r=this.app.vault.getAbstractFileByPath(e);return r&&r instanceof ake.TFile&&n.length>0&&r.stat.mtime>n[0].mtime&&(j(`ChunkManager: File ${e} modified, regenerating chunks`),n=await this.regenerateChunks(e),!n||n.length===0)?(W(`ChunkManager: Failed to regenerate chunks after modification for ${e}`),[]):n}getChunkTextSync(e){let[n]=e.split("#");for(let[r,o]of this.cache.entries())if(r.startsWith(n+":")){let i=o.find(s=>s.id===e);if(i)return i.content}return W(`ChunkManager: Chunk not in cache: ${e} (use async getChunkText for auto-regeneration)`),""}async regenerateChunks(e){try{let n=await this.generateChunksForNote(e,ske),r=this.getCacheKey(e,ske);if(n.length>0){let o=this.calculateChunkBytes(n);if(this.memoryUsage+o<=ske.maxBytesTotal){let i=this.cache.get(r);i&&(this.memoryUsage-=this.calculateChunkBytes(i)),this.cache.set(r,n),this.memoryUsage+=o}else j(`ChunkManager: Cannot cache regenerated chunks for ${e}, would exceed memory budget`)}return n}catch(n){return W(`ChunkManager: Failed to regenerate chunks for ${e}`,n),[]}}clearCache(){this.cache.clear(),this.memoryUsage=0,j("ChunkManager: Cache cleared")}async generateChunksForNote(e,n){try{let r=this.app.vault.getAbstractFileByPath(e);if(!r||!(r instanceof ake.TFile))return[];let o=await this.safeReadFile(r);if(!o?.trim())return[];let i=this.app.metadataCache.getFileCache(r),s=(i?.headings||[]).slice().sort((p,m)=>p.position.start.offset-m.position.start.offset),a=[],l=0,c=this.findFrontmatterEnd(o,i?.frontmatter),u=o.substring(c),d=s.length>0?s[0].heading:"";if(`
NOTE TITLE: [[${r.basename}]]
NOTE BLOCK CONTENT:
`.length+u.length<=n.maxChars){let p=await this.processContentSection(u,d,r,l,n);return a.push(...p),a}if(s.length===0){let p=await this.processContentSection(u,"",r,l,n);return a.push(...p),a}for(let p=0;p<s.length;p++){let m=s[p],h=s[p+1],g=p===0?c:m.position.start.offset,v=h?.position.start.offset||o.length,y=o.substring(g,v),w=await this.processContentSection(y,m.heading,r,l,n);a.push(...w),l+=w.length}return a}catch(r){return W(`ChunkManager: Failed to chunk note ${e}`,r),[]}}async processContentSection(e,n,r,o,i){let s=r.basename,a=[],l=`
NOTE TITLE: [[${s}]]
NOTE BLOCK CONTENT:
`,c=l+e;if(c.length<=i.maxChars){let u=this.generateChunkId(r.path,o),d=this.calculateContentHash(c);a.push({id:u,notePath:r.path,chunkIndex:o,content:c,contentHash:d,title:s,heading:n,mtime:r.stat.mtime})}else try{let d=await this.createSplitter(i).createDocuments([e],[],{chunkHeader:l,appendChunkOverlapHeader:i.overlap>0});this.coalesceTinySplitChunks(d.map(p=>p.pageContent),l,i.maxChars).forEach((p,m)=>{let h=o+m,g=this.generateChunkId(r.path,h),v=this.calculateContentHash(p);a.push({id:g,notePath:r.path,chunkIndex:h,content:p,contentHash:v,title:s,heading:n,mtime:r.stat.mtime})})}catch(u){W(`ChunkManager: Failed to split section in ${r.path}`,u);let d=this.generateChunkId(r.path,o),f=this.calculateContentHash(c);a.push({id:d,notePath:r.path,chunkIndex:o,content:c,contentHash:f,title:s,heading:n,mtime:r.stat.mtime})}return a}coalesceTinySplitChunks(e,n,r){if(e.length<=1)return e;let o=[...e],i=0;for(;i<o.length-1;){if(this.isTinyStructuralChunk(o[i],n)){let s=this.mergeChunkContents(o[i],o[i+1],n);if(s.length<=r){o.splice(i,2,s);continue}}i++}if(o.length>1){let s=o.length-1;if(this.isTinyStructuralChunk(o[s],n)){let a=this.mergeChunkContents(o[s-1],o[s],n);a.length<=r&&o.splice(s-1,2,a)}}return o}isTinyStructuralChunk(e,n){let r=this.stripChunkHeader(e,n).trim();if(!r)return!0;let o=r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);return o.length===1&&/^#{1,6}\s+\S+/.test(o[0])}mergeChunkContents(e,n,r){let o=this.stripChunkHeader(e,r).replace(/\s+$/,""),i=this.stripChunkHeader(n,r).replace(/^\s+/,"");return`${r}${o}${o&&i?`
`:""}${i}`}stripChunkHeader(e,n){return e.startsWith(n)?e.slice(n.length):e}calculateChunkBytes(e){return e.reduce((n,r)=>n+kD.getByteSize(r.content),0)}async safeReadFile(e){try{return(await this.app.vault.cachedRead(e))?.trim()||""}catch(n){return W(`ChunkManager: Failed to read ${e.path}`,n),""}}generateChunkId(e,n){return`${e}#${n}`}calculateContentHash(e){let n=e.length.toString(16),r=e.slice(0,32).replace(/\s/g,"").substring(0,8);return n+r}formatMemoryUsage(){return`${(this.memoryUsage/1024/1024).toFixed(1)}MB`}findFrontmatterEnd(e,n){if(!n||!e.startsWith("---"))return 0;let r=e.match(/\n---(\r?\n|$)/);return r&&r.index!==void 0?r.index+r[0].length:0}},art=null});var lke,Yte,qmn=b(()=>{es();GH();pe();jmn();Zte();Se();ut();Py();lke=require("obsidian");ha();Yte=class{constructor(e,n,r){this.app=e;this.indexBackend=n;this.embeddingsManager=r;this.state={isIndexingPaused:!1,isIndexingCancelled:!1,indexedCount:0,totalFilesToIndex:0,processedFiles:new Set};this.refreshRuntimeIndexingConfig(),this.chunkManager=DM(e),zr(()=>{this.refreshRuntimeIndexingConfig()})}refreshRuntimeIndexingConfig(){let e=Y();this.rateLimiter=new ike(e.embeddingRequestsPerMin),this.embeddingBatchSize=Math.max(1,e.embeddingBatchSize),this.checkpointInterval=8*this.embeddingBatchSize}async indexVaultToVectorStore(e,n){if(!Y().enableSemanticSearchV3)return W("indexVaultToVectorStore called with semantic search disabled, skipping."),0;let r=[];zEe();try{let o=this.indexBackend.requiresEmbeddings(),i=o?await this.embeddingsManager.getEmbeddingsAPI():void 0;if(o&&!i)return H("Embedding instance not found."),BEe({isActive:!1,isPaused:!1,isCancelled:!1,indexedCount:0,totalFiles:0,errors:["Embedding model not available. Please check your Copilot settings to make sure you have a working embedding model."],completionStatus:"error"}),0;(o?await this.indexBackend.checkAndHandleEmbeddingModelChange(i):!1)&&(e=!0),e?(await this.indexBackend.clearIndex(i),this.indexBackend.clearFilesMissingEmbeddings()):await this.indexBackend.garbageCollect();let a=await this.getFilesToIndex(e);if(a.length===0)return n?.userInitiated&&ad({completionStatus:"success"}),0;this.initializeIndexingState(a.length),this.indexBackend.clearFilesMissingEmbeddings();let l=o&&i?Gc.getModelName(i):"",c=await this.prepareAllChunks(a,l);if(c.length===0)return zEe(),0;if(this.shouldStopIndexing())return ad({isActive:!1,completionStatus:"cancelled"}),0;let u=new Set(c.map(f=>f.fileInfo.path)).size;this.state.totalFilesToIndex=u,ad({totalFiles:u});let d=0;for(;d<c.length&&!this.shouldStopIndexing();){await this.handlePause();let f=c.slice(d,d+this.embeddingBatchSize);try{let p=[];if(o&&i){await this.rateLimiter.wait();let g=await i.embedDocuments(f.map(v=>v.content));if(!g||g.length!==f.length)throw new Error(`Embedding model returned ${g?.length??0} embeddings for ${f.length} documents`);for(let v=0;v<f.length;v++){let y=f[v],w=g[v];if(!w||!Array.isArray(w)||w.length===0){H(`Invalid embedding for document ${String(y.fileInfo.path)}: ${JSON.stringify(w)}`),this.indexBackend.markFileMissingEmbeddings(y.fileInfo.path);continue}p.push({doc:{...y.fileInfo,id:this.getDocHash(y.content),content:y.content,embedding:w,created_at:Date.now(),nchars:y.content.length},filePath:y.fileInfo.path})}}else for(let g of f)p.push({doc:{...g.fileInfo,id:this.getDocHash(g.content),content:g.content,embedding:[],created_at:Date.now(),nchars:g.content.length},filePath:g.fileInfo.path});if(p.length>0)try{await this.indexBackend.upsertBatch(p.map(g=>g.doc)),p.forEach(g=>this.state.processedFiles.add(g.filePath))}catch(g){H("Batch upsert failed; falling back to per-document upserts.",g);for(let v of p)try{await this.indexBackend.upsert(v.doc),this.state.processedFiles.add(v.filePath)}catch(y){this.handleError(y,{filePath:v.filePath,errors:r}),o&&this.indexBackend.markFileMissingEmbeddings(v.filePath)}}this.state.indexedCount=this.state.processedFiles.size,uft(this.state.indexedCount);let m=Math.floor((this.state.indexedCount-f.length)/this.checkpointInterval);Math.floor(this.state.indexedCount/this.checkpointInterval)>m&&(await this.indexBackend.save(),j("Copilot index checkpoint save completed."))}catch(p){if(this.handleError(p,{filePath:f?.[0]?.fileInfo?.path,errors:r,batch:f}),this.isRateLimitError(p))break}d+=f.length}return this.finalizeIndexing(r),window.setTimeout(()=>{this.indexBackend.save().then(()=>{j("Copilot index final save completed."),this.indexBackend.checkIndexIntegrity().catch(f=>{H("Background integrity check failed:",f)})}).catch(f=>{H("Background save failed:",f)})},100),this.state.indexedCount}catch(o){return this.handleError(o),ad({isActive:!1,completionStatus:"error",errors:[o instanceof Error?o.message:String(o)]}),0}}async prepareAllChunks(e,n){let r=[];for(let i=0;i<e.length;i+=1e3){let a=e.slice(i,i+1e3).map(c=>c.path),l=await this.chunkManager.getChunks(a);for(let c of l){let u=this.app.vault.getAbstractFileByPath(c.notePath);if(!u||!(u instanceof lke.TFile))continue;let d=this.app.metadataCache.getFileCache(u),f={title:c.title,path:c.notePath,embeddingModel:n,ctime:u.stat.ctime,mtime:c.mtime,tags:d?.tags?.map(p=>p.tag)??[],extension:u.extension,metadata:{...d?.frontmatter??{},created:Cs(new Date(u.stat.ctime)).display,modified:Cs(new Date(c.mtime)).display,chunkId:c.id,heading:c.heading}};if(c.content.trim()){let p=`METADATA:${JSON.stringify(f.metadata)}
`,m=c.content.indexOf("NOTE BLOCK CONTENT:"),h=m>0?c.content.slice(0,m)+p+c.content.slice(m):c.content;r.push({content:h,chunkId:c.id,fileInfo:f})}}}return r}getDocHash(e){return jl(e)}async getFilesToIndex(e){let{inclusions:n,exclusions:r}=Fi(),o=this.app.vault.getMarkdownFiles();if(e)return o.filter(u=>ii(this.app,u,n,r));let i=new Set(await this.indexBackend.getIndexedFiles()),s=await this.indexBackend.getLatestFileMtime(),a=new Set(this.indexBackend.getFilesMissingEmbeddings()),l=new Set,c=new Set;for(let u of o){if(!ii(this.app,u,n,r))continue;let d=await this.app.vault.cachedRead(u);if(!d||d.trim().length===0){c.add(u.path);continue}let f=i.has(u.path),p=a.has(u.path);(!f||p||u.stat.mtime>s)&&l.add(u)}return j([`Files to index: ${l.size}`,`Previously indexed: ${i.size}`,`Empty files skipped: ${c.size}`,`Files missing embeddings: ${a.size}`].join(`
`)),Array.from(l)}initializeIndexingState(e){this.state={isIndexingPaused:!1,isIndexingCancelled:!1,indexedCount:0,totalFilesToIndex:e,processedFiles:new Set},BEe({isActive:!0,isPaused:!1,isCancelled:!1,indexedCount:0,totalFiles:e,errors:[],completionStatus:"none"})}shouldStopIndexing(){return this.state.isIndexingCancelled||Jie().isCancelled||!Y().enableSemanticSearchV3}async handlePause(){let e=Jie();if(this.state.isIndexingPaused=e.isPaused,this.state.isIndexingCancelled=e.isCancelled,this.state.isIndexingPaused){for(;this.state.isIndexingPaused&&!this.shouldStopIndexing();){await new Promise(r=>window.setTimeout(r,100));let n=Jie();this.state.isIndexingPaused=n.isPaused,this.state.isIndexingCancelled=n.isCancelled}if(!this.shouldStopIndexing()){this.refreshRuntimeIndexingConfig();let n=await this.getFilesToIndex();if(n.length===0){j("No files to index after filter change, stopping indexing"),await this.cancelIndexing();return}let r=Math.max(this.state.indexedCount+n.length,1);this.state.totalFilesToIndex=r,ad({totalFiles:r})}}}isStringLengthError(e){if(!e)return!1;if(e instanceof RangeError&&e.message.toLowerCase().includes("string length"))return!0;let r=(e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)??"").toLowerCase();return r.includes("string length")||r.includes("rangeerror")}handleError(e,n){let r=n?.filePath;if(r?(n.batch?H("Batch processing error:",{error:e,batchSize:n.batch.length||0,firstChunk:n.batch[0]?{path:n.batch[0].fileInfo?.path,contentLength:n.batch[0].content?.length,hasFileInfo:!!n.batch[0].fileInfo}:"No chunks in batch",errorType:e instanceof Error?e.constructor?.name:typeof e,errorMessage:e instanceof Error?e.message:String(e)}):H(`Error indexing file ${r}:`,e),n.errors?.push(r)):H("Fatal error during indexing:",e),this.isStringLengthError(e)){new lke.Notice("Vault is too large for 1 partition, please increase the number of partitions in your Copilot QA settings!",1e4);return}}isRateLimitError(e){return e instanceof Error&&e.message.toLowerCase().includes("rate limit")||!1}finalizeIndexing(e){if(dft(),this.shouldStopIndexing()){ad({isActive:!1,completionStatus:"cancelled",errors:e});return}ad({isActive:!1,completionStatus:e.length>0?"error":"success",errors:e,indexedCount:this.state.indexedCount})}async reindexFile(e){try{let n=this.indexBackend.requiresEmbeddings(),r=n?await this.embeddingsManager.getEmbeddingsAPI():void 0;if(n&&!r)return;if(await this.indexBackend.removeByPath(e.path),n&&r&&await this.indexBackend.checkAndHandleEmbeddingModelChange(r)){await this.indexVaultToVectorStore(!0);return}let o=n&&r?Gc.getModelName(r):"",i=await this.prepareAllChunks([e],o);if(i.length===0)return;if(n&&r){let s=await r.embedDocuments(i.map(a=>a.content));for(let a=0;a<i.length;a++){let l=i[a];await this.indexBackend.upsert({...l.fileInfo,id:this.getDocHash(l.content),content:l.content,embedding:s[a],created_at:Date.now(),nchars:l.content.length})}}else for(let s of i)await this.indexBackend.upsert({...s.fileInfo,id:this.getDocHash(s.content),content:s.content,embedding:[],created_at:Date.now(),nchars:s.content.length});this.indexBackend.markUnsavedChanges(),Y().debug&&j(`Reindexed file: ${e.path}`)}catch(n){this.handleError(n,{filePath:e.path})}}async cancelIndexing(){j("Indexing cancelled by user"),this.state.isIndexingCancelled=!0,ad({isCancelled:!0,isActive:!1,completionStatus:"cancelled"}),await new Promise(e=>window.setTimeout(e,100))}}});var nd={};sr(nd,{default:()=>qv});var Jte,qv,El=b(()=>{es();iy();pe();GH();zu();Se();Jte=require("obsidian");Dmn();Fmn();Umn();nrt();qmn();qv=class t{constructor(e){this.app=e,this.embeddingsManager=Gc.getInstance(),this.oramaBackend=new oke(e),this.miyoBackend=new rke(e),this.activeBackendKey=this.getBackendKey(Y()),this.indexBackend=this.activeBackendKey==="miyo"?this.miyoBackend:this.oramaBackend,this.indexOps=new Yte(e,this.indexBackend,this.embeddingsManager),this.eventHandler=new Kte(e,this.indexOps,this.indexBackend),this.initializationPromise=this.initialize(),this.setupSettingsSubscription()}static getInstance(e){if(!t.instance){if(!e)throw new Error("VectorStoreManager.getInstance() requires `app` on first call (seed it at plugin load).");t.instance=new t(e)}return t.instance}setupSettingsSubscription(){this.lastKnownSettings={...Y()};let e=async()=>{let n=Y(),r=this.lastKnownSettings;if(this.lastKnownSettings={...n},n.enableIndexSync!==r?.enableIndexSync&&this.activeBackendKey==="orama"){let o=await this.embeddingsManager.getEmbeddingsAPI();await this.oramaBackend.reinitializeForIndexSyncChange(o)}await this.refreshBackend(n,r)};zr(()=>{this.initializationPromise=e()})}async initialize(){if(Y().enableSemanticSearchV3)try{let n=3;for(;n>0;)try{let r=this.indexBackend.requiresEmbeddings()?await this.embeddingsManager.getEmbeddingsAPI():void 0;await this.indexBackend.initialize(r);break}catch(r){if(r instanceof Nr&&r.message.includes("Vault adapter not available")&&(n--,n>0)){await new Promise(o=>window.setTimeout(o,100));continue}new Jte.Notice("Failed to initialize vector store. Please make sure you have a valid API key for your embedding model and restart the plugin."),H("Failed to initialize vector store:",r);break}}catch(n){H("Failed to initialize vector store:",n)}}async waitForInitialization(){await this.initializationPromise}async indexVaultToVectorStore(e,n){if(await this.waitForInitialization(),!Y().enableSemanticSearchV3)return W("indexVaultToVectorStore called with semantic search disabled, skipping."),0;if(this.activeBackendKey==="miyo")return await this.miyoBackend.requestIndexRefresh(!!e),Gte(),0;if(Jte.Platform.isMobile&&Y().disableIndexOnMobile&&!this.indexBackend.isRemoteBackend())return new Jte.Notice("Indexing is disabled on mobile devices"),0;let r=await this.indexOps.indexVaultToVectorStore(e,n);return Gte(),r}async clearIndex(){await this.waitForInitialization();let e=this.indexBackend.requiresEmbeddings()?await this.embeddingsManager.getEmbeddingsAPI():void 0;await this.indexBackend.clearIndex(e),Gte()}async garbageCollectVectorStore(){return await this.waitForInitialization(),this.indexBackend.garbageCollect()}async getIndexedFiles(){return await this.waitForInitialization(),this.indexBackend.getIndexedFiles()}async isIndexEmpty(){return await this.waitForInitialization(),await this.indexBackend.isIndexEmpty()}async hasIndex(e){return await this.waitForInitialization(),this.indexBackend.hasIndex(e)}async getDocumentsByPath(e){return await this.waitForInitialization(),this.indexBackend.getDocumentsByPath(e)}pauseIndexing(){ad({isPaused:!0})}resumeIndexing(){ad({isPaused:!1})}async cancelIndexing(){await this.indexOps.cancelIndexing()}shouldUseMiyo(e){return Bu(e)==="miyo"}getBackendKey(e){return this.shouldUseMiyo(e)?"miyo":"orama"}async refreshBackend(e,n){let r=this.getBackendKey(e);if(r!==this.activeBackendKey){if(this.activeBackendKey=r,this.indexBackend=r==="miyo"?this.miyoBackend:this.oramaBackend,this.indexOps=new Yte(this.app,this.indexBackend,this.embeddingsManager),this.eventHandler.cleanup(),this.eventHandler=new Kte(this.app,this.indexOps,this.indexBackend),Y().debug&&j(`VectorStoreManager: switched backend to ${r}`),e.enableSemanticSearchV3){let o=this.indexBackend.requiresEmbeddings()?await this.embeddingsManager.getEmbeddingsAPI():void 0;await this.indexBackend.initialize(o)}n&&e.enableSemanticSearchV3&&e.enableMiyo!==n.enableMiyo&&j("VectorStoreManager: Miyo backend toggled; reindex recommended.")}}onunload(){this.eventHandler.cleanup(),this.indexBackend.onunload()}async getDb(){await this.waitForInitialization();let e=this.oramaBackend.getDb();if(!e)throw new Error("Database is not loaded. Please restart the plugin.");return e}async reindexFile(e){await this.waitForInitialization(),this.activeBackendKey!=="miyo"&&(await this.indexOps.reindexFile(e),Gte())}}});function bRr(){return Bu(Y())==="miyo"}function _Rr(t,e){let n=new Map;for(let r of t){let o=r.document.path,i=n.get(o);i?r.score>i&&n.set(o,r.score):n.set(o,r.score)}return n.delete(e),n}function Gmn(t){if(t.size<=cke)return t;let e=Array.from(t.entries()).sort((n,r)=>r[1]-n[1]).slice(0,cke);return new Map(e)}function xRr(t){return Array.isArray(t.embedding)&&t.embedding.length>0}function SRr(t){return t.some(e=>e.content.trim().length>0)}async function CRr({db:t,filePath:e,currentNoteEmbeddings:n}){let r=n.map(a=>LM.getDocsByEmbedding(t,a,{limit:cke,similarity:0})),i=(await Promise.all(r)).flat(),s=_Rr(i,e);return Gmn(s)}async function Kmn(t,e){let n=Y(),r=new jc,o=Mp(t),i=Dye(t,e);try{let s=await r.resolveBaseUrl(Ci(n)),a=await r.searchRelated(s,i,{folderName:o,limit:cke}),l=new Map,c=a.results||[];for(let u of c){let d=o$(t,u.path);if(d===e||typeof u.score!="number"||Number.isNaN(u.score))continue;let f=l.get(d);(f===void 0||u.score>f)&&l.set(d,u.score)}if(n.debug){let u=c[0]?.path,d=u?o$(t,u):void 0;j(`RelevantNotes(Miyo): file_path=${i} folder_name=${o} received ${c.length} chunks, collected ${l.size} note scores (sample response.path=${u??"n/a"} \u2192 stripped=${d??"n/a"})`)}return Gmn(l)}catch(s){return H(`RelevantNotes(Miyo): searchRelated failed for file_path=${i} folder_name=${o}: ${s.message}`),new Map}}async function kRr(t,e){if(bRr())return Kmn(t,e);let n=await qv.getInstance().getDocumentsByPath(e);if(n.length===0)return new Map;let r=n.filter(o=>xRr(o)).map(o=>o.embedding);if(r.length>0)try{let o=await qv.getInstance().getDb();return CRr({db:o,filePath:e,currentNoteEmbeddings:r})}catch(o){return W("RelevantNotes(Orama): failed to compute similarity scores",o),new Map}return SRr(n)?Kmn(t,e):new Map}function IRr(t,e){let n=new Map,o=apn(t,e).map(a=>a.path);for(let a of o)n.set(a,{links:!0,backlinks:!1});let s=lpn(t,e).map(a=>a.path);for(let a of s)n.has(a)?n.set(a,{links:!0,backlinks:!0}):n.set(a,{links:!1,backlinks:!0});return n}async function Zmn({app:t,filePath:e}){let n=t.vault.getAbstractFileByPath(e);if(!(n instanceof crt.TFile))return[];let r=await kRr(t,e),o=IRr(t,n),i=new Set([...r.keys(),...o.keys()]);return i.delete(e),Array.from(i).filter(pX(t)).sort((a,l)=>{let c=r.get(a),u=r.get(l);return c==null&&u==null?0:c==null?1:u==null?-1:u-c}).map(a=>{let l=t.vault.getAbstractFileByPath(a);if(!(l instanceof crt.TFile)||l.extension!=="md")return null;let c=r.get(a);return{note:{path:a,title:l.basename},metadata:{score:c??0,similarityScore:c,hasOutgoingLinks:o.get(a)?.links??!1,hasBacklinks:o.get(a)?.backlinks??!1}}}).filter(a=>a!==null)}var crt,cke,Ymn=b(()=>{pe();nA();zu();cpn();nke();ha();El();Se();crt=require("obsidian"),cke=20});function TRr(t){let e=vn(),[n,r]=(0,Ke.useState)([]),[o,i]=(0,Ke.useState)(0),s=mnt();return(0,Ke.useEffect)(()=>trt(()=>i(a=>a+1)),[]),(0,Ke.useEffect)(()=>{async function a(){if(s?.path)try{let l=await Zmn({app:e,filePath:s.path});r(l)}catch(l){W("Failed to fetch relevant notes",l),r([])}}a()},[e,s?.path,t,o]),n}function PRr(t,e){let[n,r]=(0,Ke.useState)(!0),[o,i]=(0,Ke.useState)(0);return(0,Ke.useEffect)(()=>trt(()=>i(s=>s+1)),[]),(0,Ke.useEffect)(()=>{if(!t)return;async function s(){try{let a=(await Promise.resolve().then(()=>(El(),nd))).default,{getSettings:l}=await Promise.resolve().then(()=>(Se(),SC)),c=l();if(Bu(c)==="miyo"){let f=await a.getInstance().isIndexEmpty();r(!f);return}let d=await a.getInstance().hasIndex(t);r(d)}catch{r(!1)}}s()},[t,e,o]),n}function ARr(t){return`${Math.max(0,Math.min(100,t*100))}%`}function ERr(t){let e=t*100,n=Math.max(0,Math.min(1,(e-30)/45));return`color-mix(in srgb, var(--interactive-accent) ${Math.round(40+60*n)}%, var(--text-faint))`}function Xmn({score:t,className:e}){return Ke.default.createElement("div",{className:J("tw-h-[3px] tw-w-full tw-overflow-hidden tw-rounded-full tw-bg-modifier-hover",e)},Ke.default.createElement("div",{className:J("copilot-relevance-meter-fill tw-h-full tw-rounded-full"),style:{"--relevance-meter-fill":ARr(t),"--relevance-meter-color":ERr(t)}}))}function Jmn({icon:t,label:e}){return Ke.default.createElement("span",{title:e,className:"tw-flex tw-items-center tw-justify-center tw-rounded-sm tw-bg-modifier-hover tw-p-1 tw-text-faint"},t)}function MRr({note:t,onAddToChat:e,onNavigateToNote:n,children:r}){let o=vn(),[i,s]=(0,Ke.useState)(!1),[a,l]=(0,Ke.useState)(null),c=t.metadata.similarityScore,u=(0,Ke.useCallback)(async()=>{if(a)return;let d=o.vault.getAbstractFileByPath(t.note.path);if(d instanceof uke.TFile){let f=await o.vault.cachedRead(d),p=f;if(f.startsWith("---")){let m=f.indexOf("---",3);m!==-1&&(p=f.slice(m+3).trim())}l(p)}},[o,a,t.note.path]);return(0,Ke.useEffect)(()=>{i&&u()},[i,u]),Ke.default.createElement(nc,{open:i,onOpenChange:s},Ke.default.createElement(den,{asChild:!0},Ke.default.createElement("div",{onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1)},r)),Ke.default.createElement(Cl,{side:"left",align:"start",sideOffset:0,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),onOpenAutoFocus:d=>d.preventDefault(),className:"tw-flex tw-w-fit tw-min-w-72 tw-max-w-96 tw-flex-col tw-gap-3 tw-overflow-hidden tw-p-3"},Ke.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1"},Ke.default.createElement("span",{className:"tw-text-sm tw-font-semibold tw-text-normal"},t.note.title),Ke.default.createElement("span",{className:"tw-flex tw-items-center tw-gap-1.5 tw-text-xs tw-text-faint"},Ke.default.createElement(Jo,{className:"tw-size-3.5 tw-shrink-0"}),Ke.default.createElement("span",{className:"tw-truncate"},t.note.path))),a&&Ke.default.createElement("p",{className:"tw-m-0 tw-max-h-64 tw-overflow-y-auto tw-whitespace-pre-line tw-text-xs tw-leading-normal tw-text-muted"},a),c!=null&&Ke.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ke.default.createElement("span",{className:"tw-shrink-0 tw-text-xs tw-text-faint"},"Similarity"),Ke.default.createElement(Xmn,{score:c,className:"tw-h-1 tw-flex-1"}),Ke.default.createElement("span",{className:"tw-shrink-0 tw-text-xs tw-font-medium tw-tabular-nums tw-text-normal"},(c*100).toFixed(1),"%")),(t.metadata.hasOutgoingLinks||t.metadata.hasBacklinks)&&Ke.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-4 tw-text-xs tw-text-faint"},t.metadata.hasOutgoingLinks&&Ke.default.createElement("span",{className:"tw-flex tw-items-center tw-gap-1"},Ke.default.createElement(H2,{className:"tw-size-3.5"}),"Outgoing links"),t.metadata.hasBacklinks&&Ke.default.createElement("span",{className:"tw-flex tw-items-center tw-gap-1"},Ke.default.createElement(z2,{className:"tw-size-3.5"}),"Backlinks")),Ke.default.createElement("div",{className:"tw-flex tw-gap-2"},Ke.default.createElement(oe,{variant:"secondary",size:"sm",onClick:e,className:"tw-flex-1 tw-gap-1.5"},Ke.default.createElement(Sh,{className:"tw-size-4"}),"Add to Chat"),Ke.default.createElement(oe,{variant:"default",size:"sm",onClick:n,className:"tw-flex-1 tw-gap-1.5"},"Open note",Ke.default.createElement(j2,{className:"tw-size-4"})))))}function ORr({note:t,onAddToChat:e,onNavigateToNote:n}){let r=vn(),o=opn(),i=t.metadata.similarityScore;return Ke.default.createElement(MRr,{note:t,onAddToChat:e,onNavigateToNote:n},Ke.default.createElement("div",{className:"tw-group tw-rounded-md tw-px-2.5 tw-py-1.5 tw-transition-colors hover:tw-bg-modifier-hover"},Ke.default.createElement("div",{className:"tw-flex tw-min-h-6 tw-items-center tw-gap-2"},Ke.default.createElement("a",{draggable:!0,onDragStart:s=>{let a=r.vault.getAbstractFileByPath(t.note.path);a instanceof uke.TFile&&o(s,a)},onClick:s=>{s.preventDefault(),n()},onAuxClick:s=>{s.button===1&&(s.preventDefault(),n())},className:"tw-min-w-0 tw-flex-1 tw-cursor-pointer tw-truncate tw-text-sm tw-font-medium tw-text-normal !tw-no-underline"},t.note.title),Ke.default.createElement("div",{className:"tw-flex tw-shrink-0 tw-items-center tw-gap-1.5 group-hover:tw-hidden"},t.metadata.hasOutgoingLinks&&Ke.default.createElement(Jmn,{icon:Ke.default.createElement(H2,{className:"tw-size-3"}),label:"Outgoing link"}),t.metadata.hasBacklinks&&Ke.default.createElement(Jmn,{icon:Ke.default.createElement(z2,{className:"tw-size-3"}),label:"Backlink"}),i!=null&&Ke.default.createElement("span",{className:"tw-text-xs tw-font-medium tw-tabular-nums tw-text-muted"},Math.round(i*100),"%")),Ke.default.createElement("div",{className:"tw-hidden tw-shrink-0 tw-items-center tw-gap-0.5 group-hover:tw-flex"},Ke.default.createElement(oe,{variant:"ghost2",size:"icon",title:"Add to Chat",className:"tw-size-6 tw-p-0",onClick:s=>{s.stopPropagation(),e()}},Ke.default.createElement(Sh,{className:"tw-size-4"})),Ke.default.createElement(oe,{variant:"ghost2",size:"icon",title:"Open note",className:"tw-size-6 tw-p-0",onClick:s=>{s.stopPropagation(),n()}},Ke.default.createElement(j2,{className:"tw-size-4"})))),i!=null&&Ke.default.createElement(Xmn,{score:i,className:"tw-mt-1.5"})))}function NRr({activeFileName:t,isBuilding:e,onBuild:n}){return Ke.default.createElement("div",{className:"tw-flex tw-flex-none tw-items-center tw-gap-2 tw-border-[0px] tw-border-b tw-border-solid tw-border-border tw-px-3 tw-py-2"},Ke.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-1.5 tw-text-xs tw-text-faint"},Ke.default.createElement("span",{className:"tw-shrink-0"},"Relevant to"),t?Ke.default.createElement("span",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-1 tw-text-muted"},Ke.default.createElement(Jo,{className:"tw-size-3.5 tw-shrink-0"}),Ke.default.createElement("span",{className:"tw-truncate tw-font-medium tw-text-normal"},t)):Ke.default.createElement("span",{className:"tw-text-muted"},"\u2014")),Ke.default.createElement(oe,{variant:"secondary",size:"sm",disabled:e,onClick:n,className:"tw-ml-auto tw-shrink-0 tw-gap-1.5"},Ke.default.createElement(kh,{className:J("tw-size-3.5",e&&"tw-animate-spin")}),e?"Building\u2026":"Build index"))}function RRr({indexedCount:t,totalFiles:e}){let n=e>0?Math.round(t/e*100):0;return Ke.default.createElement("div",{className:"tw-absolute tw-inset-0 tw-flex tw-flex-col tw-items-center tw-justify-center tw-gap-4 tw-px-10 tw-text-center tw-backdrop-blur-sm tw-bg-primary/90"},Ke.default.createElement(Dr,{className:"tw-size-6 tw-animate-spin tw-text-accent"}),Ke.default.createElement("span",{className:"tw-text-sm tw-font-semibold tw-text-normal"},"Indexing your vault"),Ke.default.createElement(Op,{value:n,className:"tw-h-1 tw-w-48"}),e>0&&Ke.default.createElement("span",{className:"tw-text-xs tw-tabular-nums tw-text-faint"},t," / ",e," notes embedded"))}var uke,Ke,Xte,urt=b(()=>{es();pnt();yt();Gb();d$();ko();npn();ipn();De();pe();zu();Ymn();nrt();ha();Se();Re();uke=require("obsidian"),Ke=L(B());Xte=(0,Ke.memo)(({className:t,onAddToChat:e})=>{let n=vn(),[r,o]=(0,Ke.useState)(0),i=TRr(r),s=mnt(),a=PRr(s?.path??"",r),[l]=kT(),c=xt(),u=(0,Ke.useMemo)(()=>{if(!s)return!1;let{inclusions:m,exclusions:h}=Fi({inclusions:c.qaInclusions,exclusions:c.qaExclusions});return!ii(n,s,m,h)},[n,s,c.qaInclusions,c.qaExclusions]),d=m=>{let h=n.vault.getAbstractFileByPath(m);h instanceof uke.TFile&&n.workspace.getLeaf(!0).openFile(h).catch(v=>H("openFile failed",v))},f=m=>{e(`[[${m}]]`)},p=async()=>{let{getSettings:m,updateSetting:h}=await Promise.resolve().then(()=>(Se(),SC));m().enableSemanticSearchV3?(await(await Promise.resolve().then(()=>(El(),nd))).default.getInstance().indexVaultToVectorStore(!1,{userInitiated:!0}),o(r+1)):new YV(n,async()=>{h("enableSemanticSearchV3",!0),await(await Promise.resolve().then(()=>(El(),nd))).default.getInstance().indexVaultToVectorStore(!1,{userInitiated:!0}),o(r+1)},!0).open()};return Ke.default.createElement("div",{className:J("tw-flex tw-min-h-full tw-w-full tw-flex-1 tw-flex-col",t)},u&&Ke.default.createElement("div",{"data-relevant-notes-empty-state":!0,className:"tw-flex tw-flex-1 tw-flex-col tw-items-center tw-justify-center tw-px-6"},Ke.default.createElement("div",{className:"tw-flex tw-w-full tw-max-w-xs tw-flex-col tw-items-center tw-gap-6 tw-text-center"},Ke.default.createElement("div",{className:"tw-flex tw-size-16 tw-items-center tw-justify-center tw-rounded-xl tw-border tw-border-solid tw-border-border tw-bg-secondary"},Ke.default.createElement($C,{className:"tw-size-7 tw-text-muted"})),Ke.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1.5"},Ke.default.createElement("span",{className:"tw-text-lg tw-font-semibold tw-text-normal"},"This note is excluded"),Ke.default.createElement("span",{className:"tw-text-sm tw-text-muted"},"It falls outside your semantic index settings, so related notes can't be shown here. Adjust inclusions or exclusions in Copilot settings to include it.")))),!u&&!a&&Ke.default.createElement("div",{"data-relevant-notes-empty-state":!0,className:"tw-flex tw-flex-1 tw-flex-col tw-items-center tw-justify-center tw-px-6"},Ke.default.createElement("div",{className:"tw-flex tw-w-full tw-max-w-xs tw-flex-col tw-items-center tw-gap-6 tw-text-center"},Ke.default.createElement("div",{className:"tw-flex tw-size-16 tw-items-center tw-justify-center tw-rounded-xl tw-border tw-border-solid tw-border-border tw-bg-secondary"},Ke.default.createElement(W2,{className:"tw-size-7 tw-text-accent"})),Ke.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1.5"},Ke.default.createElement("span",{className:"tw-text-lg tw-font-semibold tw-text-normal"},"No semantic index yet"),Ke.default.createElement("span",{className:"tw-text-sm tw-text-muted"},"Build it once to surface notes related to whatever you're writing.")),Ke.default.createElement("div",{className:"tw-flex tw-w-full tw-flex-col tw-items-center tw-gap-3"},Ke.default.createElement(oe,{variant:"default",onClick:()=>void p(),className:"tw-h-11 tw-w-full tw-gap-2 tw-rounded-lg"},Ke.default.createElement(W2,{className:"tw-size-4"}),"Build index")))),!u&&a&&Ke.default.createElement(Ke.default.Fragment,null,Ke.default.createElement(NRr,{activeFileName:s?.basename,isBuilding:l.isActive,onBuild:()=>void p()}),Ke.default.createElement("div",{className:"tw-relative tw-min-h-0 tw-flex-1"},Ke.default.createElement("div",{className:"tw-absolute tw-inset-0 tw-overflow-y-auto tw-p-2"},i.length===0?Ke.default.createElement("div",{className:"tw-flex tw-h-full tw-items-center tw-justify-center tw-px-4 tw-text-center"},Ke.default.createElement("span",{className:"tw-text-sm tw-text-muted"},"No relevant notes found")):Ke.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-0.5"},i.map(m=>Ke.default.createElement(ORr,{key:m.note.path,note:m,onAddToChat:()=>f(m.note.title),onNavigateToNote:()=>d(m.note.path)})))),l.isActive&&Ke.default.createElement(RRr,{indexedCount:l.indexedCount,totalFiles:l.totalFiles}))))});Xte.displayName="RelevantNotes"});function Qmn({onPopOut:t,onAddToChat:e}){let n=vn(),[r,o]=(0,Kv.useState)(()=>Gfn(n)),i=()=>{Zfn(n),o(!0)};return Kv.default.createElement("div",{className:J("tw-flex tw-min-h-0 tw-w-full tw-flex-1 tw-flex-col tw-overflow-hidden")},!r&&Kv.default.createElement("div",{className:J("tw-flex tw-shrink-0 tw-items-center tw-gap-2 tw-rounded-md tw-border tw-border-solid","tw-border-border tw-bg-secondary tw-px-2 tw-py-1.5 tw-text-ui-smaller tw-text-muted")},Kv.default.createElement("span",{className:"tw-min-w-0 tw-flex-1"},"Open Relevant Notes in its own pane to keep it while you chat."),Kv.default.createElement(oe,{variant:"ghost2",size:"fit",className:J("tw-shrink-0 tw-text-muted","hover:tw-text-normal"),onClick:t},Kv.default.createElement(Ch,{className:"tw-size-3"}),"Open pane"),Kv.default.createElement(oe,{variant:"ghost2",size:"fit",className:J("tw-shrink-0 tw-text-muted","hover:tw-text-normal"),onClick:i,"aria-label":"Dismiss hint"},Kv.default.createElement(pn,{className:"tw-size-3"}))),Kv.default.createElement("div",{className:J("tw-flex tw-min-h-0 tw-flex-1 tw-flex-col")},Kv.default.createElement(Xte,{className:J("[&>[data-relevant-notes-empty-state]]:tw-py-6"),onAddToChat:e})))}var Kv,ehn=b(()=>{unt();urt();yt();ko();De();Re();Kv=L(B())});function thn(t){let[e,n]=(0,dke.useState)(()=>t.workspace.getLeavesOfType(iT).length>0);return(0,dke.useEffect)(()=>{let r=()=>n(t.workspace.getLeavesOfType(iT).length>0);r();let o=t.workspace.on("layout-change",r);return()=>t.workspace.offref(o)},[t]),e}var dke,nhn=b(()=>{gt();dke=L(B())});function drt(t){return{backend:t,state:{messages:t.getMessages(),isStarting:t.isStarting(),hasPendingPlanPermission:t.hasPendingPlanPermission(),currentPlan:t.getCurrentPlan(),currentTodoList:t.getCurrentTodoList(),pendingToolPermissions:t.getPendingToolPermissions(),pendingAskUserQuestions:t.getPendingAskUserQuestions()}}}function rhn(t){let[e,n]=(0,ID.useState)(()=>drt(t)),r=(0,ID.useRef)(!1);return(0,ID.useEffect)(()=>(r.current=!0,()=>{r.current=!1}),[]),(0,ID.useEffect)(()=>{let o=()=>{n(drt(t))};return o(),t.subscribe(()=>{r.current&&o()})},[t]),e.backend===t?e.state:drt(t).state}var ID,ohn=b(()=>{ID=L(B())});function shn(t,e,n){let[r,o]=(0,$d.useState)([]),i=n??tr,[s,a]=(0,$d.useState)(i),l=s===i?r:LRr,[c,u]=(0,$d.useState)(null),d=c===i,f=(0,$d.useRef)(!1);(0,$d.useEffect)(()=>(f.current=!0,()=>{f.current=!1}),[]);let p=(0,$d.useRef)(i);(0,$d.useEffect)(()=>{p.current=i},[i]);let m=(0,$d.useCallback)(async(_,S,I=!1)=>{try{return await S()}catch(C){if(H(`[AgentMode] ${_} failed`,C),new ihn.Notice(`Failed to ${_}.`),I)throw C}},[]),h=(0,$d.useCallback)(async()=>{let _=n??tr;await m("load chat history",async()=>{let S=await t.getChatHistoryItems(n);f.current&&p.current===_&&(a(_),o(S))}),f.current&&p.current===_&&u(_)},[t,m,n]),g=(0,$d.useCallback)(async _=>{await m("load chat",()=>e.loadChatById(_))},[e,m]),v=(0,$d.useCallback)(async(_,S)=>{await m("update chat title",async()=>{await t.updateChatTitle(_,S),await h()},!0)},[t,h,m]),y=(0,$d.useCallback)(async _=>{await m("delete chat",async()=>{await t.deleteChatHistory(_),await h()},!0)},[t,h,m]),w=(0,$d.useCallback)(async _=>{await m("open chat source",()=>e.openChatSourceFile(_))},[e,m]);return{chatHistoryItems:l,chatHistorySettled:d,loadChatHistory:h,loadChat:g,updateChatTitle:v,deleteChat:y,openSourceFile:w}}var ihn,$d,LRr,ahn=b(()=>{_S();pe();ihn=require("obsidian"),$d=L(B()),LRr=Object.freeze([])});function lhn({activeChatInputId:t,liveChatInputIds:e,defaultIncludeActiveNote:n}){let[r,o]=(0,Ml.useState)({}),i=e.join("\0"),s=(0,Ml.useRef)(new Set(e));(0,Ml.useEffect)(()=>{let _=new Set(e);s.current=_,o(S=>{let I=!1,C={};for(let[k,T]of Object.entries(S))_.has(k)?C[k]=T:I=!0;return I?C:S})},[i]);let a=(0,Ml.useCallback)((_,S)=>{o(I=>{if(!s.current.has(_))return I;let C=I[_]??URr(n),k=S(C);return k===C?I:{...I,[_]:k}})},[n]),l=(0,Ml.useCallback)(_=>a(t,_),[t,a]),c=(0,Ml.useCallback)(_=>l(S=>({...S,input:_})),[l]),u=(0,Ml.useCallback)(_=>l(S=>({...S,contextNotes:frt(_,S.contextNotes)})),[l]),d=(0,Ml.useCallback)(_=>l(S=>({...S,images:frt(_,S.images)})),[l]),f=(0,Ml.useCallback)(_=>l(S=>({...S,images:[...S.images,..._]})),[l]),p=(0,Ml.useCallback)(_=>l(S=>({...S,includeActiveNote:_})),[l]),m=(0,Ml.useCallback)(_=>l(S=>({...S,includeActiveWebTab:_})),[l]),h=(0,Ml.useCallback)(_=>l(S=>({...S,loading:_})),[l]),g=(0,Ml.useCallback)(_=>l(S=>({...S,queue:frt(_,S.queue)})),[l]),v=(0,Ml.useCallback)(()=>l(_=>({..._,input:"",images:[],contextNotes:[],includeActiveNote:!1,includeActiveWebTab:!1})),[l]),y=r[t],w=(0,Ml.useMemo)(()=>y??{input:"",images:$Rr,contextNotes:DRr,includeActiveNote:n,includeActiveWebTab:!1,loading:!1,queue:FRr},[y,n]);return(0,Ml.useMemo)(()=>({...w,setInput:c,setContextNotes:u,setSelectedImages:d,addImages:f,setIncludeActiveNote:p,setIncludeActiveWebTab:m,setLoading:h,setQueue:g,resetCompose:v}),[w,c,u,d,f,p,m,h,g,v])}var Ml,$Rr,DRr,FRr,URr,frt,chn=b(()=>{Ml=L(B()),$Rr=Object.freeze([]),DRr=Object.freeze([]),FRr=Object.freeze([]),URr=t=>({input:"",images:[],contextNotes:[],includeActiveNote:t,includeActiveWebTab:!1,loading:!1,queue:[]}),frt=(t,e)=>typeof t=="function"?t(e):t});function jRr(t,e){if(t===e)return!0;if(t.size!==e.size)return!1;for(let n of t)if(!e.has(n))return!1;return!0}function fke(t,e){let n=(0,d3.useRef)(e);n.current=e;let[r,o]=(0,d3.useState)(()=>e(t));return(0,d3.useEffect)(()=>{let i=()=>{let s=n.current(t);o(a=>jRr(a,s)?a:s)};return i(),t.subscribe(i)},[t]),r}var d3,prt=b(()=>{d3=L(B())});function uhn(t){return fke(t,BRr)}var BRr,dhn=b(()=>{prt();BRr=t=>t.getAttentionChatIds()});function fhn(t){return fke(t,zRr)}var zRr,phn=b(()=>{prt();zRr=t=>t.getRunningChatIds()});function mhn(){let{focusInput:t}=IM(),e=(0,pke.useContext)(Gd);(0,pke.useEffect)(()=>{let n=e instanceof by?e:null,r=()=>{n?.consumePendingVisible(),t()};return e?.addEventListener(cs.CHAT_IS_VISIBLE,r),n?.consumePendingVisible()&&t(),()=>e?.removeEventListener(cs.CHAT_IS_VISIBLE,r)},[e,t])}var pke,hhn=b(()=>{gt();ko();hte();pke=L(B())});function ghn({activeProjectId:t,signature:e,isLanding:n,blocking:r,draftEmpty:o,refresh:i}){let s=(0,b_.useRef)(i);(0,b_.useEffect)(()=>{s.current=i},[i]);let a=(0,b_.useRef)(null),l=(0,b_.useRef)(!1),c=(0,b_.useRef)(!0);(0,b_.useEffect)(()=>()=>{c.current=!1},[]);let[u,d]=(0,b_.useState)(0);(0,b_.useEffect)(()=>{if(e===null||t===tr){a.current=null;return}let f=a.current;if(!f||f.projectId!==t){a.current={projectId:t,signature:e};return}if(f.signature!==e){if(!n){a.current={projectId:t,signature:e};return}!o||r||l.current||(l.current=!0,s.current().then(p=>{p&&c.current&&(a.current={projectId:t,signature:e},d(m=>m+1))}).catch(()=>{}).finally(()=>{l.current=!1}))}},[e,t,n,r,o,u])}var b_,yhn=b(()=>{_S();b_=L(B())});function f3(t){return!Object.values(t).some(e=>e.origin.kind==="copilot-plus")}function mke(t={}){return vhn.length===0?HRr:vhn.map(e=>({name:e.id,provider:"copilot-plus",displayName:e.displayName||e.id,enabled:!0,isBuiltIn:!1,_disabledReason:WRr,_needsLicense:!0,_subtitle:e.description,_group:t.group,_backendId:t.backendId}))}var HRr,WRr,vhn,hke=b(()=>{gt();mp();HRr=Object.freeze([]),WRr="Copilot license required",vhn=gj.filter(t=>Uce.includes(t.id))});function ene(t,e){if(t instanceof da){new TD.Notice(`This agent doesn't support runtime ${e} switching.`);return}H(`[AgentMode] ${e} apply failed`,t),new TD.Notice(`Failed to switch ${e}. See console for details.`)}function VRr(t,e,n){let r=e.getEnabledModelEntries?.(n.settings)??null;if(r){if(!n.backendModels){if(!n.useEnabledFallback)return;qRr(t,e,r);return}KRr(t,e,r,n.backendModels,n.keepBaseModelId)}}function qRr(t,e,n){for(let r of n){let o=Qte(r.baseModelId,r.name||r.baseModelId,e,r.description,r.isFree,r.capabilities);r.credentialState==="missing_key"&&(o._disabledReason=gke),t.push(o)}}function KRr(t,e,n,r,o){let i=new Map(r.map(a=>[a.baseModelId,a])),s=new Set;for(let a of n){let l=i.get(a.baseModelId),c=l?.name||a.name||a.baseModelId,u=l?.description??a.description,d=a.capabilities,f=Qte(a.baseModelId,c,e,u,a.isFree,d),p=GRr(a.credentialState,!!l);p&&(f._disabledReason=p),a.needsSelfHostWarning&&(f._needsSelfHostWarning=!0),t.push(f),s.add(a.baseModelId)}if(o&&!s.has(o)){let a=i.get(o);a&&t.push(Qte(a.baseModelId,a.name,e,a.description,void 0,void 0))}}function GRr(t,e){if(t==="missing_key")return gke;if(!e)return"Not offered by agent"}function ZRr(t){switch(t.kind){case"absent":return"Not set up";case"incompatible":return"Update required";case"error":return"Setup error";case"checking":case"ready":return}}function Qte(t,e,n,r,o,i){return{name:t,provider:bhn,enabled:!0,isBuiltIn:!1,displayName:e||t,capabilities:i,_group:n.displayName,_backendId:n.id,_subtitle:r,_isFree:o}}function whn(t,e){let n=e==="pending";return{...Qte(`__preload_${e}__`,n?"Loading models\u2026":"Failed to load",t),_disabledReason:n?"Loading\u2026":"Unavailable"}}function yke(t){return t.provider===bhn?t.name:void 0}function YRr(t){let e=t.getActiveSession(),n=t.getActiveChatUIState(),r=e?.backendId??null,o=r?$a[r]:void 0,i=e?.hasUserVisibleMessages()??!1,a=(e?.getState()??null)?.model??null,l=a?.availableModels.find(c=>c.baseModelId===a.current.baseModelId);return{activeSession:e,activeChatUIState:n,activeBackendId:r,activeDescriptor:o,activeSessionHasHistory:i,activeModelState:a,activeCurrentEntry:l}}function JRr(t,e,n,r){let o=[];for(let s of e){let a=s.id===n.activeBackendId;if(!a&&n.activeSessionHasHistory)continue;let l=t.getCachedModelCatalog(s.id),c=a?n.activeModelState?.current.baseModelId??null:t.getDefaultSelection(s.id)?.baseModelId??null,u=l?.availableModels??null,d=l===null,f=t.getPreloadStatus(s.id),p=o.length;if(VRr(o,s,{backendModels:u,keepBaseModelId:c,settings:r,useEnabledFallback:d&&(f==="ready"||f==="error")}),d&&o.length===p&&(f==="pending"?o.push(whn(s,"pending")):(f==="ready"||f==="error")&&o.push(whn(s,"error"))),!a){let m=ZRr(s.getInstallState(r));if(m)for(let h=p;h<o.length;h++)o[h]._disabledReason=m}if(RI(s,r))for(let m=p;m<o.length;m++)o[m]._needsSelfHostWarning=!0;s.routesCopilotModels&&f3(r.providers)&&o.splice(p,0,...mke({group:s.displayName,backendId:s.id}))}let i="";if(n.activeBackendId&&n.activeDescriptor&&n.activeModelState&&n.activeCurrentEntry){let s=n.activeModelState.current.baseModelId,a=o.find(l=>l._backendId===n.activeBackendId&&yke(l)===s);if(a)i=Jn(a);else{let l=Qte(s,n.activeCurrentEntry.name,n.activeDescriptor,n.activeCurrentEntry.description,void 0,void 0);RI(n.activeDescriptor,r)&&(l._needsSelfHostWarning=!0),o.unshift(l),i=Jn(l)}}return{entries:o,valueKey:i}}function XRr(t,e){let{activeBackendId:n,activeCurrentEntry:r,activeModelState:o,activeChatUIState:i}=e;if(!(!n||!r)&&r.effortOptions.length!==0&&o)return{options:r.effortOptions,value:o.current.effort,disabled:i?.canSwitchEffort()===!1,onChange:s=>{t.applySelection({effort:s},{expectBackendId:n}).catch(a=>{ene(a,"effort")})}}}function _hn(t,e,n,r,o,i){(async()=>{try{let s={baseModelId:o,effort:i};e?await t.replaceSessionInPlace(e,n,{preserveChatInput:!0,seedSelection:s}):await t.createSession(n,void 0,s),t.setDefaultBackend(n)}catch(s){H("[AgentMode] cross-backend pick failed",s),new TD.Notice(`Failed to start ${r.displayName}. See console for details.`)}})()}function QRr(t,e,n){let{activeSession:r,activeChatUIState:o}=e;return i=>{let s=n.find(u=>Jn(u)===i);if(!s)return;let a=s._backendId;if(!a){H("[AgentMode] picker entry missing _backendId",s);return}let l=$a[a];if(!l){H("[AgentMode] picker entry references unknown backend",a);return}let c=yke(s);if(!c){new TD.Notice("Could not resolve a model id for this selection.");return}if(!r||r.backendId!==a){let u=t.getDefaultSelection(a)?.effort??null;_hn(t,r?.internalId,a,l,c,u);return}if(t.setDefaultBackend(a),o?.canSwitchModel()===!1){new TD.Notice("This agent doesn't support runtime model switching.");return}t.applySelection({baseModelId:c}).catch(u=>{ene(u,"model")})}}function eLr(t,e){let n={};for(let r of e){let o=r._backendId,i=yke(r);!o||!i||(n[Jn(r)]=hrt(t,o,i))}return n}function hrt(t,e,n){let i=(t.getCachedModelCatalog(e)?.availableModels??null)?.find(s=>s.baseModelId===n)?.effortOptions??[];return i.length>0?i:t.getEffortCatalog(e)?.[n]??mrt}function tLr(t,e,n,r){let{activeSession:o,activeChatUIState:i}=e;return(s,a)=>{let l=n.find(f=>Jn(f)===s);if(!l)return;let c=yke(l),u=l._backendId;if(!c||!u){r(s);return}let d=$a[u];if(!d){H("[AgentMode] commitSelection references unknown backend",u);return}if(!o||o.backendId!==u){_hn(t,o?.internalId,u,d,c,a);return}if(i?.canSwitchModel()===!1){new TD.Notice("This agent doesn't support runtime model switching.");return}t.applySelection({baseModelId:c,effort:a}).catch(f=>{ene(f,"model")})}}function xhn(t){let{manager:e,descriptors:n,settings:r}=t;if(!e)return null;let o=YRr(e),{entries:i,valueKey:s}=JRr(e,n,o,r),a=QRr(e,o,i);return{models:i,value:s,disabled:!1,effort:XRr(e,o),effortOptionsByModelKey:eLr(e,i),onChange:a,commitSelection:tLr(e,o,i,a)}}var TD,mrt,gke,bhn,vke=b(()=>{TD=require("obsidian");pe();hke();ok();Wm();Se();mrt=Object.freeze([]),gke="Add API key";bhn="agent"});function p3(t){return(0,Shn.useCallback)(e=>{if(!t)return()=>{};let n=null,r=null,o=()=>{let a=t.getActiveChatUIState();a!==r&&(n?.(),r=a,n=a?.subscribe(e)??null)};o();let i=t.subscribe(()=>{o(),e()}),s=t.subscribeModelCache(e);return()=>{i(),s(),n?.()}},[t])}var Shn,wke=b(()=>{Shn=L(B())});function nLr(t,e){let n=p3(t),r=(0,PD.useCallback)(()=>{if(!t)return"";let o=t.getActiveSession(),i=[o?.internalId??"",o?.backendId??"",o?.getStatus()??"",o?.hasUserVisibleMessages()?"1":"0",b2t(o?.getState()??null)];for(let s of e)i.push(`${s.id}:${t.getModelCacheSignature(s.id)}`);return i.join("|")},[t,e]);return(0,PD.useSyncExternalStore)(n,r,r)}function bke(t,e){let n=xt(),r=(0,PD.useMemo)(()=>ss(),[]),o=CCe(e),i=nLr(t,r);return(0,PD.useMemo)(()=>xhn({manager:t,descriptors:r,settings:n}),[t,r,n,i,o])}var PD,grt=b(()=>{PD=L(B());Se();Wm();XB();yD();vke();wke()});function rLr(t){let e=t.getActiveSession(),n=t.getActiveChatUIState(),r=e?.backendId??null,o=e?.getState()??null;return{activeBackendId:r,activeMode:o?.mode??null,activeChatUIState:n}}function Chn(t){let{manager:e}=t;if(!e)return null;let n=rLr(e),{activeBackendId:r,activeMode:o,activeChatUIState:i}=n;return!r||!o?null:{options:o.options,value:o.current,disabled:i?.canSwitchMode()===!1,onChange:s=>{let a=o.apply[s];a&&e.applyMode(r,s,a).catch(l=>{ene(l,"mode")})}}}var khn=b(()=>{vke()});function oLr(t){let e=p3(t),n=(0,m3.useCallback)(()=>{if(!t)return"";let r=t.getActiveSession(),o=r?.getState()??null;return[r?.internalId??"",r?.backendId??"",r?.getStatus()??"",x2t(o)].join("|")},[t]);return(0,m3.useSyncExternalStore)(e,n,n)}function _ke(t){let e=oLr(t);return(0,m3.useMemo)(()=>Chn({manager:t}),[t,e])}var m3,yrt=b(()=>{m3=L(B());XB();khn();wke()});function Thn(){let t=Math.floor(Math.random()*Ihn.length);return Ihn[t]}var Ihn,Phn=b(()=>{Ihn=Object.freeze(["What can I help with?","Where should we start?","What's on your mind?","What are you working on?","How can I help today?","Ready when you are.","What would you like to explore?","Let's pick up where you left off.","What can I do for you?","Got something to capture?","What's next on your list?","Where to begin?","What shall we dig into?","Ask me anything."])});function iLr(t,e){let n=e.match(/obsidian:\/\/open\?vault=.*?&file=(.*)$/);if(!n)return null;let r=decodeURIComponent(n[1]),o=t.vault.getAbstractFileByPath(r);return o instanceof AD.TFile||(o=t.vault.getAbstractFileByPath(r+".md"),o instanceof AD.TFile)?o:null}function sLr(t,e){let n=e.split(`
`).filter(o=>o.trim()),r=[];for(let o of n){let i=iLr(t,o.trim());i&&r.push(i)}return r}function aLr(t){let e=t.toLowerCase();return e==="jpg"?"image/jpeg":`image/${e}`}function Ske(t){let{app:e,contextNotes:n,setContextNotes:r,selectedImages:o,onAddImage:i,containerRef:s}=t,[a,l]=(0,xke.useState)(!1);return(0,xke.useEffect)(()=>{let c=s.current;if(!c)return;let u=h=>{if((h.target instanceof HTMLElement?h.target:null)?.closest("[data-copilot-drop-zone]")){l(!1);return}if(h.preventDefault(),h.dataTransfer){if(h.dataTransfer.dropEffect="copy",h.dataTransfer.types.includes("copilot/internal-drag"))return;let v=Array.from(h.dataTransfer.items).some(w=>w.kind==="string"),y=Array.from(h.dataTransfer.items).some(w=>w.kind==="file");(v||y)&&l(!0)}},d=h=>{let g=c.getBoundingClientRect(),v=h.clientX,y=h.clientY;(v<g.left||v>=g.right||y<g.top||y>=g.bottom)&&l(!1)},f=async h=>{if(!h.dataTransfer||(h.target instanceof HTMLElement?h.target:null)?.closest("[data-copilot-drop-zone]"))return;h.preventDefault(),l(!1);let v=h.dataTransfer.items,y=[],w=[];for(let _=0;_<v.length;_++){let S=v[_];S.kind==="string"?y.push(S):S.kind==="file"&&w.push(S)}if(y.length>0){h.stopPropagation();let _=y.map(C=>new Promise(k=>{C.getAsString(T=>k(T))})),S=await Promise.all(_),I=new Map;for(let C of S){let k=sLr(e,C);for(let T of k)I.set(T.path,T)}for(let C of I.values())if(["png","gif","jpeg","jpg","webp"].includes(C.extension)){if(o.some($=>$.name===C.name)){new AD.Notice("This image is already in the context");continue}let P=await e.vault.readBinary(C),E=new Blob([P]),O=new File([E],C.name,{type:aLr(C.extension)});i([O])}else if(U_(C)){if(n.some(P=>P.path===C.path)){new AD.Notice("This note is already in the context");continue}r(P=>[...P,C])}else new AD.Notice(`Unsupported file type: ${C.extension}. Supported types: md, pdf, canvas, and images.`)}else if(w.length>0){let _=[];for(let S of w){let I=S.getAsFile();I&&I.type.startsWith("image/")&&_.push(I)}_.length>0&&i(_)}},p=h=>{f(h)},m=()=>l(!1);return c.addEventListener("dragover",u,!0),c.addEventListener("dragleave",d),c.addEventListener("drop",p),c.addEventListener("drop",m,!0),()=>{c.removeEventListener("dragover",u,!0),c.removeEventListener("dragleave",d),c.removeEventListener("drop",p),c.removeEventListener("drop",m,!0)}},[e,n,o,i,r,s]),{isDragActive:a}}var AD,xke,vrt=b(()=>{ut();AD=require("obsidian"),xke=L(B())});var FM,It,lLr,cLr,Ahn,Ehn=b(()=>{dun();iJe();Cun();Mun();Jdn();ufn();ffn();bfn();Gtt();kfn();Efn();Lfn();$fn();ont();ltt();Hfn();unt();tpn();ehn();nhn();ohn();ahn();chn();dhn();phn();hhn();yhn();grt();yrt();yD();Phn();_S();es();Htt();yCe();kS();gt();ko();hte();vrt();De();pe();zI();Jwe();Md();Se();Us();Re();FM=require("obsidian"),It=L(B());Hl();lLr=Object.freeze({}),cLr=({backend:t,sessionId:e,chatInputId:n,manager:r,plugin:o,onSaveChat:i,updateUserMessageHistory:s})=>{let a=(0,It.useContext)(fN),l=o.app||a,c=xt(),u=(0,It.useContext)(Gd),d=IM(),f=thn(l);mhn(),(0,It.useEffect)(()=>{let Vt=u instanceof by?u:null,vi=ry=>{Vt?.consumePendingInsertText();let pc=ry.detail?.text;typeof pc=="string"&&d.insertTextWithPills(pc,!0)};u?.addEventListener(cs.INSERT_TEXT_TO_CHAT,vi);let fc=Vt?.consumePendingInsertText();return typeof fc=="string"&&d.insertTextWithPills(fc,!0),()=>{u?.removeEventListener(cs.INSERT_TEXT_TO_CHAT,vi)}},[u,d]);let{messages:p,isStarting:m,hasPendingPlanPermission:h,currentPlan:g,currentTodoList:v,pendingToolPermissions:y,pendingAskUserQuestions:w}=rhn(t),[_,S]=(0,It.useState)(null),I=(0,It.useRef)(null);(0,It.useEffect)(()=>{i(async()=>{await r.saveActiveSession()})},[i,r]);let C=(0,It.useCallback)(async()=>{try{await r.saveActiveSession()?new FM.Notice("Chat saved as note."):new FM.Notice("Nothing to save yet.")}catch(Vt){H("[AgentMode] manual save failed",Vt),new FM.Notice("Failed to save chat as note. Check console for details.")}},[r]),k=(0,It.useCallback)(()=>{if(r.getIsStarting())return;let Vt=r.getActiveSession();if(!Vt||!Vt.hasUserVisibleMessages())return;let vi=Vt.internalId;(async()=>{try{await r.replaceSessionInPlace(vi,Vt.backendId)}catch(fc){H("[AgentMode] new chat failed",fc),new FM.Notice("Failed to start a new chat. Please try again.")}})()},[r]),T=KS(r),P=(0,It.useCallback)(()=>{T.openInstallUI(o)},[T,o]),E=Zwe(),O=(0,It.useMemo)(()=>E.length===0?lLr:Object.fromEntries(E.map(Vt=>[Vt.id,Vt.name])),[E]),$=(0,It.useMemo)(()=>nl.getInstance(l).getProjectUsageTimestampsManager(),[l]),U=r.getActiveProjectId(),V=U!==tr,K=V?E.find(Vt=>Vt.id===U):void 0,se=V&&!K,le=K?.name??"",Q=(0,It.useRef)({name:le,orphaned:se});V&&(Q.current={name:le,orphaned:se});let ne=V?le:Q.current.name,ee=V?se:Q.current.orphaned,{chatHistoryItems:ae,chatHistorySettled:q,loadChatHistory:F,loadChat:z,updateChatTitle:N,deleteChat:R,openSourceFile:X}=shn(r,o,U),D=xn(F),G=fhn(r),ce=uhn(r),Z=Ar(my,{store:on}),te=V&&(Z[U]?.blocking??!1),fe=(0,It.useCallback)(()=>{r.exitProject().catch(Vt=>{H("[AgentMode] exit project failed",Vt),new FM.Notice("Failed to leave project. Please try again.")})},[r]),de=(0,It.useCallback)(Vt=>{r.getActiveProjectId()===Vt&&r.exitProject().catch(vi=>{H("[AgentMode] exit after delete failed",vi)})},[r]),ye=(0,It.useCallback)(Vt=>{r.enterProject(Vt.id).catch(vi=>{H("[AgentMode] enter project failed",vi),new FM.Notice("Failed to open project. Please try again.")})},[r]),[Te,Be]=(0,It.useState)(null),qe=(0,It.useCallback)(Vt=>{Be(Vt)},[]),Ae=(0,It.useCallback)(async({name:Vt})=>{let vi=hfn(Vt);try{await nl.getInstance(l).createProject(vi),await r.enterProject(vi.id)}catch(fc){throw H("[AgentMode] create project failed",fc),fc}Be(null)},[l,r]),Xt=(0,It.useCallback)(()=>{At("agentMode",{...Y().agentMode,welcomeDismissed:!0})},[]);(0,It.useEffect)(()=>{se&&new FM.Notice("This project no longer exists.")},[se]);let Ve=bke(r,o),Ee=_ke(r),st=(0,It.useCallback)(()=>{if(!Ee||Ee.disabled)return;let{options:Vt,value:vi,onChange:fc}=Ee;if(Vt.length===0)return;let ry=Vt.findIndex(pw=>pw.value===vi),pc=Vt[(ry+1)%Vt.length];pc.value!==vi&&fc(pc.value)},[Ee]),Ne=r.getSessions(),He=Ne.map(Vt=>Vt.chatInputId).join("\0"),et=(0,It.useMemo)(()=>Ne.map(Vt=>Vt.chatInputId),[He]),it=lhn({activeChatInputId:n,liveChatInputIds:et,defaultIncludeActiveNote:c.autoAddActiveContentToContext===!0}),{isDragActive:Br}=Ske({app:l,contextNotes:it.contextNotes,setContextNotes:it.setContextNotes,selectedImages:it.images,onAddImage:it.addImages,containerRef:I}),Xr=!r.getActiveSession()?.hasUserVisibleMessages(),An=Xr&&V,zn=(0,It.useCallback)(async()=>{let Vt=r.getActiveSession();if(!Vt||Vt.hasUserVisibleMessages()||!(it.input.trim()===""&&it.images.length===0&&it.contextNotes.length===0&&it.queue.length===0))return!1;try{return await r.replaceSessionInPlace(Vt.internalId,Vt.backendId,{preserveChatInput:!0}),!0}catch(fc){return H("[AgentMode] refresh landing context failed",fc),!1}},[r,it]),Yp=it.input.trim()===""&&it.images.length===0&&it.contextNotes.length===0&&it.queue.length===0,la=(0,It.useMemo)(()=>{if(!V)return null;let Vt=mo(U);return Vt?DQ(l,Vt):null},[l,V,U,E]);ghn({activeProjectId:U,signature:la,isLanding:Xr,blocking:te,draftEmpty:Yp,refresh:zn});let vu=An?`${U}\0${e}`:null,Ds=(0,It.useRef)(null);if(vu===null)Ds.current=null;else if(q){let Vt=ae.length>0;Ds.current?.key!==vu?Ds.current={key:vu,standalone:!Vt}:Ds.current.standalone&&Vt&&(Ds.current={key:vu,standalone:!1})}else Ds.current?.key!==vu&&(Ds.current=null);let hh=Ds.current,N_=r.getActiveSession()?.backendId??r.getStartingBackendId()??null,ty=(0,It.useMemo)(()=>Thn(),[e]);(0,It.useEffect)(()=>{Xr&&F()},[Xr,F]);let[fl,wu]=(0,It.useState)(()=>qfn(l,cnt)),ct=(0,It.useCallback)(Vt=>{wu(Vt),Kfn(l,cnt,Vt)},[l]),Qt=(0,It.useMemo)(()=>[{id:"chats",icon:It.default.createElement(q2,{className:"tw-size-4"}),title:"Recent Chats",renderBody:()=>It.default.createElement($Ce,{items:ae,onLoadChat:z,onUpdateTitle:N,onDeleteChat:R,onOpenSourceFile:X,onLoadHistory:D,runningChatIds:G,attentionChatIds:ce,projectNamesById:O})},...f?[]:[{id:"relevant-notes",icon:It.default.createElement(mG,{className:"tw-size-4"}),title:"Relevant Notes",renderBody:()=>It.default.createElement(Qmn,{onPopOut:()=>void o.activateRelevantNotesView(),onAddToChat:Vt=>void o.insertTextIntoActiveChat(Vt)})}],{id:"projects",icon:It.default.createElement(Fl,{className:"tw-size-4"}),title:"Projects",count:E.length,renderBody:()=>It.default.createElement(fnt,{projects:E,onSelect:ye,onCreate:qe,app:l,onProjectDeleted:de,projectUsageTimestampsManager:$})}],[E,O,ae,l,$,ye,qe,de,z,N,R,X,D,G,ce,f,o]),ir=(0,It.useMemo)(()=>Ydn(K),[K]),Ct=(0,It.useMemo)(()=>[{id:"project-chats",icon:It.default.createElement(q2,{className:"tw-size-4"}),title:"Recent Chats",renderBody:()=>It.default.createElement($Ce,{items:ae,variant:"project",onLoadChat:z,onUpdateTitle:N,onDeleteChat:R,onOpenSourceFile:X,onLoadHistory:D,runningChatIds:G,attentionChatIds:ce})},{id:"project-context",icon:It.default.createElement(hG,{className:"tw-size-4"}),title:"Context",count:ir.totalItems,renderBody:()=>It.default.createElement(_Ce,{app:l,projectId:U,popoverContainer:_})}],[ae,ir.totalItems,l,U,_,z,N,R,X,D,G,ce]),wt=()=>{K&&new EM(l,Vt=>{nl.getInstance(l).updateProject(U,Vt).catch(vi=>H("[AgentMode] save context changes failed",vi))},K).open()},_t=V&&!se&&K?It.default.createElement(ztt,{app:l,activeProjectId:U,project:K,hasConfiguredContextSource:!ir.isEmpty,landing:Xr,onReindex:()=>r.rematerializeContext(U),onRetryItem:Vt=>r.rematerializeSource(U,{kind:Vt.cacheKind,source:Vt.id}).catch(vi=>(H("[AgentMode] retry source failed",vi),!1)),onRefreshLanding:zn,onEditContext:wt}):void 0,an=It.default.createElement(Sun,{backend:t,plugin:o,chatInputId:n,draft:it,app:l,mainAgentId:N_,updateUserMessageHistory:s,isStarting:m,hasPendingPlanPermission:h,modelPickerOverride:Ve??void 0,modePickerOverride:Ee??void 0,onCycleMode:st,activeProjectId:U,contextLoadBlocking:te,disabled:se,contextStatusIndicator:_t,isLanding:Xr}),Vo=An&&!se?`Chat in ${le}`:ty,ny=It.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-items-center tw-justify-center tw-gap-3"},It.default.createElement(OCe,{className:"tw-size-4 tw-shrink-0 tw-text-normal"}),It.default.createElement(si,{className:"tw-min-w-0 tw-text-ui-title tw-font-[330] tw-text-normal",tooltipContent:Vo},Vo));return It.default.createElement("div",{ref:S,className:"tw-flex tw-size-full tw-flex-col tw-overflow-hidden"},It.default.createElement("div",{className:J("tw-grid tw-shrink-0 tw-transition-[grid-template-rows,opacity] tw-duration-200 tw-ease-out motion-reduce:tw-transition-none",V?"tw-grid-rows-[1fr] tw-opacity-100":"tw-pointer-events-none tw-grid-rows-[0fr] tw-opacity-0"),"aria-hidden":!V},It.default.createElement("div",{className:"tw-min-h-0 tw-overflow-hidden"},It.default.createElement(Ytt,{projectName:ne,onExit:fe,orphaned:ee,menu:K?It.default.createElement(nnt,{app:l,project:K,todoList:v,container:_}):void 0}))),It.default.createElement(Nfn,{manager:r}),Te&&It.default.createElement(wfn,{anchorEl:Te,onClose:()=>Be(null),onSave:Ae}),It.default.createElement("div",{className:"tw-min-h-0 tw-flex-1"},It.default.createElement("div",{ref:I,className:"tw-flex tw-size-full tw-flex-col tw-overflow-hidden"},It.default.createElement("div",{className:"tw-h-full"},It.default.createElement("div",{className:"tw-relative tw-flex tw-h-full tw-flex-col"},Br&&It.default.createElement("div",{className:"tw-pointer-events-none tw-absolute tw-inset-0 tw-z-modal tw-flex tw-items-center tw-justify-center tw-rounded-md tw-border tw-border-dashed tw-bg-primary tw-opacity-80"},It.default.createElement("span",null,"Drop files here...")),It.default.createElement("div",{className:Xr?"tw-flex tw-size-full tw-flex-col tw-overflow-y-auto tw-px-2":"tw-flex tw-size-full tw-flex-col tw-overflow-hidden","data-agent-landing":An?"project":Xr?"global":"conversation"},It.default.createElement(ICe,{manager:r,plugin:o,onInstallClick:P}),Xr?It.default.createElement(dfn,{hero:ny,composer:an,floating:!An&&E.length===0&&!c.agentMode.welcomeDismissed?It.default.createElement(rnt,{onCreate:qe,onDismiss:Xt}):void 0,context:An&&!se&&hh?.standalone?It.default.createElement("div",{className:"tw-px-2 tw-pb-1 tw-pt-3"},It.default.createElement(_Ce,{app:l,projectId:U,popoverContainer:_})):void 0,shelf:An?hh&&!hh.standalone?It.default.createElement(att,{key:U,sections:Ct}):null:It.default.createElement(att,{sections:Qt,activeSectionId:fl,onSectionSelect:ct})}):It.default.createElement(It.default.Fragment,null,It.default.createElement(uun,{key:e,messages:p,app:l,currentPlan:g,pendingToolPermissions:y,pendingAskUserQuestions:w,chatBackend:t,isLoading:it.loading}),It.default.createElement(nee,{onNewChat:k,onSaveAsNote:C,chatHistoryItems:ae,onLoadHistory:F,onLoadChat:z,onUpdateChatTitle:N,onDeleteChat:R,onOpenSourceFile:X,usageMeter:It.default.createElement(itt,{backend:t}),showMultiAgentUpsell:!0}),an)))))))},Ahn=t=>It.default.createElement(PSe,null,It.default.createElement(cLr,{...t}))});var uu,uLr,Mhn,Ohn=b(()=>{pm();yt();De();Re();uu=L(B()),uLr={checking:{label:"Checking\u2026",variant:"secondary",Icon:Dr},installed:{label:"Installed",variant:"success",Icon:Hr},outdated:{label:"Update required",variant:"destructive",Icon:Wr},error:{label:"Error",variant:"destructive",Icon:Wr}},Mhn=({rows:t,selectedId:e,onSelect:n,ctaLabel:r,footerNote:o,onCta:i,ctaDisabled:s=!1})=>{let a=uu.default.useId(),l=uu.default.useRef([]),c=t.findIndex(p=>p.id===e),u=c===-1?0:c,d=(p,m)=>{let h=(p+m+t.length)%t.length;l.current[h]?.focus(),n(t[h].id)},f=(p,m)=>{switch(p.key){case"ArrowDown":case"ArrowRight":p.preventDefault(),d(m,1);break;case"ArrowUp":case"ArrowLeft":p.preventDefault(),d(m,-1);break;default:break}};return uu.default.createElement("div",{className:"tw-flex tw-w-full tw-flex-col tw-gap-3 tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-secondary tw-p-3"},uu.default.createElement("h3",{id:a,className:"tw-m-0 tw-text-ui-medium tw-font-semibold tw-leading-tight tw-text-normal"},"Select your agent"),uu.default.createElement("div",{role:"radiogroup","aria-labelledby":a,className:"tw-flex tw-flex-col tw-gap-1"},t.map((p,m)=>{let h=p.id===e,g=uLr[p.status];return uu.default.createElement("button",{key:p.id,ref:v=>{l.current[m]=v},type:"button",role:"radio","aria-checked":h,tabIndex:m===u?0:-1,onClick:()=>n(p.id),onKeyDown:v=>f(v,m),className:J("tw-flex tw-h-auto tw-w-full tw-cursor-pointer tw-items-start tw-gap-2 !tw-whitespace-normal !tw-rounded-md tw-border-none !tw-p-2 tw-text-left !tw-shadow-none tw-transition-colors focus-visible:tw-outline-none focus-visible:tw-ring-1 focus-visible:tw-ring-ring",h?"!tw-bg-modifier-hover":"!tw-bg-transparent hover:!tw-bg-modifier-hover")},uu.default.createElement("span",{"aria-hidden":"true",className:J("tw-mt-0.5 tw-flex tw-size-4 tw-shrink-0 tw-items-center tw-justify-center tw-rounded-full tw-border tw-border-solid",h?"tw-border-interactive-accent":"tw-border-border")},h&&uu.default.createElement("span",{className:"tw-size-2 tw-rounded-full tw-bg-interactive-accent"})),uu.default.createElement("span",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-flex-col tw-gap-1"},uu.default.createElement("span",{className:"tw-flex tw-flex-wrap tw-items-center tw-gap-1.5"},uu.default.createElement("span",{className:"tw-break-words tw-text-ui-small tw-font-semibold tw-text-normal"},p.name),g&&uu.default.createElement(ei,{variant:g.variant,className:"tw-gap-1"},uu.default.createElement(g.Icon,{"aria-hidden":!0,className:J("tw-size-3",p.status==="checking"&&"tw-animate-spin")}),g.label),p.recommended&&uu.default.createElement(ei,{variant:"accent"},"Recommended")),uu.default.createElement("span",{className:"tw-break-words tw-text-ui-smaller tw-text-muted"},p.description)))})),uu.default.createElement("div",{className:J("copilot-divider-t tw-flex tw-flex-wrap tw-items-center tw-gap-2 tw-pt-3",o?"tw-justify-between":"tw-justify-end")},o&&uu.default.createElement("span",{className:"tw-min-w-0 tw-flex-1 tw-break-words tw-text-ui-smaller tw-text-muted"},o),uu.default.createElement(oe,{size:"sm",onClick:i,disabled:s,className:"tw-shrink-0"},r)))}});function fLr(t){switch(t){case"ready":return"installed";case"checking":return"checking";case"incompatible":return"outdated";case"error":return"error";case"absent":return"absent"}}function pLr(t){return t.kind==="incompatible"||t.kind==="error"?t.message:null}function Nhn(t,e,n){return t.length===0?dLr:t.map(r=>{let o=e[r.id]??{kind:"absent"};return{id:r.id,name:r.displayName,description:r.setupDescription,status:fLr(o.kind),recommended:r.id===n,statusMessage:pLr(o)}})}function Rhn(t){return t.status==="checking"?{label:"Checking\u2026",note:`Checking ${t.name} setup\u2026`,action:"wait"}:t.status==="installed"?{label:"Start chat",note:null,action:"start"}:{label:"Configure",note:t.statusMessage??`${t.name} isn't set up on this machine yet.`,action:"configure"}}var dLr,Lhn=b(()=>{dLr=Object.freeze([])});function $hn(t,e){let n=x$(),r=CCe(t),o=KS(e).id,[i,s]=tne.default.useState(null),a=i??o,l=tne.default.useMemo(()=>Nhn(n,r,zwe),[n,r]),c=l.find(f=>f.id===a)??l[0],u=tne.default.useMemo(()=>Rhn(c),[c]),d=tne.default.useCallback(()=>{let f=c.id;if(u.action!=="wait"){if(u.action==="configure"){$a[f].openInstallUI(t);return}e&&(e.setDefaultBackend(f),e.getOrCreateActiveSession().catch(p=>{H("[AgentMode] agent select start failed",p)}))}},[u.action,e,t,c.id]);return{rows:l,selectedId:a,select:s,cta:u,runCta:d}}var tne,Dhn=b(()=>{Wm();Lhn();yD();pe();tne=L(B())});var Fhn,Uhn,jhn=b(()=>{Ohn();Dhn();Fhn=L(B()),Uhn=({plugin:t,manager:e})=>{let{rows:n,selectedId:r,select:o,cta:i,runCta:s}=$hn(t,e);return Fhn.default.createElement(Mhn,{rows:n,selectedId:r,onSelect:o,ctaLabel:i.label,footerNote:i.note,onCta:s,ctaDisabled:i.action==="wait"})}});var Cke,Bhn,zhn=b(()=>{Cke=L(B()),Bhn=({children:t,controls:e})=>Cke.default.createElement("div",{className:"tw-flex tw-size-full tw-flex-col tw-overflow-hidden"},Cke.default.createElement("div",{className:"tw-flex tw-min-h-0 tw-flex-1 tw-flex-col tw-overflow-y-auto tw-p-2"},Cke.default.createElement("div",{className:"tw-m-auto tw-w-full"},t)),e)});var lh,kke,wrt=b(()=>{iJe();Ehn();Gtt();jhn();zhn();yD();pe();lh=L(B()),kke=({plugin:t,onSaveChat:e,updateUserMessageHistory:n})=>{let r=t.agentSessionManager,o=KS(r),i=MM(o,t),[s,a]=lh.default.useState(0);lh.default.useEffect(()=>{if(r)return r.subscribe(()=>a(p=>p+1))},[r]);let l=r?.isPreloadReady(o.id)??!0;lh.default.useEffect(()=>{r&&l&&(r.getSessionsForScope(r.getActiveProjectId()).length>0||r.getIsStarting()||r.getLastError()||i.kind==="ready"&&r.getOrCreateActiveSession().catch(p=>{H("[AgentMode] auto-start failed",p)}))},[r,i.kind,l,s]);let c=lh.default.useCallback(()=>{o.openInstallUI(t)},[o,t]);if(!r)return null;if(!l)return lh.default.createElement("div",{className:"tw-flex tw-size-full tw-items-center tw-justify-center tw-text-muted"},"Loading agent models\u2026");let u=r.getActiveSession(),d=r.getActiveChatUIState();return u&&d?lh.default.createElement(Ahn,{backend:d,sessionId:u.internalId,chatInputId:u.chatInputId,manager:r,plugin:t,onSaveChat:e,updateUserMessageHistory:n}):!r.getIsStarting()&&r.getLastError()===null&&(i.kind==="absent"||i.kind==="incompatible"||i.kind==="error")?lh.default.createElement(Bhn,{controls:lh.default.createElement(nee,null)},lh.default.createElement(Uhn,{plugin:t,manager:r})):lh.default.createElement("div",{className:"tw-flex tw-size-full tw-flex-col tw-overflow-hidden"},lh.default.createElement("div",{className:"tw-flex-1"}),lh.default.createElement(ICe,{manager:r,plugin:t,onInstallClick:c}),lh.default.createElement(nee,null))}});function Whn(t){if(!Hhn.Platform.isMobile)return{dispose:()=>{},rebindDrawerObserver:()=>{}};let e=null,n=()=>{e?.disconnect();let o=t.closest(".workspace-drawer");if(!o)return;let i=o.classList.contains("is-hidden");e=new MutationObserver(()=>{let s=o.classList.contains("is-hidden");s&&!i&&t.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0,cancelable:!0})),i=s}),e.observe(o,{attributes:!0,attributeFilter:["class"]})};return n(),{dispose:()=>{e?.disconnect()},rebindDrawerObserver:n}}var Hhn,Vhn=b(()=>{Hhn=require("obsidian")});function h3(t,e){t.registerEvent(t.app.workspace.on("active-leaf-change",n=>{n?.view instanceof qhn.MarkdownView&&n.view.file&&e.dispatchEvent(new CustomEvent(cs.ACTIVE_LEAF_CHANGE))}))}var qhn,Ike=b(()=>{gt();qhn=require("obsidian")});function Tke(t,e,n){let r=Er(t.children[1],e);r.render(n());let o=t.onWindowMigrated(()=>{r.unmount(),r=Er(t.children[1],e),r.render(n())});return{rerender(){r.render(n())},unmount(){o(),r.unmount()}}}var brt=b(()=>{Pa()});var Khn,Pke,nne,Ghn=b(()=>{wrt();Vhn();gt();ko();Ike();brt();ode();Khn=require("obsidian"),Pke=L(B()),nne=class extends Khn.ItemView{constructor(n,r){super(n);this.plugin=r;this.viewRoot=null;this.handleSaveAsNote=null;this.disposeLayoutObservers=null;this.app=r.app,this.eventTarget=new by,this.plugin=r}getViewType(){return Vd}getIcon(){return oT}getTitle(){return"Copilot Agent Chat"}getDisplayText(){return"Copilot Agent"}async onOpen(){this.viewRoot=Tke(this.containerEl,this.app,()=>this.renderTree());let n=Whn(this.containerEl);this.disposeLayoutObservers=n.dispose,h3(this,this.eventTarget),this.registerEvent(this.app.workspace.on("layout-change",()=>{window.requestAnimationFrame(()=>n.rebindDrawerObserver())}))}renderTree(){return Pke.createElement(Gd.Provider,{value:this.eventTarget},Pke.createElement(Vj,{delayDuration:0},Pke.createElement(kke,{plugin:this.plugin,onSaveChat:n=>{this.handleSaveAsNote=n},updateUserMessageHistory:n=>this.plugin.updateUserMessageHistory(n)})))}async saveChat(){this.handleSaveAsNote&&await this.handleSaveAsNote()}updateView(){this.viewRoot?.rerender()}async onClose(){this.disposeLayoutObservers?.(),this.disposeLayoutObservers=null,this.viewRoot?.unmount(),this.viewRoot=null}}});function mLr(t){let e=t.indexOf("/");return e===-1?t:t.slice(0,e)}function Ake(t,e){if(t.length===0)return Zhn;let n=new Set,r=[];for(let o of t){if(n.has(o))continue;let i=mLr(o);e.has(i)||(n.add(o),r.push(o))}return r.length===0?Zhn:r}var Zhn,Yhn=b(()=>{Zhn=Object.freeze([])});function Xhn({value:t,options:e,disabledLabel:n,onChange:r}){let o=e.length>0,i=o?e.map(s=>({label:s.label,value:s.value??""})):[{label:n,value:""}];return Jhn.default.createElement(_o,{type:"select",title:"Default effort",value:o?t??"":"",onChange:s=>r(s===""?null:s),options:i,disabled:!o})}var Jhn,Qhn=b(()=>{Iv();Jhn=L(B())});function gLr(t){let e=t.name||t.baseModelId;return t.credentialState==="missing_key"?`${e} (${gke})`:e}var ED,Eke,Mke,hLr,Oke,egn=b(()=>{Iv();pe();Se();ED=L(B());Qhn();vke();wke();Eke="__agent_default__",Mke="Agent default",hLr="Not supported",Oke=({descriptor:t,manager:e})=>{let n=p3(e);(0,ED.useSyncExternalStore)(n,()=>e.getModelCacheSignature(t.id),()=>e.getModelCacheSignature(t.id));let r=xt(),o=t.getEnabledModelEntries?.(r)??null,i=e.getDefaultSelection(t.id),s=i!==null;if((!o||o.length===0)&&!s)return null;let a=i?.baseModelId??Eke,l=s?hrt(e,t.id,a):mrt,c=l.length>0&&!l.some(h=>h.value===null)?[{value:null,label:Mke},...l]:l,u=h=>{if(h===Eke){e.persistDefaultSelection(t.id,null).catch(g=>H(`[AgentMode] clear default model for ${t.id} failed`,g));return}e.persistDefaultSelection(t.id,{baseModelId:h,effort:null}).catch(g=>H(`[AgentMode] persist default model for ${t.id} failed`,g))},d=h=>{s&&e.persistDefaultSelection(t.id,{baseModelId:a,effort:h}).catch(g=>H(`[AgentMode] persist default effort for ${t.id} failed`,g))},f=(o??[]).map(h=>({label:gLr(h),value:h.baseModelId})),m=s&&!f.some(h=>h.value===a)?[{label:Mke,value:Eke},{label:`${i?.baseModelId} (disabled)`,value:a},...f]:[{label:Mke,value:Eke},...f];return ED.default.createElement(ED.default.Fragment,null,ED.default.createElement(_o,{type:"select",title:"Default model",description:"Used for new chats and multi-agent answers on this agent. Open chats switch on their next turn.",value:a,onChange:u,options:m}),ED.default.createElement(Xhn,{value:i?.effort??null,options:c,disabledLabel:s?hLr:Mke,onChange:d}))}});var Xi,g3,tgn=b(()=>{pm();Sj();kQe();v_e();Lh();MZ();pk();OP();De();Re();Xi=L(B()),g3=({groups:t,onToggle:e,query:n,onQueryChange:r,searchPlaceholder:o="Search models\u2026",emptyState:i,defaultOpenGroupKey:s})=>{let a=n.trim().length>0,[l,c]=Xi.default.useState({}),u=m=>a?!0:m in l?l[m]:s===void 0||m===s,d=(m,h)=>c(g=>({...g,[m]:h})),f=m=>Xi.default.createElement("div",{className:"tw-space-y-1"},m.map(h=>Xi.default.createElement("div",{key:h.id,className:J("tw-flex tw-items-center tw-justify-between tw-gap-2 tw-rounded tw-px-2 tw-py-1","hover:tw-bg-modifier-hover")},Xi.default.createElement("div",{className:"tw-min-w-0"},Xi.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-1"},Xi.default.createElement("span",{className:"tw-truncate"},h.label),h.locked&&Xi.default.createElement(F6,null),h.isFree&&Xi.default.createElement(Lxe,null),AZ(h.capabilities)&&Xi.default.createElement("span",{className:"tw-flex tw-shrink-0 tw-items-center tw-gap-0.5"},Xi.default.createElement(EZ,{capabilities:h.capabilities,iconSize:14}))),h.description&&Xi.default.createElement("div",{className:"tw-truncate tw-text-xs tw-text-muted"},h.description)),Xi.default.createElement(fp,{checked:h.enabled,disabled:h.locked,onCheckedChange:g=>e(h.id,g)})))),p=t.some(m=>m.rows.length>0);return Xi.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Xi.default.createElement(rf,{value:n,onChange:r,placeholder:o}),Xi.default.createElement("div",{className:"tw-max-h-80 tw-overflow-y-auto tw-pr-1"},p?Xi.default.createElement("div",{className:"tw-space-y-2"},t.filter(m=>m.rows.length>0).map(m=>Xi.default.createElement(dx,{key:m.key,open:u(m.key),onOpenChange:h=>d(m.key,h)},Xi.default.createElement(fx,{asChild:!0},Xi.default.createElement("div",{className:"tw-flex tw-w-full tw-cursor-pointer tw-items-center tw-gap-1 tw-rounded tw-px-2 tw-py-1.5 tw-text-left tw-text-ui-medium tw-font-bold hover:tw-bg-modifier-hover"},Xi.default.createElement(Vi,{className:J("tw-size-3 tw-shrink-0 tw-text-muted tw-transition-transform",u(m.key)&&"tw-rotate-90")}),Xi.default.createElement("span",{className:J("tw-truncate",m.highlight&&"tw-font-bold tw-text-accent")},m.label),m.badge&&Xi.default.createElement(ei,{variant:"secondary",className:"tw-shrink-0 tw-font-normal"},m.badge),m.tooltip&&Xi.default.createElement("span",{className:"tw-flex tw-shrink-0 tw-items-center",onClick:h=>h.stopPropagation(),onPointerDown:h=>h.stopPropagation()},Xi.default.createElement(rs,{content:m.tooltip,side:"top",buttonClassName:"tw-size-4"},Xi.default.createElement(_G,{className:"tw-size-3.5 tw-shrink-0 tw-text-muted"}))))),Xi.default.createElement(px,null,Xi.default.createElement("div",{className:"tw-pl-4"},f(m.rows)))))):Xi.default.createElement("div",{className:"tw-py-6 tw-text-center tw-text-sm tw-text-muted"},i??(a?`No models match \u201C${n.trim()}\u201D.`:"No models."))))}});async function ngn(t){try{let n=require("electron")?.remote;if(!n)return null;let r=t.ownerDocument.defaultView;if(!r)return null;let o=yLr(n,r);if(!o)return null;let i=t.getBoundingClientRect();if(i.width<=0||i.height<=0)return null;let s={x:Math.max(0,Math.floor(i.left)),y:Math.max(0,Math.floor(i.top)),width:Math.ceil(i.width),height:Math.ceil(i.height)},l=(await o.webContents.capturePage(s)).toPNG();return l.length>0?l:null}catch(e){return W("captureViewScreenshot failed:",e),null}}function yLr(t,e){let n=t.getCurrentWindow?.()??null;if(e===window)return n;let r=t.BrowserWindow?.getAllWindows?.()??[];if(r.length===0)return n;if(r.length===1)return r[0];let o=null,i=Number.POSITIVE_INFINITY;for(let s of r)try{let a=s.getBounds(),l=Math.abs(a.x-e.screenX)+Math.abs(a.y-e.screenY)+Math.abs(a.width-e.outerWidth)+Math.abs(a.height-e.outerHeight);l<i&&(i=l,o=s)}catch{}return o??n}var rgn=b(()=>{pe()});function ogn(t){return vLr.reduce((e,n)=>e.replace(n.pattern,n.replacement),t)}var vLr,ign=b(()=>{vLr=[{pattern:/(\/(?:Users|home)\/)[^/\s"'\\:]+/g,replacement:"$1<user>"},{pattern:/([A-Za-z]:\\Users\\)[^\\\s"']+/gi,replacement:"$1<user>"},{pattern:/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,replacement:"<email>"},{pattern:/\bsk-[A-Za-z0-9_-]{12,}/g,replacement:"<secret>"},{pattern:/\bAIza[A-Za-z0-9_-]{20,}/g,replacement:"<secret>"},{pattern:/\bAKIA[0-9A-Z]{16}\b/g,replacement:"<secret>"},{pattern:/\bgh[pousr]_[A-Za-z0-9]{20,}/g,replacement:"<secret>"},{pattern:/\bxox[baprs]-[A-Za-z0-9-]{10,}/g,replacement:"<secret>"},{pattern:/(bearer\s+)[A-Za-z0-9._-]{12,}/gi,replacement:"$1<token>"},{pattern:/("?(?:api[_-]?key|access[_-]?token|refresh[_-]?token|client[_-]?secret|secret|password|passwd|authorization|license[_-]?key)"?\s*[:=]\s*"?)[^"'\s,}]{6,}/gi,replacement:"$1<redacted>"}]});async function cgn(t,e=SLr()){let n=e.join(t.reportsRootDir,`report-${t.timestamp}`);await e.mkdir(n,{recursive:!0});let r=[];if(t.screenshotPng&&t.screenshotPng.length>0)try{await e.writeFile(e.join(n,sgn),t.screenshotPng),r.push(sgn)}catch{}for(let i of[{path:t.frameLogPath,name:bLr},{path:t.opencodeLogPath,name:_Lr}])if(i.path)try{let s=ogn(await e.readFile(i.path));await e.writeFile(e.join(n,i.name),s),r.push(i.name)}catch{}let o=ugn(t,r);return await e.writeFile(e.join(n,agn),o),r.unshift(agn),{folderPath:n,files:r,issueUrl:xLr(t,r)}}function ugn(t,e){let n=t.note.trim()||"_No description provided._",r=e.length>0?e:["(none captured)"];return["## What went wrong","",n,"","## Environment","",`- Plugin version: ${t.env.pluginVersion}`,`- Active backend: ${t.env.activeBackend}`,`- Platform: ${t.env.platform}`,...t.env.obsidianVersion?[`- Obsidian: ${t.env.obsidianVersion}`]:[],"","## Attached files","",...r.map(o=>`- ${o}`),"","> These files were saved to the bundle folder that just opened. Drag them","> into the GitHub issue to attach them.",""].join(`
`)}function xLr(t,e){let n=t.note.trim().split(`
`)[0]?.slice(0,80).trim(),r=n?`[Agent Mode] ${n}`:"[Agent Mode] Issue report",o=ugn(t,e),i=`https://github.com/${wLr}/issues/new?`,s=c=>i+new URLSearchParams({title:r,body:c,labels:"bug"}).toString();if(s(o).length<=_rt)return s(o);let a=o.length,l=s(o.slice(0,a)+lgn);for(;a>0&&l.length>_rt;)a=Math.max(0,a-Math.ceil((l.length-_rt)/3)),l=s(o.slice(0,a)+lgn);return l}function SLr(){let t=Pe("fs/promises"),e=Pe("path");return{join:(...n)=>e.join(...n),mkdir:async(n,r)=>{await t.mkdir(n,r)},writeFile:(n,r)=>t.writeFile(n,r),readFile:n=>t.readFile(n,"utf8")}}var wLr,sgn,bLr,_Lr,agn,_rt,lgn,dgn=b(()=>{ign();$n();wLr="logancyang/obsidian-copilot",sgn="screenshot.png",bLr="acp-frames.ndjson.txt",_Lr="opencode.log",agn="report.md";_rt=1800,lgn="\n\n_\u2026report truncated. The full report is saved as `report.md` in the bundle folder that just opened \u2014 paste it here._"});function CLr(t,e,n){let r=t.XDG_DATA_HOME?.trim(),o=r||n(e,".local","share");return n(o,"opencode","log")}async function fgn(t,e,n=kLr()){try{let r=CLr(t,e,n.join),i=(await n.readdir(r)).filter(l=>l.endsWith(".log"));if(i.length===0)return null;let s=null,a=Number.NEGATIVE_INFINITY;for(let l of i){let c=n.join(r,l);try{let{mtimeMs:u}=await n.stat(c);u>a&&(a=u,s=c)}catch{}}return s}catch{return null}}function kLr(){let t=Pe("fs/promises"),e=Pe("path");return{join:(...n)=>e.join(...n),readdir:n=>t.readdir(n),stat:async n=>({mtimeMs:(await t.stat(n)).mtimeMs})}}var pgn=b(()=>{$n()});function ILr(){try{let t=require("electron");return t?.shell??t?.remote?.shell??null}catch{return null}}function TLr(){try{let t=Pe("os");return Pe("path").join(t.tmpdir(),"obsidian-copilot","reports")}catch{return null}}function PLr(t){let e=n=>String(n).padStart(2,"0");return`${t.getFullYear()}${e(t.getMonth()+1)}${e(t.getDate())}-${e(t.getHours())}${e(t.getMinutes())}${e(t.getSeconds())}`}function hgn(t){return new Promise(e=>window.setTimeout(e,t))}function ALr({showOpencodeOption:t,onSubmit:e,onCancel:n}){let[r,o]=$s.default.useState(""),[i,s]=$s.default.useState(!1);return $s.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},$s.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1"},$s.default.createElement("span",{className:"tw-text-sm tw-font-medium"},"What went wrong?"),$s.default.createElement(If,{autoFocus:!0,value:r,onChange:a=>o(a.target.value),placeholder:"Describe what you were doing and what happened\u2026",className:"tw-min-h-24"})),t&&$s.default.createElement("label",{className:"tw-flex tw-items-start tw-gap-2 tw-text-sm"},$s.default.createElement(Wl,{checked:i,onCheckedChange:a=>s(a===!0),className:"tw-mt-0.5"}),$s.default.createElement("span",null,"Include the OpenCode log (helps diagnose backend issues)")),$s.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1.5 tw-text-sm"},$s.default.createElement("span",{className:"tw-font-medium"},"When you click \u201CPrepare report\u201D"),$s.default.createElement("ul",{className:"tw-m-0 tw-flex tw-flex-col tw-gap-1 tw-pl-5 tw-text-muted"},$s.default.createElement("li",null,"A screenshot of the ",$s.default.createElement("strong",{className:"tw-text-normal"},"Agent Mode chat pane")," ","(not your whole screen) and a recent activity log are saved to a folder on your computer."),$s.default.createElement("li",null,"That folder opens, and a pre-filled GitHub issue opens in your browser."),$s.default.createElement("li",null,"Drag the saved files into the issue to attach them, then submit."))),$s.default.createElement("div",{className:J("tw-flex tw-items-start tw-gap-2.5 tw-rounded-md tw-border tw-border-solid tw-border-warning/100","tw-bg-callout-warning/20 tw-px-3.5 tw-py-2.5 tw-text-sm tw-text-warning"),role:"alert"},$s.default.createElement(Wr,{className:"tw-mt-0.5 tw-size-4 tw-shrink-0","aria-hidden":"true"}),$s.default.createElement("div",{className:"tw-flex-1"},$s.default.createElement("span",{className:"tw-block tw-font-semibold"},"Before you share these files"),$s.default.createElement("span",{className:"tw-mt-0.5 tw-block tw-text-normal"},"The activity log can include your prompts, note contents, and tool inputs/outputs in plain text. Review the saved files and remove anything sensitive before posting them publicly."))),$s.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},$s.default.createElement(oe,{variant:"secondary",onClick:n},"Cancel"),$s.default.createElement(oe,{variant:"default",onClick:()=>e(r,i)},"Prepare report")))}async function ELr(){try{let t=Pe("os"),e=Y().agentMode?.backends?.opencode?.envOverrides??{},n={...process.env,...e},r=e.HOME??t.homedir();return await fgn(n,r)}catch{return null}}var JS,$s,mgn,Nke,ggn=b(()=>{iY();yt();RP();xI();pe();rgn();$n();dgn();pgn();Pa();De();Se();Re();JS=require("obsidian"),$s=L(B()),mgn="opencode";Nke=class extends JS.Modal{constructor(n){super(n.app);this.params=n;this.root=null;this.setTitle("Report an Agent Mode issue")}onOpen(){if(!Ln()){new JS.Notice("Reporting an issue is available on desktop only."),this.close();return}this.root=Er(this.contentEl,this.app),this.root.render($s.default.createElement(ALr,{showOpencodeOption:this.params.activeBackend===mgn,onSubmit:(n,r)=>{this.close(),this.prepareReport(n,r)},onCancel:()=>this.close()}))}onClose(){this.root?.unmount(),this.root=null,this.contentEl.empty()}async prepareReport(n,r){let o=TLr();if(!o){new JS.Notice("Could not prepare the report (filesystem unavailable).");return}new JS.Notice("Preparing issue report\u2026");try{await hgn(200);let i=await this.params.resolveCaptureTarget();await hgn(250);let s=i?await ngn(i):null,a=null;Y().agentMode.debugFullFrames&&(await $k.flush(),a=$k.getPath());let l=r&&this.params.activeBackend===mgn?await ELr():null,c={pluginVersion:this.params.pluginVersion,platform:process.platform,obsidianVersion:JS.apiVersion,activeBackend:this.params.activeBackend},u=await cgn({note:n,env:c,screenshotPng:s,frameLogPath:a,opencodeLogPath:l,reportsRootDir:o,timestamp:PLr(new Date)}),d=ILr();d?.openPath?.(u.folderPath).catch(()=>{}),d?.openExternal?.(u.issueUrl).catch(()=>{}),j(`[ReportIssue] bundle written to ${u.folderPath} (${u.files.join(", ")})`),new JS.Notice("Report ready. Attach the saved files to the GitHub issue that just opened.")}catch(i){H("[ReportIssue] failed to prepare report:",i),new JS.Notice("Failed to prepare the issue report. See the console for details.")}}}});var d_={};sr(d_,{AGENT_CHAT_MODE:()=>WF,AgentDefaultModelSetting:()=>Oke,AgentModeChat:()=>kke,CopilotAgentView:()=>nne,InstallBadge:()=>Gye,ModelEnableList:()=>g3,PLAN_PREVIEW_VIEW_TYPE:()=>R6,PlanPreviewView:()=>c_e,RECOMMENDED_BACKEND_ID:()=>zwe,ReportIssueModal:()=>Nke,SkillManager:()=>qu,SkillsSettings:()=>B7e,acpFrameSink:()=>$k,applyCopilotDefaultModel:()=>OLr,backendDisplayOrder:()=>x$,backendNeedsSelfHostWarning:()=>RI,createAgentSessionManager:()=>RLr,getActiveBackendDescriptor:()=>MQ,getCloudAgentIds:()=>Hwe,getManagedSkills:()=>GW,installBadge:()=>L9e,installMiyoSearchSkill:()=>TQt,isAgentModeEnabled:()=>xrt,isOpencodeZenWireId:()=>kQ,listBackendDescriptors:()=>ss,mapProviderToOpencodeId:()=>bS,partitionOpencodeOnlyWireIds:()=>Ake,removeMiyoSearchSkill:()=>PQt,setFrameSinkVaultBasePath:()=>yUt,useActiveBackendDescriptor:()=>Sfn,useAgentModePicker:()=>_ke,useAgentModelPicker:()=>bke,useBackendInstallState:()=>MM,useIsAgentModeEnabled:()=>MLr,useManagedSkills:()=>xQ,useSessionBackendDescriptor:()=>KS});function xrt(){return!wgn.Platform.isMobile}function MLr(){return xrt()}function OLr(t){return CQt(ss(),t)}function NLr(){let t={};for(let e of ss())t[e.id]=e.skillsProjectDir;return t}function ygn(t){return sP()}function vgn(t,e){let r=t.agentMode?.backends?.[e]?.envOverrides??{};return JSON.stringify(Object.entries(r).sort(([o],[i])=>o.localeCompare(i)))}function RLr(t,e){let n=Pe("os"),r=Pe("path"),o=qu.initialize(t,NLr()),i=new Vwe(t,e,_=>$a[_]),s=new Wwe(t),a=Eae(t),l=r.join(TU(n.homedir()),"vaults",a,"agent-chat-index.json"),c=new Kwe(mJt(),l),u=null,d=AQt(_=>u?.getSessionByBackendId(_)??null,_=>u?.isReadOnlyFanoutSession(_)??!1),f=EQt(_=>u?.getSessionByBackendId(_)??null),p=new Ibe(t,e,{permissionPrompter:d,askUserQuestionPrompter:f,resolveDescriptor:_=>$a[_],modelPreloader:i,persistenceManager:s,sessionIndex:c});u=p,o.subscribeToSkillSetChange(_=>{$a[_]?.restartOnManagedSkillsChange&&p.restartBackend(_,"managed skills changed").catch(I=>H(`[Skills] Failed to refresh backend after skill change: ${_}`,I))});let m=_=>{for(let S of ss())S.restartOnProviderConfigChange&&p.restartBackend(S.id,_).catch(I=>H(`[AgentMode] restart after ${_} failed: ${S.id}`,I))};e.modelManagement.providerRegistry.subscribe(()=>m("provider config changed")),e.modelManagement.backendConfigRegistry.subscribe(()=>m("backend enabled models changed"));let h=new Map;for(let _ of ss())_.restartOnSystemPromptChange&&h.set(_.id,ygn(_.id));let g=()=>{for(let _ of ss()){if(!_.restartOnSystemPromptChange)continue;let S=ygn(_.id);S!==h.get(_.id)&&(h.set(_.id,S),p.restartBackend(_.id,"system prompt changed").catch(I=>H(`[AgentMode] restart after system prompt change failed: ${_.id}`,I)))}};Svt(g),zr((_,S)=>{for(let I of ss())vgn(_,I.id)!==vgn(S,I.id)&&p.restartBackend(I.id,"env overrides changed").catch(C=>H(`[AgentMode] restart after env overrides change failed: ${I.id}`,C))});let v=Promise.resolve(),y=_=>(v=v.then(async()=>{try{let S=Abe(t),I=Y(),{seed:C,prune:k}=KKt({search:I.enableMiyoSearchSkill===!0,documents:I.docProcessorBackend==="miyo"});await Tbe({skillsFolderRelPath:_,fs:S,skills:C});for(let T of k)await Pbe(_,T,S)}catch(S){H("[Skills] builtin skill seeding failed",S)}try{await o.refresh()}catch(S){H("[Skills] skill refresh after seeding failed",S)}}),v);zr((_,S)=>{if(_.isPaidUser!==S.isPaidUser||_.plusLicenseKey!==S.plusLicenseKey||_.miyoServerUrl!==S.miyoServerUrl)for(let T of ss())p.restartBackend(T.id,"managed agent env changed").catch(P=>H(`[AgentMode] restart after managed env change failed: ${T.id}`,P));let I=Sw(_),C=Sw(S),k=_.enableMiyoSearchSkill!==S.enableMiyoSearchSkill||_.docProcessorBackend!==S.docProcessorBackend||_.enableMiyo!==S.enableMiyo||_.miyoServerUrl!==S.miyoServerUrl||_.isPaidUser!==S.isPaidUser;(I!==C||k)&&y(C).then(()=>{if(k&&(g(),_.docProcessorBackend!==S.docProcessorBackend))for(let T of ss())T.restartOnSystemPromptChange||p.restartBackend(T.id,"document processor changed").catch(P=>H(`[AgentMode] restart after doc processor change failed: ${T.id}`,P))}).catch(T=>H("[Skills] builtin skill re-seeding failed",T))});for(let _ of ss())_.subscribeInstallState(e,()=>{p.onInstallStateChanged(_.id).catch(S=>H(`[AgentMode] install-state refresh failed: ${_.id}`,S))});y(M2()).catch(_=>{H("[Skills] Initial discovery pass failed",_)});for(let _ of ss())_.onPluginLoad?.(e).catch(S=>H(`[AgentMode] backend ${_.id} onPluginLoad failed`,S));let w=Y();if(!xrt())return p;for(let _ of ss()){if(_.getInstallState(w).kind!=="ready")continue;let S=p.preloadModels(_.id);p.registerPreload(_.id,S.catch(I=>{throw H(`[AgentMode] preload ${_.id} failed`,I),I}))}return p}var wgn,Hf=b(()=>{wgn=require("obsidian");pe();Se();Is();rk();Mae();$n();O9();Wm();cJt();uJt();pJt();hJt();SQt();kQt();Dwe();wX();HYe();WYe();MQt();gt();wrt();Ghn();yD();grt();yrt();Yhn();Fwe();$9e();egn();tgn();AJe();ggn();Wm();iY();Dwe();WYe()});function UM(){return Y().enableSelfHostMode===!0&&kgn("self_host")}function LLr(t){let e=Y(),n=e.configuredModels.find(r=>r.configuredModelId===t);return n?e.providers[n.providerId]?.origin.kind==="copilot-plus":t.split("|")[1]==="copilot-plus"}function yvt(t){return LLr(t.defaultModelKey)?!0:Object.values(t.agentMode?.backends??{}).some(e=>{let n=e?.defaultModel?.baseModelId;return n!==void 0&&$Lr.has(n)})}function Sgn(){return Y().isPaidUser===!0}function Cgn(t){return t.entitlementExpiresAt>0&&Date.now()>=t.entitlementExpiresAt}function krt(){return Gv.token===Y().entitlementToken&&Date.now()<Gv.expiresAt}function kgn(t){return krt()&&Gv.features.has(t)}function bgn(){let t=Y();return t.entitlementExpiresAt>0?kgn("multi_agent"):t.isPlusUser===!0}function Lke(){return xt().isPaidUser}function FLr(){let t=xt();return Cgn(t)?!1:t.isPlusUser}async function GXt(t){return bgn()?!0:(await Gi.getInstance().validateLicenseKey(t,{trigger:"multi_agent_per_turn"}),bgn())}function ZXt(){new Crt.Notice("Multi-agent QA (@-mentioning more than one agent in a turn) is a Copilot Plus feature. Opening the upgrade page\u2026",8e3),ek(hw.MULTI_AGENT)}function Ybe(){return FLr()===!0}async function ch(t,e){return Y().plusLicenseKey?(await Gi.getInstance().validateLicenseKey(t,e).catch(o=>(j("License validation unreachable; falling back to the cached entitlement:",o),{isValid:void 0}))).isValid??(krt()&&Gv.paid):(Prt(t),!1)}function Ign(){let t=xt(),e=Rke.default.useRef(null);return t.plusLicenseKey?krt()?Gv.paid?(e.current?.plan!==Gv.plan&&(e.current={status:"active",plan:Gv.plan}),e.current):_gn:t.isPaidUser===!0&&!Cgn(t)?jLr:_gn:ULr}function Tgn(){let t=xt(),[e,n]=Rke.default.useState(void 0);return Rke.default.useEffect(()=>{let r=!1;return E9(t.entitlementToken,{expectedUserId:t.userId}).then(o=>{if(r)return;let i=o?.features.includes("self_host")===!0;o&&!i&&t.enableSelfHostMode&&At("enableSelfHostMode",!1),n(i)}),()=>{r=!0}},[t.entitlementToken,t.userId,t.enableSelfHostMode]),e}function Srt(t){let e=new Set(Object.values(t.providers).filter(n=>n.origin.kind==="copilot-plus").map(n=>n.providerId));return t.configuredModels.find(n=>e.has(n.providerId)&&n.info.id===y3)?.configuredModelId}function zLr(){let t=Srt(Y());return t?Promise.resolve(t):new Promise(e=>{let n=!1,r=a=>{n||(n=!0,window.clearTimeout(i),o(),e(a))},o=zr((a,l)=>{let c=Srt(l);c&&r(c)}),i=window.setTimeout(()=>r(void 0),BLr),s=Srt(Y());s&&r(s)})}async function Pgn(){let t=await zLr();if(!t){W(`applyLicenseSettings: ${y3} was never configured, nothing to apply`),new Crt.Notice("Copilot could not set a default model. Pick one under Settings \u2192 Basic \u2192 Agents once your license is active.");return}if(aft(t),En({defaultModelKey:t}),!!Ln())try{let{applyCopilotDefaultModel:e}=await Promise.resolve().then(()=>(Hf(),d_)),n=e(t);j("applyLicenseSettings: seeded the agent default model",{backends:n})}catch(e){H("applyLicenseSettings: seeding the agent default model failed",e)}}function Irt(t){return`https://www.obsidiancopilot.com?utm_source=obsidian&utm_medium=${t}`}function ek(t){window.open(Irt(t),"_blank")}function Trt(){En({isPaidUser:!0,isPlusUser:!1,entitlementToken:"",entitlementExpiresAt:0})}function HLr(){En({isPaidUser:!1,isPlusUser:!1,entitlementToken:"",entitlementExpiresAt:0})}function Prt(t){let e=Y().isPaidUser;HLr(),e&&t&&new kae(t).open()}async function Agn(t){let e=await E9(t,{expectedUserId:Y().userId});return e?(Gv={token:t,features:new Set(e.features),plan:e.plan,expiresAt:e.exp*1e3,paid:e.tier!=="free"},En({entitlementToken:t,entitlementExpiresAt:Gv.expiresAt,isPaidUser:Gv.paid,isPlusUser:Gv.features.has("multi_agent")}),!0):!1}async function Egn(){let{entitlementToken:t,userId:e}=Y(),n=t?await E9(t,{expectedUserId:e}):null;Y().entitlementToken===t&&(Gv={token:t,features:new Set(n?.features),plan:n?.plan??"",expiresAt:(n?.exp??0)*1e3,paid:n?n.tier!=="free":!1})}var Crt,Rke,y3,xgn,$Lr,DLr,Gv,ULr,_gn,jLr,BLr,vc=b(()=>{es();gvt();gt();_vt();_v();pe();Se();$n();Crt=require("obsidian"),Rke=L(B()),y3="copilot-plus-flash",xgn=24*60*60*1e3;$Lr=Object.freeze(new Set([y3,`copilot-plus/${y3}`]));DLr=Object.freeze({token:"",features:Object.freeze(new Set),plan:"",expiresAt:0,paid:!1}),Gv=DLr;ULr=Object.freeze({status:"none"}),_gn=Object.freeze({status:"inactive"}),jLr=Object.freeze({status:"active"});BLr=15e3});async function WLr(t){let e=`----CopilotBoundary${Math.random().toString(16).slice(2)}${Date.now().toString(16)}`,n=new TextEncoder,r=[];for(let[a,l]of t.entries())if(r.push(n.encode(`--${e}\r
`)),l instanceof Blob){let c=l instanceof File?l.name:"blob",u=l.type||"application/octet-stream";r.push(n.encode(`Content-Disposition: form-data; name="${a}"; filename="${c}"\r
Content-Type: ${u}\r
\r
`));let d=await l.arrayBuffer();r.push(new Uint8Array(d)),r.push(n.encode(`\r
`))}else r.push(n.encode(`Content-Disposition: form-data; name="${a}"\r
\r
`)),r.push(n.encode(String(l))),r.push(n.encode(`\r
`));r.push(n.encode(`--${e}--\r
`));let o=r.reduce((a,l)=>a+l.byteLength,0),i=new Uint8Array(o),s=0;for(let a of r)i.set(a,s),s+=a.byteLength;return{body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),contentType:`multipart/form-data; boundary=${e}`}}function Mgn(t,e){let n=t.json;if(typeof n=="string")try{n=JSON.parse(n)}catch{}if(t.status<200||t.status>=300){let o=n?.detail;if(o?.reason){let i=new Error(o.reason);return o.error&&(i.name=o.error),{data:null,error:i}}return{data:null,error:new Error(`HTTP error: ${t.status}`)}}let r=n&&typeof n=="object"&&"entitlement"in n?{...n,entitlement:"[redacted]"}:n;return j(`[API ${e} request]:`,r),{data:n}}var rne,Gi,_v=b(()=>{gt();iy();pe();vc();Se();jV();rne=require("obsidian");Gi=class t{constructor(){this.pluginVersion="Unknown"}static getInstance(){return t.instance||(t.instance=new t),t.instance}checkLicenseKey(){if(!Y().plusLicenseKey)throw new sT("Copilot Plus license key not found. Please enter your license key in the settings.")}setPluginVersion(e){this.pluginVersion=e}getPluginVersionHeaders(){return{"X-Client-Version":this.pluginVersion}}async makeRequest(e,n,r="POST",o=!1,i=!1){i||this.checkLicenseKey(),n.user_id=Y().userId;let s=new URL(`${K5}${e}`);r==="GET"&&Object.entries(n).forEach(([c,u])=>{s.searchParams.append(c,u)});let a={"Content-Type":"application/json",...this.getPluginVersionHeaders()};o||(a.Authorization=`Bearer ${Y().plusLicenseKey}`);let l=await(0,rne.requestUrl)({url:s.toString(),method:r,headers:a,...r==="POST"&&{body:JSON.stringify(n)},throw:!1});return Mgn(l,e)}async makeFormDataRequest(e,n,r=!1){r||this.checkLicenseKey(),n.append("user_id",Y().userId);let o=new URL(`${K5}${e}`);try{let{body:i,contentType:s}=await WLr(n),a=await(0,rne.requestUrl)({url:o.toString(),method:"POST",headers:{"Content-Type":s,Authorization:`Bearer ${Y().plusLicenseKey}`,...this.getPluginVersionHeaders()},body:i,throw:!1});return Mgn(a,`${e} form-data`)}catch(i){return{data:null,error:i instanceof Error?i:new Error(String(i))}}}async validateLicenseKey(e,n){let r=Y().plusLicenseKey,o={license_key:r};if(n&&typeof n=="object"){let a=Object.fromEntries(Object.entries(n).filter(([c,u])=>u!=null)),l=new Set(["license_key","user_id"]);for(let c of l)c in a&&delete a[c];Object.assign(o,a)}let{data:i,error:s}=await this.makeRequest("/license",o,"POST",!0,!0);return Y().plusLicenseKey!==r?{isValid:void 0}:s?s.message==="Invalid license key"?(Prt(e),{isValid:!1}):{isValid:void 0}:(i?.entitlement?await Agn(i.entitlement)||Trt():Trt(),{isValid:!0,plan:i?.plan})}async rerank(e,n){let{data:r,error:o}=await this.makeRequest("/rerank",{query:e,documents:n,model:"rerank-2"});if(o)throw o;if(!r)throw new Error("No data returned from rerank");return r}async getUsage(){let e=Y().plusLicenseKey;if(!e)return null;try{let n=await(0,rne.requestUrl)({url:`${Jp}/usage`,method:"GET",headers:{Authorization:`Bearer ${e}`,...this.getPluginVersionHeaders()},throw:!1});return n.status!==200?(j(`[BrevilabsClient] usage read returned ${n.status}; no cap meters`),null):n.json}catch(n){return j("[BrevilabsClient] usage read failed; no cap meters",n),null}}async getModels(){try{let e=await(0,rne.requestUrl)({url:`${Jp}/models`,method:"GET",headers:this.getPluginVersionHeaders(),throw:!1});return e.status!==200?(j(`[BrevilabsClient] models read returned ${e.status}`),null):e.json}catch(e){return j("[BrevilabsClient] models read failed",e),null}}async url4llm(e){let{data:n,error:r}=await this.makeRequest("/url4llm",{url:e});if(r)throw r;if(!n)throw new Error("No data returned from url4llm");return n}async pdf4llm(e){let n=Fv(e),{data:r,error:o}=await this.makeRequest("/pdf4llm",{pdf:n});if(o)throw o;if(!r)throw new Error("No data returned from pdf4llm");return r}async docs4llm(e,n){let r=new FormData,o=this.getMimeTypeFromExtension(n),i=new Blob([e],{type:o}),s=`file.${n}`,a=new File([i],s,{type:o});r.append("files",a),r.append("file_type",n);let{data:l,error:c}=await this.makeFormDataRequest("/docs4llm",r);if(c)throw c;if(!l)throw new Error("No data returned from docs4llm");return l}getMimeTypeFromExtension(e){return{pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",epub:"application/epub+zip",txt:"text/plain",rtf:"application/rtf",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",bmp:"image/bmp",svg:"image/svg+xml",tiff:"image/tiff",webp:"image/webp",html:"text/html",htm:"text/html",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xls:"application/vnd.ms-excel",csv:"text/csv",mp3:"audio/mpeg",mp4:"video/mp4",wav:"audio/wav",webm:"video/webm"}[e.toLowerCase()]||"application/octet-stream"}async webSearch(e){let{data:n,error:r}=await this.makeRequest("/websearch",{query:e});if(r)throw r;if(!n)throw new Error("No data returned from websearch");return n}async youtube4llm(e){let{data:n,error:r}=await this.makeRequest("/youtube4llm",{url:e});if(r)throw r;if(!n)throw new Error("No data returned from youtube4llm");return n}async twitter4llm(e){let{data:n,error:r}=await this.makeRequest("/twitter4llm",{url:e});if(r)throw r;if(!n)throw new Error("No data returned from twitter4llm");return n}}});var HM,ine=b(()=>{br();EA();qx();Lu();HM=class extends Uo{constructor(e){super(e);M(this,"callbacks");M(this,"tags");M(this,"metadata");M(this,"verbose");this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,n){throw new Error("Not implemented!")}async invoke(e,n){let r=wo(JL(n)),o=await(await Ru.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,r.runId,void 0,void 0,void 0,r.runName);try{let i=await this._getRelevantDocuments(e,o);return await o?.handleRetrieverEnd(i),i}catch(i){throw await o?.handleRetrieverError(i),i}}}});var XLr,Bgn,zgn,Dd,sne,b3,QLr,Hgn,ane,Hke,$rt,Ort,e1r,Wgn,Vgn,Urt,jrt,qgn,t1r,lne,Nrt,n1r,r1r,o1r,i1r,Rrt,Dgn,s1r,Drt,Frt,Lrt,a1r,Fgn,Ugn,jgn,Bke,zke,Kgn,l1r,Ggn=b(()=>{XLr="ENTRIES",Bgn="KEYS",zgn="VALUES",Dd="",sne=class{constructor(e,n){let r=e._tree,o=Array.from(r.keys());this.set=e,this._type=n,this._path=o.length>0?[{node:r,keys:o}]:[]}next(){let e=this.dive();return this.backtrack(),e}dive(){if(this._path.length===0)return{done:!0,value:void 0};let{node:e,keys:n}=b3(this._path);if(b3(n)===Dd)return{done:!1,value:this.result()};let r=e.get(b3(n));return this._path.push({node:r,keys:Array.from(r.keys())}),this.dive()}backtrack(){if(this._path.length===0)return;let e=b3(this._path).keys;e.pop(),!(e.length>0)&&(this._path.pop(),this.backtrack())}key(){return this.set._prefix+this._path.map(({keys:e})=>b3(e)).filter(e=>e!==Dd).join("")}value(){return b3(this._path).node.get(Dd)}result(){switch(this._type){case zgn:return this.value();case Bgn:return this.key();default:return[this.key(),this.value()]}}[Symbol.iterator](){return this}},b3=t=>t[t.length-1],QLr=(t,e,n)=>{let r=new Map;if(e===void 0)return r;let o=e.length+1,i=o+n,s=new Uint8Array(i*o).fill(n+1);for(let a=0;a<o;++a)s[a]=a;for(let a=1;a<i;++a)s[a*o]=a;return Hgn(t,e,n,r,s,1,o,""),r},Hgn=(t,e,n,r,o,i,s,a)=>{let l=i*s;e:for(let c of t.keys())if(c===Dd){let u=o[l-1];u<=n&&r.set(a,[t.get(c),u])}else{let u=i;for(let d=0;d<c.length;++d,++u){let f=c[d],p=s*u,m=p-s,h=o[p],g=Math.max(0,u-n-1),v=Math.min(s-1,u+n);for(let y=g;y<v;++y){let w=f!==e[y],_=o[m+y]+ +w,S=o[m+y+1]+1,I=o[p+y]+1,C=o[p+y+1]=Math.min(_,S,I);C<h&&(h=C)}if(h>n)continue e}Hgn(t.get(c),e,n,r,o,u,s,a+c)}},ane=class t{constructor(e=new Map,n=""){this._size=void 0,this._tree=e,this._prefix=n}atPrefix(e){if(!e.startsWith(this._prefix))throw new Error("Mismatched prefix");let[n,r]=Hke(this._tree,e.slice(this._prefix.length));if(n===void 0){let[o,i]=Urt(r);for(let s of o.keys())if(s!==Dd&&s.startsWith(i)){let a=new Map;return a.set(s.slice(i.length),o.get(s)),new t(a,e)}}return new t(n,e)}clear(){this._size=void 0,this._tree.clear()}delete(e){return this._size=void 0,e1r(this._tree,e)}entries(){return new sne(this,XLr)}forEach(e){for(let[n,r]of this)e(n,r,this)}fuzzyGet(e,n){return QLr(this._tree,e,n)}get(e){let n=$rt(this._tree,e);return n!==void 0?n.get(Dd):void 0}has(e){let n=$rt(this._tree,e);return n!==void 0&&n.has(Dd)}keys(){return new sne(this,Bgn)}set(e,n){if(typeof e!="string")throw new Error("key must be a string");return this._size=void 0,Ort(this._tree,e).set(Dd,n),this}get size(){if(this._size)return this._size;this._size=0;let e=this.entries();for(;!e.next().done;)this._size+=1;return this._size}update(e,n){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;let r=Ort(this._tree,e);return r.set(Dd,n(r.get(Dd))),this}fetch(e,n){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;let r=Ort(this._tree,e),o=r.get(Dd);return o===void 0&&r.set(Dd,o=n()),o}values(){return new sne(this,zgn)}[Symbol.iterator](){return this.entries()}static from(e){let n=new t;for(let[r,o]of e)n.set(r,o);return n}static fromObject(e){return t.from(Object.entries(e))}},Hke=(t,e,n=[])=>{if(e.length===0||t==null)return[t,n];for(let r of t.keys())if(r!==Dd&&e.startsWith(r))return n.push([t,r]),Hke(t.get(r),e.slice(r.length),n);return n.push([t,e]),Hke(void 0,"",n)},$rt=(t,e)=>{if(e.length===0||t==null)return t;for(let n of t.keys())if(n!==Dd&&e.startsWith(n))return $rt(t.get(n),e.slice(n.length))},Ort=(t,e)=>{let n=e.length;e:for(let r=0;t&&r<n;){for(let i of t.keys())if(i!==Dd&&e[r]===i[0]){let s=Math.min(n-r,i.length),a=1;for(;a<s&&e[r+a]===i[a];)++a;let l=t.get(i);if(a===i.length)t=l;else{let c=new Map;c.set(i.slice(a),l),t.set(e.slice(r,r+a),c),t.delete(i),t=c}r+=a;continue e}let o=new Map;return t.set(e.slice(r),o),o}return t},e1r=(t,e)=>{let[n,r]=Hke(t,e);if(n!==void 0){if(n.delete(Dd),n.size===0)Wgn(r);else if(n.size===1){let[o,i]=n.entries().next().value;Vgn(r,o,i)}}},Wgn=t=>{if(t.length===0)return;let[e,n]=Urt(t);if(e.delete(n),e.size===0)Wgn(t.slice(0,-1));else if(e.size===1){let[r,o]=e.entries().next().value;r!==Dd&&Vgn(t.slice(0,-1),r,o)}},Vgn=(t,e,n)=>{if(t.length===0)return;let[r,o]=Urt(t);r.set(o+e,n),r.delete(o)},Urt=t=>t[t.length-1],jrt="or",qgn="and",t1r="and_not",lne=class t{constructor(e){if(e?.fields==null)throw new Error('MiniSearch: option "fields" must be provided');let n=e.autoVacuum==null||e.autoVacuum===!0?Lrt:e.autoVacuum;this._options={...Rrt,...e,autoVacuum:n,searchOptions:{...Dgn,...e.searchOptions||{}},autoSuggestOptions:{...s1r,...e.autoSuggestOptions||{}}},this._index=new ane,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldIds={},this._fieldLength=new Map,this._avgFieldLength=[],this._nextId=0,this._storedFields=new Map,this._dirtCount=0,this._currentVacuum=null,this._enqueuedVacuum=null,this._enqueuedVacuumConditions=Frt,this.addFields(this._options.fields)}add(e){let{extractField:n,stringifyField:r,tokenize:o,processTerm:i,fields:s,idField:a}=this._options,l=n(e,a);if(l==null)throw new Error(`MiniSearch: document does not have ID field "${a}"`);if(this._idToShortId.has(l))throw new Error(`MiniSearch: duplicate ID ${l}`);let c=this.addDocumentId(l);this.saveStoredFields(c,e);for(let u of s){let d=n(e,u);if(d==null)continue;let f=o(r(d,u),u),p=this._fieldIds[u],m=new Set(f).size;this.addFieldLength(c,p,this._documentCount-1,m);for(let h of f){let g=i(h,u);if(Array.isArray(g))for(let v of g)this.addTerm(p,c,v);else g&&this.addTerm(p,c,g)}}}addAll(e){for(let n of e)this.add(n)}addAllAsync(e,n={}){let{chunkSize:r=10}=n,o={chunk:[],promise:Promise.resolve()},{chunk:i,promise:s}=e.reduce(({chunk:a,promise:l},c,u)=>(a.push(c),(u+1)%r===0?{chunk:[],promise:l.then(()=>new Promise(d=>setTimeout(d,0))).then(()=>this.addAll(a))}:{chunk:a,promise:l}),o);return s.then(()=>this.addAll(i))}remove(e){let{tokenize:n,processTerm:r,extractField:o,stringifyField:i,fields:s,idField:a}=this._options,l=o(e,a);if(l==null)throw new Error(`MiniSearch: document does not have ID field "${a}"`);let c=this._idToShortId.get(l);if(c==null)throw new Error(`MiniSearch: cannot remove document with ID ${l}: it is not in the index`);for(let u of s){let d=o(e,u);if(d==null)continue;let f=n(i(d,u),u),p=this._fieldIds[u],m=new Set(f).size;this.removeFieldLength(c,p,this._documentCount,m);for(let h of f){let g=r(h,u);if(Array.isArray(g))for(let v of g)this.removeTerm(p,c,v);else g&&this.removeTerm(p,c,g)}}this._storedFields.delete(c),this._documentIds.delete(c),this._idToShortId.delete(l),this._fieldLength.delete(c),this._documentCount-=1}removeAll(e){if(e)for(let n of e)this.remove(n);else{if(arguments.length>0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new ane,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}}discard(e){let n=this._idToShortId.get(e);if(n==null)throw new Error(`MiniSearch: cannot discard document with ID ${e}: it is not in the index`);this._idToShortId.delete(e),this._documentIds.delete(n),this._storedFields.delete(n),(this._fieldLength.get(n)||[]).forEach((r,o)=>{this.removeFieldLength(n,o,this._documentCount,r)}),this._fieldLength.delete(n),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()}maybeAutoVacuum(){if(this._options.autoVacuum===!1)return;let{minDirtFactor:e,minDirtCount:n,batchSize:r,batchWait:o}=this._options.autoVacuum;this.conditionalVacuum({batchSize:r,batchWait:o},{minDirtCount:n,minDirtFactor:e})}discardAll(e){let n=this._options.autoVacuum;try{this._options.autoVacuum=!1;for(let r of e)this.discard(r)}finally{this._options.autoVacuum=n}this.maybeAutoVacuum()}replace(e){let{idField:n,extractField:r}=this._options,o=r(e,n);this.discard(o),this.add(e)}vacuum(e={}){return this.conditionalVacuum(e)}conditionalVacuum(e,n){return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&n,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(()=>{let r=this._enqueuedVacuumConditions;return this._enqueuedVacuumConditions=Frt,this.performVacuuming(e,r)}),this._enqueuedVacuum)):this.vacuumConditionsMet(n)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(e),this._currentVacuum)}async performVacuuming(e,n){let r=this._dirtCount;if(this.vacuumConditionsMet(n)){let o=e.batchSize||Drt.batchSize,i=e.batchWait||Drt.batchWait,s=1;for(let[a,l]of this._index){for(let[c,u]of l)for(let[d]of u)this._documentIds.has(d)||(u.size<=1?l.delete(c):u.delete(d));this._index.get(a).size===0&&this._index.delete(a),s%o===0&&await new Promise(c=>setTimeout(c,i)),s+=1}this._dirtCount-=r}await null,this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null}vacuumConditionsMet(e){if(e==null)return!0;let{minDirtCount:n,minDirtFactor:r}=e;return n=n||Lrt.minDirtCount,r=r||Lrt.minDirtFactor,this.dirtCount>=n&&this.dirtFactor>=r}get isVacuuming(){return this._currentVacuum!=null}get dirtCount(){return this._dirtCount}get dirtFactor(){return this._dirtCount/(1+this._documentCount+this._dirtCount)}has(e){return this._idToShortId.has(e)}getStoredFields(e){let n=this._idToShortId.get(e);if(n!=null)return this._storedFields.get(n)}search(e,n={}){let{searchOptions:r}=this._options,o={...r,...n},i=this.executeQuery(e,n),s=[];for(let[a,{score:l,terms:c,match:u}]of i){let d=c.length||1,f={id:this._documentIds.get(a),score:l*d,terms:Object.keys(u),queryTerms:c,match:u};Object.assign(f,this._storedFields.get(a)),(o.filter==null||o.filter(f))&&s.push(f)}return e===t.wildcard&&o.boostDocument==null||s.sort(Ugn),s}autoSuggest(e,n={}){n={...this._options.autoSuggestOptions,...n};let r=new Map;for(let{score:i,terms:s}of this.search(e,n)){let a=s.join(" "),l=r.get(a);l!=null?(l.score+=i,l.count+=1):r.set(a,{score:i,terms:s,count:1})}let o=[];for(let[i,{score:s,terms:a,count:l}]of r)o.push({suggestion:i,terms:a,score:s/l});return o.sort(Ugn),o}get documentCount(){return this._documentCount}get termCount(){return this._index.size}static loadJSON(e,n){if(n==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJS(JSON.parse(e),n)}static async loadJSONAsync(e,n){if(n==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJSAsync(JSON.parse(e),n)}static getDefault(e){if(Rrt.hasOwnProperty(e))return Nrt(Rrt,e);throw new Error(`MiniSearch: unknown option "${e}"`)}static loadJS(e,n){let{index:r,documentIds:o,fieldLength:i,storedFields:s,serializationVersion:a}=e,l=this.instantiateMiniSearch(e,n);l._documentIds=Bke(o),l._fieldLength=Bke(i),l._storedFields=Bke(s);for(let[c,u]of l._documentIds)l._idToShortId.set(u,c);for(let[c,u]of r){let d=new Map;for(let f of Object.keys(u)){let p=u[f];a===1&&(p=p.ds),d.set(parseInt(f,10),Bke(p))}l._index.set(c,d)}return l}static async loadJSAsync(e,n){let{index:r,documentIds:o,fieldLength:i,storedFields:s,serializationVersion:a}=e,l=this.instantiateMiniSearch(e,n);l._documentIds=await zke(o),l._fieldLength=await zke(i),l._storedFields=await zke(s);for(let[u,d]of l._documentIds)l._idToShortId.set(d,u);let c=0;for(let[u,d]of r){let f=new Map;for(let p of Object.keys(d)){let m=d[p];a===1&&(m=m.ds),f.set(parseInt(p,10),await zke(m))}++c%1e3===0&&await Kgn(0),l._index.set(u,f)}return l}static instantiateMiniSearch(e,n){let{documentCount:r,nextId:o,fieldIds:i,averageFieldLength:s,dirtCount:a,serializationVersion:l}=e;if(l!==1&&l!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");let c=new t(n);return c._documentCount=r,c._nextId=o,c._idToShortId=new Map,c._fieldIds=i,c._avgFieldLength=s,c._dirtCount=a||0,c._index=new ane,c}executeQuery(e,n={}){if(e===t.wildcard)return this.executeWildcardQuery(n);if(typeof e!="string"){let f={...n,...e,queries:void 0},p=e.queries.map(m=>this.executeQuery(m,f));return this.combineResults(p,f.combineWith)}let{tokenize:r,processTerm:o,searchOptions:i}=this._options,s={tokenize:r,processTerm:o,...i,...n},{tokenize:a,processTerm:l}=s,d=a(e).flatMap(f=>l(f)).filter(f=>!!f).map(i1r(s)).map(f=>this.executeQuerySpec(f,s));return this.combineResults(d,s.combineWith)}executeQuerySpec(e,n){let r={...this._options.searchOptions,...n},o=(r.fields||this._options.fields).reduce((h,g)=>({...h,[g]:Nrt(r.boost,g)||1}),{}),{boostDocument:i,weights:s,maxFuzzy:a,bm25:l}=r,{fuzzy:c,prefix:u}={...Dgn.weights,...s},d=this._index.get(e.term),f=this.termResults(e.term,e.term,1,e.termBoost,d,o,i,l),p,m;if(e.prefix&&(p=this._index.atPrefix(e.term)),e.fuzzy){let h=e.fuzzy===!0?.2:e.fuzzy,g=h<1?Math.min(a,Math.round(e.term.length*h)):h;g&&(m=this._index.fuzzyGet(e.term,g))}if(p)for(let[h,g]of p){let v=h.length-e.term.length;if(!v)continue;m?.delete(h);let y=u*h.length/(h.length+.3*v);this.termResults(e.term,h,y,e.termBoost,g,o,i,l,f)}if(m)for(let h of m.keys()){let[g,v]=m.get(h);if(!v)continue;let y=c*h.length/(h.length+v);this.termResults(e.term,h,y,e.termBoost,g,o,i,l,f)}return f}executeWildcardQuery(e){let n=new Map,r={...this._options.searchOptions,...e};for(let[o,i]of this._documentIds){let s=r.boostDocument?r.boostDocument(i,"",this._storedFields.get(o)):1;n.set(o,{score:s,terms:[],match:{}})}return n}combineResults(e,n=jrt){if(e.length===0)return new Map;let r=n.toLowerCase(),o=n1r[r];if(!o)throw new Error(`Invalid combination operator: ${n}`);return e.reduce(o)||new Map}toJSON(){let e=[];for(let[n,r]of this._index){let o={};for(let[i,s]of r)o[i]=Object.fromEntries(s);e.push([n,o])}return{documentCount:this._documentCount,nextId:this._nextId,documentIds:Object.fromEntries(this._documentIds),fieldIds:this._fieldIds,fieldLength:Object.fromEntries(this._fieldLength),averageFieldLength:this._avgFieldLength,storedFields:Object.fromEntries(this._storedFields),dirtCount:this._dirtCount,index:e,serializationVersion:2}}termResults(e,n,r,o,i,s,a,l,c=new Map){if(i==null)return c;for(let u of Object.keys(s)){let d=s[u],f=this._fieldIds[u],p=i.get(f);if(p==null)continue;let m=p.size,h=this._avgFieldLength[f];for(let g of p.keys()){if(!this._documentIds.has(g)){this.removeTerm(f,g,n),m-=1;continue}let v=a?a(this._documentIds.get(g),n,this._storedFields.get(g)):1;if(!v)continue;let y=p.get(g),w=this._fieldLength.get(g)[f],_=o1r(y,m,this._documentCount,w,h,l),S=r*o*d*v*_,I=c.get(g);if(I){I.score+=S,a1r(I.terms,e);let C=Nrt(I.match,n);C?C.push(u):I.match[n]=[u]}else c.set(g,{score:S,terms:[e],match:{[n]:[u]}})}}return c}addTerm(e,n,r){let o=this._index.fetch(r,jgn),i=o.get(e);if(i==null)i=new Map,i.set(n,1),o.set(e,i);else{let s=i.get(n);i.set(n,(s||0)+1)}}removeTerm(e,n,r){if(!this._index.has(r)){this.warnDocumentChanged(n,e,r);return}let o=this._index.fetch(r,jgn),i=o.get(e);i==null||i.get(n)==null?this.warnDocumentChanged(n,e,r):i.get(n)<=1?i.size<=1?o.delete(e):i.delete(n):i.set(n,i.get(n)-1),this._index.get(r).size===0&&this._index.delete(r)}warnDocumentChanged(e,n,r){for(let o of Object.keys(this._fieldIds))if(this._fieldIds[o]===n){this._options.logger("warn",`MiniSearch: document with ID ${this._documentIds.get(e)} has changed before removal: term "${r}" was not present in field "${o}". Removing a document after it has changed can corrupt the index!`,"version_conflict");return}}addDocumentId(e){let n=this._nextId;return this._idToShortId.set(e,n),this._documentIds.set(n,e),this._documentCount+=1,this._nextId+=1,n}addFields(e){for(let n=0;n<e.length;n++)this._fieldIds[e[n]]=n}addFieldLength(e,n,r,o){let i=this._fieldLength.get(e);i==null&&this._fieldLength.set(e,i=[]),i[n]=o;let a=(this._avgFieldLength[n]||0)*r+o;this._avgFieldLength[n]=a/(r+1)}removeFieldLength(e,n,r,o){if(r===1){this._avgFieldLength[n]=0;return}let i=this._avgFieldLength[n]*r-o;this._avgFieldLength[n]=i/(r-1)}saveStoredFields(e,n){let{storeFields:r,extractField:o}=this._options;if(r==null||r.length===0)return;let i=this._storedFields.get(e);i==null&&this._storedFields.set(e,i={});for(let s of r){let a=o(n,s);a!==void 0&&(i[s]=a)}}};lne.wildcard=Symbol("*");Nrt=(t,e)=>Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0,n1r={[jrt]:(t,e)=>{for(let n of e.keys()){let r=t.get(n);if(r==null)t.set(n,e.get(n));else{let{score:o,terms:i,match:s}=e.get(n);r.score=r.score+o,r.match=Object.assign(r.match,s),Fgn(r.terms,i)}}return t},[qgn]:(t,e)=>{let n=new Map;for(let r of e.keys()){let o=t.get(r);if(o==null)continue;let{score:i,terms:s,match:a}=e.get(r);Fgn(o.terms,s),n.set(r,{score:o.score+i,terms:o.terms,match:Object.assign(o.match,a)})}return n},[t1r]:(t,e)=>{for(let n of e.keys())t.delete(n);return t}},r1r={k:1.2,b:.7,d:.5},o1r=(t,e,n,r,o,i)=>{let{k:s,b:a,d:l}=i;return Math.log(1+(n-e+.5)/(e+.5))*(l+t*(s+1)/(t+s*(1-a+a*r/o)))},i1r=t=>(e,n,r)=>{let o=typeof t.fuzzy=="function"?t.fuzzy(e,n,r):t.fuzzy||!1,i=typeof t.prefix=="function"?t.prefix(e,n,r):t.prefix===!0,s=typeof t.boostTerm=="function"?t.boostTerm(e,n,r):1;return{term:e,fuzzy:o,prefix:i,termBoost:s}},Rrt={idField:"id",extractField:(t,e)=>t[e],stringifyField:(t,e)=>t.toString(),tokenize:t=>t.split(l1r),processTerm:t=>t.toLowerCase(),fields:void 0,searchOptions:void 0,storeFields:[],logger:(t,e)=>{typeof console?.[t]=="function"&&console[t](e)},autoVacuum:!0},Dgn={combineWith:jrt,prefix:!1,fuzzy:!1,maxFuzzy:6,boost:{},weights:{fuzzy:.45,prefix:.375},bm25:r1r},s1r={combineWith:qgn,prefix:(t,e,n)=>e===n.length-1},Drt={batchSize:1e3,batchWait:10},Frt={minDirtFactor:.1,minDirtCount:20},Lrt={...Drt,...Frt},a1r=(t,e)=>{t.includes(e)||t.push(e)},Fgn=(t,e)=>{for(let n of e)t.includes(n)||t.push(n)},Ugn=({score:t},{score:e})=>e-t,jgn=()=>new Map,Bke=t=>{let e=new Map;for(let n of Object.keys(t))e.set(parseInt(n,10),t[n]);return e},zke=async t=>{let e=new Map,n=0;for(let r of Object.keys(t))e.set(parseInt(r,10),t[r]),++n%1e3===0&&await Kgn(0);return e},Kgn=t=>new Promise(e=>setTimeout(e,t)),l1r=/[\n\r\p{Z}\p{P}]+/u});var Vke,sl,Wke,Zgn=b(()=>{pe();gt();Ggn();Vke=require("obsidian");Zte();srt();sl=class sl{constructor(e,n){this.app=e;this.index=null;this.indexedChunks=new Set;this.memoryManager=new kD,this.chunkManager=n||DM(e)}createIndex(){return new lne({fields:["title","heading","path","tags","body"],storeFields:["id","notePath","title","heading","chunkIndex"],tokenize:this.tokenizeMixed.bind(this),searchOptions:{boost:{title:sl.FIELD_WEIGHTS.title,heading:sl.FIELD_WEIGHTS.heading,path:sl.FIELD_WEIGHTS.path,tags:sl.FIELD_WEIGHTS.tags,body:sl.FIELD_WEIGHTS.body},prefix:!0,fuzzy:!1,combineWith:"OR"}})}tokenizeMixed(e){if(!e)return[];let n=new Set,r=e.toLowerCase(),o=r,i=null;try{i=r.match(/#[\p{L}\p{N}_/-]+/gu)}catch{i=r.match(/#[a-z0-9_/-]+/g)}if(i)for(let c of i){n.add(c);let u=c.slice(1);if(!u)continue;n.add(u);let d=u.split("/").filter(p=>p.length>0);if(d.length>0){let p="";for(let m of d)p=p?`${p}/${m}`:m,n.add(p),n.add(`#${p}`),n.add(m)}let f=c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");o=o.replace(new RegExp(f,"gu")," ")}(o.match(/[a-z0-9_]+/g)||[]).forEach(c=>n.add(c));let a=/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]+/g,l=e.match(a)||[];for(let c of l){c.length===1&&n.add(c);for(let u=0;u<c.length-1;u++)n.add(c.slice(u,u+2))}return Array.from(n)}async buildFromCandidates(e){j(`FullTextEngine: [CHUNKS] Starting with ${e.length} candidate notes`),this.indexedChunks.clear(),this.memoryManager.reset(),await new Promise(c=>window.setTimeout(c,0));let n=Date.now();this.index=this.createIndex();let r=Date.now()-n;j(`FullTextEngine: MiniSearch index created in ${r}ms`);let o={maxChars:qoe,overlap:0,maxBytesTotal:this.memoryManager.getMaxBytes()*sl.CHUNK_MEMORY_PERCENTAGE},i=await this.chunkManager.getChunks(e,o);if(i.length===0)return j("FullTextEngine: No chunks generated"),0;j(`FullTextEngine: Generated ${i.length} chunks from ${e.length} notes`);let s=0,a=sl.BATCH_SIZE,l=new Map;for(let c=0;c<i.length;c++){let u=i[c],d=kD.getByteSize(u.content);if(!this.memoryManager.canAddContent(d)){j(`FullTextEngine: Memory limit reached at ${s} chunks`);break}let f=u.notePath.replace(/\.md$/,"").split("/").join(" "),p=l.get(u.notePath);if(!p){let h=this.app.vault.getAbstractFileByPath(u.notePath);if(h instanceof Vke.TFile){let g=this.app.metadataCache.getFileCache(h),v=g?.frontmatter??{},y=g?(0,Vke.getAllTags)(g)??[]:[],w=this.extractFrontmatterTags(v),_=this.normalizeTagList([...y,...w]),S=this.app.metadataCache.resolvedLinks[h.path]??{},I=this.app.metadataCache.getBacklinksForFile(h)?.data??{},C=Object.keys(S),k=Object.keys(I),T=[...C,...k],P=this.extractPropertyValues(v);p={tags:_,links:T,props:P},l.set(u.notePath,p)}else p={tags:[],links:[],props:[]}}let m=[u.content,...p.props].join(" ");this.index.add({id:u.id,title:u.title,heading:u.heading,path:f,body:m,tags:p.tags.join(" "),notePath:u.notePath,chunkIndex:u.chunkIndex}),this.memoryManager.addBytes(d),this.indexedChunks.add(u.id),s++,c>0&&c%a===0&&await new Promise(h=>window.setTimeout(h,0))}return j(`FullTextEngine: [CHUNKS] Indexed ${s}/${i.length} chunks (${this.memoryManager.getUsagePercent()}% memory)`),s}extractPropertyValues(e){let n=[];if(e&&typeof e=="object")for(let r of Object.values(e))this.extractPrimitiveValues(r,n,sl.MAX_EXTRACTION_DEPTH);return n}extractFrontmatterTags(e){if(!e||typeof e!="object")return[];let n=[],r=["tags","tag"],o=i=>{let s=i.trim();s.length>0&&n.push(s)};for(let i of r){let s=e[i];if(s)if(Array.isArray(s))for(let a of s)typeof a=="string"&&o(a);else typeof s=="string"&&s.split(/[,\s]+/g).map(a=>a.trim()).filter(a=>a.length>0).forEach(o)}return n}normalizeTagList(e){let n=new Set;for(let r of e){if(typeof r!="string")continue;let o=r.trim();if(o.length===0)continue;let i=o.replace(/^#+/,"");if(i.length===0)continue;let s=i.toLowerCase();n.add(`#${s}`),n.add(s);let a=s.split("/").filter(l=>l.length>0);if(a.length>1){let l="";for(let c of a)l=l?`${l}/${c}`:c,n.add(`#${l}`),n.add(l),n.add(c)}else a.length===1&&(n.add(`#${a[0]}`),n.add(a[0]))}return Array.from(n)}extractPrimitiveValues(e,n,r){if(!(r<=0||e==null))if(typeof e=="string"){let o=e.trim();o&&n.push(o)}else typeof e=="number"||typeof e=="boolean"?n.push(String(e)):e instanceof Date?n.push(e.toISOString()):Array.isArray(e)&&e.slice(0,sl.MAX_ARRAY_ITEMS).forEach(o=>{if(typeof o=="string"||typeof o=="number"||typeof o=="boolean"){let i=typeof o=="string"?o.trim():String(o);i&&n.push(i)}})}search(e,n=30,r=[],o){if(!this.index)return[];let i=r.length>0?r.join(" "):o||e[0]||"";if(!i.trim())return[];let s={boost:{title:sl.FIELD_WEIGHTS.title,heading:sl.FIELD_WEIGHTS.heading,path:sl.FIELD_WEIGHTS.path,tags:sl.FIELD_WEIGHTS.tags,body:sl.FIELD_WEIGHTS.body},prefix:!0,fuzzy:!1,combineWith:"OR"};try{let a=this.index.search(i,s);return j(`FullText: Search found ${a.length} results for "${i.substring(0,50)}..."`),a.slice(0,n).map(l=>({id:l.id,score:l.score,engine:"fulltext",explanation:{lexicalMatches:this.extractLexicalMatches(l),baseScore:l.score,finalScore:l.score}}))}catch(a){return W(`FullText: Search failed for "${i}": ${a}`),[]}}extractLexicalMatches(e){let n=[];if(e.match)for(let[r,o]of Object.entries(e.match))for(let i of o)n.push({field:r,query:i,weight:this.getFieldWeight(r)});return n}getFieldWeight(e){return sl.FIELD_WEIGHTS[e]||1}clear(){try{this.index=null,this.indexedChunks.clear(),this.memoryManager.reset(),j("FullTextEngine: Cleanup completed successfully")}catch(e){W(`FullTextEngine: Cleanup error: ${e}`)}}getStats(){return{documentsIndexed:this.indexedChunks.size,memoryUsed:this.memoryManager.getBytesUsed(),memoryPercent:this.memoryManager.getUsagePercent()}}};sl.BATCH_SIZE=10,sl.CHUNK_MEMORY_PERCENTAGE=.35,sl.MAX_ARRAY_ITEMS=10,sl.MAX_EXTRACTION_DEPTH=2,sl.FIELD_WEIGHTS={title:5,heading:2.5,headings:1.5,path:1.5,tags:4,props:1.5,links:1.5,body:1};Wke=sl});function _3(t){if(!t)return[];let e=null;try{e=t.match(/#[\p{L}\p{N}_/-]+/gu)}catch{e=t.match(/#[a-zA-Z0-9_/-]+/g)}if(!e)return[];let n=new Set;for(let r of e){let o=r.trim();o.length<=1||n.add(o.toLowerCase())}return Array.from(n)}var Brt=b(()=>{});var Kke,qke,Ygn=b(()=>{gt();iy();pe();Brt();ut();Kke=class Kke{constructor(e={}){this.options=e;this.cache=new Map;this.config={maxVariants:e.maxVariants??2,timeout:e.timeout??Koe,cacheSize:e.cacheSize??100,minTermLength:2}}async expand(e){if(!e?.trim())return{queries:[],salientTerms:[],originalQuery:"",expandedQueries:[]};let n=this.cache.get(e);if(n)return this.cache.delete(e),this.cache.set(e,n),j(`QueryExpander: Using cached expansion for "${e}"`),n;try{let r=await this.expandWithTimeout(e);return this.cacheResult(e,r),r}catch(r){return W(`QueryExpander: Failed to expand query "${e}":`,r),this.fallbackExpansion(e)}}async expandWithTimeout(e){try{return await Bie(n=>this.expandWithLLM(e,n),this.config.timeout,"Query expansion")}catch(n){if(n instanceof Q5)return j(`QueryExpander: Timeout reached for "${e}"`),this.fallbackExpansion(e);throw n}}async expandWithLLM(e,n){try{if(!this.options.getChatModel)return j("QueryExpander: No chat model getter provided"),this.fallbackExpansion(e);let r=await this.options.getChatModel();if(!r)return j("QueryExpander: No chat model available"),this.fallbackExpansion(e);let o=Kke.PROMPT_TEMPLATE.replace("{count}",this.config.maxVariants.toString()).replace("{query}",e),i=await Jf(async()=>await r.invoke(o,n?{signal:n}:void 0));if(!i)return this.fallbackExpansion(e);let s=this.extractContent(i);if(!s)return this.fallbackExpansion(e);let a=this.parseXMLResponse(s,e);return j(`QueryExpander: Expanded "${e}" to ${a.queries.length} queries and ${a.salientTerms.length} terms`),a}catch(r){return H("QueryExpander: LLM expansion failed:",r),this.fallbackExpansion(e)}}extractContent(e){let n=e,r=n?.content??n?.text??"";return typeof e=="string"?e:(typeof r=="string"?r:typeof r=="number"?String(r):"").trim()||null}extractSalientTermsFromOriginal(e){let n=this.extractTermsFromQueries([e]),r=_3(e);return this.combineBaseAndTagTerms(n,r,e)}parseXMLResponse(e,n){let r=[n],o=new Set,i=/<query>(.*?)<\/query>/g,s;for(;(s=i.exec(e))!==null;){let f=s[1]?.trim();f&&f!==n&&r.length<=this.config.maxVariants&&r.push(f)}let a=e.match(/<salient>([\s\S]*?)<\/salient>/);if(a){let f=/<term>(.*?)<\/term>/g,p;for(;(p=f.exec(a[1]))!==null;){let m=p[1]?.trim().toLowerCase();m&&this.isValidTerm(m)&&o.add(m)}}if(!(r.length>1||o.size>0||/<term>/.test(e)))return this.fallbackExpansion(n);let c=_3(n),u=o.size>0?Array.from(new Set([...o,...c])):this.extractSalientTermsFromOriginal(n),d=r.slice(1);return{queries:r.slice(0,this.config.maxVariants+1),salientTerms:u,originalQuery:n,expandedQueries:d.slice(0,this.config.maxVariants)}}fallbackExpansion(e){let n=this.extractTermsFromQueries([e]),r=_3(e),o=this.combineBaseAndTagTerms(n,r,e);return{queries:[e],salientTerms:o,originalQuery:e,expandedQueries:[]}}extractTermsFromQueries(e){let n=new Set;for(let r of e){let o=r.toLowerCase().replace(/[^\w\s-]/g," ").split(/\s+/);for(let i of o)this.isValidTerm(i)&&(n.add(i),i.includes("-")&&i.split("-").forEach(s=>{this.isValidTerm(s)&&n.add(s)}))}return Array.from(n)}isValidTerm(e){if(e.length<this.config.minTermLength)return!1;if(e.startsWith("#"))try{return/^#[\p{L}\p{N}_/-]+$/u.test(e)}catch{return/^#[A-Za-z0-9_/-]+$/.test(e)}try{return/^[\p{L}\p{N}_-]+$/u.test(e)}catch{return/^[A-Za-z0-9_-]+$/.test(e)}}combineBaseAndTagTerms(e,n,r){let o=new Set([...e,...n]);if(n.length===0)return Array.from(o);let i=this.collectStandaloneTerms(r);for(let s of n){let a=s.slice(1);a.length>0&&!i.has(a)&&o.delete(a)}return Array.from(o)}collectStandaloneTerms(e){let n=new Set;if(!e)return n;let r=e.toLowerCase(),o=this.findTagRanges(r),i=[/[\p{L}\p{N}_-]+/gu,/[a-z0-9_-]+/g];for(let s of i)try{for(let a of r.matchAll(s)){if(a.index===void 0)continue;let l=a.index,c=l+a[0].length;if(o.some(({start:f,end:p})=>l>=f&&c<=p))continue;let d=a[0];this.isValidTerm(d)&&!d.startsWith("#")&&(n.add(d),d.includes("-")&&d.split("-").forEach(f=>{this.isValidTerm(f)&&!f.startsWith("#")&&n.add(f)}))}break}catch{continue}return n}findTagRanges(e){let n=[],r=[/#[\p{L}\p{N}_/-]+/gu,/#[a-z0-9_/-]+/g];for(let o of r)try{for(let i of e.matchAll(o))i.index!==void 0&&n.push({start:i.index,end:i.index+i[0].length});break}catch{continue}return n}cacheResult(e,n){if(this.cache.size>=this.config.cacheSize){let r=this.cache.keys().next().value;r&&this.cache.delete(r)}this.cache.set(e,n)}clearCache(){this.cache.clear(),j("QueryExpander: Cache cleared")}getCacheSize(){return this.cache.size}};Kke.PROMPT_TEMPLATE=`Analyze this search query and provide:
1. SALIENT TERMS from the original query (for ranking)
2. Alternative queries and related terms (for finding more results)
Query: "{query}"
Instructions:
SALIENT TERMS (for ranking - ONLY from original query):
- Extract meaningful words FROM THE ORIGINAL QUERY ONLY
- Include: nouns, proper nouns, technical terms, domain concepts
- Exclude: action verbs (find, search, get), pronouns (my, your), articles (the, a), prepositions (in, on, for), conjunctions (and, or)
- These terms determine search ranking - must be from original query
ALTERNATIVE QUERIES (for recall - specific alternative phrasings):
- Alternative phrasings of the query (specific enough to be useful for search)
Example: "find my piano notes"
- Salient (from original): piano, notes
- Queries: "piano lesson notes", "piano practice sheets"
Example: "\u67E5\u627E\u6211\u7684\u5B66\u4E60\u7B14\u8BB0"
- Salient (from original): \u5B66\u4E60, \u7B14\u8BB0
- Queries: "\u4E2A\u4EBA\u7B14\u8BB0\u6587\u6863"
Format:
<salient>
<term>word_from_original_query</term>
</salient>
<queries>
<query>alternative query</query>
</queries>`;qke=Kke});var x3,Gke,Jgn=b(()=>{pe();ha();x3=class x3{constructor(e){this.app=e}async batchCachedReadGrep(e,n){let{inclusions:r,exclusions:o}=Fi(),s=this.app.vault.getMarkdownFiles().filter(h=>ii(this.app,h,r,o)),a=x3.CONFIG.BATCH_SIZE,l=e.map(h=>h.toLowerCase()).filter(h=>this.isGrepWorthy(h)),c=[],u=x3.CONFIG.YIELD_INTERVAL;for(let h=0;h<s.length;h++){let g=s[h],v=g.path.toLowerCase(),y=0;for(let w of l)v.includes(w)&&y++;y>0&&c.push({path:g.path,matchCount:y}),h>0&&h%u===0&&await new Promise(w=>window.setTimeout(w,0))}c.sort((h,g)=>g.matchCount-h.matchCount);let d=new Set(c.map(h=>h.path)),f=Math.max(0,n-d.size),p=new Set;if(f>0)for(let h=0;h<s.length&&p.size<f;h+=a){let g=s.slice(h,h+a);await Promise.all(g.map(async v=>{if(!(p.size>=f)&&!d.has(v.path))try{let w=(await this.app.vault.cachedRead(v)).toLowerCase();for(let _ of l)if(w.includes(_)){p.add(v.path);break}}catch(y){j(`GrepScanner: Skipping file ${v.path}: ${y}`)}})),h%x3.CONFIG.YIELD_INTERVAL===0&&await new Promise(v=>window.setTimeout(v,0))}let m=[...d,...p].slice(0,n);if(m.length>0){let h=Math.min(d.size,n),g=m.length-h;j(` Grep: ${m.length} files match (${h} path, ${g} content) [${e.slice(0,3).join(", ")}${e.length>3?"...":""}]`)}return m}async grep(e,n=200){return this.batchCachedReadGrep([e],n)}isGrepWorthy(e){return!(!e||e.length<=1)}async fileContainsAny(e,n){try{let r=e.path.toLowerCase(),o=0;for(let a of n)r.includes(a.toLowerCase())&&o++;if(o>0)return!0;let s=(await this.app.vault.cachedRead(e)).toLowerCase();return n.some(a=>s.includes(a.toLowerCase()))}catch{return!1}}};x3.CONFIG={BATCH_SIZE:30,YIELD_INTERVAL:100};Gke=x3});function __(t){let e=t.lastIndexOf("#");return e===-1?t:t.substring(0,e)}var Zke=b(()=>{});var c1r,Yke,Xgn=b(()=>{pe();Zke();c1r={enabled:!0,minDocsForBoost:2,maxBoostFactor:1.15,minRelevanceRatio:.4},Yke=class{constructor(e){this.config=c1r;this.app=e||null}setConfig(e){this.config={...this.config,...e}}applyBoosts(e){if(!this.config.enabled||e.length===0)return e;let n=this.calculateFolderStats(e);return this.logBoostedFolders(n),e.map(r=>{let o=__(r.id),i=this.extractFolder(o),s=n.get(i);if(s){let a=r.score*s.boostFactor;return{...r,score:a,explanation:r.explanation?{...r.explanation,folderBoost:{folder:s.folderPath,documentCount:s.documentCount,totalDocsInFolder:s.totalDocsInFolder,relevanceRatio:s.relevanceRatio,boostFactor:s.boostFactor},finalScore:a}:void 0}}return r})}calculateFolderStats(e){let n=new Map;for(let s of e){let a=__(s.id),l=this.extractFolder(a);n.has(l)||n.set(l,new Set),n.get(l).add(a)}let r=new Map;for(let[s,a]of n.entries())r.set(s,a.size);let o=this.getTotalDocsPerFolder(),i=new Map;for(let[s,a]of r.entries()){let l=o.get(s)||a,c=a/l;if(a>=this.config.minDocsForBoost&&c>=this.config.minRelevanceRatio){let d=1+(1+Math.log2(a+1)-1)*Math.sqrt(c),f=Math.min(d,this.config.maxBoostFactor);i.set(s,{folderPath:s,documentCount:a,totalDocsInFolder:l,relevanceRatio:c,boostFactor:f})}}return i}getTotalDocsPerFolder(){let e=new Map;if(!this.app)return e;let n=this.app.vault.getMarkdownFiles();for(let r of n){let o=this.extractFolder(r.path);e.set(o,(e.get(o)||0)+1)}return e}extractFolder(e){return e.substring(0,e.lastIndexOf("/"))||""}logBoostedFolders(e){let n=Array.from(e.values()).sort((r,o)=>o.relevanceRatio-r.relevanceRatio);n.length>0&&(j(`Folder boost: Boosting ${n.length} folders with significant relevance`),n.slice(0,5).forEach(r=>{let o=(r.relevanceRatio*100).toFixed(1);j(` ${r.folderPath||"(root)"}: ${r.documentCount}/${r.totalDocsInFolder} docs (${o}% relevant, ${r.boostFactor.toFixed(2)}x boost)`)}))}getFolderBoosts(e){return this.config.enabled?this.calculateFolderStats(e):new Map}}});var Qgn,u1r,Jke,eyn=b(()=>{pe();Qgn=require("obsidian");Zke();u1r={enabled:!0,maxCandidates:10,backlinkWeight:1,coCitationWeight:.5,sharedTagWeight:.3,boostStrength:.1,maxBoostMultiplier:1.2},Jke=class{constructor(e,n={}){this.metadataCache=e.metadataCache,this.config={...u1r,...n}}applyBoost(e){if(!this.config.enabled||e.length===0)return e;let n=this.filterCandidates(e);if(n.length<2)return e;let r=new Set(n.map(a=>__(a.id))),o=new Map;for(let a of r){let l=this.calculateConnections(a,r);o.set(a,l)}let i=e.map(a=>{let l=__(a.id),c=o.get(l);return!c||c.boostMultiplier===1?a:{...a,score:a.score*c.boostMultiplier,explanation:a.explanation?{...a.explanation,graphConnections:{backlinks:c.backlinks.length,coCitations:c.coCitations.length,sharedTags:c.sharedTags.length,score:c.connectionScore,boostMultiplier:c.boostMultiplier}}:void 0}}),s=i.filter(a=>{let l=__(a.id),c=o.get(l);return c&&c.boostMultiplier>1});return s.length>0&&j(`GraphBoostCalculator: Boosted ${s.length} notes based on connections`),i}calculateConnections(e,n){let r=this.findBacklinks(e,n),o=this.findCoCitations(e,n),i=this.findSharedTags(e,n),s=r.length*this.config.backlinkWeight+o.length*this.config.coCitationWeight+i.length*this.config.sharedTagWeight,a=1;return s>0&&(a=1+this.config.boostStrength*Math.log(1+s),a=Math.min(a,this.config.maxBoostMultiplier)),{backlinks:r,coCitations:o,sharedTags:i,connectionScore:s,boostMultiplier:a}}resolveFile(e){let n=this.metadataCache.getFirstLinkpathDest(e,"");return n instanceof Qgn.TFile?n:null}findBacklinks(e,n){let r=[],o=this.resolveFile(e);if(!o)return r;let i=this.metadataCache.getBacklinksForFile(o);if(!i)return r;for(let[s]of i.data)n.has(s)&&s!==e&&r.push(s);return r}findCoCitations(e,n){let r=[],o=new Set,i=this.resolveFile(e);if(!i)return r;let s=this.metadataCache.getBacklinksForFile(i);if(!s)return r;for(let[a]of s.data)o.add(a);if(o.size===0)return r;for(let a of n){if(a===e)continue;let l=this.resolveFile(a);if(!l)continue;let c=this.metadataCache.getBacklinksForFile(l);if(c){for(let[u]of c.data)if(o.has(u)){r.push(a);break}}}return r}findSharedTags(e,n){let r=[],o=this.resolveFile(e);if(!o)return r;let i=this.metadataCache.getFileCache(o);if(!i||!i.tags||i.tags.length===0)return r;let s=new Set(i.tags.map(a=>a.tag));for(let a of n){if(a===e)continue;let l=this.resolveFile(a);if(!l)continue;let c=this.metadataCache.getFileCache(l);if(!c||!c.tags)continue;c.tags.some(d=>s.has(d.tag))&&r.push(a)}return r}filterCandidates(e){let n=new Map;for(let i of e){let s=__(i.id);n.has(s)||n.set(s,i)}let r=Array.from(n.values()),o=r.length;return r=r.slice(0,this.config.maxCandidates),o>this.config.maxCandidates&&j(`GraphBoost: Limited to top ${this.config.maxCandidates} note candidates (from ${o} unique notes)`),r}setConfig(e){this.config={...this.config,...e}}}});function tyn(t,e={}){let n={...d1r,...e};if(t.length===0)return{results:[],cutoffScore:null,uniqueNotes:0,totalBefore:0};let r=[...t].sort((c,u)=>u.score-c.score),o=r[0].score,i=Math.max(o*n.relativeThreshold,n.absoluteMinScore),s;n.ensureDiversity?s=p1r(r,i,n):s=f1r(r,i,n);let a=new Set(s.map(c=>__(c.id))).size,l=s.length<r.length?i:null;return j(`AdaptiveCutoff: ${s.length}/${r.length} results kept (${a} unique notes, threshold=${i.toFixed(3)})`),{results:s,cutoffScore:l,uniqueNotes:a,totalBefore:r.length}}function f1r(t,e,n){let r=[];for(let o of t){if(r.length>=n.ceiling||r.length>=n.floor&&o.score<e)break;r.push(o)}return r}function p1r(t,e,n){let r=[],o=new Set,i=[];for(let s of t){let a=__(s.id);if(!o.has(a)&&(r.length<n.floor||s.score>=e)){if(o.add(a),r.push(s),r.length>=n.ceiling)break;continue}i.push(s)}if(r.length<n.ceiling)for(let s of i){if(r.length>=n.ceiling||s.score<e&&r.length>=n.floor)break;r.push(s)}return r.sort((s,a)=>a.score-s.score),r}var d1r,nyn=b(()=>{pe();Zke();d1r={floor:3,ceiling:30,relativeThreshold:.3,absoluteMinScore:.01,ensureDiversity:!0}});var Xke,ryn=b(()=>{Xke=class{constructor(e={}){this.config={method:"zscore-tanh",tanhScale:2.5,clipMin:.02,clipMax:.98};this.config={...this.config,...e}}updateExplanation(e,n,r){if(e)return{...e,baseScore:n,finalScore:r}}normalize(e){if(e.length===0)return e;switch(this.config.method){case"zscore-tanh":return this.normalizeZScoreTanh(e);case"minmax":return this.normalizeMinMax(e);case"percentile":return this.normalizePercentile(e);default:return e}}normalizeZScoreTanh(e){let n=e.map(c=>c.score),r=n.reduce((c,u)=>c+u,0)/n.length,o=n.reduce((c,u)=>c+Math.pow(u-r,2),0)/n.length,i=Math.sqrt(o);if(i===0)return e.map(c=>({...c,score:.5,explanation:this.updateExplanation(c.explanation,c.score,.5)}));let s=this.config.tanhScale||2.5,a=this.config.clipMin||.02,l=this.config.clipMax||.98;return e.map(c=>{let u=(c.score-r)/i,d=.5+.5*Math.tanh(u/s),f=Math.max(a,Math.min(l,d));return{...c,score:f,explanation:this.updateExplanation(c.explanation,c.score,f)}})}normalizeMinMax(e){let n=e.map(l=>l.score),r=Math.min(...n),o=Math.max(...n);if(o===r)return e.map(l=>({...l,score:.5,explanation:this.updateExplanation(l.explanation,l.score,.5)}));let i=this.config.clipMin||.02,s=this.config.clipMax||.98;return e.map(l=>{let c=(l.score-r)/(o-r),u=i+c*(s-i);return{...l,score:u,explanation:this.updateExplanation(l.explanation,l.score,u)}})}normalizePercentile(e){let n=e.length,r=this.config.clipMin||.02,o=this.config.clipMax||.98,i=[...e].sort((a,l)=>a.score-l.score),s=new Map;return i.forEach((a,l)=>{let c=l/(n-1),u=r+c*(o-r);s.set(a.id,u)}),e.map(a=>{let l=s.get(a.id)||.5;return{...a,score:l,explanation:this.updateExplanation(a.explanation,a.score,l)}})}getStatistics(e){if(e.length===0)return{mean:0,std:0,min:0,max:0,median:0};let n=e.map(u=>u.score),r=[...n].sort((u,d)=>u-d),o=n.reduce((u,d)=>u+d,0)/n.length,i=n.reduce((u,d)=>u+Math.pow(d-o,2),0)/n.length,s=Math.sqrt(i),a=r[0],l=r[r.length-1],c=r[Math.floor(r.length/2)];return{mean:o,std:s,min:a,max:l,median:c}}}});function m1r(t,e){return t.length<=e?t:tyn(t,{floor:0,ceiling:e,relativeThreshold:0,absoluteMinScore:0,ensureDiversity:!0}).results}var zrt,al,Qke,S3=b(()=>{gt();pe();Zte();Zgn();Ygn();Jgn();Xgn();eyn();nyn();ryn();zrt=3,al=100,Qke=class{constructor(e,n){this.app=e;this.getChatModel=n;this.grepScanner=new Gke(e),this.chunkManager=DM(e),this.fullTextEngine=new Wke(e,this.chunkManager),this.queryExpander=new qke({getChatModel:this.getChatModel,maxVariants:3,timeout:Koe}),this.folderBoostCalculator=new Yke(e),this.graphBoostCalculator=new Jke(e,{enabled:!0,maxCandidates:20,boostStrength:.1,maxBoostMultiplier:1.15}),this.scoreNormalizer=new Xke({method:"minmax",clipMin:.02,clipMax:.98})}async retrieve(e,n={}){let r={queries:[],salientTerms:[],originalQuery:e||"",expandedQueries:[]};if(!e||typeof e!="string")return W("SearchCore: Invalid query provided"),{results:[],queryExpansion:r};let o=e.trim();if(o.length===0)return W("SearchCore: Empty query provided"),{results:[],queryExpansion:r};o.length>1e3?(W("SearchCore: Query too long, truncating"),e=o.substring(0,1e3)):e=o;let i=!!n.returnAll,s=i?al:Math.min(Math.max(1,n.maxResults||30),100),a=i?al:Math.min(Math.max(10,n.candidateLimit||200),1e3),l=!!(n.enableLexicalBoosts??!0);try{j(`SearchCore: Searching for "${e}"`);let c;n.preExpandedQuery?(j("SearchCore: Using pre-expanded query data (skipping QueryExpander)"),c={queries:n.preExpandedQuery.queries||[e],salientTerms:n.preExpandedQuery.salientTerms||[],originalQuery:n.preExpandedQuery.originalQuery||e,expandedQueries:n.preExpandedQuery.expandedQueries||[]}):c=await this.queryExpander.expand(e);let u=c.queries,d=n.salientTerms?[...new Set([...c.salientTerms,...n.salientTerms])]:c.salientTerms,f=[],p=new Set,m=_=>{if(!_)return;let S=_.toLowerCase();S.length===0||p.has(S)||(p.add(S),f.push(S))};u.forEach(m),d.forEach(m),(u.length>1||d.length>0)&&j(`Query expansion: variants=${JSON.stringify(u)}, salient=${JSON.stringify(d)}`);let h=i?al:200,g=await this.grepScanner.batchCachedReadGrep(f,h),v=g.slice(0,a);j(`SearchCore: ${v.length} candidates (from ${g.length} grep hits)`);let w=await this.executeLexicalSearch(v,f,d,s,c.originalQuery,i);if(l&&(w=this.folderBoostCalculator.applyBoosts(w),w=this.graphBoostCalculator.applyBoost(w)),w=this.scoreNormalizer.normalize(w),this.fullTextEngine.clear(),w.length>s&&(w=m1r(w,s)),w.length>0){let _=this.app.vault.getAbstractFileByPath(w[0].id);j(`SearchCore: ${w.length} results found (top: ${_?.name||w[0].id})`)}else j("SearchCore: No results found");return{results:w,queryExpansion:c}}catch(c){H("SearchCore: Retrieval failed",c);try{return{results:await this.fallbackSearch(e,s),queryExpansion:r}}catch(u){return H("SearchCore: Fallback search also failed",u),{results:[],queryExpansion:r}}}}async fallbackSearch(e,n){try{return(await this.grepScanner.grep(e,n)).map((o,i)=>({id:o,score:1/(i+1),engine:"grep"}))}catch(r){return H("SearchCore: Fallback search failed",r),[]}}getStats(){return{fullTextStats:this.fullTextEngine.getStats()}}getChunkManager(){return this.chunkManager}clear(){this.fullTextEngine.clear(),this.queryExpander.clearCache(),j("SearchCore: Cleared all caches")}async executeLexicalSearch(e,n,r,o,i,s=!1){try{let a=Date.now(),l=await this.fullTextEngine.buildFromCandidates(e),c=Date.now()-a,u=Date.now(),d=s?al:Number.isFinite(o)?Math.min(o,1e3):e.length||30,f=s?al*zrt:Math.max(d*zrt,zrt),p=this.fullTextEngine.search(n,f,r,i),m=Date.now()-u;return j(`Full-text: ${l} docs indexed (${c}ms), ${p.length} results (${m}ms)`),p}catch(a){return H("Full-text search failed",a),[]}}}});var tIe,oyn=b(()=>{_v();GH();pe();El();Se();ut();$M();ine();eke();tIe=class extends HM{constructor(n,r){super();this.options=n;this.vault=r;this.lc_namespace=["hybrid_retriever"]}async getRelevantDocuments(n){return Jf(async()=>{let r=j_(n,this.vault),o=r.map(p=>p.basename),i=[...new Set([...this.options.salientTerms,...o])],s=await this.getExplicitChunks(r),a=await this.getOramaChunks(n,i,this.options.textWeight),l=this.filterAndFormatChunks(a,s),c=l;if(l.length===0)return Y().debug&&j("No chunks found for query:",n),c;let u=l.reduce((p,m)=>{let h=m.metadata.score;return typeof h=="number"&&!isNaN(h)?Math.max(p,h):p},0),d=l.every(p=>typeof p.metadata.score!="number"||isNaN(p.metadata.score)),f=this.options.useRerankerThreshold&&(u<this.options.useRerankerThreshold||d);return f&&(c=(await Gi.getInstance().rerank(n,l.map(m=>m.pageContent.slice(0,3e3)))).response.data.map(m=>({...l[m.index],metadata:{...l[m.index].metadata,rerank_score:m.relevance_score}}))),Y().debug&&(j("*** HYBRID RETRIEVER DEBUG INFO: ***"),j(`
Explicit Chunks: `,s),j("Orama Chunks: ",a),j("Combined Chunks: ",l),j("Max Orama Score: ",u),f?j("Reranked Chunks: ",c):j("No reranking applied.")),c})}async getExplicitChunks(n){let r=[];for(let o of n){let i=await qv.getInstance().getDocumentsByPath(o.path);if(i.length===0)continue;let s=i.map(a=>new cu({pageContent:a.content,metadata:{...a.metadata,score:1,path:a.path,mtime:a.mtime,ctime:a.ctime,title:a.title,id:a.id,embeddingModel:a.embeddingModel,tags:a.tags,extension:a.extension,created_at:a.created_at,nchars:a.nchars,chunkId:a.metadata?.chunkId}}));r.push(...s)}return r}async getOramaChunks(n,r,o){let i;try{i=await this.convertQueryToVector(n)}catch(c){throw H("Error in convertQueryToVector, please ensure your embedding model is working and has an adequate context length:",c,`
Query:`,n),c}let s=await qv.getInstance().getDb(),a={similarity:this.options.minSimilarityScore,limit:this.options.maxK,includeVectors:!0};if(r.length>0){let c;o||(o=.5),c=1-o;let u=!0;for(let d of r)if(!d.startsWith("#")){u=!1;break}u&&(Y().debug&&j("Tag only query detected, setting textWeight to 1 and vectorWeight to 0."),o=1,c=0),a.mode="hybrid",a.term=r.join(" "),a.vector={value:i,property:"embedding"},a.hybridWeights={text:o,vector:c}}else a.mode="vector",a.vector={value:i,property:"embedding"};if(this.options.timeRange){let{startTime:c,endTime:u}=this.options.timeRange,d=this.generateDailyNoteDateRange(c,u);j("Daily note date range:",d[0],d[d.length-1]);let f=j_(d.join(", "),this.vault),m=(await this.getExplicitChunks(f)).map(w=>({...w,metadata:{...w.metadata,includeInContext:!0}}));j("Modified time range:",c,u),a.where={mtime:{between:[c,u]}};let g=(await ah(s,a)).hits.map(w=>new cu({pageContent:w.document.content,metadata:{...w.document.metadata,score:w.score,path:w.document.path,mtime:w.document.mtime,ctime:w.document.ctime,title:w.document.title,id:w.document.id,embeddingModel:w.document.embeddingModel,tags:w.document.tags,extension:w.document.extension,created_at:w.document.created_at,nchars:w.document.nchars,chunkId:w.document.metadata?.chunkId}})),v=[...m,...g];return Array.from(new Set(v.map(w=>w.metadata.id))).map(w=>v.find(_=>_.metadata.id===w)).filter(w=>w!==void 0)}j(`Orama search params:
`,a);let l=await ah(s,a);return!l||!l.hits?(W("Search results or hits are undefined"),[]):l.hits.map(c=>!c||!c.document?(W("Invalid hit or document in search results"),null):((typeof c.score!="number"||isNaN(c.score))&&W("NaN/invalid score detected:",{score:c.score,path:c.document.path,title:c.document.title}),new cu({pageContent:c.document.content||"",metadata:{...c.document.metadata||{},score:c.score,path:c.document.path||"",mtime:c.document.mtime,ctime:c.document.ctime,title:c.document.title||"",id:c.document.id,embeddingModel:c.document.embeddingModel,tags:c.document.tags||[],extension:c.document.extension,created_at:c.document.created_at,nchars:c.document.nchars,chunkId:c.document.metadata?.chunkId}}))).filter(c=>c!==null)}async convertQueryToVector(n){let o=await(await Gc.getInstance().getEmbeddingsAPI()).embedQuery(n);if(o.length===0)throw new Error("Query embedding returned an empty vector");return o}generateDailyNoteDateRange(n,r){let o=[],i=new Date(n),s=new Date(r),a=new Date(i);for(;a<=s;)o.push(`[[${a.toLocaleDateString("en-CA")}]]`),a.setDate(a.getDate()+1);return o}filterAndFormatChunks(n,r){let o=this.options.minSimilarityScore,i=n.filter(l=>{let c=l.metadata.score;return typeof c!="number"||isNaN(c)?!0:c>=o}),s=new Set(r.map(l=>l.pageContent)),a=[...r];for(let l of i){let c=l.pageContent;s.has(c)||(s.add(c),a.push(l))}return a.map(l=>({...l,metadata:{...l.metadata,includeInContext:!0}}))}}});function Hrt(t){let e=[];for(let n of t)n.type==="tool_use"&&e.push({name:n.name,args:n.input,id:n.id,type:"tool_call"});return e}var iyn,Wrt=b(()=>{tv();a4();iyn=class extends i4{constructor(e){super(e);M(this,"lc_namespace",["langchain","anthropic","output_parsers"]);M(this,"returnId",!1);M(this,"keyName");M(this,"returnSingle",!1);M(this,"zodSchema");M(this,"serializableSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema,this.serializableSchema=e.serializableSchema}static lc_name(){return"AnthropicToolsOutputParser"}async _validateResult(e){let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch(o){throw new Cd(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(o.message)}`,e)}else n=e;if(this.serializableSchema!==void 0){let o=await this.serializableSchema["~standard"].validate(n);if(o.issues)throw new Cd(`Failed to parse. Text: "${JSON.stringify(n,null,2)}". Error: ${JSON.stringify(o.issues)}`,JSON.stringify(n,null,2));return o.value}if(this.zodSchema===void 0)return n;let r=await oL(this.zodSchema,n);if(r.success)return r.data;throw new Cd(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.error.issues)}`,JSON.stringify(n,null,2))}async parseResult(e){let n=e.flatMap(o=>{let{message:i}=o;return Array.isArray(i.content)?Hrt(i.content)[0]:[]});if(n[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");let[r]=n;return await this._validateResult(r.args)}}});function syn(t){return typeof t.input_schema!="object"||t.input_schema===null?[]:g1r.filter(e=>Object.prototype.hasOwnProperty.call(t.input_schema,e))}function ayn(t){if(t)return t==="any"||t==="required"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}var g1r,lyn,Vrt,cyn=b(()=>{Eb();g1r=["oneOf","anyOf","allOf"];lyn=Ace({cache_control:Lce().optional().nullable(),defer_loading:fj().optional(),input_examples:_P(lx()).optional(),allowed_callers:_P(lx()).optional(),strict:fj().optional()}),Vrt={tool_search_tool_regex_20251119:"advanced-tool-use-2025-11-20",tool_search_tool_bm25_20251119:"advanced-tool-use-2025-11-20",memory_20250818:"context-management-2025-06-27",web_fetch_20250910:"web-fetch-2025-09-10",code_execution_20250825:"code-execution-2025-08-25",computer_20251124:"computer-use-2025-11-24",computer_20250124:"computer-use-2025-01-24",mcp_toolset:"mcp-client-2025-11-20"}});function uyn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function dyn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function nIe(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="compaction"}function fyn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function pyn(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}var myn,qrt=b(()=>{oi();myn={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){let e=hf({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){let e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}}});var rIe,Krt=b(()=>{rIe=t=>t()});function y1r(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function v1r(t){function*e(){for(let n of t)y1r(n)&&(n.source==="char"?yield{type:"char_location",file_id:n.url??"",start_char_index:n.startIndex??0,end_char_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="page"?yield{type:"page_location",file_id:n.url??"",start_page_number:n.startIndex??0,end_page_number:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="block"?yield{type:"content_block_location",file_id:n.url??"",start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="url"?yield{type:"web_search_result_location",url:n.url??"",title:n.title??null,encrypted_index:String(n.startIndex??0),cited_text:n.citedText??""}:n.source==="search"&&(yield{type:"search_result_location",title:n.title??null,start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,search_result_index:0,source:n.source??"",cited_text:n.citedText??""}))}return Array.from(e())}function cne(t){return typeof t=="string"?t:w1r(t)}function w1r(t){let e=[];for(let n=0,{length:r}=t;n<r;n++)e.push(String.fromCharCode(t[n]));return btoa(e.join(""))}function Grt(t){return(t??"").split(";")[0].toLowerCase()}function une(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function C3(t,e){let n=une(e,"cache_control");n!==void 0&&(t.cache_control=n);let r=une(e,"citations");r!==void 0&&(t.citations=r);let o=une(e,"context");o!==void 0&&(t.context=o);let i=une(e,"title");return i!==void 0&&(t.title=i),t}function Zrt(t,e){let n=une(e,"cache_control");return n!==void 0&&(t.cache_control=n),t}function hyn(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function gyn(t){let e=[],n=t.response_metadata,r="model_provider"in n&&n?.model_provider==="anthropic";for(let o of t.contentBlocks)if(o.type==="text")o.annotations?e.push({type:"text",text:o.text,citations:v1r(o.annotations)}):e.push({type:"text",text:o.text});else if(o.type==="tool_call")e.push({type:"tool_use",id:o.id??"",name:o.name,input:o.args});else if(o.type==="tool_call_chunk"){let i=rIe(()=>{if(typeof o.args!="string")return o.args;try{return JSON.parse(o.args)}catch{return{}}});e.push({type:"tool_use",id:o.id??"",name:o.name??"",input:i})}else if(o.type==="reasoning"&&r)e.push({type:"thinking",thinking:o.reasoning,signature:String(o.signature)});else if(o.type==="server_tool_call"&&r)o.name==="web_search"?e.push({type:"server_tool_use",name:o.name,id:o.id??"",input:o.args}):o.name==="code_execution"&&e.push({type:"server_tool_use",name:o.name,id:o.id??"",input:o.args});else if(o.type==="server_tool_call_result"&&r)if(o.name==="web_search"&&Array.isArray(o.output.urls)){let i=o.output.urls.map(s=>({type:"web_search_result",title:"",encrypted_content:"",url:s}));e.push({type:"web_search_tool_result",tool_use_id:o.toolCallId??"",content:i})}else o.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:o.toolCallId??"",content:o.output}):o.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:o.toolCallId??"",content:o.output});else{if(o.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(o.type==="file"){let i=o.metadata;if(o.fileId){e.push(C3({type:"document",source:{type:"file",file_id:o.fileId}},i));continue}if(o.url){let s=Grt(o.mimeType);if(s==="application/pdf"||s===""){e.push(C3({type:"document",source:{type:"url",url:o.url}},i));continue}}if(o.data){let s=Grt(o.mimeType);if(s===""||s==="application/pdf")e.push(C3({type:"document",source:{type:"base64",data:cne(o.data),media_type:"application/pdf"}},i));else if(s==="text/plain")e.push(C3({type:"document",source:{type:"text",data:cne(o.data),media_type:"text/plain"}},i));else if(hyn(s))e.push(C3({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:cne(o.data),media_type:s}}]}},i));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${s}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(o.type==="image"){let i=o.metadata;if(o.fileId){e.push(Zrt({type:"image",source:{type:"file",file_id:o.fileId}},i));continue}if(o.url){e.push(Zrt({type:"image",source:{type:"url",url:o.url}},i));continue}if(o.data){let s=Grt(o.mimeType)||"image/png";hyn(s)&&e.push(Zrt({type:"image",source:{type:"base64",data:cne(o.data),media_type:s}},i));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else o.type==="video"||(o.type==="text-plain"?o.data&&e.push(C3({type:"document",source:{type:"text",data:cne(o.data),media_type:"text/plain"}},o.metadata)):o.type==="non_standard"&&r&&e.push(o.value))}return e}var yyn=b(()=>{Krt()});function Yrt(t){let e=hf({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let n;try{n=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
`))}if(n.protocol==="http:"||n.protocol==="https:")return{type:"url",url:t};throw new Error([`Invalid image URL protocol: ${JSON.stringify(n.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
`))}function b1r(t){let e=[];for(let n of t)if(n._getType()==="tool")if(typeof n.content=="string"){let r=e[e.length-1];r?._getType()==="human"&&Array.isArray(r.content)&&"type"in r.content[0]&&r.content[0].type==="tool_result"?r.content.push({type:"tool_result",content:n.content,tool_use_id:n.tool_call_id}):e.push(new na({content:[{type:"tool_result",content:n.content,tool_use_id:n.tool_call_id}]}))}else e.push(new na({content:[{type:"tool_result",...n.content!=null?{content:Xrt(n)}:{},tool_use_id:n.tool_call_id}]}));else e.push(n);return e}function Jrt(t){if(t.id===void 0)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:t.id,name:t.name,input:t.args}}function*_1r(t,e){let n=["bash_code_execution_tool_result","input_json_delta","server_tool_use","text_editor_code_execution_tool_result","tool_result","tool_use","web_search_result","web_search_tool_result"],r=["text","text_delta"];for(let o of t){mf(o)&&(yield qk(o,myn));let i="cache_control"in o?o.cache_control:void 0;if(o.type==="image_url"){let s;typeof o.image_url=="string"?s=Yrt(o.image_url):typeof o.image_url=="object"&&o.image_url!==null&&"url"in o.image_url&&typeof o.image_url.url=="string"&&(s=Yrt(o.image_url.url)),s&&(yield{type:"image",source:s,...i?{cache_control:i}:{}})}else if(pyn(o))yield o;else if(o.type==="image"){let s;"url"in o&&typeof o.url=="string"?s=Yrt(o.url):"data"in o&&(typeof o.data=="string"||o.data instanceof Uint8Array)?s={type:"base64",media_type:"mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:"image/jpeg",data:typeof o.data=="string"?o.data:Buffer.from(o.data).toString("base64")}:"fileId"in o&&typeof o.fileId=="string"&&(s={type:"file",file_id:o.fileId}),s&&(yield{type:"image",source:s,...i?{cache_control:i}:{}})}else if(o.type==="file"){let s;"url"in o&&typeof o.url=="string"?s={type:"url",url:o.url}:"data"in o&&(typeof o.data=="string"||o.data instanceof Uint8Array)?s={type:"base64",media_type:"mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:"application/pdf",data:typeof o.data=="string"?o.data:Buffer.from(o.data).toString("base64")}:"fileId"in o&&typeof o.fileId=="string"&&(s={type:"file",file_id:o.fileId}),s&&(yield{type:"document",source:s,...i?{cache_control:i}:{}})}else if(o.type==="document")yield{...o,...i?{cache_control:i}:{}};else if(uyn(o))yield{type:"thinking",thinking:o.thinking,signature:o.signature,...i?{cache_control:i}:{}};else if(dyn(o))yield{type:"redacted_thinking",data:o.data,...i?{cache_control:i}:{}};else if(nIe(o))yield{type:"compaction",content:o.content,...i?{cache_control:i}:{}};else if(fyn(o))yield{type:"search_result",title:o.title,source:o.source,..."cache_control"in o&&o.cache_control?{cache_control:o.cache_control}:{},..."citations"in o&&o.citations?{citations:o.citations}:{},content:o.content};else if(r.find(s=>s===o.type)&&"text"in o)yield{type:"text",text:o.text,...i?{cache_control:i}:{},..."citations"in o&&o.citations?{citations:o.citations}:{}};else if(n.find(s=>s===o.type)){let s={...o};if(s.type==="input_json_delta")continue;if(s.type==="tool_use"&&typeof s.input=="string"){let a=e?.find(l=>l.id===s.id);a?s.input=a.args:s.input=t.filter(l=>l.index===s.index&&l.type==="input_json_delta"&&typeof l.input=="string").reduce((l,c)=>l+c.input,s.input)}if("index"in s&&delete s.index,"input"in s&&typeof s.input=="string")try{s.input=JSON.parse(s.input)}catch{s.input={}}yield{...s,...i?{cache_control:i}:{}}}else o.type==="container_upload"&&(yield{...o,...i?{cache_control:i}:{}})}}function Xrt(t,e){let{content:n}=t;return typeof n=="string"?n:Array.from(_1r(n,e))}function dne(t){let e=b1r(t),n;return e.length>0&&e[0]._getType()==="system"&&(n=t[0].content),{messages:x1r((n!==void 0?e.slice(1):e).map(r=>{let o;if(r._getType()==="human")o="user";else if(r._getType()==="ai")o="assistant";else if(r._getType()==="tool")o="user";else throw r._getType()==="system"?new Error("System messages are only permitted as the first passed message."):new Error(`Message type "${r.type}" is not supported.`);if(cr.isInstance(r)&&r.response_metadata?.output_version==="v1")return{role:o,content:gyn(r)};if(cr.isInstance(r)&&r.tool_calls?.length){if(typeof r.content=="string")return r.content===""?{role:o,content:r.tool_calls.map(Jrt)}:{role:o,content:[{type:"text",text:r.content},...r.tool_calls.map(Jrt)]};{let{content:i}=r,s=Xrt(r,r.tool_calls),a=Array.isArray(s)?s:[{type:"text",text:s}],l=r.tool_calls.filter(c=>!i.find(u=>(u.type==="tool_use"||u.type==="input_json_delta"||u.type==="server_tool_use")&&u.id===c.id));return{role:o,content:[...a,...l.map(Jrt)]}}}else return{role:o,content:Xrt(r,cr.isInstance(r)?r.tool_calls:void 0)}})),system:n}}function x1r(t){if(!t||t.length<=1)return t;let e=[],n=t[0],r=i=>typeof i=="string"?[{type:"text",text:i}]:i,o=i=>i.role!=="user"||typeof i.content=="string"?!1:Array.isArray(i.content)&&i.content.every(s=>s.type==="tool_result");for(let i=1;i<t.length;i+=1){let s=t[i];o(n)&&o(s)?n={...n,content:[...r(n.content),...r(s.content)]}:(e.push(n),n=s)}return e.push(n),e}var Qrt=b(()=>{qrt();yyn();oi()});function eot(t,e){return t?e.some(n=>t.startsWith(n)):!1}function vyn(t){return t.type==="enabled"||t.type==="adaptive"}function C1r(t){return eot(t,["claude-opus-4-7"])}function wyn(t){return eot(t,S1r)}function byn(t,e){let n=e&&typeof e=="object"&&"task_budget"in e&&e.task_budget!=null;return C1r(t)&&n?["task-budgets-2026-03-13"]:[]}function _yn(t){let{model:e,thinking:n,outputConfig:r,topK:o,topP:i,temperature:s}=t,a=wyn(e),l=e??"this model";if(a&&n.type==="enabled")throw new Error(`thinking.type="enabled" is not supported for ${l}; use thinking.type="adaptive" instead`);if(a&&typeof n=="object"&&n!=null&&"budget_tokens"in n)throw new Error(`thinking.budget_tokens is not supported for ${l}; use outputConfig.effort instead`);if(eot(e,["claude-opus-5"])&&n.type==="disabled"&&(r?.effort==="xhigh"||r?.effort==="max"))throw new Error(`thinking.type="disabled" is not supported for ${l} with outputConfig.effort="${r.effort}"; use thinking.type="adaptive" or omit thinking instead`);if(a){if(o!==void 0)throw new Error(`topK is not supported for ${l}; omit topK/topP/temperature or use model prompting instead`);if(i!==void 0&&i!==1)throw new Error(`topP is not supported for ${l} when set to non-default values`);if(s!==void 0&&s!==1)throw new Error(`temperature is not supported for ${l} when set to non-default values`)}if(vyn(n)){if(o!==void 0)throw new Error("topK is not supported when thinking is enabled");if(i!==void 0)throw new Error("topP is not supported when thinking is enabled");if(s!==void 0&&s!==1)throw new Error("temperature is not supported when thinking is enabled")}}function xyn(t){let{model:e,thinking:n,topK:r,topP:o,temperature:i}=t,s={};return vyn(n)||wyn(e)||(i!==void 0&&(s.temperature=i),r!==void 0&&(s.top_k=r),o!==void 0&&(s.top_p=o)),s}var S1r,Syn=b(()=>{S1r=["claude-opus-4-7","claude-opus-4-8","claude-opus-5","claude-fable-5","claude-mythos-5","claude-mythos-preview"]});function Cyn(t,e){let n={model_provider:"anthropic"};if(t.type==="message_start"){let{content:r,usage:o,...i}=t.message,s={};for(let[d,f]of Object.entries(i))f!=null&&(s[d]=f);let{input_tokens:a,output_tokens:l,...c}=o??{},u=Iyn(o);return{chunk:new On({content:e.coerceContentToString?"":[],additional_kwargs:s,usage_metadata:e.streamUsage?u:void 0,response_metadata:{...n,usage:{...c}},id:t.message.id})}}else if(t.type==="message_delta"){let r={input_tokens:0,output_tokens:t.usage.output_tokens,total_tokens:t.usage.output_tokens},o=rIe(()=>{let i={};return"context_management"in t.delta&&(i.context_management=t.delta.context_management),"usage"in t&&"cost"in t.usage&&typeof t.usage.cost=="number"&&(i.usage={cost:t.usage.cost}),i});return{chunk:new On({content:e.coerceContentToString?"":[],response_metadata:o,additional_kwargs:{...t.delta},usage_metadata:e.streamUsage?r:void 0})}}else if(t.type==="content_block_start"&&["tool_use","document","server_tool_use","web_search_tool_result"].includes(t.content_block.type)){let r=t.content_block,o;return r.type==="tool_use"?o=[{id:r.id,index:t.index,name:r.name,args:""}]:o=[],{chunk:new On({content:e.coerceContentToString?"":[{index:t.index,...t.content_block,input:r.type==="server_tool_use"||r.type==="tool_use"?"":void 0}],response_metadata:n,additional_kwargs:{},tool_call_chunks:o})}}else if(t.type==="content_block_delta"&&["text_delta","citations_delta","thinking_delta","signature_delta"].includes(t.delta.type)){if(e.coerceContentToString&&"text"in t.delta)return{chunk:new On({content:t.delta.text})};{let r=t.delta;return"citation"in r&&(r.citations=[r.citation],delete r.citation),r.type==="thinking_delta"||r.type==="signature_delta"?{chunk:new On({content:[{index:t.index,...r,type:"thinking"}],response_metadata:n})}:{chunk:new On({content:[{index:t.index,...r,type:"text"}],response_metadata:n})}}}else{if(t.type==="content_block_delta"&&t.delta.type==="input_json_delta")return{chunk:new On({content:e.coerceContentToString?"":[{index:t.index,input:t.delta.partial_json,type:t.delta.type}],response_metadata:n,additional_kwargs:{},tool_call_chunks:[{index:t.index,args:t.delta.partial_json}]})};if(t.type==="content_block_start"&&t.content_block.type==="text"){let r=t.content_block?.text;if(r!==void 0)return{chunk:new On({content:e.coerceContentToString?r:[{index:t.index,...t.content_block}],response_metadata:n,additional_kwargs:{}})}}else{if(t.type==="content_block_start"&&t.content_block.type==="redacted_thinking")return{chunk:new On({content:e.coerceContentToString?"":[{index:t.index,...t.content_block}],response_metadata:n})};if(t.type==="content_block_start"&&t.content_block.type==="thinking"){let r=t.content_block.thinking;return{chunk:new On({content:e.coerceContentToString?r:[{index:t.index,...t.content_block}],response_metadata:n})}}else{if(t.type==="content_block_start"&&nIe(t.content_block))return{chunk:new On({content:e.coerceContentToString?"":[{index:t.index,...t.content_block}],response_metadata:n})};if(t.type==="content_block_delta"&&t.delta.type==="compaction_delta")return{chunk:new On({content:e.coerceContentToString?"":[{index:t.index,...t.delta,type:"compaction"}],response_metadata:n})}}}}return null}function kyn(t,e){let n={...e,model_provider:"anthropic"},r=e.usage,o=r!=null?Iyn(r):void 0;return t.length===1&&t[0].type==="text"?[{text:t[0].text,message:new cr({content:t[0].text,additional_kwargs:e,usage_metadata:o,response_metadata:n,id:e.id})}]:[{text:"",message:new cr({content:t,additional_kwargs:e,tool_calls:Hrt(t),usage_metadata:o,response_metadata:n,id:e.id})}]}function Iyn(t){let e=t.cache_creation_input_tokens??0,n=t.cache_read_input_tokens??0,r=t.input_tokens+e+n;return{input_tokens:r,output_tokens:t.output_tokens,total_tokens:r+t.output_tokens,input_token_details:{cache_creation:e,cache_read:n}}}var Tyn=b(()=>{Wrt();qrt();Krt();oi()});function fne(t,e){return t.lc_error_code=e,t.message=`${t.message}
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
`,t}function tot(t){let e;return t.status===400&&typeof t.message=="string"&&t.message.includes("prompt is too long")?e=fne(Wme.fromError(t),"CONTEXT_OVERFLOW"):t.status===400&&t.message.includes("tool")?e=Gl(fne(t,"INVALID_TOOL_RESULTS"),!1):t.status===401?e=Gl(fne(t,"MODEL_AUTHENTICATION"),!1):t.status===404?e=Gl(fne(t,"MODEL_NOT_FOUND"),!1):t.status===429?e=Gl(fne(t,"MODEL_RATE_LIMIT"),!0):e=t,e}var Pyn=b(()=>{Kk()});var Ayn,Eyn=b(()=>{Ayn={"claude-sonnet-4-6":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-6":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-fable-5":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-8":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-1":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5-20250929":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-5-20251101":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5-20251001":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-7":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-5":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-5":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-1-20250805":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0}}});async function*Myn(t,e={}){let n=e.streamUsage??!0,r=new Map,o,i={},s=null;for await(let a of t)switch(a.type){case"message_start":{let{usage:l,id:c,model:u}=a.message;l&&n&&(o=I1r(l)),yield{event:"message-start",id:c,...o?{usage:o}:{}},yield{event:"provider",provider:"anthropic",name:"message_start",payload:{model:u,id:c}};break}case"message_delta":s=a.delta.stop_reason,"usage"in a&&"cost"in a.usage&&typeof a.usage.cost=="number"&&(i={usage:{cost:a.usage.cost}}),n&&a.usage&&(o?o={...o,output_tokens:o.output_tokens+a.usage.output_tokens,total_tokens:o.input_tokens+o.output_tokens+a.usage.output_tokens}:o={input_tokens:0,output_tokens:a.usage.output_tokens,total_tokens:a.usage.output_tokens},yield{event:"usage",usage:o}),"context_management"in a.delta&&a.delta.context_management&&(yield{event:"provider",provider:"anthropic",name:"context_management",payload:a.delta.context_management});break;case"message_stop":yield{event:"message-finish",reason:k1r(s),...o?{usage:o}:{},metadata:{model_provider:"anthropic"},responseMetadata:i};break;case"content_block_start":{let{index:l,content_block:c}=a,u=T1r(c,l);r.set(l,{...u}),yield{event:"content-block-start",index:l,content:u};break}case"content_block_delta":{let{index:l,delta:c}=a,u=r.get(l);if(!u)break;let{contentDelta:d,accumulated:f}=P1r(u,c);r.set(l,f),yield{event:"content-block-delta",index:l,delta:d};break}case"content_block_stop":{let{index:l}=a,c=r.get(l);if(!c)break;yield{event:"content-block-finish",index:l,content:A1r(c)},r.delete(l);break}default:yield{event:"provider",provider:"anthropic",name:a.type,payload:a};break}}function k1r(t){switch(t){case"end_turn":case"stop_sequence":return"stop";case"tool_use":return"tool_use";case"max_tokens":return"length";default:return"stop"}}function I1r(t){let e=t.cache_creation_input_tokens??0,n=t.cache_read_input_tokens??0,r=t.input_tokens+e+n;return{input_tokens:r,output_tokens:t.output_tokens,total_tokens:r+t.output_tokens,input_token_details:{cache_creation:e,cache_read:n}}}function T1r(t,e){switch(t.type){case"text":return{type:"text",text:t.text??"",index:e};case"thinking":return{type:"reasoning",reasoning:t.thinking??"",index:e};case"redacted_thinking":return{type:"non_standard",value:{...t},index:e};case"tool_use":return{type:"tool_call_chunk",id:t.id,name:t.name,args:"",index:e};case"server_tool_use":return{type:"server_tool_call_chunk",id:t.id,name:t.name,args:"",index:e};default:return{type:"non_standard",value:{...t},index:e}}}function P1r(t,e){switch(e.type){case"text_delta":return{contentDelta:{type:"text-delta",text:e.text},accumulated:{...t,text:(t.text??"")+e.text}};case"thinking_delta":return{contentDelta:{type:"reasoning-delta",reasoning:e.thinking},accumulated:{...t,reasoning:(t.reasoning??"")+e.thinking}};case"input_json_delta":{let n=(t.args??"")+e.partial_json;return{contentDelta:{type:"block-delta",fields:{type:t.type,args:n}},accumulated:{...t,args:n}}}case"citations_delta":{let n=[...t.annotations??[],e.citation];return{contentDelta:{type:"block-delta",fields:{type:t.type,annotations:n}},accumulated:{...t,annotations:n}}}case"signature_delta":return{contentDelta:{type:"block-delta",fields:{type:t.type,signature:e.signature}},accumulated:{...t,signature:e.signature}};case"compaction_delta":return{contentDelta:{type:"block-delta",fields:{type:"non_standard",value:{...t.value??{},compaction:e}}},accumulated:{...t,value:{...t.value??{},compaction:e}}};default:return{contentDelta:{type:"block-delta",fields:{type:t.type,...e}},accumulated:t}}}function A1r(t){if(t.type==="tool_call_chunk"||t.type==="server_tool_call_chunk"){let r=t.type==="tool_call_chunk"?"tool_call":"server_tool_call",o;try{o=JSON.parse(t.args||"{}")}catch{return{type:"invalid_tool_call",id:t.id,name:t.name,args:t.args,error:"Failed to parse tool call arguments as JSON"}}return{type:r,id:t.id,name:t.name,args:o}}let{index:e,...n}=t;return n}var Oyn=b(()=>{});function je(t,e,n,r,o){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(t,n):o?o.value=n:e.set(t,n),n}function ie(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)}var jg=b(()=>{});var k3,oIe=b(()=>{k3=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return k3=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))}});function Zv(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var OD,WM=b(()=>{OD=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)}});var vt,Ol,Fd,QS,I3,pne,T3,P3,A3,E3,M3,O3,N3,R3,_a=b(()=>{WM();vt=class extends Error{},Ol=class t extends vt{constructor(e,n,r,o,i){super(`${t.makeMessage(e,n,r)}`),this.status=e,this.headers=o,this.requestID=o?.get("request-id"),this.error=n,this.type=i??null}static makeMessage(e,n,r){let o=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,n,r,o){if(!e||!o)return new QS({message:r,cause:OD(n)});let i=n,s=i?.error?.type;return e===400?new T3(e,i,r,o,s):e===401?new P3(e,i,r,o,s):e===403?new A3(e,i,r,o,s):e===404?new E3(e,i,r,o,s):e===409?new M3(e,i,r,o,s):e===422?new O3(e,i,r,o,s):e===429?new N3(e,i,r,o,s):e>=500?new R3(e,i,r,o,s):new t(e,i,r,o,s)}},Fd=class extends Ol{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},QS=class extends Ol{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}},I3=class extends QS{constructor({message:e}={}){super({message:e??"Request timed out."})}},pne=class extends vt{constructor(e,{cause:n}={}){super(e??"Retryable error."),n!==void 0&&(this.cause=n)}},T3=class extends Ol{},P3=class extends Ol{},A3=class extends Ol{},E3=class extends Ol{},M3=class extends Ol{},O3=class extends Ol{},N3=class extends Ol{},R3=class extends Ol{}});function mne(t){return typeof t!="object"?{}:t??{}}function rot(t){if(!t)return!0;for(let e in t)return!1;return!0}function Ryn(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var M1r,Nyn,Vf,not,Lyn,hne,Hp,x_=b(()=>{_a();M1r=/^[a-z][a-z0-9+.-]*:/i,Nyn=t=>M1r.test(t),Vf=t=>(Vf=Array.isArray,Vf(t)),not=Vf;Lyn=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new vt(`${t} must be an integer`);if(e<0)throw new vt(`${t} must be a positive integer`);return e},hne=t=>{try{return JSON.parse(t)}catch{return}},Hp=(t,e)=>{let n=t[e];return delete t[e],n}});var S_,L3=b(()=>{S_=(t,e)=>new Promise(n=>{if(e?.aborted)return n();let r=()=>{clearTimeout(o),n()},o=setTimeout(()=>{e?.removeEventListener("abort",r),n()},t);e?.addEventListener("abort",r,{once:!0})})});var Yv,gne=b(()=>{Yv="0.115.0"});function O1r(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function R1r(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:n}of t){let r=n.exec(navigator.userAgent);if(r){let o=r[1]||0,i=r[2]||0,s=r[3]||0;return{browser:e,version:`${o}.${i}.${s}`}}}return null}var Uyn,N1r,$yn,Dyn,Fyn,yne,iIe=b(()=>{gne();Uyn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";N1r=()=>{let t=O1r();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Yv,"X-Stainless-OS":Dyn(Deno.build.os),"X-Stainless-Arch":$yn(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Yv,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Yv,"X-Stainless-OS":Dyn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":$yn(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=R1r();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Yv,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Yv,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};$yn=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Dyn=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),yne=()=>Fyn??(Fyn=N1r())});function L1r(t,e){return()=>t.removeEventListener("abort",e)}function Byn(t,e,n){sIe.set(t,L1r(e,n))}function zyn(t,e){sIe.has(e)&&jyn?.register(t,e,e)}function eC(t){let e=sIe.get(t);e&&(sIe.delete(t),jyn?.unregister(t),e())}var sIe,jyn,aIe=b(()=>{sIe=new WeakMap,jyn=typeof globalThis.FinalizationRegistry=="function"?new globalThis.FinalizationRegistry(t=>eC(t)):null});function Hyn(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function oot(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function lIe(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return oot({start(){},async pull(n){let{done:r,value:o}=await e.next();r?n.close():n.enqueue(o)},async cancel(){await e.return?.()}})}function vne(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){let n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Wyn(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),n=e.cancel();e.releaseLock(),await n}var $3=b(()=>{});var Vyn,iot=b(()=>{Vyn=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)})});var sot,aot,lot,qyn,cot=b(()=>{sot="RFC3986",aot=t=>String(t),lot={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:aot},qyn="RFC1738"});function Gyn(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function dot(t,e){if(Vf(t)){let n=[];for(let r=0;r<t.length;r+=1)n.push(e(t[r]));return n}return e(t)}var cIe,tC,uot,Kyn,Zyn=b(()=>{cot();x_();cIe=(t,e)=>(cIe=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),cIe(t,e)),tC=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})(),uot=1024,Kyn=(t,e,n,r,o)=>{if(t.length===0)return t;let i=t;if(typeof t=="symbol"?i=Symbol.prototype.toString.call(t):typeof t!="string"&&(i=String(t)),n==="iso-8859-1")return escape(i).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let s="";for(let a=0;a<i.length;a+=uot){let l=i.length>=uot?i.slice(a,a+uot):i,c=[];for(let u=0;u<l.length;++u){let d=l.charCodeAt(u);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||o===qyn&&(d===40||d===41)){c[c.length]=l.charAt(u);continue}if(d<128){c[c.length]=tC[d];continue}if(d<2048){c[c.length]=tC[192|d>>6]+tC[128|d&63];continue}if(d<55296||d>=57344){c[c.length]=tC[224|d>>12]+tC[128|d>>6&63]+tC[128|d&63];continue}u+=1,d=65536+((d&1023)<<10|l.charCodeAt(u)&1023),c[c.length]=tC[240|d>>18]+tC[128|d>>12&63]+tC[128|d>>6&63]+tC[128|d&63]}s+=c.join("")}return s}});function F1r(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}function Qyn(t,e,n,r,o,i,s,a,l,c,u,d,f,p,m,h,g,v){let y=t,w=v,_=0,S=!1;for(;(w=w.get(fot))!==void 0&&!S;){let P=w.get(t);if(_+=1,typeof P<"u"){if(P===_)throw new RangeError("Cyclic object value");S=!0}typeof w.get(fot)>"u"&&(_=0)}if(typeof c=="function"?y=c(e,y):y instanceof Date?y=f?.(y):n==="comma"&&Vf(y)&&(y=dot(y,function(P){return P instanceof Date?f?.(P):P})),y===null){if(i)return l&&!h?l(e,du.encoder,g,"key",p):e;y=""}if(F1r(y)||Gyn(y)){if(l){let P=h?e:l(e,du.encoder,g,"key",p);return[m?.(P)+"="+m?.(l(y,du.encoder,g,"value",p))]}return[m?.(e)+"="+m?.(String(y))]}let I=[];if(typeof y>"u")return I;let C;if(n==="comma"&&Vf(y))h&&l&&(y=dot(y,l)),C=[{value:y.length>0?y.join(",")||null:void 0}];else if(Vf(c))C=c;else{let P=Object.keys(y);C=u?P.sort(u):P}let k=a?String(e).replace(/\./g,"%2E"):String(e),T=r&&Vf(y)&&y.length===1?k+"[]":k;if(o&&Vf(y)&&y.length===0)return T+"[]";for(let P=0;P<C.length;++P){let E=C[P],O=typeof E=="object"&&typeof E.value<"u"?E.value:y[E];if(s&&O===null)continue;let $=d&&a?E.replace(/\./g,"%2E"):E,U=Vf(y)?typeof n=="function"?n(T,$):T:T+(d?"."+$:"["+$+"]");v.set(t,_);let V=new WeakMap;V.set(fot,v),Xyn(I,Qyn(O,U,n,r,o,i,s,a,n==="comma"&&h&&Vf(y)?null:l,c,u,d,f,p,m,h,g,V))}return I}function U1r(t=du){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||du.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=sot;if(typeof t.format<"u"){if(!cIe(lot,t.format))throw new TypeError("Unknown format option provided.");n=t.format}let r=lot[n],o=du.filter;(typeof t.filter=="function"||Vf(t.filter))&&(o=t.filter);let i;if(t.arrayFormat&&t.arrayFormat in Jyn?i=t.arrayFormat:"indices"in t?i=t.indices?"indices":"repeat":i=du.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let s=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:du.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:du.addQueryPrefix,allowDots:s,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:du.allowEmptyArrays,arrayFormat:i,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:du.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?du.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:du.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:du.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:du.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:du.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:du.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:du.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:du.strictNullHandling}}function evn(t,e={}){let n=t,r=U1r(e),o,i;typeof r.filter=="function"?(i=r.filter,n=i("",n)):Vf(r.filter)&&(i=r.filter,o=i);let s=[];if(typeof n!="object"||n===null)return"";let a=Jyn[r.arrayFormat],l=a==="comma"&&r.commaRoundTrip;o||(o=Object.keys(n)),r.sort&&o.sort(r.sort);let c=new WeakMap;for(let f=0;f<o.length;++f){let p=o[f];r.skipNulls&&n[p]===null||Xyn(s,Qyn(n[p],p,a,l,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,c))}let u=s.join(r.delimiter),d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}var Jyn,Xyn,Yyn,du,fot,tvn=b(()=>{Zyn();cot();x_();Jyn={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Xyn=function(t,e){Array.prototype.push.apply(t,Vf(e)?e:[e])},du={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Kyn,encodeValuesOnly:!1,format:sot,formatter:aot,indices:!1,serializeDate(t){return(Yyn??(Yyn=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};fot={}});function nvn(t){return evn(t,{arrayFormat:"brackets"})}var pot=b(()=>{tvn()});function dIe(t){if(!t)return;let e;try{e=new URL(t)}catch(r){throw new ji(`Invalid token endpoint base URL "${t}": ${r}`)}if(e.protocol==="https:")return;let n=e.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(!(e.protocol==="http:"&&(n==="localhost"||n==="127.0.0.1"||n==="::1")))throw new ji(`Refusing to send credential over non-https token endpoint "${t}"`)}async function fIe(t,e){let n=await z1r(t),r;try{r=JSON.parse(n)}catch{throw new ji(`Token endpoint returned non-JSON response (status ${t.status})`,t.status,uh(n),e)}if(!r.access_token)throw new ji(`Token endpoint response missing access_token: ${JSON.stringify(uh(r))}`,t.status,uh(r),e);if(r.token_type&&r.token_type.toLowerCase()!=="bearer")throw new ji(`Token endpoint response: unsupported token_type "${r.token_type}" (want Bearer)`,t.status,uh(r),e);return r}function uh(t){if(t==null)return t;if(typeof t=="string"){let e;try{e=JSON.parse(t)}catch{return t.length<=mot?t:t.slice(0,mot)+`... <${t.length-mot} more chars>`}return JSON.stringify(uh(e))}if(typeof t=="object"&&!Array.isArray(t)){let e={};for(let[n,r]of Object.entries(t))B1r.has(n)&&(e[n]=r);return e}return null}async function pIe(t,e=n=>console.warn(`anthropic-sdk: ${n}`)){if(typeof process>"u"||process.platform==="win32")return;let n=await import("node:fs"),r=t,o;try{r=await n.promises.realpath(t),o=await n.promises.stat(r)}catch{return}let i=o.mode&511;if(i&18)throw new ji(`Credentials file at ${r} is group/world-writable (mode 0o${i.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${r}\`.`);if(i&36)throw new ji(`Credentials file at ${r} is group/world-readable (mode 0o${i.toString(8)}); run \`chmod 600 ${r}\` before retrying.`);typeof process.getuid=="function"&&o.uid!==process.getuid()&&e(`credentials file at ${r} is owned by uid ${o.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function mIe(t,e){let n=await import("node:fs"),o=(await import("node:path")).dirname(t);await n.promises.mkdir(o,{recursive:!0,mode:448});let i=`${t}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{let s=await n.promises.open(i,"w",384);try{await s.writeFile(JSON.stringify(e,null,2)),await s.sync()}finally{await s.close()}await n.promises.rename(i,t)}catch(s){throw await n.promises.unlink(i).catch(()=>{}),s}try{let s=await n.promises.open(o,"r");try{await s.sync()}finally{await s.close()}}catch{}}async function z1r(t){if(!t.body)return"";let e=t.body.getReader(),n=[],r=0;for(;;){let{done:i,value:s}=await e.read();if(i)break;if(r+s.length>rvn){let a=rvn-r;a>0&&n.push(s.subarray(0,a)),await e.cancel();break}n.push(s),r+=s.length}let o;if(n.length===1)o=n[0];else{o=new Uint8Array(n.reduce((s,a)=>s+a.length,0));let i=0;for(let s of n)o.set(s,i),i+=s.length}return new TextDecoder("utf-8").decode(o)}var ovn,ivn,uIe,ND,svn,avn,D3,lvn,rvn,mot,B1r,ji,F3=b(()=>{_a();ovn="urn:ietf:params:oauth:grant-type:jwt-bearer",ivn="refresh_token",uIe="/v1/oauth/token",ND="oauth-2025-04-20",svn="oidc-federation-2026-04-01",avn=120,D3=30,lvn=5,rvn=1<<20;mot=2e3,B1r=new Set(["error","error_description","error_uri"]);ji=class extends vt{constructor(e,n=null,r=null,o=null){super(e),this.statusCode=n,this.body=r,this.requestId=o}}});function C_(){return Math.floor(Date.now()/1e3)}var wne=b(()=>{});var hIe,cvn=b(()=>{F3();wne();hIe=class{constructor(e,n){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=e,this.onAdvisoryRefreshError=n}async getToken(){let e=this.nextForce;this.nextForce=!1;let n=this.cached;if(e||n==null)return(await this.refresh(e)).token;if(n.expiresAt==null)return n.token;let r=n.expiresAt-C_();return r>avn?n.token:r>D3?(this.backgroundRefresh(),n.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(e=!1){return this.pendingRefresh&&!e?this.pendingRefresh:this.doRefresh(e)}backgroundRefresh(){this.pendingRefresh||C_()-this.lastAdvisoryError<lvn||this.doRefresh().catch(e=>{this.lastAdvisoryError=C_(),this.onAdvisoryRefreshError?.(e)})}doRefresh(e=!1){return this.pendingRefresh=this.provider(e?{forceRefresh:!0}:void 0).then(n=>(this.cached=n,this.pendingRefresh=null,n),n=>{throw this.pendingRefresh=null,n}),this.pendingRefresh}}});var xo,U3=b(()=>{xo=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0}});function fvn(t){let e=0;for(let o of t)e+=o.length;let n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.length;return n}function j3(t){let e;return(uvn??(e=new globalThis.TextEncoder,uvn=e.encode.bind(e)))(t)}function hot(t){let e;return(dvn??(e=new globalThis.TextDecoder,dvn=e.decode.bind(e)))(t)}var uvn,dvn,gIe=b(()=>{});var pvn=b(()=>{_a();gIe()});function bne(){}function yIe(t,e,n){return!e||vIe[t]>vIe[n]?bne:e[t].bind(e)}function yot(t,e){let n=mvn.get(t);if(n&&n[0]===e)return n[1];let r={error:yIe("error",t,e),warn:yIe("warn",t,e),info:yIe("info",t,e),debug:yIe("debug",t,e)};return mvn.set(t,[e,r]),r}function hi(t){let e=t.logger,n=t.logLevel??"off";return e?yot(e,n):H1r}function gvn(){let t=xo("ANTHROPIC_LOG");return(!got||t!==hvn)&&(hvn=t,got=yot(console,wIe(t,"process.env['ANTHROPIC_LOG']",yot(console,_ne))??_ne)),got}var _ne,vIe,wIe,H1r,mvn,hvn,got,nC,R0=b(()=>{x_();U3();_ne="warn",vIe={off:0,error:200,warn:300,info:400,debug:500},wIe=(t,e,n)=>{if(t){if(Ryn(vIe,t))return t;n.warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(vIe))}`)}};H1r={error:bne,warn:bne,info:bne,debug:bne},mvn=new WeakMap;nC=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t)});var vot=b(()=>{x_();pvn();U3();R0();oIe();L3();pot()});function yvn(t){if(!t)throw new Error("profile name is empty");if(t==="."||t==="..")throw new Error(`profile name "${t}" is not allowed`);if(t.includes("/")||t.includes("\\"))throw new Error(`profile name "${t}" must not contain path separators`);if(!W1r.test(t))throw new Error(`profile name "${t}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var bIe,W1r,vvn,wvn,wot,V1r,bvn,bot=b(()=>{iIe();vot();bIe="1.0",W1r=/^[A-Za-z0-9_.-]+$/;vvn=async t=>{var e,n;let r=await wot();if(r===null)return null;let o=t??await bvn();if(o===null)return null;yvn(o);let i=await import("node:fs"),a=(await import("node:path")).join(r,"configs",`${o}.json`),l;try{l=await i.promises.readFile(a,"utf-8")}catch(d){if(d?.code!=="ENOENT")throw new Error(`failed to read config file ${a}: ${d}`);l=null}if(l===null){let d=xo("ANTHROPIC_ORGANIZATION_ID"),f=xo("ANTHROPIC_IDENTITY_TOKEN_FILE"),p=xo("ANTHROPIC_FEDERATION_RULE_ID");return p&&d?{fromFile:!1,config:{organization_id:d,workspace_id:xo("ANTHROPIC_WORKSPACE_ID"),base_url:xo("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:p,service_account_id:xo("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:f?{source:"file",path:f}:void 0,scope:xo("ANTHROPIC_SCOPE")}}}:null}let c;try{c=JSON.parse(l)}catch(d){throw new Error(`failed to parse config file ${a}: ${d}`)}if(!c.authentication)throw new Error(`config file ${a} is missing "authentication"`);let u=c.authentication.type;if(u!=="oidc_federation"&&u!=="user_oauth")throw new Error(`authentication.type "${u}" is not a known authentication type`);if(c.organization_id??(c.organization_id=xo("ANTHROPIC_ORGANIZATION_ID")),c.workspace_id??(c.workspace_id=xo("ANTHROPIC_WORKSPACE_ID")),c.base_url??(c.base_url=xo("ANTHROPIC_BASE_URL")),(e=c.authentication).scope??(e.scope=xo("ANTHROPIC_SCOPE")),c.authentication.type==="oidc_federation"){if(!c.authentication.identity_token){let d=xo("ANTHROPIC_IDENTITY_TOKEN_FILE");d&&(c.authentication.identity_token={source:"file",path:d})}c.authentication.federation_rule_id||(c.authentication.federation_rule_id=xo("ANTHROPIC_FEDERATION_RULE_ID")??""),(n=c.authentication).service_account_id??(n.service_account_id=xo("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:c,fromFile:!0}},wvn=async(t,e)=>{if(t?.authentication.credentials_path)return t.authentication.credentials_path;let n=await wot();if(!n)return null;let r=e??await bvn();return r?(yvn(r),(await import("node:path")).join(n,"credentials",`${r}.json`)):null},wot=async()=>{if(!V1r())return null;let t=await import("node:path"),e=xo("ANTHROPIC_CONFIG_DIR");if(e)return e;if(yne()["X-Stainless-OS"]==="Windows"){let i=xo("APPDATA");if(i)return t.join(i,"Anthropic");let s=xo("USERPROFILE");return s?t.join(s,"AppData","Roaming","Anthropic"):null}let r=xo("XDG_CONFIG_HOME");if(r)return t.join(r,"anthropic");let o=xo("HOME");return o?t.join(o,".config","anthropic"):null},V1r=()=>{let t=yne()["X-Stainless-Runtime"];return t==="node"||t==="deno"},bvn=async()=>{let t=await wot();if(!t)return null;let e=xo("ANTHROPIC_PROFILE");if(e)return e;let n=await import("node:fs"),o=(await import("node:path")).join(t,"active_config");try{return(await n.promises.readFile(o,"utf-8")).trim()||"default"}catch(i){if(i?.code!=="ENOENT")throw new Error(`failed to read ${o}: ${i}`);return"default"}}});function _ot(t){if(!t)throw new vt("Identity token file path is empty");return async()=>{let e=await import("node:fs"),n;try{n=await e.promises.readFile(t,"utf-8")}catch(o){throw new vt(`Failed to read identity token file at ${t}: ${o}`)}let r=n.trim();if(!r)throw new vt(`Identity token file at ${t} is empty`);return r}}function _vn(t){if(!t)throw new vt("Identity token value is empty");return()=>t}var xvn=b(()=>{_a()});function Svn(t){return async()=>{dIe(t.baseURL);let e=await t.identityTokenProvider();if(e.length>16*1024)throw new ji(`Identity token is ${Math.ceil(e.length/1024)} KiB, exceeds the 16 KiB assertion limit`);let n={grant_type:ovn,assertion:e,federation_rule_id:t.federationRuleId,organization_id:t.organizationId};t.serviceAccountId&&(n.service_account_id=t.serviceAccountId),t.workspaceId&&(n.workspace_id=t.workspaceId);let r=`${t.baseURL}${uIe}`,o;try{o=await t.fetch(r,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${ND},${svn}`,"User-Agent":t.userAgent||`anthropic-sdk-typescript/${Yv} oidcFederationProvider`},body:JSON.stringify(n)})}catch(l){throw new ji(`Failed to reach token endpoint ${r}: ${l}`)}let i=o.headers.get("Request-Id");if(!o.ok){let l=await o.text().catch(()=>""),c=uh(l),u="";throw o.status===401&&(u=` Ensure your federation rule matches your identity token. ${t.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`),new ji(`Token exchange failed with status ${o.status}${i?` (request-id ${i})`:""}: ${c}${u}`,o.status,c,i)}let s=await fIe(o,i),a=Number(s.expires_in);if(!Number.isFinite(a))throw new ji(`Token endpoint response missing required fields: ${JSON.stringify(uh(s))}`,o.status,uh(s),i);return{token:s.access_token,expiresAt:C_()+a}}}var Cvn=b(()=>{F3();wne();gne()});function kvn(t){return async e=>{let n=await import("node:fs");await pIe(t.credentialsPath,t.onSafetyWarning);let r;try{r=await n.promises.readFile(t.credentialsPath,"utf-8")}catch(g){throw new ji(`Credentials file not found at ${t.credentialsPath}: ${g}`)}let o;try{o=JSON.parse(r)}catch(g){throw new ji(`Credentials file at ${t.credentialsPath} is not valid JSON: ${g}`)}let i=o.access_token;if(!i)throw new ji(`Credentials file at ${t.credentialsPath} must include 'access_token'`);let s=o.expires_at;if(!e?.forceRefresh&&(s==null||C_()<s-D3))return{token:i,expiresAt:s??null};let a=o.refresh_token;if(!t.clientId||!a)throw new ji(`Access token at ${t.credentialsPath} has expired and no refresh is available (client_id ${t.clientId?"set":"empty"}, refresh_token ${a?"set":"empty"})`);dIe(t.baseURL);let l={grant_type:ivn,refresh_token:a,client_id:t.clientId},c=`${t.baseURL}${uIe}`,u;try{u=await t.fetch(c,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":ND,"User-Agent":t.userAgent||`anthropic-sdk-typescript/${Yv} userOAuthProvider`},body:JSON.stringify(l)})}catch(g){throw new ji(`User OAuth refresh failed to reach token endpoint: ${g}`)}let d=u.headers.get("Request-Id");if(!u.ok){let g=await u.text().catch(()=>"");throw new ji(`User OAuth refresh failed (HTTP ${u.status}): ${uh(g)}`,u.status,uh(g),d)}let f=await fIe(u,d),p=Number(f.expires_in);if(!Number.isFinite(p))throw new ji(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(uh(f))}`,u.status,uh(f),d);let m=C_()+p,h=f.refresh_token||a;return await mIe(t.credentialsPath,{...o,version:bIe,type:"oauth_token",access_token:f.access_token,expires_at:m,refresh_token:h}),{token:f.access_token,expiresAt:m}}}var Ivn=b(()=>{bot();F3();wne();gne()});function xot(t,e){let n=t.authentication.credentials_path??null,r=(t.base_url||e.baseURL).replace(/\/+$/,""),o=q1r(t,n,r,e),i={};return t.workspace_id&&t.authentication.type==="user_oauth"&&(i["anthropic-workspace-id"]=t.workspace_id),{provider:o,extraHeaders:i,baseURL:t.base_url||void 0}}async function Tvn(t,e){let n=await vvn(e);if(!n)return null;let{config:r,fromFile:o}=n,i=r.authentication.credentials_path||!o?r:{...r,authentication:{...r.authentication,credentials_path:await wvn(r,e)??void 0}};return xot(i,t)}function q1r(t,e,n,r){switch(t.authentication.type){case"oidc_federation":{let o=t.authentication,i=K1r(o);if(!i)throw new ji("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)");if(!o.federation_rule_id)throw new ji("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).");if(!t.organization_id)throw new ji("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");let s=Svn({identityTokenProvider:i,federationRuleId:o.federation_rule_id,organizationId:t.organization_id,serviceAccountId:o.service_account_id,workspaceId:t.workspace_id,baseURL:n,fetch:r.fetch,userAgent:r.userAgent});return e?G1r(s,e,r.onCacheWriteError,r.onSafetyWarning):s}case"user_oauth":{if(!e)throw new ji("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return kvn({credentialsPath:e,clientId:t.authentication.client_id,baseURL:n,fetch:r.fetch,userAgent:r.userAgent,onSafetyWarning:r.onSafetyWarning})}default:{let o=t.authentication.type;throw new ji(`authentication.type "${o}" is not a known authentication type`)}}}function K1r(t){if(t.identity_token){let r=t.identity_token.source;if(r!=="file")throw new ji(`identity_token.source "${r}" is not supported by this SDK version (only "file")`);if(!t.identity_token.path)throw new ji('identity_token.source "file" requires a non-empty path');return _ot(t.identity_token.path)}let e=xo("ANTHROPIC_IDENTITY_TOKEN_FILE");if(e)return _ot(e);let n=xo("ANTHROPIC_IDENTITY_TOKEN");return n?_vn(n):null}function G1r(t,e,n,r){return async o=>{let i=await import("node:fs");await pIe(e,r);let s;try{let l=await i.promises.readFile(e,"utf-8");s=JSON.parse(l);let c=s?.access_token;if(c&&!o?.forceRefresh){let u=s?.expires_at;if(u==null||C_()<u-D3)return{token:c,expiresAt:u??null}}}catch(l){l?.code!=="ENOENT"&&!(l instanceof SyntaxError)&&n?.(l)}let a=await t(o);try{await mIe(e,{...s??{},version:bIe,type:"oauth_token",access_token:a.token,expires_at:a.expiresAt})}catch(l){n?.(l)}return a}}var Pvn=b(()=>{U3();bot();F3();wne();xvn();Cvn();Ivn()});function Z1r(t,e){for(let o=e??0;o<t.length;o++){if(t[o]===10)return{preceding:o,index:o+1,carriage:!1};if(t[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function Avn(t){for(let r=0;r<t.length-1;r++){if(t[r]===10&&t[r+1]===10||t[r]===13&&t[r+1]===13)return r+2;if(t[r]===13&&t[r+1]===10&&r+3<t.length&&t[r+2]===13&&t[r+3]===10)return r+4}return-1}var Bg,zg,L0,Sot=b(()=>{jg();gIe();L0=class{constructor(){Bg.set(this,void 0),zg.set(this,void 0),je(this,Bg,new Uint8Array,"f"),je(this,zg,null,"f")}decode(e){if(e==null)return[];let n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?j3(e):e;je(this,Bg,fvn([ie(this,Bg,"f"),n]),"f");let r=[],o;for(;(o=Z1r(ie(this,Bg,"f"),ie(this,zg,"f")))!=null;){if(o.carriage&&ie(this,zg,"f")==null){je(this,zg,o.index,"f");continue}if(ie(this,zg,"f")!=null&&(o.index!==ie(this,zg,"f")+1||o.carriage)){r.push(hot(ie(this,Bg,"f").subarray(0,ie(this,zg,"f")-1))),je(this,Bg,ie(this,Bg,"f").subarray(ie(this,zg,"f")),"f"),je(this,zg,null,"f");continue}let i=ie(this,zg,"f")!==null?o.preceding-1:o.preceding,s=hot(ie(this,Bg,"f").subarray(0,i));r.push(s),je(this,Bg,ie(this,Bg,"f").subarray(o.index),"f"),je(this,zg,null,"f")}return r}flush(){return ie(this,Bg,"f").length?this.decode(`
`):[]}};Bg=new WeakMap,zg=new WeakMap;L0.NEWLINE_CHARS=new Set([`
`,"\r"]);L0.NEWLINE_REGEXP=/\r\n|[\n\r]/g});async function*Evn(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new vt("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new vt("Attempted to iterate over a response with no body");let n=new Cot,r=new L0,o=vne(t.body);for await(let i of Y1r(o))for(let s of r.decode(i)){let a=n.decode(s);a&&(yield a)}for(let i of r.flush()){let s=n.decode(i);s&&(yield s)}}async function*Y1r(t){let e=new Uint8Array;for await(let n of t){if(n==null)continue;let r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?j3(n):n,o=new Uint8Array(e.length+r.length);o.set(e),o.set(r,e.length),e=o;let i;for(;(i=Avn(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function J1r(t,e){let n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}var xne,Hg,Cot,Sne=b(()=>{jg();_a();$3();Sot();$3();WM();x_();gIe();R0();_a();aIe();Hg=class t{constructor(e,n,r){this.iterator=e,xne.set(this,void 0),this.controller=n,je(this,xne,r,"f")}static rawEvents(e,n=new AbortController){return Evn(e,n)}static fromSSEResponse(e,n,r){let o=!1,i=r?hi(r):console;async function*s(){if(o)throw new vt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of Evn(e,n)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(c){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),c}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop"||l.event==="message"||l.event==="user.message"||l.event==="user.interrupt"||l.event==="user.tool_confirmation"||l.event==="user.custom_tool_result"||l.event==="user.tool_result"||l.event==="agent.message"||l.event==="agent.thinking"||l.event==="agent.tool_use"||l.event==="agent.tool_result"||l.event==="agent.mcp_tool_use"||l.event==="agent.mcp_tool_result"||l.event==="agent.custom_tool_use"||l.event==="agent.thread_context_compacted"||l.event==="session.status_running"||l.event==="session.status_idle"||l.event==="session.status_rescheduled"||l.event==="session.status_terminated"||l.event==="session.error"||l.event==="session.deleted"||l.event==="session.updated"||l.event==="span.model_request_start"||l.event==="span.model_request_end"||l.event==="span.outcome_evaluation_start"||l.event==="span.outcome_evaluation_ongoing"||l.event==="span.outcome_evaluation_end"||l.event==="user.define_outcome"||l.event==="agent.thread_message_received"||l.event==="agent.thread_message_sent"||l.event==="agent.session_thread_message_received"||l.event==="agent.session_thread_message_sent"||l.event==="session.thread_created"||l.event==="session.thread_status_created"||l.event==="session.thread_status_running"||l.event==="session.thread_status_idle"||l.event==="session.thread_status_rescheduled"||l.event==="session.thread_status_terminated"||l.event==="event_start"||l.event==="event_delta"||l.event==="system.message")try{yield JSON.parse(l.data)}catch(c){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),c}if(l.event!=="ping"&&l.event==="error"){let c=hne(l.data)??l.data,u=c?.error?.type;throw new Ol(void 0,c,void 0,e.headers,u)}}a=!0}catch(l){if(Zv(l))return;throw l}finally{a||n.abort(),eC(n)}}return new t(s,n,r)}static fromReadableStream(e,n,r){let o=!1;async function*i(){let a=new L0,l=vne(e);for await(let c of l)for(let u of a.decode(c))yield u;for(let c of a.flush())yield c}async function*s(){if(o)throw new vt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of i())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(Zv(l))return;throw l}finally{a||n.abort(),eC(n)}}return new t(s,n,r)}[(xne=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],n=[],r=this.iterator(),o=i=>({next:()=>{if(i.length===0){let s=r.next();e.push(s),n.push(s)}return i.shift()}});return[new t(()=>o(e),this.controller,ie(this,xne,"f")),new t(()=>o(n),this.controller,ie(this,xne,"f"))]}toReadableStream(){let e=this,n;return oot({async start(){n=e[Symbol.asyncIterator]()},async pull(r){try{let{value:o,done:i}=await n.next();if(i)return r.close();let s=j3(JSON.stringify(o)+`
`);r.enqueue(s)}catch(o){r.error(o)}},async cancel(){await n.return?.()}})}};Cot=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,o]=J1r(e,":");return o.startsWith(" ")&&(o=o.substring(1)),n==="event"?this.event=o:n==="data"&&this.data.push(o),null}}});async function _Ie(t,e){let{response:n,requestLogID:r,retryOfRequestLogID:o,startTime:i}=e,s=await(async()=>{if(e.options.stream)return hi(t).debug("response",n.status,n.url,n.headers,n.body),Hg.fromSSEResponse(n,e.controller);if(n.status===204)return null;if(e.options.__binaryResponse)return n;let l=n.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){if(n.headers.get("content-length")==="0")return;let f=await n.json();return Cne(f,n)}return await n.text()})().finally(()=>{!e.options.stream&&!e.options.__binaryResponse&&eC(e.controller)});return hi(t).debug(`[${r}] response parsed`,nC({retryOfRequestLogID:o,url:n.url,status:n.status,body:s,durationMs:Date.now()-i})),s}function Cne(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var xIe=b(()=>{Sne();R0();aIe()});function kot(t){return typeof t=="object"&&t!==null&&Ovn.has(t)}function Nvn(t){let e=new Set;for(;typeof t=="object"&&t!==null&&!e.has(t);){if(e.add(t),kot(t)||Zv(t)||t instanceof QS||t instanceof pne)return!0;t=t.cause}return!1}function Iot(t,e,n,r){return async(o,i={})=>{if(e.length===0)return t.call(void 0,o,i);let s=i.headers instanceof Headers?i.headers:new Headers(i.headers),a=await Q1r(t,e,n,r)({...i,headers:s,url:typeof o=="string"?o:o instanceof URL?o.href:o.url});if(a.bodyUsed||a.body?.locked)throw new vt("middleware consumed the response body; use response.clone() to inspect it, or return new Response(body, response) to consume and replace it");return a}}function X1r(t,e){let n=new WeakMap;return{options:t,logger:e?hi(e):gvn(),parse(r){if(t?.stream&&r.ok)return Mvn(r,t);let o=n.get(r);return o||(o=Mvn(r,t),n.set(r,o)),o}}}async function Mvn(t,e){if(t.bodyUsed||t.body?.locked)throw new vt("cannot ctx.parse() a response whose body was already consumed; call ctx.parse() instead of reading the body, or read via response.clone()");if(e?.stream&&t.ok)return Hg.fromSSEResponse(t.clone(),new AbortController);if(t.status===204)return null;if(e?.__binaryResponse)return t;let r=t.headers.get("content-type")?.split(";")[0]?.trim();return r?.includes("application/json")||r?.endsWith("+json")?t.headers.get("content-length")==="0"?void 0:Cne(await t.clone().json(),t):await t.clone().text()}function Q1r(t,e,n,r){let o=async({url:s,...a})=>{try{return await t.call(void 0,s,a)}catch(l){let c=OD(l);throw Ovn.add(c),c}},i=X1r(n,r);for(let s=e.length-1;s>=0;s--){let a=e[s],l=o;o=async c=>a(c,l,i)}return o}var Ovn,Rvn=b(()=>{WM();xIe();R0();_a();Sne();Ovn=new WeakSet});var kne,RD,SIe=b(()=>{jg();xIe();RD=class t extends Promise{constructor(e,n,r=_Ie){super(o=>{o(null)}),this.responsePromise=n,this.parseResponse=r,kne.set(this,void 0),je(this,kne,e,"f")}_thenUnwrap(e){return new t(ie(this,kne,"f"),this.responsePromise,async(n,r)=>Cne(e(await this.parseResponse(n,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(ie(this,kne,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};kne=new WeakMap});var CIe,Ine,Tne,Jv,Lr,kIe,Bi=b(()=>{jg();_a();xIe();SIe();x_();Ine=class{constructor(e,n,r,o){CIe.set(this,void 0),je(this,CIe,e,"f"),this.options=o,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new vt("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await ie(this,CIe,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(CIe=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let n of e.getPaginatedItems())yield n}},Tne=class extends RD{constructor(e,n,r){super(e,n,async(o,i)=>new r(o,i.response,await _Ie(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let n of e)yield n}},Jv=class extends Ine{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.has_more=r.has_more||!1,this.first_id=r.first_id||null,this.last_id=r.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let n=this.first_id;return n?{...this.options,query:{...mne(this.options.query),before_id:n}}:null}let e=this.last_id;return e?{...this.options,query:{...mne(this.options.query),after_id:e}}:null}},Lr=class extends Ine{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.next_page=r.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...mne(this.options.query),page:e}}:null}},kIe=class extends Ine{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.next_page=r.next_page||null,this.prev_page=r.prev_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...mne(this.options.query),page:e}}:null}}});function LD(t,e,n){return Pot(),new File(t,e??"unknown_file",n)}function Pne(t,e){let n=typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"";return e?n.split(/[\\/]/).pop()||void 0:n}function t$r(t){let e=typeof t=="function"?t:t.fetch,n=Lvn.get(e);if(n)return n;let r=(async()=>{try{let o="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new o(i).text()}catch{return!0}})();return Lvn.set(e,r),r}var Pot,Aot,B3,Lvn,n$r,r$r,Tot,z3=b(()=>{$3();Pot=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};Aot=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",B3=async(t,e,n=!0)=>({...t,body:await n$r(t.body,e,n)}),Lvn=new WeakMap;n$r=async(t,e,n=!0)=>{if(!await t$r(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(t||{}).map(([o,i])=>Tot(r,o,i,n))),r},r$r=t=>t instanceof Blob&&"name"in t,Tot=async(t,e,n,r)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response){let o={},i=n.headers.get("Content-Type");i&&(o={type:i}),t.append(e,LD([await n.blob()],Pne(n,r),o))}else if(Aot(n))t.append(e,LD([await new Response(lIe(n)).blob()],Pne(n,r)));else if(r$r(n))t.append(e,LD([n],Pne(n,r),{type:n.type}));else if(Array.isArray(n))await Promise.all(n.map(o=>Tot(t,e+"[]",o,r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([o,i])=>Tot(t,`${e}[${o}]`,i,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}}});async function IIe(t,e,n){if(Pot(),t=await t,e||(e=Pne(t,!0)),o$r(t))return t instanceof File&&e==null&&n==null?t:LD([await t.arrayBuffer()],e??t.name,{type:t.type,lastModified:t.lastModified,...n});if(i$r(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),LD(await Eot(o),e,n)}let r=await Eot(t);if(!n?.type){let o=r.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof o=="string"&&(n={...n,type:o})}return LD(r,e,n)}async function Eot(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if($vn(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Aot(t))for await(let n of t)e.push(...await Eot(n));else{let n=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${n?`; constructor: ${n}`:""}${s$r(t)}`)}return e}function s$r(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}var $vn,o$r,i$r,Dvn=b(()=>{z3();z3();$vn=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",o$r=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&$vn(t),i$r=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function"});var Mot=b(()=>{Dvn()});var Fvn=b(()=>{});var nn,ai=b(()=>{nn=class{constructor(e){this._client=e}}});function*l$r(t){if(!t)return;if(Uvn in t){let{values:r,nulls:o}=t;yield*r.entries();for(let i of o)yield[i,null];return}let e=!1,n;t instanceof Headers?n=t.entries():not(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let r of n){let o=r[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let i=not(r[1])?r[1]:[r[1]],s=!1;for(let a of i)a!==void 0&&(e&&!s&&(s=!0,yield[o,TIe]),yield[o,a])}}var Uvn,TIe,c$r,jvn,we,So=b(()=>{x_();Uvn=Symbol.for("brand.privateNullableHeaders");TIe=Symbol("clear"),c$r=new Set(["x-stainless-helper"]),jvn=(t,e)=>{let n=t?t.split(",").map(r=>r.trim()).filter(Boolean):[];for(let r of e.split(",").map(o=>o.trim()))r&&!n.includes(r)&&n.push(r);return n.join(", ")},we=t=>{let e=new Headers,n=new Set;for(let r of t){let o=new Set;for(let[i,s]of l$r(r)){let a=i.toLowerCase();if(c$r.has(a)){if(s===TIe)continue;s===null?(e.delete(i),n.add(a)):(e.set(i,jvn(e.get(i),s)),n.delete(a));continue}(s===TIe||!o.has(a))&&(e.delete(i),o.add(a),s===TIe)||(s===null?(e.delete(i),n.add(a)):(e.append(i,s),n.delete(a)))}}return{[Uvn]:!0,values:e,nulls:n}}});function zvn(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Bvn,u$r,Oe,ls=b(()=>{_a();Bvn=Object.freeze(Object.create(null)),u$r=(t=zvn)=>function(n,...r){if(n.length===1)return n[0];let o=!1,i=[],s=n.reduce((u,d,f)=>{/[?#]/.test(d)&&(o=!0);let p=r[f],m=(o?encodeURIComponent:t)(""+p);return f!==r.length&&(p==null||typeof p=="object"&&p.toString===Object.getPrototypeOf(Object.getPrototypeOf(p.hasOwnProperty??Bvn)??Bvn)?.toString)&&(m=p+"",i.push({start:u.length+d.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(p).slice(8,-1)} is not a valid path parameter`})),u+d+(f===r.length?"":m)},""),a=s.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=l.exec(a))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(i.sort((u,d)=>u.start-d.start),i.length>0){let u=0,d=i.reduce((f,p)=>{let m=" ".repeat(p.start-u),h="^".repeat(p.length);return u=p.start+p.length,f+m+h},"");throw new vt(`Path parameters result in path with invalid segments:
${i.map(f=>f.error).join(`
`)}
${s}
${d}`)}return s},Oe=u$r(zvn)});var H3,Oot=b(()=>{ai();Bi();So();ls();H3=class extends nn{retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(Oe`/v1/deployment_runs/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/deployment_runs?beta=true",Lr,{query:o,...n,headers:we([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}}});var W3,Not=b(()=>{ai();Bi();So();ls();W3=class extends nn{create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/deployments?beta=true",{body:o,...n,headers:we([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(Oe`/v1/deployments/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(Oe`/v1/deployments/${e}?beta=true`,{body:i,...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/deployments?beta=true",Lr,{query:o,...n,headers:we([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}archive(e,n={},r){let{betas:o}=n??{};return this._client.post(Oe`/v1/deployments/${e}/archive?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}pause(e,n={},r){let{betas:o}=n??{};return this._client.post(Oe`/v1/deployments/${e}/pause?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}run(e,n={},r){let{betas:o}=n??{};return this._client.post(Oe`/v1/deployments/${e}/run?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}unpause(e,n={},r){let{betas:o}=n??{};return this._client.post(Oe`/v1/deployments/${e}/unpause?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}});var V3,Rot=b(()=>{ai();Bi();So();ls();V3=class extends nn{create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/dreams?beta=true",{body:o,...n,headers:we([{"anthropic-beta":[...r??[],"dreaming-2026-04-21"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(Oe`/v1/dreams/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"dreaming-2026-04-21"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/dreams?beta=true",Lr,{query:o,...n,headers:we([{"anthropic-beta":[...r??[],"dreaming-2026-04-21"].toString()},n?.headers])})}archive(e,n={},r){let{betas:o}=n??{};return this._client.post(Oe`/v1/dreams/${e}/archive?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"dreaming-2026-04-21"].toString()},r?.headers])})}cancel(e,n={},r){let{betas:o}=n??{};return this._client.post(Oe`/v1/dreams/${e}/cancel?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"dreaming-2026-04-21"].toString()},r?.headers])})}}});function Ene(t){return{[VM]:t}}function PIe(t){return typeof t=="object"&&t!==null&&Ane in t}function Lot(t,e){let n=new Set;if(t)for(let r of t)PIe(r)&&n.add(r[Ane]);if(e)for(let r of e){PIe(r)&&n.add(r[Ane]);let o=r.content;if(Array.isArray(o))for(let i of o)PIe(i)&&n.add(i[Ane])}return Array.from(n)}function EIe(t,e){let n=Lot(t,e);return n.length===0?{}:{[VM]:n.join(", ")}}function Hvn(t){return PIe(t)?{[VM]:t[Ane]}:{}}var VM,AIe,Ane,rC=b(()=>{VM="x-stainless-helper",AIe="x-stainless-helper-method";Ane=Symbol("anthropic.sdk.stainlessHelper")});var q3,$ot=b(()=>{ai();Bi();So();rC();z3();ls();q3=class extends nn{list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/files?beta=true",Jv,{query:o,...n,headers:we([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(Oe`/v1/files/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString()},r?.headers])})}download(e,n={},r){let{betas:o}=n??{};return this._client.get(Oe`/v1/files/${e}/content?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}retrieveMetadata(e,n={},r){let{betas:o}=n??{};return this._client.get(Oe`/v1/files/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString()},r?.headers])})}upload(e,n){let{betas:r,...o}=e;return this._client.post("/v1/files?beta=true",B3({body:o,...n,headers:we([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},Hvn(o.file),n?.headers])},this._client))}}});var K3,Dot=b(()=>{ai();Bi();So();ls();K3=class extends nn{retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(Oe`/v1/models/${e}?beta=true`,{...r,headers:we([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void 0},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/models?beta=true",Jv,{query:o,...n,headers:we([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}}});var G3,Fot=b(()=>{ai();Bi();So();ls();G3=class extends nn{create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/user_profiles?beta=true",{body:o,...n,headers:we([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(Oe`/v1/user_profiles/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(Oe`/v1/user_profiles/${e}?beta=true`,{body:i,...r,headers:we([{"anthropic-beta":[...o??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/user_profiles?beta=true",Lr,{query:o,...n,headers:we([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},n?.headers])})}createEnrollmentURL(e,n={},r){let{betas:o}=n??{};return this._client.post(Oe`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}}});var Vvn=wi(MIe=>{"use strict";Object.defineProperty(MIe,"__esModule",{value:!0});MIe.timingSafeEqual=void 0;function Wvn(t,e=""){if(!t)throw new Error(e)}function y$r(t,e){if(t.byteLength!==e.byteLength)return!1;t instanceof DataView||(t=new DataView(ArrayBuffer.isView(t)?t.buffer:t)),e instanceof DataView||(e=new DataView(ArrayBuffer.isView(e)?e.buffer:e)),Wvn(t instanceof DataView),Wvn(e instanceof DataView);let n=t.byteLength,r=0,o=-1;for(;++o<n;)r|=t.getUint8(o)^e.getUint8(o);return r===0}MIe.timingSafeEqual=y$r});var Gvn=wi(Wg=>{"use strict";var v$r=Wg&&Wg.__extends||function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var i in o)o.hasOwnProperty(i)&&(r[i]=o[i])},t(e,n)};return function(e,n){t(e,n);function r(){this.constructor=e}e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}}();Object.defineProperty(Wg,"__esModule",{value:!0});var sc=256,Uot=function(){function t(e){e===void 0&&(e="="),this._paddingCharacter=e}return t.prototype.encodedLength=function(e){return this._paddingCharacter?(e+2)/3*4|0:(e*8+5)/6|0},t.prototype.encode=function(e){for(var n="",r=0;r<e.length-2;r+=3){var o=e[r]<<16|e[r+1]<<8|e[r+2];n+=this._encodeByte(o>>>3*6&63),n+=this._encodeByte(o>>>2*6&63),n+=this._encodeByte(o>>>1*6&63),n+=this._encodeByte(o>>>0*6&63)}var i=e.length-r;if(i>0){var o=e[r]<<16|(i===2?e[r+1]<<8:0);n+=this._encodeByte(o>>>3*6&63),n+=this._encodeByte(o>>>2*6&63),i===2?n+=this._encodeByte(o>>>1*6&63):n+=this._paddingCharacter||"",n+=this._paddingCharacter||""}return n},t.prototype.maxDecodedLength=function(e){return this._paddingCharacter?e/4*3|0:(e*6+7)/8|0},t.prototype.decodedLength=function(e){return this.maxDecodedLength(e.length-this._getPaddingLength(e))},t.prototype.decode=function(e){if(e.length===0)return new Uint8Array(0);for(var n=this._getPaddingLength(e),r=e.length-n,o=new Uint8Array(this.maxDecodedLength(r)),i=0,s=0,a=0,l=0,c=0,u=0,d=0;s<r-4;s+=4)l=this._decodeChar(e.charCodeAt(s+0)),c=this._decodeChar(e.charCodeAt(s+1)),u=this._decodeChar(e.charCodeAt(s+2)),d=this._decodeChar(e.charCodeAt(s+3)),o[i++]=l<<2|c>>>4,o[i++]=c<<4|u>>>2,o[i++]=u<<6|d,a|=l&sc,a|=c&sc,a|=u&sc,a|=d&sc;if(s<r-1&&(l=this._decodeChar(e.charCodeAt(s)),c=this._decodeChar(e.charCodeAt(s+1)),o[i++]=l<<2|c>>>4,a|=l&sc,a|=c&sc),s<r-2&&(u=this._decodeChar(e.charCodeAt(s+2)),o[i++]=c<<4|u>>>2,a|=u&sc),s<r-3&&(d=this._decodeChar(e.charCodeAt(s+3)),o[i++]=u<<6|d,a|=d&sc),a!==0)throw new Error("Base64Coder: incorrect characters for decoding");return o},t.prototype._encodeByte=function(e){var n=e;return n+=65,n+=25-e>>>8&6,n+=51-e>>>8&-75,n+=61-e>>>8&-15,n+=62-e>>>8&3,String.fromCharCode(n)},t.prototype._decodeChar=function(e){var n=sc;return n+=(42-e&e-44)>>>8&-sc+e-43+62,n+=(46-e&e-48)>>>8&-sc+e-47+63,n+=(47-e&e-58)>>>8&-sc+e-48+52,n+=(64-e&e-91)>>>8&-sc+e-65+0,n+=(96-e&e-123)>>>8&-sc+e-97+26,n},t.prototype._getPaddingLength=function(e){var n=0;if(this._paddingCharacter){for(var r=e.length-1;r>=0&&e[r]===this._paddingCharacter;r--)n++;if(e.length<4||n>2)throw new Error("Base64Coder: incorrect padding")}return n},t}();Wg.Coder=Uot;var Mne=new Uot;function w$r(t){return Mne.encode(t)}Wg.encode=w$r;function b$r(t){return Mne.decode(t)}Wg.decode=b$r;var qvn=function(t){v$r(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype._encodeByte=function(n){var r=n;return r+=65,r+=25-n>>>8&6,r+=51-n>>>8&-75,r+=61-n>>>8&-13,r+=62-n>>>8&49,String.fromCharCode(r)},e.prototype._decodeChar=function(n){var r=sc;return r+=(44-n&n-46)>>>8&-sc+n-45+62,r+=(94-n&n-96)>>>8&-sc+n-95+63,r+=(47-n&n-58)>>>8&-sc+n-48+52,r+=(64-n&n-91)>>>8&-sc+n-65+0,r+=(96-n&n-123)>>>8&-sc+n-97+26,r},e}(Uot);Wg.URLSafeCoder=qvn;var Kvn=new qvn;function _$r(t){return Kvn.encode(t)}Wg.encodeURLSafe=_$r;function x$r(t){return Kvn.decode(t)}Wg.decodeURLSafe=x$r;Wg.encodedLength=function(t){return Mne.encodedLength(t)};Wg.maxDecodedLength=function(t){return Mne.maxDecodedLength(t)};Wg.decodedLength=function(t){return Mne.decodedLength(t)}});var Yvn=wi((Zvn,OIe)=>{(function(t,e){var n={};e(n);var r=n.default;for(var o in n)r[o]=n[o];typeof OIe=="object"&&typeof OIe.exports=="object"?OIe.exports=r:typeof define=="function"&&define.amd?define(function(){return r}):t.sha256=r})(Zvn,function(t){"use strict";t.__esModule=!0,t.digestLength=32,t.blockSize=64;var e=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function n(d,f,p,m,h){for(var g,v,y,w,_,S,I,C,k,T,P,E,O;h>=64;){for(g=f[0],v=f[1],y=f[2],w=f[3],_=f[4],S=f[5],I=f[6],C=f[7],T=0;T<16;T++)P=m+T*4,d[T]=(p[P]&255)<<24|(p[P+1]&255)<<16|(p[P+2]&255)<<8|p[P+3]&255;for(T=16;T<64;T++)k=d[T-2],E=(k>>>17|k<<15)^(k>>>19|k<<13)^k>>>10,k=d[T-15],O=(k>>>7|k<<25)^(k>>>18|k<<14)^k>>>3,d[T]=(E+d[T-7]|0)+(O+d[T-16]|0);for(T=0;T<64;T++)E=(((_>>>6|_<<26)^(_>>>11|_<<21)^(_>>>25|_<<7))+(_&S^~_&I)|0)+(C+(e[T]+d[T]|0)|0)|0,O=((g>>>2|g<<30)^(g>>>13|g<<19)^(g>>>22|g<<10))+(g&v^g&y^v&y)|0,C=I,I=S,S=_,_=w+E|0,w=y,y=v,v=g,g=E+O|0;f[0]+=g,f[1]+=v,f[2]+=y,f[3]+=w,f[4]+=_,f[5]+=S,f[6]+=I,f[7]+=C,m+=64,h-=64}return m}var r=function(){function d(){this.digestLength=t.digestLength,this.blockSize=t.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return d.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this},d.prototype.clean=function(){for(var f=0;f<this.buffer.length;f++)this.buffer[f]=0;for(var f=0;f<this.temp.length;f++)this.temp[f]=0;this.reset()},d.prototype.update=function(f,p){if(p===void 0&&(p=f.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");var m=0;if(this.bytesHashed+=p,this.bufferLength>0){for(;this.bufferLength<64&&p>0;)this.buffer[this.bufferLength++]=f[m++],p--;this.bufferLength===64&&(n(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(p>=64&&(m=n(this.temp,this.state,f,m,p),p%=64);p>0;)this.buffer[this.bufferLength++]=f[m++],p--;return this},d.prototype.finish=function(f){if(!this.finished){var p=this.bytesHashed,m=this.bufferLength,h=p/536870912|0,g=p<<3,v=p%64<56?64:128;this.buffer[m]=128;for(var y=m+1;y<v-8;y++)this.buffer[y]=0;this.buffer[v-8]=h>>>24&255,this.buffer[v-7]=h>>>16&255,this.buffer[v-6]=h>>>8&255,this.buffer[v-5]=h>>>0&255,this.buffer[v-4]=g>>>24&255,this.buffer[v-3]=g>>>16&255,this.buffer[v-2]=g>>>8&255,this.buffer[v-1]=g>>>0&255,n(this.temp,this.state,this.buffer,0,v),this.finished=!0}for(var y=0;y<8;y++)f[y*4+0]=this.state[y]>>>24&255,f[y*4+1]=this.state[y]>>>16&255,f[y*4+2]=this.state[y]>>>8&255,f[y*4+3]=this.state[y]>>>0&255;return this},d.prototype.digest=function(){var f=new Uint8Array(this.digestLength);return this.finish(f),f},d.prototype._saveState=function(f){for(var p=0;p<this.state.length;p++)f[p]=this.state[p]},d.prototype._restoreState=function(f,p){for(var m=0;m<this.state.length;m++)this.state[m]=f[m];this.bytesHashed=p,this.finished=!1,this.bufferLength=0},d}();t.Hash=r;var o=function(){function d(f){this.inner=new r,this.outer=new r,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var p=new Uint8Array(this.blockSize);if(f.length>this.blockSize)new r().update(f).finish(p).clean();else for(var m=0;m<f.length;m++)p[m]=f[m];for(var m=0;m<p.length;m++)p[m]^=54;this.inner.update(p);for(var m=0;m<p.length;m++)p[m]^=106;this.outer.update(p),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate);for(var m=0;m<p.length;m++)p[m]=0}return d.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},d.prototype.clean=function(){for(var f=0;f<this.istate.length;f++)this.ostate[f]=this.istate[f]=0;this.inner.clean(),this.outer.clean()},d.prototype.update=function(f){return this.inner.update(f),this},d.prototype.finish=function(f){return this.outer.finished?this.outer.finish(f):(this.inner.finish(f),this.outer.update(f,this.digestLength).finish(f)),this},d.prototype.digest=function(){var f=new Uint8Array(this.digestLength);return this.finish(f),f},d}();t.HMAC=o;function i(d){var f=new r().update(d),p=f.digest();return f.clean(),p}t.hash=i,t.default=i;function s(d,f){var p=new o(d).update(f),m=p.digest();return p.clean(),m}t.hmac=s;function a(d,f,p,m){var h=m[0];if(h===0)throw new Error("hkdf: cannot expand more");f.reset(),h>1&&f.update(d),p&&f.update(p),f.update(m),f.finish(d),m[0]++}var l=new Uint8Array(t.digestLength);function c(d,f,p,m){f===void 0&&(f=l),m===void 0&&(m=32);for(var h=new Uint8Array([1]),g=s(f,d),v=new o(g),y=new Uint8Array(v.digestLength),w=y.length,_=new Uint8Array(m),S=0;S<m;S++)w===y.length&&(a(y,v,p,h),w=0),_[S]=y[w++];return v.clean(),y.fill(0),h.fill(0),_}t.hkdf=c;function u(d,f,p,m){for(var h=new o(d),g=h.digestLength,v=new Uint8Array(4),y=new Uint8Array(g),w=new Uint8Array(g),_=new Uint8Array(m),S=0;S*g<m;S++){var I=S+1;v[0]=I>>>24&255,v[1]=I>>>16&255,v[2]=I>>>8&255,v[3]=I>>>0&255,h.reset(),h.update(f),h.update(v),h.finish(w);for(var C=0;C<g;C++)y[C]=w[C];for(var C=2;C<=p;C++){h.reset(),h.update(w).finish(w);for(var k=0;k<g;k++)y[k]^=w[k]}for(var C=0;C<g&&S*g+C<m;C++)_[S*g+C]=y[C]}for(var S=0;S<g;S++)y[S]=w[S]=0;for(var S=0;S<4;S++)v[S]=0;return h.clean(),_}t.pbkdf2=u})});var Qvn=wi(Z3=>{"use strict";Object.defineProperty(Z3,"__esModule",{value:!0});Z3.Webhook=Z3.WebhookVerificationError=void 0;var S$r=Vvn(),Jvn=Gvn(),C$r=Yvn(),Xvn=5*60,jot=class t extends Error{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype),this.name="ExtendableError",this.stack=new Error(e).stack}},qM=class t extends jot{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype),this.name="WebhookVerificationError"}};Z3.WebhookVerificationError=qM;var NIe=class t{constructor(e,n){if(!e)throw new Error("Secret can't be empty.");if(n?.format==="raw")e instanceof Uint8Array?this.key=e:this.key=Uint8Array.from(e,r=>r.charCodeAt(0));else{if(typeof e!="string")throw new Error("Expected secret to be of type string");e.startsWith(t.prefix)&&(e=e.substring(t.prefix.length)),this.key=Jvn.decode(e)}}verify(e,n){let r={};for(let f of Object.keys(n))r[f.toLowerCase()]=n[f];let o=r["webhook-id"],i=r["webhook-signature"],s=r["webhook-timestamp"];if(!i||!o||!s)throw new qM("Missing required headers");let a=this.verifyTimestamp(s),c=this.sign(o,a,e).split(",")[1],u=i.split(" "),d=new globalThis.TextEncoder;for(let f of u){let[p,m]=f.split(",");if(p==="v1"&&(0,S$r.timingSafeEqual)(d.encode(m),d.encode(c)))return JSON.parse(e.toString())}throw new qM("No matching signature found")}sign(e,n,r){if(typeof r!="string")if(r.constructor.name==="Buffer")r=r.toString();else throw new Error("Expected payload to be of type string or Buffer.");let o=new TextEncoder,i=Math.floor(n.getTime()/1e3),s=o.encode(`${e}.${i}.${r}`);return`v1,${Jvn.encode(C$r.hmac(this.key,s))}`}verifyTimestamp(e){let n=Math.floor(Date.now()/1e3),r=parseInt(e,10);if(isNaN(r))throw new qM("Invalid Signature Headers");if(n-r>Xvn)throw new qM("Message timestamp too old");if(r>n+Xvn)throw new qM("Message timestamp too new");return new Date(r*1e3)}};Z3.Webhook=NIe;NIe.prefix="whsec_"});var ewn,Y3,Bot=b(()=>{ai();ewn=L(Qvn(),1),Y3=class extends nn{unwrap(e,{headers:n,key:r}){if(n!==void 0){let o=r===void 0?this._client.webhookKey:r;if(o===null)throw new Error("Webhook key must not be null in order to unwrap");new ewn.Webhook(o).verify(e,n)}return JSON.parse(e)}}});var J3,zot=b(()=>{ai();Bi();So();ls();J3=class extends nn{list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(Oe`/v1/agents/${e}/versions?beta=true`,Lr,{query:i,...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}});var $D,Hot=b(()=>{ai();zot();zot();Bi();So();ls();$D=class extends nn{constructor(){super(...arguments),this.versions=new J3(this._client)}create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/agents?beta=true",{body:o,...n,headers:we([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o,...i}=n??{};return this._client.get(Oe`/v1/agents/${e}?beta=true`,{query:i,...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(Oe`/v1/agents/${e}?beta=true`,{body:i,...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/agents?beta=true",Lr,{query:o,...n,headers:we([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}archive(e,n={},r){let{betas:o}=n??{};return this._client.post(Oe`/v1/agents/${e}/archive?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};$D.Versions=J3});function DD(t,e){if(!t)return()=>{};if(t.aborted)return e.abort(),()=>{};let n=()=>e.abort();return t.addEventListener("abort",n),()=>t.removeEventListener("abort",n)}var RIe=b(()=>{});function KM(t,e){return t instanceof Ol&&t.status===e}function twn(t){return t instanceof Ol&&typeof t.status=="number"&&t.status>=400&&t.status<500}function GM(t){return twn(t)&&!KM(t,408)&&!KM(t,409)&&!KM(t,429)}function nwn(t,e,n){return Math.min(e*2**t,n)}function Wot(t,e){return t+Math.random()*(e-t)}function rwn(t){return t*(1-Math.random()*.25)}var One=b(()=>{_a()});function LIe(t,{authToken:e,helper:n}){if(!e)throw new vt(`copyClientForHelper: expected a non-empty authToken but received ${JSON.stringify(e)}`);let r=t,o=r._options.defaultHeaders,i=r._authState?.extraHeaders,s=i?Object.fromEntries(Object.entries(i).filter(([l])=>{let c=l.toLowerCase();return c!=="authorization"&&c!=="x-api-key"})):void 0,a=we([s,o,{[VM]:n}]);return t.withOptions({apiKey:null,authToken:e,baseURL:t.baseURL,credentials:void 0,defaultHeaders:a})}var Vot=b(()=>{_a();So();rC()});function M$r(t){return nwn(t,A$r,E$r)}function O$r(){let e=globalThis.process?.env?.HOSTNAME;return e?`${e}-${k3()}`:k3()}var X3,$Ie,Xv,DIe,FIe,UIe,Nne,Rne,Q3,P$r,A$r,E$r,ZM,jIe=b(()=>{jg();_a();R0();L3();oIe();RIe();So();One();Vot();One();P$r=999,A$r=1e3,E$r=6e4,ZM=class{constructor(e){X3.set(this,void 0),$Ie.set(this,!1),Xv.set(this,void 0),DIe.set(this,void 0),FIe.set(this,void 0),UIe.set(this,void 0),Nne.set(this,void 0),Rne.set(this,void 0),Q3.set(this,void 0),this.client=e.client,this.environmentId=e.environmentId,this.environmentKey=e.environmentKey,this.workerId=e.workerId??O$r(),je(this,X3,LIe(e.client,{authToken:e.environmentKey,helper:"environments-work-poller"}),"f"),je(this,FIe,e.autoStop??!0,"f"),je(this,UIe,e.drain??!1,"f"),je(this,Nne,e.blockMs===void 0?P$r:e.blockMs,"f"),je(this,Rne,e.reclaimOlderThanMs??null,"f"),je(this,Q3,e.requestOptions,"f"),je(this,Xv,new AbortController,"f"),je(this,DIe,DD(e.signal,ie(this,Xv,"f")),"f")}get signal(){return ie(this,Xv,"f").signal}abort(){ie(this,Xv,"f").abort()}async*[(X3=new WeakMap,$Ie=new WeakMap,Xv=new WeakMap,DIe=new WeakMap,FIe=new WeakMap,UIe=new WeakMap,Nne=new WeakMap,Rne=new WeakMap,Q3=new WeakMap,Symbol.asyncIterator)](){if(ie(this,$Ie,"f"))throw new vt("Cannot iterate over a consumed WorkPoller");je(this,$Ie,!0,"f");let e=hi(this.client);e.info("poller starting",{component:"work-poller",environment_id:this.environmentId});try{let n=0;for(;!ie(this,Xv,"f").signal.aborted;){let r;try{r=await ie(this,X3,"f").beta.environments.work.poll(this.environmentId,{"Anthropic-Worker-ID":this.workerId,...ie(this,Nne,"f")!==null?{block_ms:ie(this,Nne,"f")}:{},...ie(this,Rne,"f")!==null?{reclaim_older_than_ms:ie(this,Rne,"f")}:{}},{headers:we([ie(this,Q3,"f")?.headers]),signal:ie(this,Xv,"f").signal})}catch(o){if(ie(this,Xv,"f").signal.aborted)return;if(GM(o))throw e.error("poll failed permanently, stopping poller",{error:String(o)}),o;let i=rwn(M$r(n));e.warn("poll failed, backing off",{error:String(o),backoff_ms:i}),n++,await S_(i,ie(this,Xv,"f").signal);continue}if(n=0,r==null){if(ie(this,UIe,"f"))return;await S_(Wot(1e3,3e3),ie(this,Xv,"f").signal);continue}e.info("claimed work",{component:"work-poller",environment_id:this.environmentId,work_id:r.id,work_type:r.data.type});try{await ie(this,X3,"f").beta.environments.work.ack(r.id,{environment_id:r.environment_id},{headers:we([ie(this,Q3,"f")?.headers]),signal:ie(this,Xv,"f").signal})}catch(o){e.error("ack failed",{work_id:r.id,error:String(o)});continue}try{yield r}finally{if(ie(this,FIe,"f"))try{await ie(this,X3,"f").beta.environments.work.stop(r.id,{environment_id:r.environment_id},{headers:we([ie(this,Q3,"f")?.headers])})}catch(o){KM(o,409)||e.warn("stop failed",{work_id:r.id,error:String(o)})}}}}finally{ie(this,DIe,"f").call(this)}}}});var eq,YM,tq,BIe,own=b(()=>{jg();BIe=class{constructor(){eq.set(this,[]),YM.set(this,[]),tq.set(this,!1)}push(e){if(ie(this,tq,"f"))return!1;let n=ie(this,YM,"f").shift();return n?n({done:!1,value:e}):ie(this,eq,"f").push(e),!0}close(){if(!ie(this,tq,"f"))for(je(this,tq,!0,"f");ie(this,YM,"f").length>0;)ie(this,YM,"f").shift()({done:!0,value:void 0})}next(e){return ie(this,eq,"f").length>0?Promise.resolve({done:!1,value:ie(this,eq,"f").shift()}):ie(this,tq,"f")||e?.aborted?Promise.resolve({done:!0,value:void 0}):new Promise(n=>{let r=i=>{e?.removeEventListener("abort",o),n(i)},o=()=>{let i=ie(this,YM,"f").indexOf(r);i>=0&&ie(this,YM,"f").splice(i,1),n({done:!0,value:void 0})};ie(this,YM,"f").push(r),e?.addEventListener("abort",o,{once:!0})})}tryShift(){return ie(this,eq,"f").shift()}};eq=new WeakMap,YM=new WeakMap,tq=new WeakMap});var $0,Lne=b(()=>{$0=class extends Error{constructor(e){let n=typeof e=="string"?e:e.map(r=>r.type==="text"?r.text:`[${r.type}]`).join(" ");super(n),this.name="ToolError",this.content=e}}});function qot(t){return"name"in t?t.name:t.mcp_server_name}function N$r(t){return t instanceof $0?t.content:`Error: ${t instanceof Error?t.message:String(t)}`}async function iwn(t,e,n){try{let r=t.parse?t.parse(e):e;return{content:await t.run(r,n),isError:!1}}catch(r){return{content:N$r(r),isError:!0}}}var swn=b(()=>{Lne()});function gwn(t){return t.type==="session.status_idle"&&t.stop_reason?.type==="end_turn"}function F$r(t,e,n){return t.type==="agent.custom_tool_use"?{type:"user.custom_tool_result",custom_tool_use_id:t.id,is_error:e,content:n}:{type:"user.tool_result",tool_use_id:t.id,is_error:e,content:n}}function U$r(t){if(typeof t=="string")return[{type:"text",text:t||"(no output)"}];let e=t.map(n=>n.type==="text"?{type:"text",text:n.text||"(no output)"}:n.type==="image"||n.type==="document"?n:n.type==="search_result"?{type:"search_result",source:n.source,title:n.title,content:n.content.map(r=>({type:"text",text:r.text})),citations:{enabled:n.citations?.enabled??!1}}:{type:"text",text:JSON.stringify(n)});return e.length>0?e:[{type:"text",text:"(no output)"}]}var $ne,KIe,nq,FD,k_,ll,zIe,Ud,HIe,Dne,GIe,fu,oq,Vg,iq,JM,rq,D0,Fne,Qv,WIe,mwn,awn,lwn,cwn,Kot,uwn,VIe,qIe,Got,dwn,hwn,fwn,R$r,L$r,$$r,pwn,D$r,Zot,XM,ZIe=b(()=>{jg();_a();R0();L3();One();RIe();own();So();rC();swn();fwn=500,R$r=1e4,L$r=12e4,$$r=3e4,pwn=3,D$r=6e4;Zot=class{constructor(e,n){$ne.set(this,void 0),KIe.set(this,void 0),nq.set(this,new Set),FD.set(this,!1),k_.set(this,void 0),je(this,$ne,e,"f"),je(this,KIe,n,"f")}noteEvent(e){e.type!=="user.tool_confirmation"&&(gwn(e)?this.arm():this.disarm())}block(e){ie(this,nq,"f").add(e),ie(this,k_,"f")!==void 0&&(je(this,FD,!0,"f"),clearTimeout(ie(this,k_,"f")),je(this,k_,void 0,"f"))}unblock(e){ie(this,nq,"f").delete(e),ie(this,nq,"f").size===0&&ie(this,FD,"f")&&this.arm()}arm(){if(!(ie(this,$ne,"f")<=0)){if(ie(this,nq,"f").size>0){je(this,FD,!0,"f");return}je(this,FD,!1,"f"),ie(this,k_,"f")!==void 0&&clearTimeout(ie(this,k_,"f")),je(this,k_,setTimeout(ie(this,KIe,"f"),ie(this,$ne,"f")),"f")}}disarm(){je(this,FD,!1,"f"),ie(this,k_,"f")!==void 0&&(clearTimeout(ie(this,k_,"f")),je(this,k_,void 0,"f"))}};$ne=new WeakMap,KIe=new WeakMap,nq=new WeakMap,FD=new WeakMap,k_=new WeakMap;XM=class{constructor(e,n){ll.add(this),zIe.set(this,!1),Ud.set(this,void 0),HIe.set(this,void 0),Dne.set(this,void 0),GIe.set(this,void 0),fu.set(this,void 0),oq.set(this,new Set),Vg.set(this,new Set),iq.set(this,new Map),JM.set(this,new Map),rq.set(this,new BIe),D0.set(this,0),Fne.set(this,null),Qv.set(this,void 0),this.client=n.client,this.sessionId=e,this.tools=n.tools,this.maxIdleMs=n.maxIdleMs??D$r,je(this,fu,hi(n.client),"f"),je(this,GIe,new Map(n.tools.map(r=>[qot(r),r])),"f"),je(this,Ud,new AbortController,"f"),je(this,HIe,DD(n.signal,ie(this,Ud,"f")),"f"),je(this,Dne,n.requestOptions,"f"),je(this,Qv,new Zot(this.maxIdleMs,()=>{ie(this,fu,"f").info("session idle after end_turn; stopping",{component:"session-tool-runner",session_id:this.sessionId,max_idle_ms:this.maxIdleMs}),ie(this,Ud,"f").abort()}),"f")}get signal(){return ie(this,Ud,"f").signal}abort(){ie(this,Ud,"f").abort()}async*[(zIe=new WeakMap,Ud=new WeakMap,HIe=new WeakMap,Dne=new WeakMap,GIe=new WeakMap,fu=new WeakMap,oq=new WeakMap,Vg=new WeakMap,iq=new WeakMap,JM=new WeakMap,rq=new WeakMap,D0=new WeakMap,Fne=new WeakMap,Qv=new WeakMap,ll=new WeakSet,Symbol.asyncIterator)](){if(ie(this,zIe,"f"))throw new vt("Cannot iterate over a consumed SessionToolRunner");je(this,zIe,!0,"f"),ie(this,fu,"f").info("session tool runner starting",{component:"session-tool-runner",session_id:this.sessionId});let e=ie(this,ll,"m",mwn).call(this).catch(n=>{ie(this,Ud,"f").signal.aborted||ie(this,fu,"f").error("stream loop failed",{error:String(n)}),ie(this,Ud,"f").abort()});try{for(;;){let r=await ie(this,rq,"f").next(ie(this,Ud,"f").signal);if(r.done)break;yield r.value}await e;let n;for(;(n=ie(this,rq,"f").tryShift())!==void 0;)yield n}finally{ie(this,Ud,"f").abort(),ie(this,Qv,"f").disarm(),await e;try{await ie(this,ll,"m",hwn).call(this)}catch(n){ie(this,fu,"f").warn("drain failed",{error:String(n)})}ie(this,rq,"f").close();for(let n of this.tools)try{await n.close?.()}catch(r){ie(this,fu,"f").warn("tool.close failed",{tool:qot(n),error:String(r)})}ie(this,HIe,"f").call(this)}}};WIe=function(){return{...ie(this,Dne,"f"),headers:we([Ene("session-tool-runner"),ie(this,Dne,"f")?.headers]),signal:ie(this,Ud,"f").signal}},mwn=async function(){let e=ie(this,Ud,"f"),n=fwn;for(;!e.signal.aborted;){try{let r=await this.client.beta.sessions.events.stream(this.sessionId,{},ie(this,ll,"m",WIe).call(this));await ie(this,ll,"m",awn).call(this);for await(let o of r)if(n=fwn,await ie(this,ll,"m",cwn).call(this,o))return}catch(r){if(e.signal.throwIfAborted(),GM(r))throw ie(this,fu,"f").error("permanent stream failure, shutting down",{error:String(r)}),e.abort(),r;ie(this,fu,"f").warn("stream disconnected, reconnecting",{error:String(r),backoff_ms:n})}e.signal.throwIfAborted(),await S_(n,e.signal),n=Math.min(n*2,R$r)}},awn=async function(){let e=ie(this,Ud,"f"),n=[],r=!1;try{for await(let s of this.client.beta.sessions.events.list(this.sessionId,{limit:1e3},ie(this,ll,"m",WIe).call(this)))ie(this,ll,"m",lwn).call(this,s,n),r=gwn(s)}catch(s){e.signal.throwIfAborted(),ie(this,fu,"f").warn("reconcile list failed",{error:String(s)});for(let a of n)ie(this,oq,"f").delete(a.id);return}let o=n.filter(s=>!ie(this,Vg,"f").has(s.id));ie(this,Qv,"f").disarm();for(let s of o)await ie(this,ll,"m",Kot).call(this,s);for(let s of[...ie(this,JM,"f").values()]){let a=ie(this,iq,"f").get(s.id);a!==void 0&&await ie(this,ll,"m",VIe).call(this,s,a)}let i=o.filter(s=>!ie(this,Vg,"f").has(s.id)&&!ie(this,JM,"f").has(s.id));r&&i.length===0?ie(this,Qv,"f").arm():ie(this,Qv,"f").disarm()},lwn=function(e,n){e.type==="agent.tool_use"||e.type==="agent.custom_tool_use"?(ie(this,oq,"f").add(e.id),ie(this,Vg,"f").has(e.id)||n.push(e)):e.type==="user.tool_result"?ie(this,Vg,"f").add(e.tool_use_id):e.type==="user.custom_tool_result"?ie(this,Vg,"f").add(e.custom_tool_use_id):e.type==="user.tool_confirmation"&&(ie(this,Vg,"f").has(e.tool_use_id)||ie(this,iq,"f").set(e.tool_use_id,e.result))},cwn=async function(e){switch(ie(this,Qv,"f").noteEvent(e),e.type){case"agent.tool_use":case"agent.custom_tool_use":return ie(this,oq,"f").has(e.id)||(ie(this,oq,"f").add(e.id),await ie(this,ll,"m",Kot).call(this,e)),!1;case"user.tool_confirmation":return await ie(this,ll,"m",uwn).call(this,e),!1;case"user.tool_result":return ie(this,Vg,"f").add(e.tool_use_id),!1;case"user.custom_tool_result":return ie(this,Vg,"f").add(e.custom_tool_use_id),!1;case"session.status_terminated":case"session.deleted":return ie(this,fu,"f").info("session terminated",{component:"session-tool-runner",session_id:this.sessionId}),ie(this,Ud,"f").abort(),!0;default:return!1}},Kot=async function(e){let n=e.evaluated_permission,r=n==="deny"?"deny":ie(this,iq,"f").get(e.id);if(r===void 0){n===void 0||n==="allow"?await ie(this,ll,"m",Got).call(this,e,void 0):ie(this,JM,"f").has(e.id)||(ie(this,fu,"f").info("tool call awaiting confirmation; holding",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),ie(this,JM,"f").set(e.id,e),ie(this,Qv,"f").block(e.id));return}await ie(this,ll,"m",VIe).call(this,e,r)},uwn=async function(e){ie(this,iq,"f").set(e.tool_use_id,e.result);let n=ie(this,JM,"f").get(e.tool_use_id);n!==void 0&&await ie(this,ll,"m",VIe).call(this,n,e.result)},VIe=async function(e,n){let r=ie(this,JM,"f").delete(e.id);if(n==="allow"){ie(this,fu,"f").info("tool call confirmed",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),r||ie(this,Qv,"f").block(e.id);try{await ie(this,ll,"m",Got).call(this,e,"allow")}finally{ie(this,Qv,"f").unblock(e.id)}return}r&&ie(this,Qv,"f").unblock(e.id),ie(this,Vg,"f").add(e.id),ie(this,fu,"f").info("tool call denied; not executing",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),ie(this,ll,"m",qIe).call(this,{event:e,toolUseId:e.id,name:e.name,isError:!1,posted:!1,confirmation:"deny"})},qIe=function(e){ie(this,rq,"f").push(e)},Got=async function(e,n){var r,o;if(!ie(this,Vg,"f").has(e.id)){ie(this,fu,"f").info("executing tool",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),je(this,D0,(r=ie(this,D0,"f"),r++,r),"f");try{let i=ie(this,GIe,"f").get(e.name);if(!i){ie(this,fu,"f").info("tool not owned by this runner; leaving the tool_use_id pending for its owner",{component:"session-tool-runner",session_id:this.sessionId,tool:e.name,tool_use_id:e.id}),ie(this,ll,"m",qIe).call(this,{event:e,toolUseId:e.id,name:e.name,isError:!1,posted:!1,confirmation:n});return}let s,a,l=new AbortController,c=DD(ie(this,Ud,"f").signal,l),u=setTimeout(()=>l.abort(),L$r);try{let p=await iwn(i,e.input,{toolUse:e,toolUseBlock:e,signal:l.signal});s=p.content,a=p.isError}finally{clearTimeout(u),c()}let d=F$r(e,a,U$r(s)),f=await ie(this,ll,"m",dwn).call(this,d,e.id);ie(this,ll,"m",qIe).call(this,{event:e,result:d,toolUseId:e.id,name:e.name,isError:a,posted:f,confirmation:n})}finally{je(this,D0,(o=ie(this,D0,"f"),o--,o),"f"),ie(this,D0,"f")===0&&ie(this,Fne,"f")?.call(this)}}},dwn=async function(e,n){let r=ie(this,Ud,"f"),o;for(let i=0;i<pwn;i++){r.signal.throwIfAborted();try{return await this.client.beta.sessions.events.send(this.sessionId,{events:[e]},ie(this,ll,"m",WIe).call(this)),ie(this,Vg,"f").add(n),!0}catch(s){if(o=s,GM(s))break;i<pwn-1&&await S_((i+1)*1e3,r.signal)}}return ie(this,fu,"f").error("failed to send tool result",{tool_use_id:n,error:String(o)}),!1},hwn=async function(){ie(this,D0,"f")!==0&&(await Promise.race([new Promise(e=>je(this,Fne,e,"f")),S_($$r)]),je(this,Fne,null,"f"),ie(this,D0,"f")>0&&ie(this,fu,"f").warn("drain timeout exceeded"))}});var ywn={};sr(ywn,{BashSession:()=>Yot,betaAgentToolset20260401:()=>H$r,betaBashTool:()=>V$r,betaEditTool:()=>G$r,betaGlobTool:()=>Z$r,betaGrepTool:()=>Y$r,betaReadTool:()=>q$r,betaWriteTool:()=>K$r,extractSkillArchive:()=>z$r,resolvePath:()=>W$r,resolveSkillVersion:()=>B$r,setupSkills:()=>j$r});function Wp(t){throw new vt(`${t} requires Node.js or a Node-compatible runtime`)}function j$r(t){return Wp("setupSkills")}function B$r(t,e,n){return Wp("resolveSkillVersion")}function z$r(t,e){return Wp("extractSkillArchive")}function H$r(t){return Wp("betaAgentToolset20260401")}function W$r(t,e){return Wp("resolvePath")}function V$r(t){return Wp("betaBashTool")}function q$r(t){return Wp("betaReadTool")}function K$r(t){return Wp("betaWriteTool")}function G$r(t){return Wp("betaEditTool")}function Z$r(t){return Wp("betaGlobTool")}function Y$r(t){return Wp("betaGrepTool")}var Yot,vwn=b(()=>{_a();Yot=class{constructor(e,n){Wp("BashSession")}get closed(){return Wp("BashSession")}exec(e,n={}){return Wp("BashSession")}close(){Wp("BashSession")}}});async function X$r(t,e,n,r){try{await t.beta.environments.work.stop(e.id,{environment_id:e.environment_id,force:!0},{...r,headers:we([r?.headers])})}catch(o){KM(o,409)||n.error("force-stop on exit failed",{work_id:e.id,error:String(o)})}}async function Q$r(t,e,n,r,o){let i=wwn,s=J$r,a=async()=>{try{let l=await t.beta.environments.work.heartbeat(e.id,{environment_id:e.environment_id,expected_last_heartbeat:s},{...o,headers:we([o?.headers]),signal:n.signal});s=l.last_heartbeat,l.ttl_seconds>0&&(i=Math.max(1e3,Math.min(l.ttl_seconds*1e3/2,wwn))),(l.state==="stopping"||l.state==="stopped")&&(r.info("heartbeat signals shutdown",{work_id:e.id,state:l.state}),n.abort()),l.lease_extended||(r.warn("lease not extended, shutting down",{work_id:e.id}),n.abort())}catch(l){if(n.signal.throwIfAborted(),GM(l))throw r.error("permanent heartbeat failure",{work_id:e.id,error:String(l)}),n.abort(),l;r.warn("transient heartbeat failure",{work_id:e.id,error:String(l)})}};for(await a();!n.signal.aborted;)await S_(i,n.signal),n.signal.throwIfAborted(),await a()}var YIe,Une,Jot,wwn,J$r,sq,Xot=b(()=>{jg();_a();R0();U3();L3();One();RIe();So();ZIe();jIe();Vot();wwn=3e4,J$r="NO_HEARTBEAT",sq=class{constructor(e){YIe.add(this),Une.set(this,void 0),this.client=e.client,this.environmentId=e.environmentId,this.environmentKey=e.environmentKey,this.tools=e.tools,this.workdir=e.workdir??process.cwd(),this.unrestrictedPaths=e.unrestrictedPaths,this.maxFileBytes=e.maxFileBytes,this.maxIdleMs=e.maxIdleMs,this.workerId=e.workerId,this.requestOptions=e.requestOptions,je(this,Une,e.signal,"f")}async run(e){let{environmentId:n,environmentKey:r}=this;if(n===void 0||r===void 0)throw new vt("EnvironmentWorker.run: environmentId and environmentKey are required to poll for work");let o=e??ie(this,Une,"f"),i=new ZM({client:this.client,environmentId:n,environmentKey:r,...this.workerId!==void 0?{workerId:this.workerId}:{},...o?{signal:o}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},autoStop:!1});for await(let s of i)await ie(this,YIe,"m",Jot).call(this,s,r,i.signal)}async handleItem(e){let n=e?.workId??xo("ANTHROPIC_WORK_ID"),r=e?.environmentId??xo("ANTHROPIC_ENVIRONMENT_ID"),o=e?.sessionId??xo("ANTHROPIC_SESSION_ID"),i=e?.environmentKey??this.environmentKey??xo("ANTHROPIC_ENVIRONMENT_KEY");if(!n)throw new vt("handleItem: workId is required \u2014 pass it or set ANTHROPIC_WORK_ID");if(!r)throw new vt("handleItem: environmentId is required \u2014 pass it or set ANTHROPIC_ENVIRONMENT_ID");if(!o)throw new vt("handleItem: sessionId is required \u2014 pass it or set ANTHROPIC_SESSION_ID");if(!i)throw new vt("handleItem: environmentKey is required \u2014 pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY");let s={id:n,environment_id:r,data:{type:"session",id:o}};await ie(this,YIe,"m",Jot).call(this,s,i,e?.signal??ie(this,Une,"f"))}};Une=new WeakMap,YIe=new WeakSet,Jot=async function(e,n,r){let o=hi(this.client),i=LIe(this.client,{authToken:n,helper:"environments-worker"}),s=e.data.id,a={workdir:this.workdir,client:this.client,sessionId:s,...this.unrestrictedPaths!==void 0?{unrestrictedPaths:this.unrestrictedPaths}:{},...this.maxFileBytes!==void 0?{maxFileBytes:this.maxFileBytes}:{}},l=await Promise.resolve().then(()=>(vwn(),ywn)),c=async()=>{};try{c=await l.setupSkills(a)}catch(m){o.warn("skill setup failed",{session_id:s,work_id:e.id,error:String(m)})}let u=typeof this.tools=="function"?this.tools(a):this.tools??l.betaAgentToolset20260401(a),d=new AbortController,f=DD(r,d),p=Q$r(i,e,d,o,this.requestOptions).catch(m=>{d.signal.aborted||o.error("heartbeat loop failed",{work_id:e.id,error:String(m)}),d.abort()});try{let m=new XM(s,{client:i,tools:u,...this.maxIdleMs!==void 0?{maxIdleMs:this.maxIdleMs}:{},...this.requestOptions!==void 0?{requestOptions:this.requestOptions}:{},signal:d.signal});for await(let h of m);}finally{d.abort(),f(),await p,await c().catch(m=>{o.warn("skill cleanup failed",{session_id:s,work_id:e.id,error:String(m)})}),await X$r(i,e,o,this.requestOptions)}}});var QM,Qot=b(()=>{ai();Bi();So();ls();jIe();Xot();jIe();Xot();QM=class extends nn{retrieve(e,n,r){let{environment_id:o,betas:i}=n;return this._client.get(Oe`/v1/environments/${o}/work/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{environment_id:o,betas:i,...s}=n;return this._client.post(Oe`/v1/environments/${o}/work/${e}?beta=true`,{body:s,...r,headers:we([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(Oe`/v1/environments/${e}/work?beta=true`,Lr,{query:i,...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}ack(e,n,r){let{environment_id:o,betas:i}=n;return this._client.post(Oe`/v1/environments/${o}/work/${e}/ack?beta=true`,{...r,headers:we([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}heartbeat(e,n,r){let{environment_id:o,desired_ttl_seconds:i,expected_last_heartbeat:s,betas:a}=n;return this._client.post(Oe`/v1/environments/${o}/work/${e}/heartbeat?beta=true`,{query:{desired_ttl_seconds:i,expected_last_heartbeat:s},...r,headers:we([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}poll(e,n={},r){let{betas:o,"Anthropic-Worker-ID":i,...s}=n??{};return this._client.get(Oe`/v1/environments/${e}/work/poll?beta=true`,{query:s,...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString(),...i!=null?{"Anthropic-Worker-ID":i}:void 0},r?.headers])})}stats(e,n={},r){let{betas:o}=n??{};return this._client.get(Oe`/v1/environments/${e}/work/stats?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}stop(e,n,r){let{environment_id:o,betas:i,...s}=n;return this._client.post(Oe`/v1/environments/${o}/work/${e}/stop?beta=true`,{body:s,...r,headers:we([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}poller(e){return new ZM({...e,client:this._client})}worker(e){return new sq({...e,client:this._client})}};QM.WorkPoller=ZM;QM.EnvironmentWorker=sq});var UD,eit=b(()=>{ai();Qot();Qot();Bi();So();ls();UD=class extends nn{constructor(){super(...arguments),this.work=new QM(this._client)}create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/environments?beta=true",{body:o,...n,headers:we([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(Oe`/v1/environments/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(Oe`/v1/environments/${e}?beta=true`,{body:i,...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/environments?beta=true",Lr,{query:o,...n,headers:we([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(Oe`/v1/environments/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,n={},r){let{betas:o}=n??{};return this._client.post(Oe`/v1/environments/${e}/archive?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};UD.Work=QM});var aq,tit=b(()=>{ai();Bi();So();ls();aq=class extends nn{create(e,n,r){let{view:o,betas:i,...s}=n;return this._client.post(Oe`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:o},body:s,...r,headers:we([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString()},r?.headers])})}retrieve(e,n,r){let{memory_store_id:o,betas:i,...s}=n;return this._client.get(Oe`/v1/memory_stores/${o}/memories/${e}?beta=true`,{query:s,...r,headers:we([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString()},r?.headers])})}update(e,n,r){let{memory_store_id:o,view:i,betas:s,...a}=n;return this._client.post(Oe`/v1/memory_stores/${o}/memories/${e}?beta=true`,{query:{view:i},body:a,...r,headers:we([{"anthropic-beta":[...s??[],"agent-memory-2026-07-22"].toString()},r?.headers])})}list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(Oe`/v1/memory_stores/${e}/memories?beta=true`,Lr,{query:i,...r,headers:we([{"anthropic-beta":[...o??[],"agent-memory-2026-07-22"].toString()},r?.headers])})}delete(e,n,r){let{memory_store_id:o,expected_content_sha256:i,betas:s}=n;return this._client.delete(Oe`/v1/memory_stores/${o}/memories/${e}?beta=true`,{query:{expected_content_sha256:i},...r,headers:we([{"anthropic-beta":[...s??[],"agent-memory-2026-07-22"].toString()},r?.headers])})}}});var lq,nit=b(()=>{ai();Bi();So();ls();lq=class extends nn{retrieve(e,n,r){let{memory_store_id:o,betas:i,...s}=n;return this._client.get(Oe`/v1/memory_stores/${o}/memory_versions/${e}?beta=true`,{query:s,...r,headers:we([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString()},r?.headers])})}list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(Oe`/v1/memory_stores/${e}/memory_versions?beta=true`,Lr,{query:i,...r,headers:we([{"anthropic-beta":[...o??[],"agent-memory-2026-07-22"].toString()},r?.headers])})}redact(e,n,r){let{memory_store_id:o,betas:i}=n;return this._client.post(Oe`/v1/memory_stores/${o}/memory_versions/${e}/redact?beta=true`,{...r,headers:we([{"anthropic-beta":[...i??[],"agent-memory-2026-07-22"].toString()},r?.headers])})}}});var eO,rit=b(()=>{ai();tit();tit();nit();nit();Bi();So();ls();eO=class extends nn{constructor(){super(...arguments),this.memories=new aq(this._client),this.memoryVersions=new lq(this._client)}create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/memory_stores?beta=true",{body:o,...n,headers:we([{"anthropic-beta":[...r??[],"agent-memory-2026-07-22"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(Oe`/v1/memory_stores/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"agent-memory-2026-07-22"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(Oe`/v1/memory_stores/${e}?beta=true`,{body:i,...r,headers:we([{"anthropic-beta":[...o??[],"agent-memory-2026-07-22"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/memory_stores?beta=true",Lr,{query:o,...n,headers:we([{"anthropic-beta":[...r??[],"agent-memory-2026-07-22"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(Oe`/v1/memory_stores/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"agent-memory-2026-07-22"].toString()},r?.headers])})}archive(e,n={},r){let{betas:o}=n??{};return this._client.post(Oe`/v1/memory_stores/${e}/archive?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"agent-memory-2026-07-22"].toString()},r?.headers])})}};eO.Memories=aq;eO.MemoryVersions=lq});var cq=b(()=>{_a()});var uq,oit=b(()=>{_a();$3();Sot();uq=class t{constructor(e,n){this.iterator=e,this.controller=n}async*decoder(){let e=new L0;for await(let n of this.iterator)for(let r of e.decode(n))yield JSON.parse(r);for(let n of e.flush())yield JSON.parse(n)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,n){if(!e.body)throw n.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new vt("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new vt("Attempted to iterate over a response with no body");return new t(vne(e.body),n)}}});var dq,iit=b(()=>{ai();Bi();So();oit();cq();ls();dq=class extends nn{create(e,n){let{betas:r,user_profile_id:o,...i}=e;return this._client.post("/v1/messages/batches?beta=true",{body:i,...n,headers:we([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString(),...o!=null?{"anthropic-user-profile-id":o}:void 0},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(Oe`/v1/messages/batches/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",Jv,{query:o,...n,headers:we([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(Oe`/v1/messages/batches/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},r?.headers])})}cancel(e,n={},r){let{betas:o}=n??{};return this._client.post(Oe`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},r?.headers])})}async results(e,n={},r){let o=await this.retrieve(e);if(!o.results_url)throw new vt(`No batch \`results_url\`; Has it finished processing? ${o.processing_status} - ${o.id}`);let{betas:i}=n??{};return this._client.get(o.results_url,{...r,headers:we([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},r?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((s,a)=>uq.fromResponse(a.response,a.controller))}}});var JIe,sit=b(()=>{JIe={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192}});function bwn(t){return t?.output_format??t?.output_config?.format}function ait(t,e,n){let r=bwn(e);return!e||!("parse"in(r??{}))?{...t,content:t.content.map(o=>{if(o.type==="text"){let i=Object.defineProperty({...o},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(i,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return o}),parsed_output:null}:lit(t,e,n)}function lit(t,e,n){let r=null,o=t.content.map(i=>{if(i.type==="text"){let s=sDr(e,i.text);r===null&&(r=s);let a=Object.defineProperty({...i},"parsed_output",{value:s,enumerable:!1});return Object.defineProperty(a,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),s},enumerable:!1})}return i});return{...t,content:o,parsed_output:r}}function sDr(t,e){let n=bwn(t);if(n?.type!=="json_schema")return null;try{return"parse"in n?n.parse(e):JSON.parse(e)}catch(r){throw new vt(`Failed to parse structured output: ${r}`)}}var cit=b(()=>{_a()});var uit=b(()=>{Sne()});var aDr,fq,lDr,cDr,_wn,xwn=b(()=>{aDr=t=>{let e=0,n=[];for(;e<t.length;){let r=t[e];if(r==="\\"){e++;continue}if(r==="{"){n.push({type:"brace",value:"{"}),e++;continue}if(r==="}"){n.push({type:"brace",value:"}"}),e++;continue}if(r==="["){n.push({type:"paren",value:"["}),e++;continue}if(r==="]"){n.push({type:"paren",value:"]"}),e++;continue}if(r===":"){n.push({type:"separator",value:":"}),e++;continue}if(r===","){n.push({type:"delimiter",value:","}),e++;continue}if(r==='"'){let a="",l=!1;for(r=t[++e];r!=='"';){if(e===t.length){l=!0;break}if(r==="\\"){if(e++,e===t.length){l=!0;break}a+=r+t[e],r=t[++e]}else a+=r,r=t[++e]}r=t[++e],l||n.push({type:"string",value:a});continue}if(r&&/\s/.test(r)){e++;continue}let i=/[0-9]/;if(r&&i.test(r)||r==="-"||r==="."){let a="";for(r==="-"&&(a+=r,r=t[++e]);r&&(i.test(r)||r==="."||r==="e"||r==="E"||(r==="-"||r==="+")&&(a[a.length-1]==="e"||a[a.length-1]==="E"));)a+=r,r=t[++e];n.push({type:"number",value:a});continue}let s=/[a-z]/i;if(r&&s.test(r)){let a="";for(;r&&s.test(r)&&e!==t.length;)a+=r,r=t[++e];if(a=="true"||a=="false"||a==="null")n.push({type:"name",value:a});else{e++;continue}continue}e++}return n},fq=t=>{if(t.length===0)return t;let e=t[t.length-1];switch(e.type){case"separator":return t=t.slice(0,t.length-1),fq(t);break;case"number":let n=e.value[e.value.length-1];if(n==="."||n==="-"||n==="+"||n==="e"||n==="E")return t=t.slice(0,t.length-1),fq(t);case"string":let r=t[t.length-2];if(r?.type==="delimiter")return t=t.slice(0,t.length-1),fq(t);if(r?.type==="brace"&&r.value==="{")return t=t.slice(0,t.length-1),fq(t);break;case"delimiter":return t=t.slice(0,t.length-1),fq(t);break}return t},lDr=t=>{let e=[];return t.map(n=>{n.type==="brace"&&(n.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),n.type==="paren"&&(n.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(n=>{n==="}"?t.push({type:"brace",value:"}"}):n==="]"&&t.push({type:"paren",value:"]"})}),t},cDr=t=>{let e="";return t.map(n=>{switch(n.type){case"string":e+='"'+n.value+'"';break;default:e+=n.value;break}}),e},_wn=t=>JSON.parse(cDr(lDr(fq(aDr(t)))))});function XIe(t,e){let n={};for(let i of Object.keys(t))i!=="input"&&(n[i]=t[i]);Object.defineProperty(n,tO,{value:e,enumerable:!1,writable:!0});let r,o=!1;return Object.defineProperty(n,"input",{enumerable:!0,configurable:!0,get(){return o||(r=e?_wn(e):{},o=!0),r}}),n}var tO,dit=b(()=>{xwn();tO="__json_buf"});function yit(t){return t.type==="tool_use"||t.type==="server_tool_use"||t.type==="mcp_tool_use"}var dh,nO,pq,jne,QIe,Bne,zne,e0e,Hne,oC,Wne,t0e,n0e,jD,r0e,o0e,Vne,fit,Swn,qne,pit,mit,hit,Cwn,git,i0e,kwn=b(()=>{jg();rC();cq();WM();uit();cit();dit();i0e=class t{constructor(e,n){dh.add(this),this.messages=[],this.receivedMessages=[],nO.set(this,void 0),pq.set(this,null),this.controller=new AbortController,jne.set(this,void 0),QIe.set(this,()=>{}),Bne.set(this,()=>{}),zne.set(this,void 0),e0e.set(this,()=>{}),Hne.set(this,()=>{}),oC.set(this,{}),Wne.set(this,!1),t0e.set(this,!1),n0e.set(this,!1),jD.set(this,!1),r0e.set(this,void 0),o0e.set(this,void 0),Vne.set(this,void 0),qne.set(this,r=>{if(je(this,t0e,!0,"f"),Zv(r)&&(r=new Fd),r instanceof Fd)return je(this,n0e,!0,"f"),this._emit("abort",r);if(r instanceof vt)return this._emit("error",r);if(r instanceof Error){let o=new vt(r.message);return o.cause=r,this._emit("error",o)}return this._emit("error",new vt(String(r)))}),je(this,jne,new Promise((r,o)=>{je(this,QIe,r,"f"),je(this,Bne,o,"f")}),"f"),je(this,zne,new Promise((r,o)=>{je(this,e0e,r,"f"),je(this,Hne,o,"f")}),"f"),ie(this,jne,"f").catch(()=>{}),ie(this,zne,"f").catch(()=>{}),je(this,pq,e,"f"),je(this,Vne,n?.logger??console,"f")}get response(){return ie(this,r0e,"f")}get request_id(){return ie(this,o0e,"f")}async withResponse(){je(this,jD,!0,"f");let e=await ie(this,jne,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let n=new t(null);return n._run(()=>n._fromReadableStream(e)),n}static createMessage(e,n,r,{logger:o}={}){let i=new t(n,{logger:o});for(let s of n.messages)i._addMessageParam(s);return je(i,pq,{...n,stream:!0},"f"),i._run(()=>i._createMessage(e,{...n,stream:!0},{...r,headers:{...r?.headers,[AIe]:"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},ie(this,qne,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,n=!0){this.receivedMessages.push(e),n&&this._emit("message",e)}async _createMessage(e,n,r){let o=r?.signal,i;o&&(o.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),o.addEventListener("abort",i));try{ie(this,dh,"m",pit).call(this);let{response:s,data:a}=await e.create({...n,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(s);for await(let l of a)ie(this,dh,"m",mit).call(this,l);if(a.controller.signal?.aborted)throw new Fd;ie(this,dh,"m",hit).call(this)}finally{o&&i&&o.removeEventListener("abort",i)}}_connected(e){this.ended||(je(this,r0e,e,"f"),je(this,o0e,e?.headers.get("request-id"),"f"),ie(this,QIe,"f").call(this,e),this._emit("connect"))}get ended(){return ie(this,Wne,"f")}get errored(){return ie(this,t0e,"f")}get aborted(){return ie(this,n0e,"f")}abort(){this.controller.abort()}on(e,n){return(ie(this,oC,"f")[e]||(ie(this,oC,"f")[e]=[])).push({listener:n}),this}off(e,n){let r=ie(this,oC,"f")[e];if(!r)return this;let o=r.findIndex(i=>i.listener===n);return o>=0&&r.splice(o,1),this}once(e,n){return(ie(this,oC,"f")[e]||(ie(this,oC,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,r)=>{je(this,jD,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,n)})}async done(){je(this,jD,!0,"f"),await ie(this,zne,"f")}get currentMessage(){return ie(this,nO,"f")}async finalMessage(){return await this.done(),ie(this,dh,"m",fit).call(this)}async finalText(){return await this.done(),ie(this,dh,"m",Swn).call(this)}_emit(e,...n){if(ie(this,Wne,"f"))return;e==="end"&&(je(this,Wne,!0,"f"),ie(this,e0e,"f").call(this));let r=ie(this,oC,"f")[e];if(r&&(ie(this,oC,"f")[e]=r.filter(o=>!o.once),r.forEach(({listener:o})=>o(...n))),e==="abort"){let o=n[0];!ie(this,jD,"f")&&!r?.length&&Promise.reject(o),ie(this,Bne,"f").call(this,o),ie(this,Hne,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=n[0];!ie(this,jD,"f")&&!r?.length&&Promise.reject(o),ie(this,Bne,"f").call(this,o),ie(this,Hne,"f").call(this,o),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",ie(this,dh,"m",fit).call(this))}async _fromReadableStream(e,n){let r=n?.signal,o;r&&(r.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),r.addEventListener("abort",o));try{ie(this,dh,"m",pit).call(this),this._connected(null);let i=Hg.fromReadableStream(e,this.controller);for await(let s of i)ie(this,dh,"m",mit).call(this,s);if(i.controller.signal?.aborted)throw new Fd;ie(this,dh,"m",hit).call(this)}finally{r&&o&&r.removeEventListener("abort",o)}}[(nO=new WeakMap,pq=new WeakMap,jne=new WeakMap,QIe=new WeakMap,Bne=new WeakMap,zne=new WeakMap,e0e=new WeakMap,Hne=new WeakMap,oC=new WeakMap,Wne=new WeakMap,t0e=new WeakMap,n0e=new WeakMap,jD=new WeakMap,r0e=new WeakMap,o0e=new WeakMap,Vne=new WeakMap,qne=new WeakMap,dh=new WeakSet,fit=function(){if(this.receivedMessages.length===0)throw new vt("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Swn=function(){if(this.receivedMessages.length===0)throw new vt("stream ended without producing a Message with role=assistant");let n=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(n.length===0)throw new vt("stream ended without producing a content block with type=text");return n.join(" ")},pit=function(){this.ended||je(this,nO,void 0,"f")},mit=function(n){if(this.ended)return;let r=ie(this,dh,"m",Cwn).call(this,n);switch(this._emit("streamEvent",n,r),n.type){case"content_block_delta":{let o=r.content.at(-1);switch(n.delta.type){case"text_delta":{o.type==="text"&&this._emit("text",n.delta.text,o.text||"");break}case"citations_delta":{o.type==="text"&&this._emit("citation",n.delta.citation,o.citations??[]);break}case"input_json_delta":{if(yit(o)&&ie(this,oC,"f").inputJson?.length){let i;try{i=o.input}catch(s){ie(this,qne,"f").call(this,ie(this,dh,"m",git).call(this,o,s));break}this._emit("inputJson",n.delta.partial_json,i)}break}case"thinking_delta":{o.type==="thinking"&&this._emit("thinking",n.delta.thinking,o.thinking);break}case"signature_delta":{o.type==="thinking"&&this._emit("signature",o.signature);break}case"compaction_delta":{o.type==="compaction"&&o.content&&this._emit("compaction",o.content);break}default:n.delta}break}case"message_stop":{this._addMessageParam(r),this._addMessage(ait(r,ie(this,pq,"f"),{logger:ie(this,Vne,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{je(this,nO,r,"f");break}case"content_block_start":case"message_delta":break}},hit=function(){if(this.ended)throw new vt("stream has ended, this shouldn't happen");let n=ie(this,nO,"f");if(!n)throw new vt("request ended without sending any chunks");return je(this,nO,void 0,"f"),ait(n,ie(this,pq,"f"),{logger:ie(this,Vne,"f")})},Cwn=function(n){let r=ie(this,nO,"f");if(n.type==="message_start"){if(r)throw new vt(`Unexpected event order, got ${n.type} before receiving "message_stop"`);return n.message}if(!r)throw new vt(`Unexpected event order, got ${n.type} before "message_start"`);switch(n.type){case"message_stop":return r;case"message_delta":return r.container=n.delta.container,r.stop_reason=n.delta.stop_reason,r.stop_sequence=n.delta.stop_sequence,n.delta.stop_details!=null&&(r.stop_details=n.delta.stop_details),r.usage.output_tokens=n.usage.output_tokens,r.context_management=n.context_management,n.usage.input_tokens!=null&&(r.usage.input_tokens=n.usage.input_tokens),n.usage.cache_creation_input_tokens!=null&&(r.usage.cache_creation_input_tokens=n.usage.cache_creation_input_tokens),n.usage.cache_read_input_tokens!=null&&(r.usage.cache_read_input_tokens=n.usage.cache_read_input_tokens),n.usage.server_tool_use!=null&&(r.usage.server_tool_use=n.usage.server_tool_use),n.usage.iterations!=null&&(r.usage.iterations=n.usage.iterations),n.usage.fallback_credit!=null&&(r.usage.fallback_credit=n.usage.fallback_credit),r;case"content_block_start":return r.content.push(n.content_block),n.content_block.type==="fallback"&&(r.model=n.content_block.to.model),r;case"content_block_delta":{let o=r.content.at(n.index);switch(n.delta.type){case"text_delta":{o?.type==="text"&&(r.content[n.index]={...o,text:(o.text||"")+n.delta.text});break}case"citations_delta":{o?.type==="text"&&(r.content[n.index]={...o,citations:[...o.citations??[],n.delta.citation]});break}case"input_json_delta":{if(o&&yit(o)){let i=(o[tO]||"")+n.delta.partial_json;r.content[n.index]=XIe(o,i)}break}case"thinking_delta":{o?.type==="thinking"&&(r.content[n.index]={...o,thinking:o.thinking+n.delta.thinking});break}case"signature_delta":{o?.type==="thinking"&&(r.content[n.index]={...o,signature:n.delta.signature});break}case"compaction_delta":{o?.type==="compaction"&&(r.content[n.index]={...o,content:(o.content||"")+n.delta.content,encrypted_content:n.delta.encrypted_content});break}default:n.delta}return r}case"content_block_stop":{let o=r.content.at(n.index);if(o&&yit(o)&&tO in o){let i;try{i=o.input}catch(s){i={},ie(this,qne,"f").call(this,ie(this,dh,"m",git).call(this,o,s))}Object.defineProperty(o,"input",{value:i,enumerable:!0,configurable:!0,writable:!0})}return r}}},git=function(n,r){let o=n[tO];return new vt(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${r}. JSON: ${o}`)},Symbol.asyncIterator)](){let e=[],n=[],r=!1;return this.on("streamEvent",o=>{let i=n.shift();i?i.resolve(o):e.push(o)}),this.on("end",()=>{r=!0;for(let o of n)o.resolve(void 0);n.length=0}),this.on("abort",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),this.on("error",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,s)=>n.push({resolve:i,reject:s})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Hg(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}});function vit(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}var Iwn=b(()=>{});var Twn,Pwn=b(()=>{Twn=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
1. Task Overview
The user's core request and success criteria
Any clarifications or constraints they specified
2. Current State
What has been completed so far
Files created, modified, or analyzed (with paths if relevant)
Key outputs or artifacts produced
3. Important Discoveries
Technical constraints or requirements uncovered
Decisions made and their rationale
Errors encountered and how they were resolved
What approaches were tried that didn't work (and why)
4. Next Steps
Specific actions needed to complete the task
Any blockers or open questions to resolve
Priority order if multiple steps remain
5. Context to Preserve
User preferences or style requirements
Domain-specific details that aren't obvious
Any promises made to the user
Be concise but complete\u2014err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
Wrap your summary in <summary></summary> tags.`});async function dDr(t,e=t.messages.at(-1),n){if(!e||e.role!=="assistant"||!e.content||typeof e.content=="string")return null;let r=e.content.filter(s=>s.type==="tool_use");if(r.length===0)return null;let o=pDr(t);return{role:"user",content:await Promise.all(r.map(async s=>{let a=t.tools.find(l=>("name"in l?l.name:l.mcp_server_name)===s.name);if(!a||!("run"in a)||!o.has(s.name))return fDr(s);try{let l=s.input;"parse"in a&&a.parse&&(l=a.parse(l));let c=await a.run(l,{toolUse:s,toolUseBlock:s,signal:n?.signal});return{type:"tool_result",tool_use_id:s.id,content:c}}catch(l){return{type:"tool_result",tool_use_id:s.id,content:l instanceof $0?l.content:`Error: ${l instanceof Error?l.message:String(l)}`,is_error:!0}}}))}}function fDr(t){return{type:"tool_result",tool_use_id:t.id,content:`Error: Tool '${t.name}' not found`,is_error:!0}}function pDr(t){let e=new Set;for(let n of t.tools)"run"in n&&e.add(n.name);for(let n of t.messages)if(!(n.role!=="system"||typeof n.content=="string"))for(let r of n.content)mDr(r,e);return e}function mDr(t,e){switch(t.type){case"tool_removal":case"tool_addition":Ewn(t,e);break;case"mid_conv_system":for(let n of t.content)(n.type==="tool_removal"||n.type==="tool_addition")&&Ewn(n,e);break;default:break}}function Ewn(t,e){let n=hDr(t.tool);n!==void 0&&(t.type==="tool_removal"?e.delete(n):e.add(n))}function hDr(t){switch(t.type){case"tool_reference":return t.name;default:return}}var Kne,mq,BD,pu,fh,qg,F0,rO,Gne,Awn,wit,hq,bit=b(()=>{jg();Lne();_a();So();Iwn();Pwn();rC();hq=class{constructor(e,n,r){Kne.add(this),this.client=e,mq.set(this,!1),BD.set(this,!1),pu.set(this,void 0),fh.set(this,void 0),qg.set(this,void 0),F0.set(this,void 0),rO.set(this,void 0),Gne.set(this,0),je(this,pu,{params:{...n,messages:structuredClone(n.messages)}},"f");let o=Lot(n.tools,n.messages);je(this,fh,{...r,headers:we([Ene("BetaToolRunner"),o.length?{[VM]:o.join(", ")}:void 0,r?.headers])},"f"),je(this,rO,vit(),"f"),n.compactionControl?.enabled&&console.warn('Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction')}async*[(mq=new WeakMap,BD=new WeakMap,pu=new WeakMap,fh=new WeakMap,qg=new WeakMap,F0=new WeakMap,rO=new WeakMap,Gne=new WeakMap,Kne=new WeakSet,Awn=async function(){let n=ie(this,pu,"f").params.compactionControl;if(!n||!n.enabled)return!1;let r=0;if(ie(this,qg,"f")!==void 0)try{let c=await ie(this,qg,"f");r=c.usage.input_tokens+(c.usage.cache_creation_input_tokens??0)+(c.usage.cache_read_input_tokens??0)+c.usage.output_tokens}catch{return!1}let o=n.contextTokenThreshold??1e5;if(r<o)return!1;let i=n.model??ie(this,pu,"f").params.model,s=n.summaryPrompt??Twn,a=ie(this,pu,"f").params.messages;if(a[a.length-1].role==="assistant"){let c=a[a.length-1];if(Array.isArray(c.content)){let u=c.content.filter(d=>d.type!=="tool_use");u.length===0?a.pop():c.content=u}}let l=await this.client.beta.messages.create({model:i,messages:[...a,{role:"user",content:[{type:"text",text:s}]}],max_tokens:ie(this,pu,"f").params.max_tokens},{signal:ie(this,fh,"f").signal,headers:we([ie(this,fh,"f").headers,Ene("compaction")])});if(l.content[0]?.type!=="text")throw new vt("Expected text response for compaction");return ie(this,pu,"f").params.messages=[{role:"user",content:l.content}],!0},Symbol.asyncIterator)](){var e;if(ie(this,mq,"f"))throw new vt("Cannot iterate over a consumed stream");je(this,mq,!0,"f"),je(this,BD,!0,"f"),je(this,F0,void 0,"f");try{for(;;){let n;try{if(ie(this,pu,"f").params.max_iterations&&ie(this,Gne,"f")>=ie(this,pu,"f").params.max_iterations)break;je(this,BD,!1,"f"),je(this,F0,void 0,"f"),je(this,Gne,(e=ie(this,Gne,"f"),e++,e),"f"),je(this,qg,void 0,"f");let{max_iterations:r,compactionControl:o,...i}=ie(this,pu,"f").params;if(i.stream?(n=this.client.beta.messages.stream({...i},ie(this,fh,"f")),je(this,qg,n.finalMessage(),"f"),ie(this,qg,"f").catch(()=>{}),yield n):(je(this,qg,this.client.beta.messages.create({...i,stream:!1},ie(this,fh,"f")),"f"),yield ie(this,qg,"f")),!await ie(this,Kne,"m",Awn).call(this)){if(!ie(this,BD,"f")){let l=await ie(this,qg,"f");if(ie(this,pu,"f").params.messages.push({role:l.role,content:l.content}),l.stop_reason==="refusal")break}let a=await ie(this,Kne,"m",wit).call(this,ie(this,pu,"f").params.messages.at(-1));if(a)ie(this,pu,"f").params.messages.push(a);else if(!ie(this,BD,"f"))break}}finally{n&&n.abort()}}if(!ie(this,qg,"f"))throw new vt("ToolRunner concluded without a message from the server");ie(this,rO,"f").resolve(await ie(this,qg,"f"))}catch(n){throw je(this,mq,!1,"f"),ie(this,rO,"f").promise.catch(()=>{}),ie(this,rO,"f").reject(n),je(this,rO,vit(),"f"),n}}setMessagesParams(e){typeof e=="function"?ie(this,pu,"f").params=e(ie(this,pu,"f").params):ie(this,pu,"f").params=e,je(this,BD,!0,"f"),je(this,F0,void 0,"f")}setRequestOptions(e){typeof e=="function"?je(this,fh,e(ie(this,fh,"f")),"f"):je(this,fh,{...ie(this,fh,"f"),...e},"f")}async generateToolResponse(e=ie(this,fh,"f").signal){let n=await ie(this,qg,"f")??this.params.messages.at(-1);return n?ie(this,Kne,"m",wit).call(this,n,e):null}done(){return ie(this,rO,"f").promise}async runUntilDone(){if(!ie(this,mq,"f"))for await(let e of this);return this.done()}get params(){return ie(this,pu,"f").params}pushMessages(...e){this.setMessagesParams(n=>({...n,messages:[...n.messages,...e]}))}then(e,n){return this.runUntilDone().then(e,n)}};wit=async function(e,n=ie(this,fh,"f").signal){return ie(this,F0,"f")!==void 0?ie(this,F0,"f"):(je(this,F0,dDr(ie(this,pu,"f").params,e,{...ie(this,fh,"f"),signal:n}),"f"),ie(this,F0,"f"))}});function Own(t){if(!t.output_format)return t;if(t.output_config?.format)throw new vt("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:e,...n}=t;return{...n,output_config:{...t.output_config,format:e}}}var Mwn,gDr,U0,_it=b(()=>{cq();iit();ai();sit();So();rC();cit();kwn();bit();Lne();iit();bit();Lne();Mwn={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026","claude-3-5-haiku-latest":"February 19th, 2026","claude-3-5-haiku-20241022":"February 19th, 2026","claude-opus-4-0":"June 15th, 2026","claude-opus-4-20250514":"June 15th, 2026","claude-sonnet-4-0":"June 15th, 2026","claude-sonnet-4-20250514":"June 15th, 2026","claude-opus-4-1":"August 5th, 2026","claude-opus-4-1-20250805":"August 5th, 2026","claude-mythos-preview":"June 30th, 2026"},gDr=["claude-mythos-preview","claude-opus-4-6"],U0=class extends nn{constructor(){super(...arguments),this.batches=new dq(this._client)}create(e,n){let r=Own(e),{betas:o,user_profile_id:i,...s}=r;s.model in Mwn&&console.warn(`The model '${s.model}' is deprecated and will reach end-of-life on ${Mwn[s.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),gDr.includes(s.model)&&s.thinking&&s.thinking.type==="enabled"&&console.warn(`Using Claude with ${s.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let a=this._client._options.timeout;if(!s.stream&&a==null){let c=JIe[s.model]??void 0;a=this._client.calculateNonstreamingTimeout(s.max_tokens,c)}let l=EIe(s.tools,s.messages);return this._client.post("/v1/messages?beta=true",{body:s,timeout:a??6e5,...n,headers:we([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void 0,...i!=null?{"anthropic-user-profile-id":i}:void 0},l,n?.headers]),stream:r.stream??!1})}parse(e,n){return n={...n,headers:we([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},n?.headers])},this.create(e,n).then(r=>lit(r,e,{logger:this._client.logger??console}))}stream(e,n){return i0e.createMessage(this,e,n)}countTokens(e,n){let r=Own(e),{betas:o,user_profile_id:i,...s}=r;return this._client.post("/v1/messages/count_tokens?beta=true",{body:s,...n,headers:we([{"anthropic-beta":[...o??[],"token-counting-2024-11-01"].toString(),...i!=null?{"anthropic-user-profile-id":i}:void 0},n?.headers])})}toolRunner(e,n){return new hq(this._client,e,n)}};U0.Batches=dq;U0.BetaToolRunner=hq;U0.ToolError=$0});var zD,xit=b(()=>{ai();Bi();So();ls();ZIe();ZIe();zD=class extends nn{list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(Oe`/v1/sessions/${e}/events?beta=true`,Lr,{query:i,...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}send(e,n,r){let{betas:o,...i}=n;return this._client.post(Oe`/v1/sessions/${e}/events?beta=true`,{body:i,...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}stream(e,n={},r){let{betas:o,...i}=n??{};return this._client.get(Oe`/v1/sessions/${e}/events/stream?beta=true`,{query:i,...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers]),stream:!0})}toolRunner(e,n){return new XM(e,{...n,client:this._client})}};zD.SessionToolRunner=XM});var gq,Sit=b(()=>{ai();Bi();So();ls();gq=class extends nn{retrieve(e,n,r){let{session_id:o,betas:i}=n;return this._client.get(Oe`/v1/sessions/${o}/resources/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{session_id:o,betas:i,...s}=n;return this._client.post(Oe`/v1/sessions/${o}/resources/${e}?beta=true`,{body:s,...r,headers:we([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(Oe`/v1/sessions/${e}/resources?beta=true`,Lr,{query:i,...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,n,r){let{session_id:o,betas:i}=n;return this._client.delete(Oe`/v1/sessions/${o}/resources/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}add(e,n,r){let{betas:o,...i}=n;return this._client.post(Oe`/v1/sessions/${e}/resources?beta=true`,{body:i,...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}});var yq,Cit=b(()=>{ai();Bi();So();ls();yq=class extends nn{list(e,n,r){let{session_id:o,betas:i,...s}=n;return this._client.getAPIList(Oe`/v1/sessions/${o}/threads/${e}/events?beta=true`,Lr,{query:s,...r,headers:we([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}stream(e,n,r){let{session_id:o,betas:i,...s}=n;return this._client.get(Oe`/v1/sessions/${o}/threads/${e}/stream?beta=true`,{query:s,...r,headers:we([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers]),stream:!0})}}});var HD,kit=b(()=>{ai();Cit();Cit();Bi();So();ls();HD=class extends nn{constructor(){super(...arguments),this.events=new yq(this._client)}retrieve(e,n,r){let{session_id:o,betas:i}=n;return this._client.get(Oe`/v1/sessions/${o}/threads/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(Oe`/v1/sessions/${e}/threads?beta=true`,Lr,{query:i,...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,n,r){let{session_id:o,betas:i}=n;return this._client.post(Oe`/v1/sessions/${o}/threads/${e}/archive?beta=true`,{...r,headers:we([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};HD.Events=yq});var j0,Iit=b(()=>{ai();xit();xit();Sit();Sit();kit();kit();Bi();So();ls();j0=class extends nn{constructor(){super(...arguments),this.events=new zD(this._client),this.resources=new gq(this._client),this.threads=new HD(this._client)}create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/sessions?beta=true",{body:o,...n,headers:we([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(Oe`/v1/sessions/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(Oe`/v1/sessions/${e}?beta=true`,{body:i,...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/sessions?beta=true",kIe,{query:o,...n,headers:we([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(Oe`/v1/sessions/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,n={},r){let{betas:o}=n??{};return this._client.post(Oe`/v1/sessions/${e}/archive?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};j0.Events=zD;j0.Resources=gq;j0.Threads=HD});var vq,Tit=b(()=>{ai();Bi();So();z3();ls();vq=class extends nn{create(e,n,r){let{betas:o,...i}=n;return this._client.post(Oe`/v1/skills/${e}/versions?beta=true`,B3({body:i,...r,headers:we([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},r?.headers])},this._client,!1))}retrieve(e,n,r){let{skill_id:o,betas:i}=n;return this._client.get(Oe`/v1/skills/${o}/versions/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...i??[],"skills-2025-10-02"].toString()},r?.headers])})}list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(Oe`/v1/skills/${e}/versions?beta=true`,Lr,{query:i,...r,headers:we([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},r?.headers])})}delete(e,n,r){let{skill_id:o,betas:i}=n;return this._client.delete(Oe`/v1/skills/${o}/versions/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...i??[],"skills-2025-10-02"].toString()},r?.headers])})}download(e,n,r){let{skill_id:o,betas:i}=n;return this._client.get(Oe`/v1/skills/${o}/versions/${e}/content?beta=true`,{...r,headers:we([{"anthropic-beta":[...i??[],"skills-2025-10-02"].toString(),Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}});var WD,Pit=b(()=>{ai();Tit();Tit();Bi();So();z3();ls();WD=class extends nn{constructor(){super(...arguments),this.versions=new vq(this._client)}create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/skills?beta=true",B3({body:o,...n,headers:we([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},n?.headers])},this._client,!1))}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(Oe`/v1/skills/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/skills?beta=true",Lr,{query:o,...n,headers:we([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(Oe`/v1/skills/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},r?.headers])})}};WD.Versions=vq});var wq,Ait=b(()=>{ai();Bi();So();ls();wq=class extends nn{create(e,n,r){let{betas:o,...i}=n;return this._client.post(Oe`/v1/tunnels/${e}/certificates?beta=true`,{body:i,...r,headers:we([{"anthropic-beta":[...o??[],"mcp-tunnels-2026-06-22"].toString()},r?.headers])})}retrieve(e,n,r){let{tunnel_id:o,betas:i}=n;return this._client.get(Oe`/v1/tunnels/${o}/certificates/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString()},r?.headers])})}list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(Oe`/v1/tunnels/${e}/certificates?beta=true`,Lr,{query:i,...r,headers:we([{"anthropic-beta":[...o??[],"mcp-tunnels-2026-06-22"].toString()},r?.headers])})}archive(e,n,r){let{tunnel_id:o,betas:i}=n;return this._client.post(Oe`/v1/tunnels/${o}/certificates/${e}/archive?beta=true`,{...r,headers:we([{"anthropic-beta":[...i??[],"mcp-tunnels-2026-06-22"].toString()},r?.headers])})}}});var VD,Eit=b(()=>{ai();Ait();Ait();Bi();So();ls();VD=class extends nn{constructor(){super(...arguments),this.certificates=new wq(this._client)}create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/tunnels?beta=true",{body:o,...n,headers:we([{"anthropic-beta":[...r??[],"mcp-tunnels-2026-06-22"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(Oe`/v1/tunnels/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"mcp-tunnels-2026-06-22"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/tunnels?beta=true",Lr,{query:o,...n,headers:we([{"anthropic-beta":[...r??[],"mcp-tunnels-2026-06-22"].toString()},n?.headers])})}archive(e,n={},r){let{betas:o}=n??{};return this._client.post(Oe`/v1/tunnels/${e}/archive?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"mcp-tunnels-2026-06-22"].toString()},r?.headers])})}revealToken(e,n={},r){let{betas:o}=n??{};return this._client.post(Oe`/v1/tunnels/${e}/reveal_token?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"mcp-tunnels-2026-06-22"].toString()},r?.headers])})}rotateToken(e,n,r){let{betas:o,...i}=n;return this._client.post(Oe`/v1/tunnels/${e}/rotate_token?beta=true`,{body:i,...r,headers:we([{"anthropic-beta":[...o??[],"mcp-tunnels-2026-06-22"].toString()},r?.headers])})}};VD.Certificates=wq});var bq,Mit=b(()=>{ai();Bi();So();ls();bq=class extends nn{create(e,n,r){let{betas:o,...i}=n;return this._client.post(Oe`/v1/vaults/${e}/credentials?beta=true`,{body:i,...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,n,r){let{vault_id:o,betas:i}=n;return this._client.get(Oe`/v1/vaults/${o}/credentials/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{vault_id:o,betas:i,...s}=n;return this._client.post(Oe`/v1/vaults/${o}/credentials/${e}?beta=true`,{body:s,...r,headers:we([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(Oe`/v1/vaults/${e}/credentials?beta=true`,Lr,{query:i,...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,n,r){let{vault_id:o,betas:i}=n;return this._client.delete(Oe`/v1/vaults/${o}/credentials/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,n,r){let{vault_id:o,betas:i}=n;return this._client.post(Oe`/v1/vaults/${o}/credentials/${e}/archive?beta=true`,{...r,headers:we([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}mcpOAuthValidate(e,n,r){let{vault_id:o,betas:i}=n;return this._client.post(Oe`/v1/vaults/${o}/credentials/${e}/mcp_oauth_validate?beta=true`,{...r,headers:we([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}});var qD,Oit=b(()=>{ai();Mit();Mit();Bi();So();ls();qD=class extends nn{constructor(){super(...arguments),this.credentials=new bq(this._client)}create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/vaults?beta=true",{body:o,...n,headers:we([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(Oe`/v1/vaults/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(Oe`/v1/vaults/${e}?beta=true`,{body:i,...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/vaults?beta=true",Lr,{query:o,...n,headers:we([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(Oe`/v1/vaults/${e}?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,n={},r){let{betas:o}=n??{};return this._client.post(Oe`/v1/vaults/${e}/archive?beta=true`,{...r,headers:we([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};qD.Credentials=bq});var cl,Nit=b(()=>{ai();Oot();Oot();Not();Not();Rot();Rot();$ot();$ot();Dot();Dot();Fot();Fot();Bot();Bot();Hot();Hot();eit();eit();rit();rit();_it();_it();Iit();Iit();Pit();Pit();Eit();Eit();Oit();Oit();cl=class extends nn{constructor(){super(...arguments),this.models=new K3(this._client),this.messages=new U0(this._client),this.agents=new $D(this._client),this.environments=new UD(this._client),this.sessions=new j0(this._client),this.deployments=new W3(this._client),this.deploymentRuns=new H3(this._client),this.vaults=new qD(this._client),this.memoryStores=new eO(this._client),this.files=new q3(this._client),this.skills=new WD(this._client),this.webhooks=new Y3(this._client),this.userProfiles=new G3(this._client),this.dreams=new V3(this._client),this.tunnels=new VD(this._client)}};cl.Models=K3;cl.Messages=U0;cl.Agents=$D;cl.Environments=UD;cl.Sessions=j0;cl.Deployments=W3;cl.DeploymentRuns=H3;cl.Vaults=qD;cl.MemoryStores=eO;cl.Files=q3;cl.Skills=WD;cl.Webhooks=Y3;cl.UserProfiles=G3;cl.Dreams=V3;cl.Tunnels=VD});var KD,Rit=b(()=>{ai();So();KD=class extends nn{create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/complete",{body:o,timeout:this._client._options.timeout??6e5,...n,headers:we([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers]),stream:e.stream??!1})}}});function Nwn(t){return t?.output_config?.format}function Lit(t,e,n){let r=Nwn(e);return!e||!("parse"in(r??{}))?{...t,content:t.content.map(o=>o.type==="text"?Object.defineProperty({...o},"parsed_output",{value:null,enumerable:!1}):o),parsed_output:null}:$it(t,e,n)}function $it(t,e,n){let r=null,o=t.content.map(i=>{if(i.type==="text"){let s=ADr(e,i.text);return r===null&&(r=s),Object.defineProperty({...i},"parsed_output",{value:s,enumerable:!1})}return i});return{...t,content:o,parsed_output:r}}function ADr(t,e){let n=Nwn(t);if(n?.type!=="json_schema")return null;try{return"parse"in n?n.parse(e):JSON.parse(e)}catch(r){throw new vt(`Failed to parse structured output: ${r}`)}}var Dit=b(()=>{_a()});function Hit(t){return t.type==="tool_use"||t.type==="server_tool_use"}var ew,oO,_q,Zne,s0e,Yne,Jne,a0e,Xne,iC,Qne,l0e,c0e,GD,u0e,d0e,ere,Fit,Rwn,Uit,jit,Bit,zit,Lwn,f0e,$wn=b(()=>{jg();rC();WM();cq();uit();Dit();dit();f0e=class t{constructor(e,n){ew.add(this),this.messages=[],this.receivedMessages=[],oO.set(this,void 0),_q.set(this,null),this.controller=new AbortController,Zne.set(this,void 0),s0e.set(this,()=>{}),Yne.set(this,()=>{}),Jne.set(this,void 0),a0e.set(this,()=>{}),Xne.set(this,()=>{}),iC.set(this,{}),Qne.set(this,!1),l0e.set(this,!1),c0e.set(this,!1),GD.set(this,!1),u0e.set(this,void 0),d0e.set(this,void 0),ere.set(this,void 0),Uit.set(this,r=>{if(je(this,l0e,!0,"f"),Zv(r)&&(r=new Fd),r instanceof Fd)return je(this,c0e,!0,"f"),this._emit("abort",r);if(r instanceof vt)return this._emit("error",r);if(r instanceof Error){let o=new vt(r.message);return o.cause=r,this._emit("error",o)}return this._emit("error",new vt(String(r)))}),je(this,Zne,new Promise((r,o)=>{je(this,s0e,r,"f"),je(this,Yne,o,"f")}),"f"),je(this,Jne,new Promise((r,o)=>{je(this,a0e,r,"f"),je(this,Xne,o,"f")}),"f"),ie(this,Zne,"f").catch(()=>{}),ie(this,Jne,"f").catch(()=>{}),je(this,_q,e,"f"),je(this,ere,n?.logger??console,"f")}get response(){return ie(this,u0e,"f")}get request_id(){return ie(this,d0e,"f")}async withResponse(){je(this,GD,!0,"f");let e=await ie(this,Zne,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let n=new t(null);return n._run(()=>n._fromReadableStream(e)),n}static createMessage(e,n,r,{logger:o}={}){let i=new t(n,{logger:o});for(let s of n.messages)i._addMessageParam(s);return je(i,_q,{...n,stream:!0},"f"),i._run(()=>i._createMessage(e,{...n,stream:!0},{...r,headers:{...r?.headers,[AIe]:"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},ie(this,Uit,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,n=!0){this.receivedMessages.push(e),n&&this._emit("message",e)}async _createMessage(e,n,r){let o=r?.signal,i;o&&(o.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),o.addEventListener("abort",i));try{ie(this,ew,"m",jit).call(this);let{response:s,data:a}=await e.create({...n,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(s);for await(let l of a)ie(this,ew,"m",Bit).call(this,l);if(a.controller.signal?.aborted)throw new Fd;ie(this,ew,"m",zit).call(this)}finally{o&&i&&o.removeEventListener("abort",i)}}_connected(e){this.ended||(je(this,u0e,e,"f"),je(this,d0e,e?.headers.get("request-id"),"f"),ie(this,s0e,"f").call(this,e),this._emit("connect"))}get ended(){return ie(this,Qne,"f")}get errored(){return ie(this,l0e,"f")}get aborted(){return ie(this,c0e,"f")}abort(){this.controller.abort()}on(e,n){return(ie(this,iC,"f")[e]||(ie(this,iC,"f")[e]=[])).push({listener:n}),this}off(e,n){let r=ie(this,iC,"f")[e];if(!r)return this;let o=r.findIndex(i=>i.listener===n);return o>=0&&r.splice(o,1),this}once(e,n){return(ie(this,iC,"f")[e]||(ie(this,iC,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,r)=>{je(this,GD,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,n)})}async done(){je(this,GD,!0,"f"),await ie(this,Jne,"f")}get currentMessage(){return ie(this,oO,"f")}async finalMessage(){return await this.done(),ie(this,ew,"m",Fit).call(this)}async finalText(){return await this.done(),ie(this,ew,"m",Rwn).call(this)}_emit(e,...n){if(ie(this,Qne,"f"))return;e==="end"&&(je(this,Qne,!0,"f"),ie(this,a0e,"f").call(this));let r=ie(this,iC,"f")[e];if(r&&(ie(this,iC,"f")[e]=r.filter(o=>!o.once),r.forEach(({listener:o})=>o(...n))),e==="abort"){let o=n[0];!ie(this,GD,"f")&&!r?.length&&Promise.reject(o),ie(this,Yne,"f").call(this,o),ie(this,Xne,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=n[0];!ie(this,GD,"f")&&!r?.length&&Promise.reject(o),ie(this,Yne,"f").call(this,o),ie(this,Xne,"f").call(this,o),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",ie(this,ew,"m",Fit).call(this))}async _fromReadableStream(e,n){let r=n?.signal,o;r&&(r.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),r.addEventListener("abort",o));try{ie(this,ew,"m",jit).call(this),this._connected(null);let i=Hg.fromReadableStream(e,this.controller);for await(let s of i)ie(this,ew,"m",Bit).call(this,s);if(i.controller.signal?.aborted)throw new Fd;ie(this,ew,"m",zit).call(this)}finally{r&&o&&r.removeEventListener("abort",o)}}[(oO=new WeakMap,_q=new WeakMap,Zne=new WeakMap,s0e=new WeakMap,Yne=new WeakMap,Jne=new WeakMap,a0e=new WeakMap,Xne=new WeakMap,iC=new WeakMap,Qne=new WeakMap,l0e=new WeakMap,c0e=new WeakMap,GD=new WeakMap,u0e=new WeakMap,d0e=new WeakMap,ere=new WeakMap,Uit=new WeakMap,ew=new WeakSet,Fit=function(){if(this.receivedMessages.length===0)throw new vt("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Rwn=function(){if(this.receivedMessages.length===0)throw new vt("stream ended without producing a Message with role=assistant");let n=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(n.length===0)throw new vt("stream ended without producing a content block with type=text");return n.join(" ")},jit=function(){this.ended||je(this,oO,void 0,"f")},Bit=function(n){if(this.ended)return;let r=ie(this,ew,"m",Lwn).call(this,n);switch(this._emit("streamEvent",n,r),n.type){case"content_block_delta":{let o=r.content.at(-1);switch(n.delta.type){case"text_delta":{o.type==="text"&&this._emit("text",n.delta.text,o.text||"");break}case"citations_delta":{o.type==="text"&&this._emit("citation",n.delta.citation,o.citations??[]);break}case"input_json_delta":{Hit(o)&&ie(this,iC,"f").inputJson?.length&&this._emit("inputJson",n.delta.partial_json,o.input);break}case"thinking_delta":{o.type==="thinking"&&this._emit("thinking",n.delta.thinking,o.thinking);break}case"signature_delta":{o.type==="thinking"&&this._emit("signature",o.signature);break}default:n.delta}break}case"message_stop":{this._addMessageParam(r),this._addMessage(Lit(r,ie(this,_q,"f"),{logger:ie(this,ere,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{je(this,oO,r,"f");break}case"content_block_start":case"message_delta":break}},zit=function(){if(this.ended)throw new vt("stream has ended, this shouldn't happen");let n=ie(this,oO,"f");if(!n)throw new vt("request ended without sending any chunks");return je(this,oO,void 0,"f"),Lit(n,ie(this,_q,"f"),{logger:ie(this,ere,"f")})},Lwn=function(n){let r=ie(this,oO,"f");if(n.type==="message_start"){if(r)throw new vt(`Unexpected event order, got ${n.type} before receiving "message_stop"`);return n.message}if(!r)throw new vt(`Unexpected event order, got ${n.type} before "message_start"`);switch(n.type){case"message_stop":return r;case"message_delta":return r.stop_reason=n.delta.stop_reason,r.stop_sequence=n.delta.stop_sequence,n.delta.stop_details!=null&&(r.stop_details=n.delta.stop_details),r.usage.output_tokens=n.usage.output_tokens,n.usage.input_tokens!=null&&(r.usage.input_tokens=n.usage.input_tokens),n.usage.cache_creation_input_tokens!=null&&(r.usage.cache_creation_input_tokens=n.usage.cache_creation_input_tokens),n.usage.cache_read_input_tokens!=null&&(r.usage.cache_read_input_tokens=n.usage.cache_read_input_tokens),n.usage.server_tool_use!=null&&(r.usage.server_tool_use=n.usage.server_tool_use),r;case"content_block_start":return r.content.push({...n.content_block}),r;case"content_block_delta":{let o=r.content.at(n.index);switch(n.delta.type){case"text_delta":{o?.type==="text"&&(r.content[n.index]={...o,text:(o.text||"")+n.delta.text});break}case"citations_delta":{o?.type==="text"&&(r.content[n.index]={...o,citations:[...o.citations??[],n.delta.citation]});break}case"input_json_delta":{if(o&&Hit(o)){let i=(o[tO]||"")+n.delta.partial_json;r.content[n.index]=XIe(o,i)}break}case"thinking_delta":{o?.type==="thinking"&&(r.content[n.index]={...o,thinking:o.thinking+n.delta.thinking});break}case"signature_delta":{o?.type==="thinking"&&(r.content[n.index]={...o,signature:n.delta.signature});break}default:n.delta}return r}case"content_block_stop":{let o=r.content.at(n.index);return o&&Hit(o)&&tO in o&&Object.defineProperty(o,"input",{value:o.input,enumerable:!0,configurable:!0,writable:!0}),r}}},Symbol.asyncIterator)](){let e=[],n=[],r=!1;return this.on("streamEvent",o=>{let i=n.shift();i?i.resolve(o):e.push(o)}),this.on("end",()=>{r=!0;for(let o of n)o.resolve(void 0);n.length=0}),this.on("abort",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),this.on("error",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,s)=>n.push({resolve:i,reject:s})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Hg(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}});var xq,Wit=b(()=>{ai();Bi();So();oit();cq();ls();xq=class extends nn{create(e,n){let{user_profile_id:r,...o}=e;return this._client.post("/v1/messages/batches",{body:o,...n,headers:we([{...r!=null?{"anthropic-user-profile-id":r}:void 0},n?.headers])})}retrieve(e,n){return this._client.get(Oe`/v1/messages/batches/${e}`,n)}list(e={},n){return this._client.getAPIList("/v1/messages/batches",Jv,{query:e,...n})}delete(e,n){return this._client.delete(Oe`/v1/messages/batches/${e}`,n)}cancel(e,n){return this._client.post(Oe`/v1/messages/batches/${e}/cancel`,n)}async results(e,n){let r=await this.retrieve(e);if(!r.results_url)throw new vt(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);return this._client.get(r.results_url,{...n,headers:we([{Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((o,i)=>uq.fromResponse(i.response,i.controller))}}});var iO,Dwn,MDr,Vit=b(()=>{ai();So();rC();$wn();Dit();Wit();Wit();sit();iO=class extends nn{constructor(){super(...arguments),this.batches=new xq(this._client)}create(e,n){let{user_profile_id:r,...o}=e;o.model in Dwn&&console.warn(`The model '${o.model}' is deprecated and will reach end-of-life on ${Dwn[o.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),MDr.includes(o.model)&&o.thinking&&o.thinking.type==="enabled"&&console.warn(`Using Claude with ${o.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let i=this._client._options.timeout;if(!o.stream&&i==null){let a=JIe[o.model]??void 0;i=this._client.calculateNonstreamingTimeout(o.max_tokens,a)}let s=EIe(o.tools,o.messages);return this._client.post("/v1/messages",{body:o,timeout:i??6e5,...n,headers:we([{...r!=null?{"anthropic-user-profile-id":r}:void 0},s,n?.headers]),stream:e.stream??!1})}parse(e,n){return this.create(e,n).then(r=>$it(r,e,{logger:this._client.logger??console}))}stream(e,n){return f0e.createMessage(this,e,n,{logger:this._client.logger??console})}countTokens(e,n){let{user_profile_id:r,...o}=e;return this._client.post("/v1/messages/count_tokens",{body:o,...n,headers:we([{...r!=null?{"anthropic-user-profile-id":r}:void 0},n?.headers])})}},Dwn={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026","claude-3-5-haiku-latest":"February 19th, 2026","claude-3-5-haiku-20241022":"February 19th, 2026","claude-opus-4-0":"June 15th, 2026","claude-opus-4-20250514":"June 15th, 2026","claude-sonnet-4-0":"June 15th, 2026","claude-sonnet-4-20250514":"June 15th, 2026","claude-opus-4-1":"August 5th, 2026","claude-opus-4-1-20250805":"August 5th, 2026","claude-mythos-preview":"June 30th, 2026"},MDr=["claude-mythos-preview","claude-opus-4-6"];iO.Batches=xq});var ZD,qit=b(()=>{ai();Bi();So();ls();ZD=class extends nn{retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(Oe`/v1/models/${e}`,{...r,headers:we([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void 0},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/models",Jv,{query:o,...n,headers:we([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}}});var Fwn=b(()=>{Fvn();Nit();Rit();Vit();qit()});var Kit,Git,p0e,Uwn,jwn,Bwn,Ua,sC,Zit=b(()=>{jg();oIe();x_();L3();WM();iIe();aIe();$3();iot();pot();gne();_a();F3();cvn();Pvn();Rvn();Bi();Mot();Fwn();SIe();Rit();qit();Nit();Vit();iIe();So();U3();R0();x_();jwn="\\n\\nHuman:",Bwn="\\n\\nAssistant:",Ua=class{get credentials(){return this._authState.provider}constructor({baseURL:e=xo("ANTHROPIC_BASE_URL"),apiKey:n,authToken:r,webhookKey:o=xo("ANTHROPIC_WEBHOOK_SIGNING_KEY")??null,...i}={}){if(Kit.add(this),this._requestAuthFlags=new WeakMap,p0e.set(this,void 0),n===void 0&&(n=i.profile!=null?null:xo("ANTHROPIC_API_KEY")??null),r===void 0&&(r=i.profile!=null?null:xo("ANTHROPIC_AUTH_TOKEN")??null),i.profile!=null&&(i.credentials!=null||i.config!=null))throw new TypeError("Pass at most one of `profile`, `credentials`, or `config`.");let s={apiKey:n,authToken:r,webhookKey:o,...i,baseURL:e||"https://api.anthropic.com"};if(!s.dangerouslyAllowBrowser&&Uyn())throw new vt(`It looks like you're running in a browser-like environment.
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
`);this.baseURL=s.baseURL,this._baseURLIsExplicit=i.__baseURLIsExplicit??!!e,this.timeout=s.timeout??Git.DEFAULT_TIMEOUT,this.logger=s.logger??console,this.logLevel=_ne,this.logLevel=wIe(s.logLevel,"ClientOptions.logLevel",hi(this))??wIe(xo("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",hi(this))??_ne,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??Hyn(),je(this,p0e,Vyn,"f"),this.middleware=[...s.middleware??[]];let a=xo("ANTHROPIC_CUSTOM_HEADERS");if(a){let c={};for(let u of a.split(`
`)){let d=u.indexOf(":");d>=0&&(c[u.substring(0,d).trim()]=u.substring(d+1).trim())}s.defaultHeaders={...c,...s.defaultHeaders}}let l=i.__auth;if(delete s.__auth,delete s.__baseURLIsExplicit,this._options=s,this.apiKey=typeof n=="string"?n:null,this.authToken=r,this.webhookKey=o,l)this._authState=l,!this._baseURLIsExplicit&&l.baseURL&&(this.baseURL=l.baseURL);else if(this._authState={provider:null,tokenCache:null,resolution:null,error:null,extraHeaders:{}},this.apiKey==null&&this.authToken==null){let c=s.credentials??null;if(c)this._authState.provider=c,this._authState.tokenCache=this._makeTokenCache(c);else if(s.config!=null){let u=xot(s.config,this._credentialResolverOptions());this._authState.provider=u.provider,this._authState.tokenCache=this._makeTokenCache(u.provider),this._authState.extraHeaders=u.extraHeaders,this._applyCredentialBaseURL(u.baseURL)}else s.profile!=null?this._authState.resolution=this._resolveDefaultCredentials(s.profile):this._shouldResolveDefaultCredentials()&&(this._authState.resolution=this._resolveDefaultCredentials())}}_shouldResolveDefaultCredentials(){return!0}_applyCredentialBaseURL(e){if(!e)return;let n=e.replace(/\/+$/,"");this._authState.baseURL=n,this._baseURLIsExplicit||(this.baseURL=n)}_credentialResolverOptions(){return{baseURL:this.baseURL,fetch:this._credentialsFetch(),userAgent:this.getUserAgent(),onCacheWriteError:e=>{hi(this).debug("credential cache write failed (best-effort)",e)},onSafetyWarning:e=>{hi(this).warn(e)}}}_credentialsFetch(){return Iot(this.fetch,this.middleware,void 0,this)}_makeTokenCache(e){return new hIe(e,n=>{hi(this).debug("advisory token refresh failed; serving cached token",n)})}withOptions(e){let n="credentials"in e||"config"in e||"profile"in e,r="apiKey"in e||"authToken"in e||n,o={...this._options,...this._baseURLIsExplicit?{baseURL:this.baseURL}:{},maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,middleware:this.middleware,apiKey:this.apiKey,authToken:this.authToken,webhookKey:this.webhookKey,credentials:this.credentials,...n?{credentials:void 0,config:void 0,profile:void 0}:{},...e,__auth:r?void 0:this._authState,__baseURLIsExplicit:"baseURL"in e?!0:this._baseURLIsExplicit};return new this.constructor(o)}async _resolveDefaultCredentials(e){try{let n=await Tvn(this._credentialResolverOptions(),e);if(n)this._authState.provider=n.provider,this._authState.tokenCache=this._makeTokenCache(n.provider),this._authState.extraHeaders=n.extraHeaders,this._applyCredentialBaseURL(n.baseURL);else if(e!=null)throw new vt(`Profile "${e}" could not be resolved (no <config_dir>/configs/${e}.json found).`)}catch(n){this._authState.error=n}finally{this._authState.resolution=null}}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(!(e.get("x-api-key")||e.get("authorization"))){if(this._authState.error)throw this._authState.error;if(!(this._authState.tokenCache||this._authState.resolution)&&!(this.apiKey&&e.get("x-api-key"))&&!n.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!n.has("authorization"))throw new Error('Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}}_authFlags(e){let n=this._requestAuthFlags.get(e);return n||(n={usedTokenCache:!1,didRefreshFor401:!1},this._requestAuthFlags.set(e,n)),n}async authHeaders(e){if(this._authState.resolution&&await this._authState.resolution,!this._authState.error){if(this._authState.tokenCache&&this.apiKey==null){let n=await this._authState.tokenCache.getToken();return this._authFlags(e).usedTokenCache=!0,we([{Authorization:`Bearer ${n}`}])}return we([await this.apiKeyAuth(e),await this.bearerAuth(e)])}}async apiKeyAuth(e){if(this.apiKey!=null)return we([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return we([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return nvn(e)}getUserAgent(){return`${this.constructor.name}/JS ${Yv}`}defaultIdempotencyKey(){return`stainless-node-retry-${k3()}`}makeStatusError(e,n,r,o){return Ol.generate(e,n,r,o)}buildURL(e,n,r){let o=!ie(this,Kit,"m",Uwn).call(this)&&r||this.baseURL,i=Nyn(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery(),a=Object.fromEntries(i.searchParams);return(!rot(s)||!rot(a))&&(n={...a,...s,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(i.search=this.stringifyQuery(n)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new vt("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:n,options:r}){if(this._authState.tokenCache&&this.apiKey==null){let o=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[s,a]of Object.entries(this._authState.extraHeaders))o.has(s)||o.set(s,a);o.get("anthropic-beta")?.split(",").map(s=>s.trim())?.includes(ND)||o.append("anthropic-beta",ND),e.headers=o}}backendMiddleware(){return[]}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(o=>({method:e,path:n,...o})))}request(e,n=null){return new RD(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){let o=await e,i=o.maxRetries??this.maxRetries;n==null&&(n=i,this._requestAuthFlags.delete(o)),await this.prepareOptions(o);let{req:s,url:a,timeout:l}=await this.buildRequest(o,{retryCount:i-n}),c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(o.signal?.aborted)throw new Fd;let f=new AbortController,p=await this.fetchWithTimeout(a,s,l,f,o,{requestLogID:c,retryOfRequestLogID:r}).catch(OD),m=Date.now();if(p instanceof globalThis.Error){eC(f);let v=`retrying, ${n} attempts remaining`;if(o.signal?.aborted)throw new Fd;let y=Zv(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):"")),w=this.middleware.length>0||!!o.middleware?.length||this.backendMiddleware().length>0;if(w&&!y&&!Nvn(p))throw hi(this).info(`[${c}] middleware error (not retryable)`),hi(this).debug(`[${c}] middleware error (not retryable)`,nC({retryOfRequestLogID:r,url:a,durationMs:m-d,message:p.message})),p;if(n)return hi(this).info(`[${c}] connection ${y?"timed out":"failed"} - ${v}`),hi(this).debug(`[${c}] connection ${y?"timed out":"failed"} (${v})`,nC({retryOfRequestLogID:r,url:a,durationMs:m-d,message:p.message})),this.retryRequest(o,n,r??c);throw hi(this).info(`[${c}] connection ${y?"timed out":"failed"} - error; no more retries left`),hi(this).debug(`[${c}] connection ${y?"timed out":"failed"} (error; no more retries left)`,nC({retryOfRequestLogID:r,url:a,durationMs:m-d,message:p.message})),y?new I3:w&&!kot(p)?p:new QS({cause:p})}let h=[...p.headers.entries()].filter(([v])=>v==="request-id").map(([v,y])=>", "+v+": "+JSON.stringify(y)).join(""),g=`[${c}${u}${h}] ${s.method} ${a} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${m-d}ms`;if(!p.ok){let v=await this.shouldRetry(p,o);if(n&&v){let C=`retrying, ${n} attempts remaining`;return await Wyn(p.body),eC(f),hi(this).info(`${g} - ${C}`),hi(this).debug(`[${c}] response error (${C})`,nC({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,durationMs:m-d})),this.retryRequest(o,n,r??c,p.headers)}let y=v?"error; no more retries left":"error; not retryable";hi(this).info(`${g} - ${y}`);let w=await p.text().catch(C=>OD(C).message),_=hne(w),S=_?void 0:w;throw hi(this).debug(`[${c}] response error (${y})`,nC({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,message:S,durationMs:Date.now()-d})),eC(f),this.makeStatusError(p.status,_,S,p.headers)}return hi(this).info(g),hi(this).debug(`[${c}] response start`,nC({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,durationMs:m-d})),zyn(p.body??p,f),{response:p,options:o,controller:f,requestLogID:c,retryOfRequestLogID:r,startTime:d}}getAPIList(e,n,r){return this.requestAPIList(n,r&&"then"in r?r.then(o=>({method:"get",path:e,...o})):{method:"get",path:e,...r})}requestAPIList(e,n){let r=this.makeRequest(n,null,void 0);return new Tne(this,r,e)}async fetchWithTimeout(e,n,r,o,i,s){let{signal:a,method:l,...c}=n||{},u=this._makeAbort(o);a&&(a.addEventListener("abort",u,{once:!0}),Byn(o,a,u));let d=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,f={signal:o.signal,...d?{duplex:"half"}:{},method:"GET",...c};l&&(f.method=l.toUpperCase());let p=this.fetch,m=async(w,_)=>{let S=setTimeout(u,r);try{return await p.call(void 0,w,_)}finally{clearTimeout(S)}},h=i===void 0?m:async(w,_={})=>{let S=typeof w=="string"?w:w instanceof URL?w.href:w.url;return _.headers=_.headers instanceof Headers?_.headers:new Headers(_.headers),await this.prepareRequest(_,{url:S,options:i}),s&&hi(this).debug(`[${s.requestLogID}] sending request`,nC({retryOfRequestLogID:s.retryOfRequestLogID,method:_.method,url:S,options:i,headers:_.headers})),m(w,_)},g=i?.middleware,v=this.backendMiddleware(),y=g?.length||v.length?[...this.middleware,...g??[],...v]:this.middleware;return await Iot(h,y,i,this)(e,f)}async shouldRetry(e,n){let r=this._authFlags(n);if(e.status===401&&this._authState.tokenCache&&r.usedTokenCache&&!r.didRefreshFor401)return r.didRefreshFor401=!0,this._authState.tokenCache.invalidate(),!0;let o=e.headers.get("x-should-retry");return o==="true"?!0:o==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,r,o){let i,s=o?.get("retry-after-ms");if(s){let l=parseFloat(s);Number.isNaN(l)||(i=l)}let a=o?.get("retry-after");if(a&&!i){let l=parseFloat(a);Number.isNaN(l)?i=Date.parse(a)-Date.now():i=l*1e3}if(i===void 0){let l=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(n,l)}return await S_(i),this.makeRequest(e,n-1,r)}calculateDefaultRetryTimeoutMillis(e,n){let i=n-e,s=Math.min(.5*Math.pow(2,i),8),a=1-Math.random()*.25;return s*a*1e3}calculateNonstreamingTimeout(e,n){if(36e5*e/128e3>6e5||n!=null&&e>n)throw new vt("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:n=0}={}){let r={...e},{method:o,path:i,query:s,defaultBaseURL:a}=r;this._authState.resolution&&await this._authState.resolution,!this._baseURLIsExplicit&&this._authState.baseURL&&this.baseURL!==this._authState.baseURL&&(this.baseURL=this._authState.baseURL);let l=this.buildURL(i,s,a);"timeout"in r&&Lyn("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:c,body:u}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:o,bodyHeaders:c,retryCount:n});return{req:{method:o,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...r.fetchOptions??{}},url:l,timeout:r.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:r,retryCount:o}){let i={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);let s=we([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...yne(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(s),s.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=we([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:lIe(e)}:typeof e=="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:ie(this,p0e,"f").call(this,{body:e,headers:r})}};Git=Ua,p0e=new WeakMap,Kit=new WeakSet,Uwn=function(){return this.baseURL!=="https://api.anthropic.com"};Ua.Anthropic=Git;Ua.HUMAN_PROMPT=jwn;Ua.AI_PROMPT=Bwn;Ua.DEFAULT_TIMEOUT=6e5;Ua.AnthropicError=vt;Ua.APIError=Ol;Ua.APIConnectionError=QS;Ua.APIConnectionTimeoutError=I3;Ua.APIUserAbortError=Fd;Ua.NotFoundError=E3;Ua.ConflictError=M3;Ua.RateLimitError=N3;Ua.BadRequestError=T3;Ua.AuthenticationError=P3;Ua.InternalServerError=R3;Ua.PermissionDeniedError=A3;Ua.UnprocessableEntityError=O3;Ua.toFile=IIe;sC=class extends Ua{constructor(){super(...arguments),this.completions=new KD(this),this.messages=new iO(this),this.models=new ZD(this),this.beta=new cl(this)}};sC.Completions=KD;sC.Messages=iO;sC.Models=ZD;sC.Beta=cl});var pYi,zwn=b(()=>{_a();Sne();WM();So();rC();x_();iot();pYi=new TextEncoder});var Hwn=b(()=>{Zit();Mot();SIe();zwn();Zit();Bi();_a()});function LDr(t){return JSON.parse(JSON.stringify(t))}function Wwn(t){let e=LDr(t);return YD(e)}function YD(t){let e={},n=Hp(t,"$ref");if(n!==void 0)return e.$ref=n,e;let r=Hp(t,"$defs");if(r!==void 0){let u={};e.$defs=u;for(let[d,f]of Object.entries(r))u[d]=YD(f)}let o=Hp(t,"type"),i=Hp(t,"anyOf"),s=Hp(t,"oneOf"),a=Hp(t,"allOf");if(Array.isArray(i))e.anyOf=i.map(u=>YD(u));else if(Array.isArray(s))e.anyOf=s.map(u=>YD(u));else if(Array.isArray(a))e.allOf=a.map(u=>YD(u));else{if(o===void 0)throw new Error("JSON schema must have a type defined if anyOf/oneOf/allOf are not used");e.type=o}let l=Hp(t,"description");l!==void 0&&(e.description=l);let c=Hp(t,"title");if(c!==void 0&&(e.title=c),o==="object"){let u=Hp(t,"properties")||{};e.properties=Object.fromEntries(Object.entries(u).map(([f,p])=>[f,YD(p)])),Hp(t,"additionalProperties"),e.additionalProperties=!1;let d=Hp(t,"required");d!==void 0&&(e.required=d)}else if(o==="string"){let u=Hp(t,"format");u!==void 0&&RDr.has(u)?e.format=u:u!==void 0&&(t.format=u)}else if(o==="array"){let u=Hp(t,"items");u!==void 0&&(e.items=YD(u));let d=Hp(t,"minItems");d!==void 0&&(d===0||d===1)?e.minItems=d:d!==void 0&&(t.minItems=d)}if(Object.keys(t).length>0){let u=e.description;e.description=(u?u+`
`:"")+"{"+Object.entries(t).map(([d,f])=>`${d}: ${JSON.stringify(f)}`).join(", ")+"}"}return e}var RDr,Vwn=b(()=>{vot();RDr=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"])});function DDr(t){return t?Object.entries($Dr).find(([e])=>t.startsWith(e))?.[1]??Kwn:Kwn}function FDr(t){return!!(t.tools&&t.tools.length>0)}function UDr(t){for(let e of t.messages??[])if(typeof e.content!="string"){for(let n of e.content??[])if(typeof n=="object"&&n!=null&&n.type==="document"&&typeof n.citations=="object"&&n.citations?.enabled)return!0}return!1}function jDr(t){return!!(t.thinking&&(t.thinking.type==="enabled"||t.thinking.type==="adaptive"))}function BDr(t){return!!t.context_management?.edits?.some(e=>e.type==="compact_20260112")}function Gwn(t){return"input_schema"in t}function zDr(t){return typeof t=="object"&&t!==null&&"type"in t&&("name"in t||"mcp_server_name"in t)&&typeof t.type=="string"&&["text_editor_","computer_","bash_","web_search_","web_fetch_","str_replace_editor_","str_replace_based_edit_tool_","code_execution_","memory_","tool_search_","mcp_toolset"].some(e=>typeof t.type=="string"&&t.type.startsWith(e))}function HDr(t,e,...n){return Array.from(new Set([...t??[],...e??[],...n.flatMap(r=>Array.from(r))]))}function WDr(t){if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)&&t.content.length>=1&&"input"in t.content[0])return typeof t.content[0].input=="string"?t.content[0].input:JSON.stringify(t.content[0].input);if(Array.isArray(t.content)&&t.content.length>=1&&"text"in t.content[0]&&typeof t.content[0].text=="string")return t.content[0].text}var qwn,$Dr,Kwn,Zwn,Yit,Ywn=b(()=>{Wrt();cyn();Qrt();Syn();Tyn();Pyn();Eyn();Oyn();Hwn();Vwn();oi();Sd();ys();u9e();c1();lg();tg();tv();rI();Nx();l1();qwn="**REDACTED**",$Dr={"claude-opus-5":16384,"claude-fable-5":16384,"claude-mythos-5":16384,"claude-mythos-preview":16384,"claude-opus-4-7":16384,"claude-opus-4-6":16384,"claude-sonnet-4-6":16384,"claude-opus-4-5":16384,"claude-sonnet-4-5":16384,"claude-haiku-4-5":16384,"claude-opus-4-1":16384,"claude-sonnet-4":16384,"claude-opus-4":16384,"claude-3-7-sonnet":8192,"claude-3-5-sonnet":8192,"claude-3-5-haiku":8192,"claude-3-opus":4096,"claude-3-sonnet":4096,"claude-3-haiku":4096},Kwn=4096;Zwn=class extends Cb{constructor(e,n){let r=typeof e=="string"?{...n??{},model:e}:e??{};super(r??{});M(this,"lc_serializable",!0);M(this,"anthropicApiKey");M(this,"apiKey");M(this,"apiUrl");M(this,"temperature");M(this,"topK");M(this,"topP");M(this,"maxTokens");M(this,"modelName","claude-sonnet-4-5-20250929");M(this,"model","claude-sonnet-4-5-20250929");M(this,"invocationKwargs");M(this,"stopSequences");M(this,"streaming",!1);M(this,"clientOptions");M(this,"thinking",{type:"disabled"});M(this,"thinkingExplicitlySet",!1);M(this,"contextManagement");M(this,"outputConfig");M(this,"inferenceGeo");M(this,"batchClient");M(this,"streamingClient");M(this,"streamUsage",!0);M(this,"betas");M(this,"createClient");this._addVersion("@langchain/anthropic","1.5.6");let o=_ye({baseURL:r.anthropicApiUrl??r.clientOptions?.baseURL??(Nn("ANTHROPIC_API_URL")||Nn("ANTHROPIC_BASE_URL")||void 0),providerPath:"anthropic"});if(this.anthropicApiKey=r.apiKey??r.anthropicApiKey??o.apiKey??Nn("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!r?.createClient)throw new Error("Anthropic API key not found");this.clientOptions=r?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=o.baseURL,this.modelName=r?.model??r?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=r?.invocationKwargs??{},this.topP=r?.topP??this.topP,this.temperature=r?.temperature??this.temperature,this.topK=r?.topK??this.topK,this.maxTokens=r?.maxTokens??DDr(this.model),this.stopSequences=r?.stopSequences??this.stopSequences,this.streaming=r?.streaming??!1,this.streamUsage=r?.streamUsage??this.streamUsage,r?.thinking!==void 0&&(this.thinking=r.thinking,this.thinkingExplicitlySet=!0),this.contextManagement=r?.contextManagement??this.contextManagement,this.outputConfig=r?.outputConfig??this.outputConfig,this.inferenceGeo=r?.inferenceGeo??this.inferenceGeo,this.betas=r?.betas??this.betas,this.createClient=r?.createClient??(i=>new sC(i))}static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}getLsParams(e){let n=this.invocationParams(e);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:n.temperature??void 0,ls_max_tokens:n.max_tokens??void 0,ls_stop:e.stop}}formatStructuredToolToAnthropic(e,n){if(e)return e.map(r=>{if(xf(r)&&r.extras?.providerToolDefinition)return r.extras.providerToolDefinition;if(zDr(r))return r;if(Gwn(r))return n?.strict!==void 0?{...r,strict:n.strict}:r;if(Zx(r)){let o="strict"in r.function&&typeof r.function.strict=="boolean"?r.function.strict:void 0,i=n?.strict??o;return{name:r.function.name,description:r.function.description,input_schema:r.function.parameters,...i!==void 0?{strict:i}:{}}}if(xf(r)){let{strict:o,...i}=r.extras?lyn.parse(r.extras):{},s=n?.strict??o;return{name:r.name,description:r.description,input_schema:ki(r.schema)?Ki(r.schema):r.schema,...i,...s!==void 0?{strict:s}:{}}}throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(r,null,2)}`)}).filter(r=>!Gwn(r)||syn(r).length===0)}bindTools(e,n){return this.withConfig({tools:this.formatStructuredToolToAnthropic(e,{strict:n?.strict}),...n})}invocationParams(e){let n=ayn(e?.tool_choice),r=e?.tools?.reduce((c,u)=>{if(typeof u=="object"&&"type"in u&&u.type in Vrt){let d=Vrt[u.type];if(!c.includes(d))return[...c,d]}return c},[]),o=(()=>{let c={...this.outputConfig,...e?.outputConfig};return e?.outputFormat&&!c.format&&(c.format=e.outputFormat),Object.keys(c).length>0?c:void 0})(),i=this.contextManagement?.edits?.some(c=>c.type==="compact_20260112")?["compact-2026-01-12"]:[],s=byn(this.model,o),a=this.formatStructuredToolToAnthropic(e?.tools,{strict:e?.strict});if(n?.type==="tool"&&!a?.some(c=>"name"in c&&c.name===n.name))throw new Error(`Anthropic tool_choice references "${n.name}", but that tool is not available.`);if(n?.type==="any"&&(!a||a.length===0))throw new Error("Anthropic tool_choice requires at least one available tool.");let l={model:this.model,stop_sequences:e?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:a,tool_choice:n,thinking:this.thinkingExplicitlySet?this.thinking:void 0,context_management:this.contextManagement,...this.invocationKwargs,container:e?.container,betas:HDr(this.betas,e?.betas,r??[],i,s),output_config:o,inference_geo:e?.inferenceGeo??this.inferenceGeo,mcp_servers:e?.mcp_servers,cache_control:e?.cache_control};return _yn({model:this.model,thinking:this.thinking,outputConfig:o,topK:this.topK,topP:this.topP,temperature:this.temperature}),Object.assign(l,xyn({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature})),l}_getInvocationParamsForTracing(e){let n=this.invocationParams(e);return Array.isArray(n.mcp_servers)?{...n,mcp_servers:n.mcp_servers.map(r=>"authorization_token"in r?{...r,authorization_token:qwn}:r)}:n}_getCallOptionsForTracing(e,n){return Array.isArray(e.mcp_servers)?{...e,mcp_servers:e.mcp_servers.map(r=>"authorization_token"in r?{...r,authorization_token:qwn}:r)}:e}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(e,n,r){let o=this.invocationParams(n),i=dne(e),s={...o,...i,stream:!0},a=!FDr(s)&&!UDr(s)&&!jDr(s)&&!BDr(s),l=await this.createStreamWithRetry(s,{headers:n.headers,signal:n.signal,maxRetries:n.maxRetries});for await(let c of l){if(n.signal?.aborted){l.controller.abort();return}let u=this.streamUsage??n.streamUsage,d=Cyn(c,{streamUsage:u,coerceContentToString:a});if(!d)continue;let{chunk:f}=d,p=WDr(f),m=new di({message:new On({content:f.content,additional_kwargs:f.additional_kwargs,tool_call_chunks:f.tool_call_chunks,usage_metadata:u?f.usage_metadata:void 0,response_metadata:f.response_metadata,id:f.id}),text:p??""});yield m,await r?.handleLLMNewToken(p??"",void 0,void 0,void 0,void 0,{chunk:m})}}async*_streamChatModelEvents(e,n,r){let o=this.invocationParams(n),i=dne(e),s={...o,...i,stream:!0},a=await this.createStreamWithRetry(s,{headers:n.headers,signal:n.signal,maxRetries:n.maxRetries}),l=this.streamUsage??n.streamUsage;yield*Myn(async function*(u,d){for await(let f of u){if(d?.aborted){u.controller?.abort();return}yield f}}(a,n.signal),{streamUsage:l??!0})}async _generateNonStreaming(e,n,r){let o=dne(e),{content:i,...s}=await this.completionWithRetry({...n,stream:!1,...o},r),a=kyn(i,s),{role:l,type:c,...u}=s;return{generations:a,llmOutput:u}}async _generate(e,n,r){if(n.signal?.throwIfAborted(),this.stopSequences&&n.stop)throw new Error('"stopSequence" parameter found in input and default params');let o=this.invocationParams(n);if(o.stream){let i,s=this._streamResponseChunks(e,n,r);for await(let a of s)i===void 0?i=a:i=i.concat(a);if(i===void 0)throw new Error("No chunks returned from Anthropic API.");return{generations:[{text:i.text,message:i.message}]}}else return this._generateNonStreaming(e,o,{signal:n.signal,headers:n.headers,maxRetries:n.maxRetries})}async createStreamWithRetry(e,n){if(!this.streamingClient){let s=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...s,apiKey:this.apiKey,maxRetries:0})}let{betas:r,...o}=e,i=async()=>{try{return e?.betas?.length?await this.streamingClient.beta.messages.create({...o,betas:r,...this.invocationKwargs,stream:!0},n):await this.streamingClient.messages.create({...o,...this.invocationKwargs,stream:!0},n)}catch(s){throw tot(s)}};return this.caller.callWithOptions({maxRetries:n?.maxRetries},i)}async completionWithRetry(e,n){if(!this.batchClient){let s=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...s,apiKey:this.apiKey,maxRetries:0})}let{betas:r,...o}=e,i=async()=>{try{return e?.betas?.length?await this.batchClient.beta.messages.create({...o,...this.invocationKwargs,betas:r},n):await this.batchClient.messages.create({...o,...this.invocationKwargs},n)}catch(s){throw tot(s)}};return this.caller.callWithOptions({signal:n.signal??void 0,maxRetries:n.maxRetries},i)}_llmType(){return"anthropic"}get profile(){return Ayn[this.model]??{}}withStructuredOutput(e,n){let r,o,{schema:i,name:s,includeRaw:a}={...n,schema:e},l=n?.method??"functionCalling";if(n?.strict!==void 0&&l!=="functionCalling")throw new Error(`Argument \`strict\` is only supported for \`method\` = "functionCalling" on Anthropic models. Got method = "${l}".`);if(l==="jsonMode"&&(console.warn('"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".'),l="jsonSchema"),l==="jsonSchema"){o=pv(i);let c=Wwn(Ki(i));r=this.withConfig({outputVersion:"v0",outputConfig:{format:{type:"json_schema",schema:c}},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:c}})}else if(l==="functionCalling"){let c=s??"extract",u;if(ki(i)||Ya(i)){let d=Ki(i);u=[{name:c,description:d.description??"A function available to call.",input_schema:d}]}else typeof i.name=="string"&&typeof i.description=="string"&&typeof i.input_schema=="object"&&i.input_schema!=null?(u=[i],c=i.name):u=[{name:c,description:i.description??"",input_schema:i}];if(o=Jx(i,c,iyn),this.thinking?.type==="enabled"||this.thinking?.type==="adaptive"){let d="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(d),r=this.withConfig({outputVersion:"v0",tools:u,ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:Ki(i)},...n?.strict!==void 0?{strict:n.strict}:{}});let f=p=>{if(!p.tool_calls||p.tool_calls.length===0)throw new Error(d);return p};r=r.pipe(f)}else r=this.withConfig({outputVersion:"v0",tools:u,tool_choice:{type:"tool",name:c},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:Ki(i)},...n?.strict!==void 0?{strict:n.strict}:{}})}else throw new TypeError(`Unrecognized structured output method '${l}'. Expected 'functionCalling' or 'jsonSchema'`);return mv(r,o,a,a?"StructuredOutputRunnable":"ChatAnthropicStructuredOutput")}},Yit=class extends Zwn{}});var Jwn=b(()=>{Qrt()});var VDr,qDr,KDr,GDr,ZDr,YDr,JDr,XDr,QDr,eFr,tFr,nFr,I_,Xwn,Qwn,ebn,tbn,nbn,rbn,obn,ibn,sbn,abn,lbn,cbn,ubn,dbn,fbn,rFr,oFr,iFr,sFr,aFr,lFr,tre=b(()=>{Eb();VDr=x.object({command:x.literal("view"),path:x.string()}),qDr=x.object({command:x.literal("create"),path:x.string(),file_text:x.string()}),KDr=x.object({command:x.literal("str_replace"),path:x.string(),old_str:x.string(),new_str:x.string()}),GDr=x.object({command:x.literal("insert"),path:x.string(),insert_line:x.number(),insert_text:x.string()}),ZDr=x.object({command:x.literal("delete"),path:x.string()}),YDr=x.object({command:x.literal("rename"),old_path:x.string(),new_path:x.string()}),JDr=x.discriminatedUnion("command",[VDr,qDr,KDr,GDr,ZDr,YDr]),XDr=x.object({command:x.literal("view"),path:x.string(),view_range:x.tuple([x.number(),x.number()]).optional()}),QDr=x.object({command:x.literal("str_replace"),path:x.string(),old_str:x.string(),new_str:x.string()}),eFr=x.object({command:x.literal("create"),path:x.string(),file_text:x.string()}),tFr=x.object({command:x.literal("insert"),path:x.string(),insert_line:x.number(),new_str:x.string()}),nFr=x.discriminatedUnion("command",[XDr,QDr,eFr,tFr]),I_=x.tuple([x.number(),x.number()]),Xwn=x.object({action:x.literal("screenshot")}),Qwn=x.object({action:x.literal("left_click"),coordinate:I_}),ebn=x.object({action:x.literal("right_click"),coordinate:I_}),tbn=x.object({action:x.literal("middle_click"),coordinate:I_}),nbn=x.object({action:x.literal("double_click"),coordinate:I_}),rbn=x.object({action:x.literal("triple_click"),coordinate:I_}),obn=x.object({action:x.literal("left_click_drag"),start_coordinate:I_,end_coordinate:I_}),ibn=x.object({action:x.literal("left_mouse_down"),coordinate:I_}),sbn=x.object({action:x.literal("left_mouse_up"),coordinate:I_}),abn=x.object({action:x.literal("scroll"),coordinate:I_,scroll_direction:x.enum(["up","down","left","right"]),scroll_amount:x.number()}),lbn=x.object({action:x.literal("type"),text:x.string()}),cbn=x.object({action:x.literal("key"),key:x.string()}),ubn=x.object({action:x.literal("mouse_move"),coordinate:I_}),dbn=x.object({action:x.literal("hold_key"),key:x.string()}),fbn=x.object({action:x.literal("wait"),duration:x.number().optional()}),rFr=x.object({action:x.literal("zoom"),region:x.tuple([x.number(),x.number(),x.number(),x.number()])}),oFr=x.discriminatedUnion("action",[Xwn,Qwn,ebn,tbn,nbn,rbn,obn,ibn,sbn,abn,lbn,cbn,ubn,dbn,fbn]),iFr=x.discriminatedUnion("action",[Xwn,Qwn,ebn,tbn,nbn,rbn,obn,ibn,sbn,abn,lbn,cbn,ubn,dbn,fbn,rFr]),sFr=x.object({command:x.string().describe("The bash command to run")}),aFr=x.object({restart:x.literal(!0).describe("Set to true to restart the bash session")}),lFr=x.union([sFr,aFr])});var pbn=b(()=>{tre();bv()});var mbn=b(()=>{});var hbn=b(()=>{});var gbn=b(()=>{});var ybn=b(()=>{tre();bv()});var vbn=b(()=>{tre();bv()});var wbn=b(()=>{});var bbn=b(()=>{tre();bv()});var _bn=b(()=>{});var xbn=b(()=>{pbn();mbn();hbn();gbn();ybn();vbn();wbn();bbn();_bn()});var Sbn=b(()=>{Ywn();Jwn();xbn()});var Cbn,kbn=b(()=>{Cbn={"deepseek-chat":{maxInputTokens:1e6,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:384e3,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"deepseek-v4-pro":{maxInputTokens:1e6,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:384e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"deepseek-reasoner":{maxInputTokens:1e6,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:384e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"deepseek-v4-flash":{maxInputTokens:1e6,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:384e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0}}});var Jit,Ibn=b(()=>{kbn();oi();ys();wI();Sd();Jit=class extends fE{constructor(e,n){let r=typeof e=="string"?{...n??{},model:e}:e??{},o=r.apiKey||Nn("DEEPSEEK_API_KEY");if(!o)throw new Error('Deepseek API key not found. Please set the DEEPSEEK_API_KEY environment variable or pass the key into "apiKey" field.');super({...r,apiKey:o,configuration:{baseURL:"https://api.deepseek.com",...r.configuration}});M(this,"lc_serializable",!0);M(this,"lc_namespace",["langchain","chat_models","deepseek"]);this._addVersion("@langchain/deepseek","1.1.8")}static lc_name(){return"ChatDeepSeek"}_llmType(){return"deepseek"}get lc_secrets(){return{apiKey:"DEEPSEEK_API_KEY"}}get streamEventProvider(){return"deepseek"}_convertCompletionsDeltaToBaseMessageChunk(e,n,r){let o=super._convertCompletionsDeltaToBaseMessageChunk(e,n,r);return o.response_metadata={...o.response_metadata,model_provider:"deepseek"},o}async*_streamResponseChunks(e,n,r){let o=super._streamResponseChunks(e,n,r),i="",s=!1;for await(let a of o){if(n.signal?.aborted)return;if(a.message.additional_kwargs.reasoning_content){yield a;continue}let l=a.text;if(!l){yield a;continue}if(i+=l,!s&&i.includes("<think>")){s=!0;let c=i.indexOf("<think>"),u=i.substring(0,c);i=i.substring(c+7)||"",u&&(yield new di({message:new On({content:u,additional_kwargs:a.message.additional_kwargs,response_metadata:a.message.response_metadata,tool_calls:a.message.tool_calls,tool_call_chunks:a.message.tool_call_chunks,id:a.message.id}),text:u,generationInfo:a.generationInfo}))}if(s&&i.includes("</think>")){s=!1;let c=i.indexOf("</think>"),u=i.substring(0,c),d=i.substring(c+8);yield new di({message:new On({content:"",additional_kwargs:{...a.message.additional_kwargs,reasoning_content:u},response_metadata:a.message.response_metadata,tool_calls:a.message.tool_calls,tool_call_chunks:a.message.tool_call_chunks,id:a.message.id}),text:"",generationInfo:a.generationInfo}),i=d||"",i&&(yield new di({message:new On({content:i,additional_kwargs:a.message.additional_kwargs,response_metadata:a.message.response_metadata,tool_calls:a.message.tool_calls,tool_call_chunks:a.message.tool_call_chunks,id:a.message.id}),text:i,generationInfo:a.generationInfo}),i="")}else if(s){let c="</think>",u=-1;for(let d=7;d>=1;d--)if(i.endsWith(c.substring(0,d))){u=i.length-d;break}if(u!==-1){let d=i.substring(0,u);d&&(yield new di({message:new On({content:"",additional_kwargs:{...a.message.additional_kwargs,reasoning_content:d},response_metadata:a.message.response_metadata,tool_calls:a.message.tool_calls,tool_call_chunks:a.message.tool_call_chunks,id:a.message.id}),text:"",generationInfo:a.generationInfo})),i=i.substring(u)}else i&&(yield new di({message:new On({content:"",additional_kwargs:{...a.message.additional_kwargs,reasoning_content:i},response_metadata:a.message.response_metadata,tool_calls:a.message.tool_calls,tool_call_chunks:a.message.tool_call_chunks,id:a.message.id}),text:"",generationInfo:a.generationInfo}),i="")}else{let c="<think>",u=-1;for(let d=6;d>=1;d--)if(i.endsWith(c.substring(0,d))){u=i.length-d;break}if(u!==-1){let d=i.substring(0,u);d&&(yield new di({message:new On({content:d,additional_kwargs:a.message.additional_kwargs,response_metadata:a.message.response_metadata,tool_calls:a.message.tool_calls,tool_call_chunks:a.message.tool_call_chunks,id:a.message.id}),text:d,generationInfo:a.generationInfo})),i=i.substring(u)}else i&&(yield new di({message:new On({content:i,additional_kwargs:a.message.additional_kwargs,response_metadata:a.message.response_metadata,tool_calls:a.message.tool_calls,tool_call_chunks:a.message.tool_call_chunks,id:a.message.id}),text:i,generationInfo:a.generationInfo}),i="")}}i&&(s?yield new di({message:new On({content:"",additional_kwargs:{reasoning_content:i}}),text:""}):yield new di({message:new On({content:i}),text:i}))}_convertCompletionsMessageToBaseMessage(e,n){let r=super._convertCompletionsMessageToBaseMessage(e,n);return r.response_metadata={...r.response_metadata,model_provider:"deepseek"},r}get profile(){return Cbn[this.model]??{}}withStructuredOutput(e,n){let r={...n};return r?.method===void 0&&(r.method="functionCalling"),super.withStructuredOutput(e,r)}}});var Tbn=b(()=>{Ibn()});var Pbn,Abn=b(()=>{Pbn={"llama3-70b-8192":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"qwen-qwq-32b":{maxInputTokens:131072,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"llama-3.1-8b-instant":{maxInputTokens:131072,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:131072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"llama-guard-3-8b":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"deepseek-r1-distill-llama-70b":{maxInputTokens:131072,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"llama3-8b-8192":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"mistral-saba-24b":{maxInputTokens:32768,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"llama-3.3-70b-versatile":{maxInputTokens:131072,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemma2-9b-it":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"moonshotai/kimi-k2-instruct":{maxInputTokens:131072,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"moonshotai/kimi-k2-instruct-0905":{maxInputTokens:262144,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"qwen/qwen3-32b":{maxInputTokens:131072,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"meta-llama/llama-4-scout-17b-16e-instruct":{maxInputTokens:131072,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"meta-llama/llama-guard-4-12b":{maxInputTokens:131072,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:1024,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"meta-llama/llama-4-maverick-17b-128e-instruct":{maxInputTokens:131072,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"openai/gpt-oss-120b":{maxInputTokens:131072,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"openai/gpt-oss-20b":{maxInputTokens:131072,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0}}});function cFr(t){if(!t||typeof t!="object"||t.type==="null"||Array.isArray(t.type)&&t.type.includes("null"))return t;if(Array.isArray(t.enum)){let e=t.enum.includes(null)?t.enum:[...t.enum,null],n=Array.isArray(t.type)?t.type.filter(o=>o!=="null"):typeof t.type=="string"?[t.type]:["string"],r=Array.from(new Set([...n,"null"]));return{...t,type:r,enum:e}}if(Array.isArray(t.anyOf)){if(t.anyOf.some(n=>n?.type==="null"||Array.isArray(n?.type)&&n.type.includes("null")))return t;let e=t.anyOf.map(n=>n?.type).filter(n=>n&&typeof n=="string");if(e.length===t.anyOf.length){let{anyOf:n,...r}=t;return{...r,type:[...e,"null"]}}return{...t,anyOf:[...t.anyOf,{type:"null"}]}}return typeof t.type=="string"?{...t,type:[t.type,"null"]}:Array.isArray(t.type)?{...t,type:Array.from(new Set([...t.type,"null"]))}:t.properties?{...t,type:["object","null"]}:t}function sO(t,e=!0){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>sO(r,!1));let n={...t};for(let r of["anyOf","oneOf","allOf"])Array.isArray(n[r])&&(n[r]=n[r].map(o=>sO(o,!1)));if(n.items&&(n.items=sO(n.items,!1)),n.$defs){n.$defs={...n.$defs};for(let r of Object.keys(n.$defs))n.$defs[r]=sO(n.$defs[r],!1)}if((n.type==="object"||Array.isArray(n.type)&&n.type.includes("object")||n.properties)&&n.properties&&typeof n.properties=="object"){n.additionalProperties=!1;let r=Object.keys(n.properties),o=new Set(Array.isArray(n.required)?n.required:[]);n.properties={...n.properties};for(let i of r)n.properties[i]=sO(n.properties[i],!1),o.has(i)||(n.properties[i]=cFr(n.properties[i]));n.required=r}if(e){if(Array.isArray(n.anyOf)){let r=n.anyOf.find(o=>o?.type==="object"||o?.properties);if(r)return{...sO(r,!0),type:"object"};throw new Error("Groq strict mode requires the root schema to be an object type, but the schema has anyOf/oneOf with no object variant.")}if(n.oneOf)throw new Error("Groq strict mode does not support oneOf at the root schema level.");if(n.not)throw new Error("Groq strict mode does not support 'not' at the root schema level.");n.properties&&(n.type="object")}return n}function uFr(t){return t.startsWith("openai/gpt-oss")}function Mbn(t,e){if(e!==void 0&&!Ebn.includes(e))throw new Error(`Invalid structured output method: ${e}. Supported methods are: ${Ebn.join(", ")}`);let n=uFr(t);if(n&&!e)return"jsonSchema";if(!n&&e==="jsonSchema")throw new Error(`Native JSON Schema structured output is not supported for model "${t}". Only models with the "openai/gpt-oss" prefix are supported. Use "functionCalling" or "jsonMode" instead.`);return e??"functionCalling"}var Ebn,Obn=b(()=>{Ebn=["jsonSchema","functionCalling","jsonMode"]});function Vp(t,e,n,r,o){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(t,n):o?o.value=n:e.set(t,n),n}function aa(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)}var nre=b(()=>{});var Xit,Nbn=b(()=>{Xit=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Xit=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))}});function rre(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var ore,m0e=b(()=>{ore=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)}});var ac,mu,JD,aO,Sq,Cq,kq,Iq,Tq,Pq,Aq,Eq,Mq,lO=b(()=>{m0e();ac=class extends Error{},mu=class t extends ac{constructor(e,n,r,o){super(`${t.makeMessage(e,n,r)}`),this.status=e,this.headers=o,this.error=n}static makeMessage(e,n,r){let o=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,n,r,o){if(!e||!o)return new aO({message:r,cause:ore(n)});let i=n;return e===400?new Cq(e,i,r,o):e===401?new kq(e,i,r,o):e===403?new Iq(e,i,r,o):e===404?new Tq(e,i,r,o):e===409?new Pq(e,i,r,o):e===422?new Aq(e,i,r,o):e===429?new Eq(e,i,r,o):e>=500?new Mq(e,i,r,o):new t(e,i,r,o)}},JD=class extends mu{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},aO=class extends mu{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}},Sq=class extends aO{constructor({message:e}={}){super({message:e??"Request timed out."})}},Cq=class extends mu{},kq=class extends mu{},Iq=class extends mu{},Tq=class extends mu{},Pq=class extends mu{},Aq=class extends mu{},Eq=class extends mu{},Mq=class extends mu{}});function tst(t){if(!t)return!0;for(let e in t)return!1;return!0}function Lbn(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var fFr,Rbn,Qit,est,$bn,Dbn,ire=b(()=>{lO();fFr=/^[a-z][a-z0-9+.-]*:/i,Rbn=t=>fFr.test(t),Qit=t=>(Qit=Array.isArray,Qit(t)),est=Qit;$bn=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new ac(`${t} must be an integer`);if(e<0)throw new ac(`${t} must be a positive integer`);return e},Dbn=t=>{try{return JSON.parse(t)}catch{return}}});var Fbn,Ubn=b(()=>{Fbn=t=>new Promise(e=>setTimeout(e,t))});var cO,nst=b(()=>{cO="1.5.0"});function pFr(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function hFr(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:n}of t){let r=n.exec(navigator.userAgent);if(r){let o=r[1]||0,i=r[2]||0,s=r[3]||0;return{browser:e,version:`${o}.${i}.${s}`}}}return null}var Hbn,mFr,jbn,Bbn,zbn,Wbn,rst=b(()=>{nst();Hbn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";mFr=()=>{let t=pFr();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cO,"X-Stainless-OS":Bbn(Deno.build.os),"X-Stainless-Arch":jbn(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cO,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cO,"X-Stainless-OS":Bbn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":jbn(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=hFr();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cO,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cO,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};jbn=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Bbn=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),Wbn=()=>zbn??(zbn=mFr())});function Vbn(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Groq({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function ost(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function h0e(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return ost({start(){},async pull(n){let{done:r,value:o}=await e.next();r?n.close():n.enqueue(o)},async cancel(){await e.return?.()}})}function ist(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){let n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function qbn(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),n=e.cancel();e.releaseLock(),await n}var sre=b(()=>{});var Kbn,Gbn=b(()=>{Kbn=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)})});function Zbn(t){return Object.entries(t).filter(([e,n])=>typeof n<"u").map(([e,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(e)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(e)}=`;throw new ac(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}var Ybn=b(()=>{lO()});function Oq(t,e,n){return ast(),new File(t,e??"unknown_file",n)}function are(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}function vFr(t){let e=typeof t=="function"?t:t.fetch,n=Jbn.get(e);if(n)return n;let r=(async()=>{try{let o="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new o(i).text()}catch{return!0}})();return Jbn.set(e,r),r}var ast,lst,Nq,Jbn,wFr,bFr,sst,Rq=b(()=>{sre();ast=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};lst=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Nq=async(t,e)=>({...t,body:await wFr(t.body,e)}),Jbn=new WeakMap;wFr=async(t,e)=>{if(!await vFr(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let n=new FormData;return await Promise.all(Object.entries(t||{}).map(([r,o])=>sst(n,r,o))),n},bFr=t=>t instanceof Blob&&"name"in t,sst=async(t,e,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response)t.append(e,Oq([await n.blob()],are(n)));else if(lst(n))t.append(e,Oq([await new Response(h0e(n)).blob()],are(n)));else if(bFr(n))t.append(e,n,are(n));else if(Array.isArray(n))await Promise.all(n.map(r=>sst(t,e+"[]",r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([r,o])=>sst(t,`${e}[${r}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}}});async function g0e(t,e,n){if(ast(),t=await t,_Fr(t))return t instanceof File?t:Oq([await t.arrayBuffer()],t.name);if(xFr(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Oq(await cst(o),e,n)}let r=await cst(t);if(e||(e=are(t)),!n?.type){let o=r.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof o=="string"&&(n={...n,type:o})}return Oq(r,e,n)}async function cst(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Xbn(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(lst(t))for await(let n of t)e.push(...await cst(n));else{let n=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${n?`; constructor: ${n}`:""}${SFr(t)}`)}return e}function SFr(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}var Xbn,_Fr,xFr,Qbn=b(()=>{Rq();Rq();Xbn=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",_Fr=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Xbn(t),xFr=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function"});var ust=b(()=>{Qbn()});var e_n=b(()=>{});var xa,tw=b(()=>{xa=class{constructor(e){this._client=e}}});function*kFr(t){if(!t)return;if(t_n in t){let{values:r,nulls:o}=t;yield*r.entries();for(let i of o)yield[i,null];return}let e=!1,n;t instanceof Headers?n=t.entries():est(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let r of n){let o=r[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let i=est(r[1])?r[1]:[r[1]],s=!1;for(let a of i)a!==void 0&&(e&&!s&&(s=!0,yield[o,null]),yield[o,a])}}var t_n,B0,y0e=b(()=>{ire();t_n=Symbol("brand.privateNullableHeaders");B0=t=>{let e=new Headers,n=new Set;for(let r of t){let o=new Set;for(let[i,s]of kFr(r)){let a=i.toLowerCase();o.has(a)||(e.delete(i),o.add(a)),s===null?(e.delete(i),n.add(a)):(e.append(i,s),n.delete(a))}}return{[t_n]:!0,values:e,nulls:n}}});var Lq,dst=b(()=>{tw();y0e();Lq=class extends xa{create(e,n){return this._client.post("/openai/v1/audio/speech",{body:e,...n,headers:B0([{Accept:"audio/wav"},n?.headers]),__binaryResponse:!0})}}});var $q,fst=b(()=>{tw();Rq();$q=class extends xa{create(e,n){return this._client.post("/openai/v1/audio/transcriptions",Nq({body:e,...n},this._client))}}});var Dq,pst=b(()=>{tw();Rq();Dq=class extends xa{create(e,n){return this._client.post("/openai/v1/audio/translations",Nq({body:e,...n},this._client))}}});var aC,mst=b(()=>{tw();dst();dst();fst();fst();pst();pst();aC=class extends xa{constructor(){super(...arguments),this.speech=new Lq(this._client),this.transcriptions=new $q(this._client),this.translations=new Dq(this._client)}};aC.Speech=Lq;aC.Transcriptions=$q;aC.Translations=Dq});function r_n(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var n_n,AFr,lC,v0e=b(()=>{lO();n_n=Object.freeze(Object.create(null)),AFr=(t=r_n)=>function(n,...r){if(n.length===1)return n[0];let o=!1,i=[],s=n.reduce((u,d,f)=>{/[?#]/.test(d)&&(o=!0);let p=r[f],m=(o?encodeURIComponent:t)(""+p);return f!==r.length&&(p==null||typeof p=="object"&&p.toString===Object.getPrototypeOf(Object.getPrototypeOf(p.hasOwnProperty??n_n)??n_n)?.toString)&&(m=p+"",i.push({start:u.length+d.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(p).slice(8,-1)} is not a valid path parameter`})),u+d+(f===r.length?"":m)},""),a=s.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=l.exec(a))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(i.sort((u,d)=>u.start-d.start),i.length>0){let u=0,d=i.reduce((f,p)=>{let m=" ".repeat(p.start-u),h="^".repeat(p.length);return u=p.start+p.length,f+m+h},"");throw new ac(`Path parameters result in path with invalid segments:
${i.map(f=>f.error).join(`
`)}
${s}
${d}`)}return s},lC=AFr(r_n)});var XD,hst=b(()=>{tw();v0e();XD=class extends xa{create(e,n){return this._client.post("/openai/v1/batches",{body:e,...n})}retrieve(e,n){return this._client.get(lC`/openai/v1/batches/${e}`,n)}list(e){return this._client.get("/openai/v1/batches",e)}cancel(e,n){return this._client.post(lC`/openai/v1/batches/${e}/cancel`,n)}}});var Fq,gst=b(()=>{tw();Fq=class extends xa{create(e,n){return this._client.post("/openai/v1/chat/completions",{body:e,...n,stream:e.stream??!1})}}});var uO,yst=b(()=>{tw();gst();gst();uO=class extends xa{constructor(){super(...arguments),this.completions=new Fq(this._client)}};uO.Completions=Fq});var QD,vst=b(()=>{tw();QD=class extends xa{}});var eF,wst=b(()=>{tw();eF=class extends xa{create(e,n){return this._client.post("/openai/v1/embeddings",{body:e,...n})}}});var tF,bst=b(()=>{tw();y0e();Rq();v0e();tF=class extends xa{create(e,n){return this._client.post("/openai/v1/files",Nq({body:e,...n},this._client))}list(e){return this._client.get("/openai/v1/files",e)}delete(e,n){return this._client.delete(lC`/openai/v1/files/${e}`,n)}content(e,n){return this._client.get(lC`/openai/v1/files/${e}/content`,{...n,headers:B0([{Accept:"application/octet-stream"},n?.headers]),__binaryResponse:!0})}info(e,n){return this._client.get(lC`/openai/v1/files/${e}`,n)}}});var nF,_st=b(()=>{tw();v0e();nF=class extends xa{retrieve(e,n){return this._client.get(lC`/openai/v1/models/${e}`,n)}list(e){return this._client.get("/openai/v1/models",e)}delete(e,n){return this._client.delete(lC`/openai/v1/models/${e}`,n)}}});var o_n=b(()=>{e_n();mst();hst();yst();vst();wst();bst();_st()});function a_n(t){let e=0;for(let o of t)e+=o.length;let n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.length;return n}function lre(t){let e;return(i_n??(e=new globalThis.TextEncoder,i_n=e.encode.bind(e)))(t)}function xst(t){let e;return(s_n??(e=new globalThis.TextDecoder,s_n=e.decode.bind(e)))(t)}var i_n,s_n,Sst=b(()=>{});function OFr(t,e){for(let o=e??0;o<t.length;o++){if(t[o]===10)return{preceding:o,index:o+1,carriage:!1};if(t[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function l_n(t){for(let r=0;r<t.length-1;r++){if(t[r]===10&&t[r+1]===10||t[r]===13&&t[r+1]===13)return r+2;if(t[r]===13&&t[r+1]===10&&r+3<t.length&&t[r+2]===13&&t[r+3]===10)return r+4}return-1}var Kg,Gg,rF,c_n=b(()=>{nre();Sst();rF=class{constructor(){Kg.set(this,void 0),Gg.set(this,void 0),Vp(this,Kg,new Uint8Array,"f"),Vp(this,Gg,null,"f")}decode(e){if(e==null)return[];let n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?lre(e):e;Vp(this,Kg,a_n([aa(this,Kg,"f"),n]),"f");let r=[],o;for(;(o=OFr(aa(this,Kg,"f"),aa(this,Gg,"f")))!=null;){if(o.carriage&&aa(this,Gg,"f")==null){Vp(this,Gg,o.index,"f");continue}if(aa(this,Gg,"f")!=null&&(o.index!==aa(this,Gg,"f")+1||o.carriage)){r.push(xst(aa(this,Kg,"f").subarray(0,aa(this,Gg,"f")-1))),Vp(this,Kg,aa(this,Kg,"f").subarray(aa(this,Gg,"f")),"f"),Vp(this,Gg,null,"f");continue}let i=aa(this,Gg,"f")!==null?o.preceding-1:o.preceding,s=xst(aa(this,Kg,"f").subarray(0,i));r.push(s),Vp(this,Kg,aa(this,Kg,"f").subarray(o.index),"f"),Vp(this,Gg,null,"f")}return r}flush(){return aa(this,Kg,"f").length?this.decode(`
`):[]}};Kg=new WeakMap,Gg=new WeakMap;rF.NEWLINE_CHARS=new Set([`
`,"\r"]);rF.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function cre(){}function w0e(t,e,n){return!e||b0e[t]>b0e[n]?cre:e[t].bind(e)}function jd(t){let e=t.logger,n=t.logLevel??"off";if(!e)return NFr;let r=u_n.get(e);if(r&&r[0]===n)return r[1];let o={error:w0e("error",e,n),warn:w0e("warn",e,n),info:w0e("info",e,n),debug:w0e("debug",e,n)};return u_n.set(e,[n,o]),o}var b0e,Cst,NFr,u_n,z0,_0e=b(()=>{ire();b0e={off:0,error:200,warn:300,info:400,debug:500},Cst=(t,e,n)=>{if(t){if(Lbn(b0e,t))return t;jd(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(b0e))}`)}};NFr={error:cre,warn:cre,info:cre,debug:cre},u_n=new WeakMap;z0=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t)});async function*RFr(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ac("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new ac("Attempted to iterate over a response with no body");let n=new kst,r=new rF,o=ist(t.body);for await(let i of LFr(o))for(let s of r.decode(i)){let a=n.decode(s);a&&(yield a)}for(let i of r.flush()){let s=n.decode(i);s&&(yield s)}}async function*LFr(t){let e=new Uint8Array;for await(let n of t){if(n==null)continue;let r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?lre(n):n,o=new Uint8Array(e.length+r.length);o.set(e),o.set(r,e.length),e=o;let i;for(;(i=l_n(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function $Fr(t,e){let n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}var ure,x0e,kst,d_n=b(()=>{nre();lO();sre();c_n();sre();m0e();Sst();_0e();lO();x0e=class t{constructor(e,n,r){this.iterator=e,ure.set(this,void 0),this.controller=n,Vp(this,ure,r,"f")}static fromSSEResponse(e,n,r){let o=!1,i=r?jd(r):console;async function*s(){if(o)throw new ac("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of RFr(e,n))if(!a){if(l.data.startsWith("[DONE]")){a=!0;continue}if(l.event===null||!l.event.startsWith("thread.")){let c;try{c=JSON.parse(l.data)}catch(u){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),u}if(c&&c.error)throw new mu(void 0,c.error,void 0,e.headers);yield c}else{let c;try{c=JSON.parse(l.data)}catch(u){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),u}if(l.event=="error")throw new mu(void 0,c.error,c.message,void 0);yield{event:l.event,data:c}}}a=!0}catch(l){if(rre(l))return;throw l}finally{a||n.abort()}}return new t(s,n,r)}static fromReadableStream(e,n,r){let o=!1;async function*i(){let a=new rF,l=ist(e);for await(let c of l)for(let u of a.decode(c))yield u;for(let c of a.flush())yield c}async function*s(){if(o)throw new ac("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of i())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(rre(l))return;throw l}finally{a||n.abort()}}return new t(s,n,r)}[(ure=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],n=[],r=this.iterator(),o=i=>({next:()=>{if(i.length===0){let s=r.next();e.push(s),n.push(s)}return i.shift()}});return[new t(()=>o(e),this.controller,aa(this,ure,"f")),new t(()=>o(n),this.controller,aa(this,ure,"f"))]}toReadableStream(){let e=this,n;return ost({async start(){n=e[Symbol.asyncIterator]()},async pull(r){try{let{value:o,done:i}=await n.next();if(i)return r.close();let s=lre(JSON.stringify(o)+`
`);r.enqueue(s)}catch(o){r.error(o)}},async cancel(){await n.return?.()}})}};kst=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,o]=$Fr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),n==="event"?this.event=o:n==="data"&&this.data.push(o),null}}});async function f_n(t,e){let{response:n,requestLogID:r,retryOfRequestLogID:o,startTime:i}=e,s=await(async()=>{if(n.status===204)return null;if(e.options.__binaryResponse)return n;if(e.options.stream)return x0e.fromSSEResponse(n,e.controller,t);let l=n.headers.get("content-type")?.split(";")[0]?.trim();return l?.includes("application/json")||l?.endsWith("+json")?n.headers.get("content-length")==="0"?void 0:await n.json():await n.text()})();return jd(t).debug(`[${r}] response parsed`,z0({retryOfRequestLogID:o,url:n.url,status:n.status,body:s,durationMs:Date.now()-i})),s}var p_n=b(()=>{d_n();_0e()});var dre,fre,Ist=b(()=>{nre();p_n();fre=class t extends Promise{constructor(e,n,r=f_n){super(o=>{o(null)}),this.responsePromise=n,this.parseResponse=r,dre.set(this,void 0),Vp(this,dre,e,"f")}_thenUnwrap(e){return new t(aa(this,dre,"f"),this.responsePromise,async(n,r)=>e(await this.parseResponse(n,r),r))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(aa(this,dre,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};dre=new WeakMap});var pre,m_n=b(()=>{pre=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0}});var Tst,Pst,mre,h_n,zi,Ast=b(()=>{nre();Nbn();ire();Ubn();m0e();rst();sre();Gbn();Ybn();nst();lO();ust();o_n();Ist();hst();vst();wst();bst();_st();mst();yst();rst();y0e();m_n();_0e();ire();zi=class{constructor({baseURL:e=pre("GROQ_BASE_URL"),apiKey:n=pre("GROQ_API_KEY"),...r}={}){if(Tst.add(this),mre.set(this,void 0),this.completions=new QD(this),this.chat=new uO(this),this.embeddings=new eF(this),this.audio=new aC(this),this.models=new nF(this),this.batches=new XD(this),this.files=new tF(this),n===void 0)throw new ac("The GROQ_API_KEY environment variable is missing or empty; either provide it, or instantiate the Groq client with an apiKey option, like new Groq({ apiKey: 'My API Key' }).");let o={apiKey:n,...r,baseURL:e||"https://api.groq.com"};if(!o.dangerouslyAllowBrowser&&Hbn())throw new ac(`It looks like you're running in a browser-like environment.
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new Groq({ apiKey, dangerouslyAllowBrowser: true })`);this.baseURL=o.baseURL,this.timeout=o.timeout??Pst.DEFAULT_TIMEOUT,this.logger=o.logger??console;let i="warn";this.logLevel=i,this.logLevel=Cst(o.logLevel,"ClientOptions.logLevel",this)??Cst(pre("GROQ_LOG"),"process.env['GROQ_LOG']",this)??i,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??Vbn(),Vp(this,mre,Kbn,"f");let s=pre("GROQ_CUSTOM_HEADERS");if(s){let a={};for(let l of s.split(`
`)){let c=l.indexOf(":");c>=0&&(a[l.substring(0,c).trim()]=l.substring(c+1).trim())}o.defaultHeaders={...a,...o.defaultHeaders}}this._options=o,this.apiKey=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){}async authHeaders(e){return B0([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Zbn(e)}getUserAgent(){return`${this.constructor.name}/JS ${cO}`}defaultIdempotencyKey(){return`stainless-node-retry-${Xit()}`}makeStatusError(e,n,r,o){return mu.generate(e,n,r,o)}buildURL(e,n,r){let o=!aa(this,Tst,"m",h_n).call(this)&&r||this.baseURL,i=Rbn(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery(),a=Object.fromEntries(i.searchParams);return(!tst(s)||!tst(a))&&(n={...a,...s,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(i.search=this.stringifyQuery(n)),i.toString()}async prepareOptions(e){}async prepareRequest(e,{url:n,options:r}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(o=>({method:e,path:n,...o})))}request(e,n=null){return new fre(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){let o=await e,i=o.maxRetries??this.maxRetries;n==null&&(n=i),await this.prepareOptions(o);let{req:s,url:a,timeout:l}=await this.buildRequest(o,{retryCount:i-n});await this.prepareRequest(s,{url:a,options:o});let c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(jd(this).debug(`[${c}] sending request`,z0({retryOfRequestLogID:r,method:o.method,url:a,options:o,headers:s.headers})),o.signal?.aborted)throw new JD;let f=new AbortController,p=await this.fetchWithTimeout(a,s,l,f).catch(ore),m=Date.now();if(p instanceof globalThis.Error){let g=`retrying, ${n} attempts remaining`;if(o.signal?.aborted)throw new JD;let v=rre(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(n)return jd(this).info(`[${c}] connection ${v?"timed out":"failed"} - ${g}`),jd(this).debug(`[${c}] connection ${v?"timed out":"failed"} (${g})`,z0({retryOfRequestLogID:r,url:a,durationMs:m-d,message:p.message})),this.retryRequest(o,n,r??c);throw jd(this).info(`[${c}] connection ${v?"timed out":"failed"} - error; no more retries left`),jd(this).debug(`[${c}] connection ${v?"timed out":"failed"} (error; no more retries left)`,z0({retryOfRequestLogID:r,url:a,durationMs:m-d,message:p.message})),v?new Sq:new aO({cause:p})}let h=`[${c}${u}] ${s.method} ${a} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${m-d}ms`;if(!p.ok){let g=await this.shouldRetry(p);if(n&&g){let I=`retrying, ${n} attempts remaining`;return await qbn(p.body),jd(this).info(`${h} - ${I}`),jd(this).debug(`[${c}] response error (${I})`,z0({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,durationMs:m-d})),this.retryRequest(o,n,r??c,p.headers)}let v=g?"error; no more retries left":"error; not retryable";jd(this).info(`${h} - ${v}`);let y=await p.text().catch(I=>ore(I).message),w=Dbn(y),_=w?void 0:y;throw jd(this).debug(`[${c}] response error (${v})`,z0({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,message:_,durationMs:Date.now()-d})),this.makeStatusError(p.status,w,_,p.headers)}return jd(this).info(h),jd(this).debug(`[${c}] response start`,z0({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,durationMs:m-d})),{response:p,options:o,controller:f,requestLogID:c,retryOfRequestLogID:r,startTime:d}}async fetchWithTimeout(e,n,r,o){let{signal:i,method:s,...a}=n||{},l=this._makeAbort(o);i&&i.addEventListener("abort",l,{once:!0});let c=setTimeout(l,r),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:o.signal,...u?{duplex:"half"}:{},method:"GET",...a};s&&(d.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(c)}}async shouldRetry(e){let n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,r,o){let i,s=o?.get("retry-after-ms");if(s){let l=parseFloat(s);Number.isNaN(l)||(i=l)}let a=o?.get("retry-after");if(a&&!i){let l=parseFloat(a);Number.isNaN(l)?i=Date.parse(a)-Date.now():i=l*1e3}if(i===void 0){let l=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(n,l)}return await Fbn(i),this.makeRequest(e,n-1,r)}calculateDefaultRetryTimeoutMillis(e,n){let i=n-e,s=Math.min(.5*Math.pow(2,i),8),a=1-Math.random()*.25;return s*a*1e3}async buildRequest(e,{retryCount:n=0}={}){let r={...e},{method:o,path:i,query:s,defaultBaseURL:a}=r,l=this.buildURL(i,s,a);"timeout"in r&&$bn("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:c,body:u}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:o,bodyHeaders:c,retryCount:n});return{req:{method:o,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...r.fetchOptions??{}},url:l,timeout:r.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:r,retryCount:o}){let i={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);let s=B0([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Wbn()},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(s),s.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:n,headers:r}=e;if(!n)return n==null&&"body"in e?aa(this,mre,"f").call(this,{body:n,headers:B0([r])}):{bodyHeaders:void 0,body:void 0};let o=B0([r]);return ArrayBuffer.isView(n)||n instanceof ArrayBuffer||n instanceof DataView||typeof n=="string"&&o.values.has("content-type")||globalThis.Blob&&n instanceof globalThis.Blob||n instanceof FormData||n instanceof URLSearchParams||globalThis.ReadableStream&&n instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:n}:typeof n=="object"&&(Symbol.asyncIterator in n||Symbol.iterator in n&&"next"in n&&typeof n.next=="function")?{bodyHeaders:void 0,body:h0e(n)}:typeof n=="object"&&o.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(n)}:aa(this,mre,"f").call(this,{body:n,headers:o})}};Pst=zi,mre=new WeakMap,Tst=new WeakSet,h_n=function(){return this.baseURL!=="https://api.groq.com"};zi.Groq=Pst;zi.DEFAULT_TIMEOUT=6e4;zi.GroqError=ac;zi.APIError=mu;zi.APIConnectionError=aO;zi.APIConnectionTimeoutError=Sq;zi.APIUserAbortError=JD;zi.NotFoundError=Tq;zi.ConflictError=Pq;zi.RateLimitError=Eq;zi.BadRequestError=Cq;zi.AuthenticationError=kq;zi.InternalServerError=Mq;zi.PermissionDeniedError=Iq;zi.UnprocessableEntityError=Aq;zi.toFile=g0e;zi.Completions=QD;zi.Chat=uO;zi.Embeddings=eF;zi.Audio=aC;zi.Models=nF;zi.Batches=XD;zi.Files=tF});var g_n=b(()=>{Ast();ust();Ist();Ast();lO()});function jFr(t){if(t.role!=="system"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function")throw new Error(`Unsupported message role: ${t.role}. Expected "system", "assistant", "user", or "function"`);return t.role}function y_n(t){switch(t.type){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!yf.isInstance(t))throw new Error("Invalid generic chat message");return jFr(t);default:throw new Error(`Unknown message type: ${t.type}`)}}function Est(t){return t.map(e=>{let n={role:y_n(e),content:e.content,name:e.name,function_call:e.additional_kwargs.function_call,tool_calls:e.additional_kwargs.tool_calls,tool_call_id:e.tool_call_id};return cv(e)&&e.tool_calls?.length?n.tool_calls=e.tool_calls.map(l4):(e.additional_kwargs.tool_calls!=null&&(n.tool_calls=e.additional_kwargs.tool_calls),e.tool_call_id!=null&&(n.tool_call_id=e.tool_call_id)),n})}function BFr(t,e,n){let r=t.tool_calls,o={...n,model_provider:"groq"};switch(t.role){case"assistant":{let i=[],s=[];for(let a of r??[])try{i.push(jA(a,{returnId:!0}))}catch(l){s.push(iI(a,l.message))}return new cr({content:t.content||"",additional_kwargs:{tool_calls:r},tool_calls:i,invalid_tool_calls:s,usage_metadata:e,response_metadata:o})}default:return new yf(t.content||"",t.role??"unknown")}}function zFr(t,e,n,r){let o=t.role??e,i=t.content??"",s;t.function_call?s={function_call:t.function_call}:t.tool_calls?s={tool_calls:t.tool_calls}:s={},t.audio&&(s.audio={...t.audio,index:n.choices[0].index});let a,l=r,c,u=n.x_groq;u?.usage&&(a={input_tokens:u.usage.prompt_tokens,output_tokens:u.usage.completion_tokens,total_tokens:u.usage.total_tokens},c={completion_time:u.usage.completion_time,prompt_time:u.usage.prompt_time,queue_time:u.usage.queue_time,total_time:u.usage.total_time}),u?.id&&(l=u.id);let d={usage:a,timing:c,model_provider:"groq"};if(o==="user")return new gA({content:i,response_metadata:d});if(o==="assistant"){let f=[];if(Array.isArray(t.tool_calls))for(let p of t.tool_calls)f.push({name:p.function?.name,args:p.function?.arguments,id:p.id,index:p.index,type:"tool_call_chunk"});return new On({content:i,tool_call_chunks:f,additional_kwargs:s,id:l,response_metadata:d})}else return o==="system"?new Lx({content:i,response_metadata:d}):o==="developer"?new Lx({content:i,response_metadata:d,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new hA({content:i,additional_kwargs:s,name:t.name,response_metadata:d}):o==="tool"?new xz({content:i,additional_kwargs:s,tool_call_id:t.tool_call_id,response_metadata:d}):new mA({content:i,role:o,response_metadata:d})}function HFr(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}var DFr,FFr,UFr,Mst,v_n=b(()=>{Abn();Obn();tg();p9e();c1();oi();Sd();ys();tv();g_n();Sye();rI();Nx();l1();DFr=["frequency_penalty","function_call","functions","logit_bias","logprobs","max_completion_tokens","max_tokens","n","parallel_tool_calls","presence_penalty","reasoning_effort","reasoning_format","response_format","seed","service_tier","stop","temperature","tool_choice","top_logprobs","top_p"],FFr=["headers","promptIndex","stream_options","tools"],UFr=[...DFr,...FFr];Mst=class extends Cb{constructor(e,n){let r=typeof e=="string"?{...n??{},model:e}:e??{};super(r);M(this,"lc_namespace",["langchain","chat_models","groq"]);M(this,"client");M(this,"model");M(this,"temperature",.7);M(this,"stop");M(this,"stopSequences");M(this,"maxTokens");M(this,"streaming",!1);M(this,"apiKey");M(this,"streamUsage",!0);M(this,"topP");M(this,"frequencyPenalty");M(this,"presencePenalty");M(this,"logprobs");M(this,"n");M(this,"logitBias");M(this,"user");M(this,"reasoningEffort");M(this,"reasoningFormat");M(this,"serviceTier");M(this,"topLogprobs");M(this,"lc_serializable",!0);this._addVersion("@langchain/groq","1.3.1");let o=r.apiKey||Nn("GROQ_API_KEY");if(!o)throw new Error('Groq API key not found. Please set the GROQ_API_KEY environment variable or provide the key into "apiKey"');let i={"User-Agent":"langchainjs",...r.defaultHeaders??{}};this.client=new zi({apiKey:o,dangerouslyAllowBrowser:!0,baseURL:r.baseUrl,timeout:r.timeout,httpAgent:r.httpAgent,fetch:r.fetch,maxRetries:0,defaultHeaders:i,defaultQuery:r.defaultQuery}),this.apiKey=o,this.temperature=r.temperature??this.temperature,this.model=r.model,this.streaming=r.streaming??this.streaming,this.stop=r.stopSequences??(typeof r.stop=="string"?[r.stop]:r.stop)??[],this.stopSequences=this.stop,this.maxTokens=r.maxTokens,this.topP=r.topP,this.frequencyPenalty=r.frequencyPenalty,this.presencePenalty=r.presencePenalty,this.logprobs=r.logprobs,this.n=r.n,this.logitBias=r.logitBias,this.user=r.user,this.reasoningEffort=r.reasoningEffort}get lc_serialized_keys(){return["client","model","temperature","stop","stopSequences","maxTokens","streaming","apiKey","streamUsage","topP","frequencyPenalty","presencePenalty","logprobs","n","logitBias","user","reasoningEffort","reasoningFormat","serviceTier","topLogprobs"]}static lc_name(){return"ChatGroq"}_llmType(){return"groq"}get lc_secrets(){return{apiKey:"GROQ_API_KEY"}}get callKeys(){return[...super.callKeys,...UFr]}getLsParams(e){let n=this.invocationParams(e);return{ls_provider:"groq",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:n.temperature??this.temperature,ls_max_tokens:n.max_tokens??this.maxTokens,ls_stop:e.stop}}async completionWithRetry(e,n){return this.caller.call(async()=>this.client.chat.completions.create(e,n))}invocationParams(e,n){let r=super.invocationParams(e),o={};e?.stream_options!==void 0?o={stream_options:e.stream_options}:(this.streamUsage&&this.streaming||n?.streaming)&&(o={stream_options:{include_usage:!0}});let i={model:this.model,frequency_penalty:this.frequencyPenalty,function_call:e?.function_call,functions:e?.functions,logit_bias:this.logitBias,logprobs:this.logprobs,n:this.n,parallel_tool_calls:e?.parallel_tool_calls,presence_penalty:this.presencePenalty,reasoning_effort:e?.reasoning_effort??this.reasoningEffort,reasoning_format:this.reasoningFormat,response_format:e?.response_format,seed:e?.seed,service_tier:this.serviceTier,stop:e?.stop??this.stopSequences,temperature:e?.temperature??this.temperature,tool_choice:HFr(e?.tool_choice),tools:e?.tools?.length?e.tools.map(s=>Gx(s)):void 0,top_logprobs:this.topLogprobs,top_p:this.topP,user:this.user,stream:this.streaming,...r,...o};return i.max_completion_tokens=e?.max_completion_tokens??e?.max_tokens??this.maxTokens,i.max_completion_tokens===-1&&delete i.max_completion_tokens,i}bindTools(e,n){return this.withConfig({tools:e.map(r=>Gx(r)),...n})}async*_streamChatModelEvents(e,n,r){let o=this.invocationParams(n,{streaming:!0}),i=Est(e),s=await this.completionWithRetry({...o,messages:i,stream:!0},{signal:n?.signal,headers:n?.headers});yield*HH(async function*(l,c){for await(let u of l){if(c?.aborted)return;yield u}}(s,n.signal),{streamUsage:!0,provider:"groq"})}async*_streamResponseChunks(e,n,r){let o=this.invocationParams(n,{streaming:!0}),i=Est(e),s=await this.completionWithRetry({...o,messages:i,stream:!0},{signal:n?.signal,headers:n?.headers}),a,l;for await(let c of s){if(n.signal?.aborted)return;l=c;let u=c?.choices[0];if(!u)continue;u.delta?.role&&(a=u.delta.role);let d=zFr(u.delta,a,c,void 0),f={prompt:n.promptIndex??0,completion:u.index??0};if(typeof d.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let p={...f};u.finish_reason!=null&&(p.finish_reason=u.finish_reason,p.system_fingerprint=c.system_fingerprint,p.model_name=c.model);let m=new di({message:d,text:d.content,generationInfo:p});yield m,await r?.handleLLMNewToken(m.text??"",f,void 0,void 0,void 0,{chunk:m})}if(l&&("choices"in l&&delete l.choices,yield new di({message:new On({content:"",response_metadata:l}),text:""})),n.signal?.aborted)throw new Error("AbortError")}async _generate(e,n,r){if(n.signal?.throwIfAborted(),this.streaming){let o={},i=this._streamResponseChunks(e,n,r),s={};for await(let a of i){let l=a.generationInfo?.completion??0;s[l]===void 0?s[l]=a:s[l]=s[l].concat(a)}return{generations:Object.entries(s).sort(([a],[l])=>parseInt(a,10)-parseInt(l,10)).map(([a,l])=>l),llmOutput:{estimatedTokenUsage:o}}}else return this._generateNonStreaming(e,n,r)}async _generateNonStreaming(e,n,r){let o={},i=this.invocationParams(n),s=Est(e),a=await this.completionWithRetry({...i,stream:!1,messages:s},{signal:n?.signal,headers:n?.headers});if("usage"in a&&a.usage){let{completion_tokens:c,prompt_tokens:u,total_tokens:d}=a.usage;c&&(o.completionTokens=(o.completionTokens??0)+c),u&&(o.promptTokens=(o.promptTokens??0)+u),d&&(o.totalTokens=(o.totalTokens??0)+d)}let l=[];if("choices"in a&&a.choices)for(let c of a.choices){let u=c.message?.content??"",d;o.totalTokens!==void 0&&(d={input_tokens:o.promptTokens??0,output_tokens:o.completionTokens??0,total_tokens:o.totalTokens});let{choices:f,...p}=a,m={text:u,message:BFr(c.message??{role:"assistant"},d,p)};m.generationInfo={...c.finish_reason?{finish_reason:c.finish_reason}:{},...c.logprobs?{logprobs:c.logprobs}:{}},l.push(m)}return{generations:l,llmOutput:{tokenUsage:o}}}get profile(){return Pbn[this.model]??{}}withStructuredOutput(e,n){let r=e,o=n?.name,i=n?.includeRaw,s=Mbn(this.model,n?.method),a=o??"extract",l,c;if(s==="jsonSchema"){let u=o??"structured_output",d=Fk(r),f=ki(r)||Ya(r)?Ki(r):r,p=sO(f);c=this.withConfig({response_format:{type:"json_schema",json_schema:{name:u,description:d,strict:!0,schema:p}},ls_structured_output_format:{kwargs:{method:"jsonSchema"},schema:{title:u,description:d,...f}}}),l=pv(r)}else if(s==="jsonMode"){l=pv(r);let u=ki(r)||Ya(r)?Ki(r):r;c=this.withConfig({response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"jsonMode"},schema:u}})}else{let u;if(ki(r)||Ya(r)){let d=Ki(r);u={name:a,description:d.description,parameters:d}}else typeof r.name=="string"&&typeof r.parameters=="object"&&r.parameters!=null?(u=r,a=r.name):(a=r.title??a,u={name:a,description:r.description??"",parameters:r});c=this.bindTools([{type:"function",function:u}]).withConfig({tool_choice:{type:"function",function:{name:a}},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:u.parameters}}),l=Jx(r,a)}return mv(c,l,i,"ChatGroqStructuredOutput")}}});var w_n=b(()=>{v_n()});function Ost(t,e,n){if(!(!t&&!e&&!n))return{...n??{},...t??{},...e??{}}}function b_n(t){if(!t)return;let e={mode:t.mode??"auto"};return t.max_search_results!==void 0&&(e.max_search_results=t.max_search_results),t.from_date!==void 0&&(e.from_date=t.from_date),t.to_date!==void 0&&(e.to_date=t.to_date),t.return_citations!==void 0&&(e.return_citations=t.return_citations),t.sources&&t.sources.length>0&&(e.sources=t.sources),e}function __n(t){if(!t?.tools)return;let e=t.tools.filter(n=>n==null||typeof n!="object"||!("type"in n)||!t?.excludedTypes?.length?!0:!t.excludedTypes.includes(n.type));return e.length>0?e:void 0}var x_n=b(()=>{});var S_n,C_n=b(()=>{S_n={"grok-3-fast-latest":{maxInputTokens:131072,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"grok-2-vision":{maxInputTokens:8192,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"grok-3":{maxInputTokens:131072,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"grok-code-fast-1":{maxInputTokens:256e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:1e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"grok-2-vision-1212":{maxInputTokens:8192,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"grok-4-1-fast-non-reasoning":{maxInputTokens:2e6,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:3e4,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"grok-3-mini-fast":{maxInputTokens:131072,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"grok-4-fast":{maxInputTokens:2e6,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:3e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"grok-4":{maxInputTokens:256e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"grok-3-latest":{maxInputTokens:131072,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"grok-4-1-fast":{maxInputTokens:2e6,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:3e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"grok-2-vision-latest":{maxInputTokens:8192,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"grok-3-mini-latest":{maxInputTokens:131072,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"grok-3-mini":{maxInputTokens:131072,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"grok-3-mini-fast-latest":{maxInputTokens:131072,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"grok-2-latest":{maxInputTokens:131072,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"grok-4-fast-non-reasoning":{maxInputTokens:2e6,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:3e4,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"grok-vision-beta":{maxInputTokens:8192,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"grok-3-fast":{maxInputTokens:131072,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0}}});var Nst,Rst=b(()=>{Nst="live_search_deprecated_20251215"});function hre(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&WFr.has(t.type)}var WFr,S0e,Lst=b(()=>{x_n();C_n();Rst();rI();ys();wI();WFr=new Set([Nst]);S0e=class extends fE{constructor(e,n){let r=typeof e=="string"?{...n??{},model:e}:e??{},o=r?.apiKey||Nn("XAI_API_KEY");if(!o)throw new Error('xAI API key not found. Please set the XAI_API_KEY environment variable or provide the key into "apiKey" field.');super({...r,model:r?.model||"grok-3-fast",apiKey:o,configuration:{baseURL:r?.baseURL??"https://api.x.ai/v1"}});M(this,"lc_serializable",!0);M(this,"lc_namespace",["langchain","chat_models","xai"]);M(this,"searchParameters");this._addVersion("@langchain/xai","1.4.8"),this.searchParameters=r?.searchParameters}static lc_name(){return"ChatXAI"}_llmType(){return"xai"}get lc_secrets(){return{apiKey:"XAI_API_KEY"}}toJSON(){let e=super.toJSON();return"kwargs"in e&&typeof e.kwargs=="object"&&e.kwargs!=null&&(delete e.kwargs.openai_api_key,delete e.kwargs.configuration),e}getLsParams(e){let n=super.getLsParams(e);return n.ls_provider="xai",n}_getEffectiveSearchParameters(e){return Ost(this.searchParameters,e?.searchParameters)}_hasBuiltInTools(e){return e?.some(hre)??!1}formatStructuredToolToXAI(e){if(!(!e||!e.length))return e.map(n=>xf(n)&&n.extras?.providerToolDefinition?n.extras.providerToolDefinition:hre(n)?n:Gx(n))}bindTools(e,n){return this.withConfig({tools:this.formatStructuredToolToXAI(e),...n})}invocationParams(e,n){let r={...super.invocationParams(e,n)},o=e?.tools?.find(hre),i=Ost(this.searchParameters,e?.searchParameters,o);return i&&(r.search_parameters=b_n(i)),r}async completionWithRetry(e,n){delete e.frequency_penalty,delete e.presence_penalty,delete e.logit_bias,delete e.functions;let r=e.messages.map(s=>s.content?s:{...s,content:""}),o;e.tools&&(o=__n({tools:e.tools,excludedTypes:[Nst]}));let i={...e,messages:r,tools:o};return i.stream===!0?super.completionWithRetry(i,n):super.completionWithRetry(i,n)}_convertCompletionsDeltaToBaseMessageChunk(e,n,r){let o=super._convertCompletionsDeltaToBaseMessageChunk(e,n,r),i=o.response_metadata;return n.choices[0]?.finish_reason?o.usage_metadata=i.usage:(delete i.usage,delete o.usage_metadata),o}get profile(){return S_n[this.model]??{}}get streamEventProvider(){return"xai"}}});var k_n=b(()=>{oi();Sd()});var I_n=b(()=>{wI()});var $st=b(()=>{k_n();I_n();ys();c1()});var T_n=b(()=>{Lst();$st()});var P_n=b(()=>{});var A_n=b(()=>{});var E_n=b(()=>{});var M_n=b(()=>{});var O_n=b(()=>{Rst();P_n();A_n();E_n();M_n()});var N_n=b(()=>{Lst();$st();T_n();O_n()});var Uq,R_n=b(()=>{oi();Sd();wI();Pb();pe();Uq=class extends gg{constructor(e){let{enableReasoning:n=!1,reasoningEffort:r,enablePromptCaching:o=!0,...i}=e;super(i),this.enableReasoning=n,this.reasoningEffort=r,this.enablePromptCaching=o;let s=e.configuration?.baseURL||"https://openrouter.ai/api/v1";this.isOpenRouter=s.includes("openrouter.ai"),this.openaiClient=new Rn({apiKey:e.apiKey,baseURL:s,defaultHeaders:e.configuration?.defaultHeaders,fetch:e.configuration?.fetch,dangerouslyAllowBrowser:!0})}invocationParams(e){let n=super.invocationParams(e),r=this.isOpenRouter&&this.enablePromptCaching?{...n,cache_control:{type:"ephemeral"}}:n;if(this.enableReasoning)if(this.reasoningEffort){let o=this.reasoningEffort==="minimal"?"low":this.reasoningEffort;return j(`OpenRouter reasoning enabled with effort: ${o}`),{...r,reasoning:{effort:o}}}else return j("OpenRouter reasoning enabled with max_tokens: 1024"),{...r,reasoning:{max_tokens:1024}};return r}async*_streamResponseChunks(e,n,r){let o=this.invocationParams(n),i=this.toOpenRouterMessages(e),s=await this.openaiClient.chat.completions.create({...o,messages:i,stream:!0,stream_options:{...o.stream_options??{},include_usage:!0}}),a;for await(let l of s){l.usage&&(a=l.usage);let c=l.choices?.[0],u=c?.delta;if(!c||!u)continue;let d=this.normalizeReasoningChunk(u?.reasoning),f=this.extractReasoningDetails(c),p=this.extractDeltaContent(u.content),m=this.buildMessageChunk({rawChunk:l,delta:u,content:p,finishReason:c.finish_reason,reasoningDetails:f,reasoningText:d}),h=new di({message:m,text:typeof m.content=="string"?m.content:"",generationInfo:{finish_reason:c.finish_reason,model:l.model}});yield h,h.text&&await r?.handleLLMNewToken(h.text)}if(a&&(yield this.buildUsageGenerationChunk(a)),n.signal?.aborted)throw new Error("AbortError")}toOpenRouterMessages(e){return e.map(n=>{let r=n,o=bl.isInstance(n)?n.type:r.role??"user",i=o==="human"?"user":o==="ai"?"assistant":o;return r.tool_call_id?{role:"tool",content:n.content,tool_call_id:r.tool_call_id}:cr.isInstance(n)&&n.tool_calls&&n.tool_calls.length>0?{role:"assistant",content:n.content,tool_calls:n.tool_calls.map(s=>({id:s.id??"",type:"function",function:{name:s.name,arguments:JSON.stringify(s.args??{})}}))}:{role:i,content:n.content}})}buildMessageChunk(e){let{rawChunk:n,delta:r,content:o,finishReason:i,reasoningText:s,reasoningDetails:a}=e,l=this.extractToolCallChunks(r.tool_calls),c={},u={};s&&(u.reasoning=s),a&&a.length>0&&(u.reasoning_details=a),Object.keys(u).length>0&&(c.delta={...c.delta,...u}),a&&a.length>0&&(c.reasoning_details=a);let d=this.buildResponseMetadata(n,i);return new On({content:o,additional_kwargs:c,tool_call_chunks:l,response_metadata:d,id:n.id})}normalizeReasoningChunk(e){if(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(n=>this.normalizeReasoningChunk(n)).filter(n=>!!n).join("");if(typeof e=="object"){let n=e,o=[n.output_text,n.text,n.reasoning,n.thinking,n.content].find(i=>typeof i=="string");if(typeof o=="string")return o}}}extractReasoningDetails(e){let n=e,r=n?.delta?.reasoning_details??n?.message?.reasoning_details??e?.reasoning_details;if(Array.isArray(r))return r.filter(o=>o!=null)}extractDeltaContent(e){return typeof e=="string"?e:Array.isArray(e)?e.map(n=>typeof n=="string"?n:n&&typeof n=="object"&&typeof n.text=="string"?n.text:"").join(""):""}extractToolCallChunks(e){if(Array.isArray(e))return e.map(n=>{let r=n;return{name:r?.function?.name,args:r?.function?.arguments,id:r?.id,index:r?.index,type:"tool_call_chunk"}})}buildResponseMetadata(e,n){let r={model_provider:"openrouter"};return n&&(r.finish_reason=n),e.model&&(r.model=e.model),e.usage&&(r.usage={...e.usage},r.tokenUsage={promptTokens:e.usage.prompt_tokens,completionTokens:e.usage.completion_tokens,totalTokens:e.usage.total_tokens}),r}buildUsageGenerationChunk(e){let n={},r={},o=e.prompt_tokens_details??{};typeof o.audio_tokens=="number"&&(n.audio=o.audio_tokens),typeof o.cached_tokens=="number"&&(n.cache_read=o.cached_tokens);let i=e.completion_tokens_details??{};typeof i.audio_tokens=="number"&&(r.audio=i.audio_tokens),typeof i.reasoning_tokens=="number"&&(r.reasoning=i.reasoning_tokens);let s={input_tokens:e.prompt_tokens??0,output_tokens:e.completion_tokens??0,total_tokens:e.total_tokens??0};Object.keys(n).length>0&&(s.input_token_details=n),Object.keys(r).length>0&&(s.output_token_details=r);let a=new On({content:"",response_metadata:{usage:{...e}},usage_metadata:s});return new di({message:a,text:""})}}});function qFr(t){let e=t||window.fetch;return async(n,r)=>{if(r?.body&&typeof r.body=="string")try{let o=JSON.parse(r.body),i=!1;Array.isArray(o.tools)&&(o.tools=o.tools.map(s=>{let a={};for(let[l,c]of Object.entries(s))c!=null&&(a[l]=c);return a}),i=!0),i&&(r={...r,body:JSON.stringify(o)})}catch{}return e(n,r)}}var C0e,L_n=b(()=>{wI();C0e=class extends gg{constructor(e){let r=e.configuration?.fetch;super({...e,useResponsesApi:!0,configuration:{...e.configuration,fetch:qFr(r)},modelKwargs:{...e.modelKwargs,text:{format:{type:"text"}}}})}}});var D_n={};sr(D_n,{default:()=>nw,normalizeAzureUrl:()=>$_n});function $_n(t){if(!t)return{baseUrl:void 0,apiVersion:void 0};let e;try{e=new URL(t)}catch{return{baseUrl:t,apiVersion:void 0}}let n=e.searchParams.get("api-version")||void 0;e.search="";let r=e.toString().replace(/\/+$/,"");return r=r.replace(/\/(chat\/completions|embeddings)$/,""),{baseUrl:r,apiVersion:n}}var KFr,GFr,Do,nw,jq=b(()=>{es();gt();pe();vc();Se();ut();eZe();Sbn();lg();Tbn();mqe();w_n();Aqe();wI();N_n();iy();R_n();L_n();_v();KFr=[{category:"HARM_CATEGORY_SEXUALLY_EXPLICIT",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_HATE_SPEECH",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_DANGEROUS_CONTENT",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_HARASSMENT",threshold:"BLOCK_NONE"}];r4.prototype.getNumTokens=async t=>{let e=typeof t=="string"?t:t.map(n=>n.text??"").join("");return Math.ceil(e.length/4)};GFr={openai:gg,"azure openai":gg,anthropic:Yit,cohereai:gg,google:fqe,xai:S0e,openrouterai:Uq,ollama:Iqe,"lm-studio":Uq,groq:Mst,"3rd party (openai-format)":gg,siliconflow:gg,"copilot-plus":Uq,mistralai:gg,deepseek:Jit};Do=class Do{constructor(){this.providerApiKeyMap={openai:()=>Y().openAIApiKey,google:()=>Y().googleApiKey,"azure openai":()=>Y().azureOpenAIApiKey,anthropic:()=>Y().anthropicApiKey,cohereai:()=>Y().cohereApiKey,openrouterai:()=>Y().openRouterAiApiKey,groq:()=>Y().groqApiKey,xai:()=>Y().xaiApiKey,ollama:()=>"default-key","lm-studio":()=>"default-key","3rd party (openai-format)":()=>"default-key","copilot-plus":()=>Y().plusLicenseKey,mistralai:()=>Y().mistralApiKey,deepseek:()=>Y().deepseekApiKey,siliconflow:()=>Y().siliconflowApiKey};this.buildModelMap(),zr(()=>{this.buildModelMap(),this.validateCurrentModel()})}static getInstance(){return Do.instance||(Do.instance=new Do),Do.instance}getTemperatureForModel(e,n,r){if(!e.isThinkingEnabled)return e.isOSeries||e.isGPT5?Do.REASONING_MODEL_TEMPERATURE:n.temperature??r.temperature}async getModelConfig(e,n=!0){let r=Y(),o=e.name,i=WK(o),{isThinkingEnabled:s,usesAdaptiveThinking:a}=i,l=this.getTemperatureForModel(i,e,r),c=e.maxTokens,u=e.requiresApiKey===!1,d={modelName:o,streaming:e.stream??!0,maxRetries:3,maxConcurrency:3,enableCors:e.enableCors,...!s&&l!==void 0?{temperature:l}:{}},p={openai:{modelName:o,apiKey:await this.resolveApiKey(e.apiKey,r.openAIApiKey,n),configuration:{baseURL:e.baseUrl,fetch:e.enableCors?ks:void 0,organization:e.openAIOrgId||r.openAIOrgId},...this.getOpenAISpecialConfig(o,c,e)},anthropic:{anthropicApiKey:await this.resolveApiKey(e.apiKey,r.anthropicApiKey,n),model:o,anthropicApiUrl:e.baseUrl,clientOptions:{defaultHeaders:{"anthropic-dangerous-direct-browser-access":"true"},fetch:e.enableCors?ks:void 0},...s&&{thinking:a?{type:"adaptive",display:"summarized"}:{type:"enabled",budget_tokens:Do.ANTHROPIC_THINKING_BUDGET_TOKENS}}},"azure openai":await(async()=>{let g=$_n(e.baseUrl);return{modelName:e.baseUrl?o:e.azureOpenAIApiDeploymentName||r.azureOpenAIApiDeploymentName,apiKey:await this.resolveApiKey(e.apiKey,r.azureOpenAIApiKey,n),configuration:{baseURL:g.baseUrl||`https://${e.azureOpenAIApiInstanceName||r.azureOpenAIApiInstanceName}.openai.azure.com/openai/deployments/${e.azureOpenAIApiDeploymentName||r.azureOpenAIApiDeploymentName}`,defaultQuery:{"api-version":g.apiVersion||e.azureOpenAIApiVersion||r.azureOpenAIApiVersion||"2024-05-01-preview"},defaultHeaders:{"Content-Type":"application/json","api-key":await this.resolveApiKey(e.apiKey,r.azureOpenAIApiKey,n)},fetch:e.enableCors?ks:void 0},...this.getOpenAISpecialConfig(o,c,e)}})(),cohereai:{modelName:o,apiKey:await this.resolveApiKey(e.apiKey,r.cohereApiKey,n),configuration:{baseURL:e.baseUrl||Qp.cohereai.host,fetch:e.enableCors?ks:void 0}},google:{apiKey:await this.resolveApiKey(e.apiKey,r.googleApiKey,n),model:o,safetySettings:KFr,baseUrl:JZt(e.baseUrl)},xai:{apiKey:await this.resolveApiKey(e.apiKey,r.xaiApiKey,n),model:o},openrouterai:{modelName:o,apiKey:await this.resolveApiKey(e.apiKey,r.openRouterAiApiKey,n),configuration:{baseURL:e.baseUrl||"https://openrouter.ai/api/v1",fetch:e.enableCors?ks:void 0,defaultHeaders:{"HTTP-Referer":"https://obsidiancopilot.com","X-Title":"Obsidian Copilot"}},enableReasoning:e.capabilities?.includes("reasoning")??!1,reasoningEffort:e.capabilities?.includes("reasoning")&&e.reasoningEffort?e.reasoningEffort:void 0,enablePromptCaching:e.enablePromptCaching??!0},groq:{apiKey:await this.resolveApiKey(e.apiKey,r.groqApiKey,n),model:o,baseUrl:XZt(e.baseUrl)},ollama:{model:o,baseUrl:e.baseUrl||"http://localhost:11434",headers:{Authorization:`Bearer ${e.apiKey||"default-key"}`},fetch:e.enableCors?ks:void 0,think:e.capabilities?.includes("reasoning")??!1,repeatPenalty:1.1,numCtx:e.numCtx??xct},"lm-studio":{modelName:o,apiKey:e.apiKey||"default-key",streamUsage:e.streamUsage??!1,configuration:{baseURL:e.baseUrl||"http://localhost:1234/v1",fetch:e.enableCors?ks:void 0},enableReasoning:e.capabilities?.includes("reasoning")??!1,reasoningEffort:e.capabilities?.includes("reasoning")&&e.reasoningEffort?e.reasoningEffort:void 0},"3rd party (openai-format)":{modelName:o,apiKey:u?void 0:await this.resolveApiKey(e.apiKey,r.openAIApiKey,n),streamUsage:e.streamUsage??!1,configuration:{baseURL:e.baseUrl,fetch:e.enableCors?ks:void 0,defaultHeaders:u?{Authorization:null}:void 0},...this.getOpenAISpecialConfig(o,c,e)},siliconflow:{modelName:o,apiKey:await this.resolveApiKey(e.apiKey,r.siliconflowApiKey,n),configuration:{baseURL:e.baseUrl||Qp.siliconflow.host,fetch:e.enableCors?ks:void 0},...this.getOpenAISpecialConfig(o,c,e)},"copilot-plus":{modelName:o,apiKey:await this.resolveApiKey(e.apiKey,r.plusLicenseKey,n),configuration:{baseURL:Jp,fetch:ks,defaultHeaders:Gi.getInstance().getPluginVersionHeaders()},enableReasoning:(e.capabilities?.includes("reasoning")??!1)&&!!e.reasoningEffort,reasoningEffort:e.capabilities?.includes("reasoning")&&e.reasoningEffort?e.reasoningEffort:void 0},mistralai:{modelName:o,apiKey:await this.resolveApiKey(e.apiKey,r.mistralApiKey,n),configuration:{baseURL:e.baseUrl||Qp.mistralai.host,fetch:e.enableCors?ks:void 0}},deepseek:{modelName:o,apiKey:await this.resolveApiKey(e.apiKey,r.deepseekApiKey,n),configuration:{baseURL:e.baseUrl||Qp.deepseek.host,fetch:e.enableCors?ks:void 0}}}[e.provider]||{},m=this.getProviderSpecificParams(e.provider,e);return{...d,...p,...m,...c===void 0?{}:{maxTokens:c}}}async resolveApiKey(e,n,r){return e||(r?n:"")}getOpenAISpecialConfig(e,n,r){let o=Y(),i=WK(e),a={temperature:this.getTemperatureForModel(i,r||{},o),...n===void 0?{}:{maxTokens:n}};if((i.isOSeries||i.isGPT5)&&r?.reasoningEffort&&(a.reasoning={effort:r.reasoningEffort},i.isGPT5&&r?.verbosity&&r?.provider!=="azure openai")){let l=r.verbosity;a.text={verbosity:l}}return a}getProviderSpecificParams(e,n){let r={};return n.topP!==void 0&&["openai","azure openai","anthropic","google","openrouterai","ollama","lm-studio","3rd party (openai-format)","mistralai","deepseek","siliconflow"].includes(e)&&(r.topP=n.topP),n.frequencyPenalty!==void 0&&["openai","azure openai","openrouterai","ollama","lm-studio","3rd party (openai-format)","mistralai","deepseek","siliconflow"].includes(e)&&(r.frequencyPenalty=n.frequencyPenalty),r}buildModelMap(){let e=Y().activeModels;Do.modelMap={};let n=Do.modelMap;(e??KF).forEach(o=>{if(o.enabled){if(!Object.values(L_).includes(o.provider)){W(`Unknown provider: ${o.provider} for model: ${o.name}`);return}let i=this.getProviderConstructor(o),s=this.hasProviderCredentials(o),a=Jn(o);n[a]={hasApiKey:s,AIConstructor:i,vendor:o.provider}}})}hasProviderCredentials(e,n=!0){if(e.requiresApiKey===!1&&e.provider==="3rd party (openai-format)")return!0;let r=this.providerApiKeyMap[e.provider];return r?!!(e.apiKey||n&&r()):!!e.apiKey}getProviderConstructor(e){let n=GFr[e.provider];if(!n)throw W(`Unknown provider: ${e.provider} for model: ${e.name}`),new Error(`Unknown provider: ${e.provider} for model: ${e.name}`);return n}getChatModel(){if(!Do.chatModel)throw new Error("No valid chat model available. Please check your API key settings.");return Do.chatModel}getActiveModel(){return Do.activeModel}isModelConfigValid(e,n){let r=Jn(e),o=Do.modelMap[r];return!(!o||!o.hasApiKey||e.plusExclusive&&!Sgn())}resolveModelForTemperatureOverride(){let e=Y();try{let n=L2();if(n){let r=Ydt(n,e.activeModels);if(this.isModelConfigValid(r,e))return r}}catch{}for(let n of e.activeModels)if(n.enabled&&!n.believerExclusive&&this.isModelConfigValid(n,e))return n;throw new Error("No valid chat model available for temperature override. Please check your API key settings and ensure at least one model is properly configured.")}async getChatModelWithTemperature(e){let r={...Do.activeModel??this.resolveModelForTemperatureOverride(),temperature:e};return Do.activeModelSource==="bridged"?await this.createModelInstanceFromBridged(r):await this.createModelInstance(r)}async setChatModel(e){try{let n=await this.createModelInstance(e);Do.chatModel=n,Do.activeModel=e,Do.activeModelSource="legacy",WK(e.name).isGPT5&&(e.provider==="openai"||e.provider==="3rd party (openai-format)")&&j(`Chat model set with Responses API for GPT-5: ${e.name}`)}catch(n){throw H(n),n}}async setChatModelFromBridged(e){try{Do.chatModel=await this.createModelInstanceFromBridged(e),Do.activeModel=e,Do.activeModelSource="bridged"}catch(n){throw H(n),n}}async createModelInstance(e){let n=Jn(e),r=Do.modelMap[n];if(!r)throw new Error(`No model found for: ${n}`);if(!r.hasApiKey){let o=`API key is not provided for the model: ${n}.`;throw e.provider==="copilot-plus"?new sT("Copilot Plus license key is not configured. Please enter your license key in the Copilot Plus section at the top of Basic Settings."):new ZF(o)}return this.instantiateChatModel(e,r.vendor,r.AIConstructor)}async createModelInstanceFromBridged(e){if(!this.hasProviderCredentials(e,!1))throw e.provider==="copilot-plus"?new sT("Copilot Plus license key is not configured. Please enter your license key in the Copilot Plus section at the top of Basic Settings."):new ZF(`API key is not provided for the model: ${e.name}.`);return this.instantiateChatModel(e,e.provider,this.getProviderConstructor(e),!1)}async instantiateChatModel(e,n,r,o=!0){let i=await this.getModelConfig(e,o),s=WK(e.name),a={...i};if(s.isGPT5&&(n==="openai"||n==="3rd party (openai-format)")&&(a.useResponsesApi=!0,j(`Enabling Responses API for GPT-5 model: ${e.name} (${n})`)),e.provider==="lm-studio"&&e.useResponsesApi!==!1){let l=new C0e(a);return j(`[ChatModelManager] Using Responses API for LM Studio model: ${e.name}`),l}return new r(a)}validateChatModel(e){return e!=null}estimateTokens(e){return e?Math.ceil(e.length/4):0}async countTokens(e){return Do.chatModel?.getNumTokens(e)??this.estimateTokens(e)}validateCurrentModel(){if(!Do.chatModel)return;let e=L2();if(!e)return;let n=Do.modelMap[e];n&&!n.hasApiKey&&(Do.chatModel=null,Do.activeModel=null,Do.activeModelSource=null,j("Failed to reinitialize model due to missing API key"))}findModelByName(e){return Do.activeModelSource==="bridged"&&Do.activeModel?.name===e?Do.activeModel:Y().activeModels.find(r=>r.name===e)}};Do.activeModel=null,Do.activeModelSource=null,Do.ANTHROPIC_THINKING_BUDGET_TOKENS=2048,Do.REASONING_MODEL_TEMPERATURE=1;nw=Do});var F_n={};sr(F_n,{TieredLexicalRetriever:()=>cC});async function ZFr(){try{if(!Dst){let e=await Promise.resolve().then(()=>(jq(),D_n));Dst=()=>e.default.getInstance()}return Dst().getChatModel()}catch{return null}}var Fst,Dst,cC,gre=b(()=>{pe();Se();ut();$M();ine();Fst=require("obsidian");Zte();S3();Dst=null;cC=class extends HM{constructor(n,r){super();this.app=n;this.options=r;this.lc_namespace=["tiered_lexical_retriever"];this.lastQueryExpansion=null;this.searchCore=new Qke(n,ZFr),this.chunkManager=DM(n)}getLastQueryExpansion(){return this.lastQueryExpansion}async getRelevantDocuments(n,r){try{let i=j_(n,this.app.vault).map(f=>f.basename),s=[...new Set([...this.options.salientTerms,...i])];Y().debug&&j("TieredLexicalRetriever: Starting search",{query:n,salientTerms:s,maxK:this.options.maxK});let a=Y(),l=await this.searchCore.retrieve(n,{maxResults:this.options.maxK,salientTerms:s,enableLexicalBoosts:a.enableLexicalBoosts,preExpandedQuery:this.options.preExpandedQuery}),c=l.results;this.lastQueryExpansion=l.queryExpansion;let u=await this.convertToDocuments(c),d=this.sortResults(u);return Y().debug&&j("TieredLexicalRetriever: Search complete",{totalResults:d.length,searchResults:c.length}),d}catch(o){return W("TieredLexicalRetriever: Error during search",o),[]}}async convertToDocuments(n){let r=[];for(let o of n)try{if(o.id.includes("#")){let[s]=o.id.split("#"),a=this.app.vault.getAbstractFileByPath(s);if(!a||!(a instanceof Fst.TFile))continue;let l="",c=this.chunkManager;if(typeof c.getChunkText=="function"?l=await c.getChunkText(o.id):typeof c.getChunkTextSync=="function"&&(l=c.getChunkTextSync(o.id)||""),!l)continue;let u=this.app.metadataCache.getFileCache(a);r.push(new cu({pageContent:l,metadata:{path:s,chunkId:o.id,title:a.basename,mtime:a.stat.mtime,ctime:a.stat.ctime,tags:u?.tags?.map(d=>d.tag)||[],score:o.score,rerank_score:o.score,engine:o.engine||"chunk-v3",includeInContext:o.score>(this.options.minSimilarityScore||.1),explanation:o.explanation,isChunk:!0}}))}else{let s=this.app.vault.getAbstractFileByPath(o.id);if(!s||!(s instanceof Fst.TFile))continue;let a=await this.app.vault.cachedRead(s);if(!a)continue;let l=this.app.metadataCache.getFileCache(s);r.push(new cu({pageContent:a,metadata:{path:o.id,title:s.basename,mtime:s.stat.mtime,ctime:s.stat.ctime,tags:l?.tags?.map(c=>c.tag)||[],score:o.score,rerank_score:o.score,engine:o.engine||"v3",includeInContext:o.score>(this.options.minSimilarityScore||.1),explanation:o.explanation,isChunk:!1}}))}}catch(i){W(`TieredLexicalRetriever: Failed to convert result ${o.id}`,i)}return j(`TieredLexicalRetriever: Converted ${r.length} results to Documents`),r}sortResults(n){return n.sort((r,o)=>{let i=r.metadata.score||0,a=(o.metadata.score||0)-i;if(Math.abs(a)>.01)return a;if(r.metadata.isChunk&&o.metadata.isChunk&&r.metadata.path===o.metadata.path){let l=parseInt(r.metadata.chunkId?.split("#")[1]||"0"),c=parseInt(o.metadata.chunkId?.split("#")[1]||"0");return l-c}return a})}}});var U_n={};sr(U_n,{MergedSemanticRetriever:()=>Bq});var dO,Bq,Ust=b(()=>{oyn();S3();gre();$M();ine();dO=class dO extends HM{constructor(n,r,o){super();this.app=n;this.options=r;this.lc_namespace=["merged_semantic_retriever"];this.originalMaxK=Math.max(1,r.maxK),this.returnAll=!!r.returnAll;let i=this.returnAll?al:Math.min(this.originalMaxK*2,al),s={...r,maxK:i,returnAll:this.returnAll};this.lexicalRetriever=new cC(n,s);let a=this.returnAll?al:Math.min(this.originalMaxK*2,al);this.semanticRetriever=o||new tIe({minSimilarityScore:r.minSimilarityScore??.1,maxK:a,salientTerms:r.salientTerms,timeRange:r.timeRange,textWeight:r.textWeight,returnAll:this.returnAll,useRerankerThreshold:r.useRerankerThreshold},this.app.vault)}async getRelevantDocuments(n){let[r,o]=await Promise.all([this.lexicalRetriever.getRelevantDocuments(n),this.semanticRetriever.getRelevantDocuments(n)]),i=new Map;for(let l of r)this.insertResult(i,l,"lexical");for(let l of o)this.insertResult(i,l,"semantic");let s=Array.from(i.values()).sort((l,c)=>(c.metadata?.score??0)-(l.metadata?.score??0)),a=this.returnAll?al:this.originalMaxK;return s.slice(0,a)}insertResult(n,r,o){let i=this.getDocumentKey(r),s=this.decorateDocument(r,o),a=n.get(i);if(!a){n.set(i,s);return}let l=a.metadata?.source,c=this.getDocumentScore(a),u=this.getDocumentScore(s);if(o==="lexical"){(l!=="lexical"||u>c)&&n.set(i,s);return}l!=="lexical"&&u>c&&n.set(i,s)}getDocumentKey(n){let r=n.metadata??{};return r.chunkId||r.path||r.id||r.title||`${n.pageContent.slice(0,64)}::${n.pageContent.length}`}decorateDocument(n,r){let o={...n.metadata??{},source:r},i=this.extractBaseScore(o),s=r==="lexical"?dO.LEXICAL_WEIGHT:dO.SEMANTIC_WEIGHT,a=i*s;return r==="lexical"&&this.hasTagMatch(o)&&(a*=dO.TAG_MATCH_BOOST),o.score=a,o.rerank_score=a,new cu({pageContent:n.pageContent,metadata:o})}extractBaseScore(n){let r=[n?.rerank_score,n?.score];for(let o of r)if(typeof o=="number"&&!Number.isNaN(o))return o;return 0}getDocumentScore(n){let r=n.metadata?.score;return typeof r=="number"&&!Number.isNaN(r)?r:0}hasTagMatch(n){let r=n?.explanation;if(!r)return!1;let o=r.lexicalMatches;return Array.isArray(o)?o.some(i=>i?.field==="tags"):!1}};dO.LEXICAL_WEIGHT=1,dO.SEMANTIC_WEIGHT=1,dO.TAG_MATCH_BOOST=1.1;Bq=dO});var B_n={};sr(B_n,{FilterRetriever:()=>fO});var j_n,fO,I0e=b(()=>{pe();Se();ha();ut();$M();j_n=require("obsidian");S3();fO=class{constructor(e,n){this.app=e;this.options=n}async getRelevantDocuments(e){if(this.options.timeRange)return this.getTimeRangeDocuments(e);let n=j_(e,this.app.vault),r=await this.getTitleMatches(n),o=await this.getTagMatches(this.resolveTagTerms(e));return this.combineGuaranteedMatches(r,o)}hasTimeRange(){return this.options.timeRange!==void 0}async getTimeRangeDocuments(e){if(!this.options.timeRange)return[];let{startTime:n,endTime:r}=this.options.timeRange,o=this.generateDailyNoteDateRange(n,r);Y().debug&&j("FilterRetriever: Generated daily note titles",{startTime:new Date(n).toISOString(),endTime:new Date(r).toISOString(),titlesCount:o.length,firstTitle:o[0],lastTitle:o[o.length-1]});let{inclusions:i,exclusions:s}=Fi(),a=o.join(", "),l=j_(a,this.app.vault).filter(v=>ii(this.app,v,i,s)),u=(await this.getTitleMatches(l)).map(v=>(v.metadata.includeInContext=!0,v)),d=this.app.vault.getMarkdownFiles().filter(v=>ii(this.app,v,i,s)),f=[],p=this.options.returnAll?al:Math.min(this.options.maxK,al);for(let v of d)if(v.stat.mtime>=n&&v.stat.mtime<=r){if(l.some(y=>y.path===v.path))continue;if(f.length>=p)break;try{let y=await this.app.vault.cachedRead(v),w=this.app.metadataCache.getFileCache(v),_=(Date.now()-v.stat.mtime)/(1e3*60*60*24),S=Math.max(.3,Math.min(1,1-_/30));f.push(new cu({pageContent:y,metadata:{path:v.path,title:v.basename,mtime:v.stat.mtime,ctime:v.stat.ctime,tags:w?.tags?.map(I=>I.tag)||[],includeInContext:!0,score:S,rerank_score:S,source:"time-filtered"}}))}catch(y){W(`FilterRetriever: Failed to read file ${v.path}`,y)}}let m=new Map;for(let v of u)m.set(v.metadata.path,v);for(let v of f)m.has(v.metadata.path)||m.set(v.metadata.path,{...v,metadata:{...v.metadata,includeInContext:!0}});let h=this.options.returnAll?al:this.options.maxK,g=Array.from(m.values()).sort((v,y)=>{let w=v.metadata.score||0;return(y.metadata.score||0)-w}).slice(0,h);return Y().debug&&j("FilterRetriever: Time range search complete",{timeRange:this.options.timeRange,dailyNotesFound:l.length,timeFilteredDocs:f.length,totalResults:g.length}),g}resolveTagTerms(e){let n=new Set;for(let r of this.options.salientTerms??[])typeof r=="string"&&r.startsWith("#")&&n.add(r.toLowerCase());if(n.size===0)for(let r of this.extractTagsFromQuery(e))n.add(r);return Array.from(n)}extractTagsFromQuery(e){if(!e)return[];let n=null;try{n=e.match(/#[\p{L}\p{N}_/-]+/gu)}catch{n=e.match(/#[a-z0-9_/-]+/g)}if(!n)return[];let r=new Set;for(let o of n){let i=o.trim();i.length<=1||r.add(i.toLowerCase())}return Array.from(r)}generateDailyNoteDateRange(e,n){let r=[],o=new Date(e),i=new Date(n),s=365;Math.ceil((n-e)/(1e3*60*60*24))>s&&(W(`FilterRetriever: Date range exceeds ${s} days, limiting to recent ${s} days`),o.setTime(i.getTime()-s*24*60*60*1e3));let l=new Date(o);for(;l<=i;)r.push(`[[${l.toLocaleDateString("en-CA")}]]`),l.setDate(l.getDate()+1);return r}async getTitleMatches(e){let n=[];for(let r of e)if(!(mX(r)||ZH(r.path)))try{let o=await this.app.vault.cachedRead(r),i=this.app.metadataCache.getFileCache(r);n.push(new cu({pageContent:o,metadata:{path:r.path,title:r.basename,mtime:r.stat.mtime,ctime:r.stat.ctime,tags:i?.tags?.map(s=>s.tag)||[],includeInContext:!0,score:1,rerank_score:1,source:"title-match"}}))}catch(o){W(`FilterRetriever: Failed to read title-matched file ${r.path}`,o)}return n}async getTagMatches(e){if(e.length===0)return[];let{inclusions:n,exclusions:r}=Fi(),o=this.app.vault.getMarkdownFiles(),i=[],s=this.options.returnAll?al:this.options.maxK;for(let a of o){if(i.length>=s)break;if(!ii(this.app,a,n,r)||mX(a))continue;let l=this.app.metadataCache.getFileCache(a);if(!l)continue;let c=(0,j_n.getAllTags)(l)??[];if(!(c.length===0||!c.some(d=>{let f=d.toLowerCase();return e.some(p=>f===p||f.startsWith(p+"/"))})))try{let d=await this.app.vault.cachedRead(a);i.push(new cu({pageContent:d,metadata:{path:a.path,title:a.basename,mtime:a.stat.mtime,ctime:a.stat.ctime,tags:c,includeInContext:!0,score:1,rerank_score:1,source:"tag-match"}}))}catch(d){W(`FilterRetriever: Failed to read tag-matched file ${a.path}`,d)}}return i}combineGuaranteedMatches(...e){let n=new Set,r=[];for(let o of e)for(let i of o){let s=i.metadata.path;n.has(s)||(n.add(s),r.push(i))}return r}}});var z_n={};sr(z_n,{mergeFilterAndSearchResults:()=>zq});function zq(t,e){let n=new Set;for(let o of t)o.metadata?.path&&n.add(o.metadata.path);let r=e.filter(o=>{let i=o.metadata?.path;return!i||!n.has(i)});return{filterResults:t,searchResults:r}}var T0e=b(()=>{});var Ixn=wi((Jst,Xst)=>{(function(t,e){typeof Jst=="object"&&typeof Xst<"u"?Xst.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs_plugin_quarterOfYear=e()})(Jst,function(){"use strict";var t="month",e="quarter";return function(n,r){var o=r.prototype;o.quarter=function(a){return this.$utils().u(a)?Math.ceil((this.month()+1)/3):this.month(this.month()%3+3*(a-1))};var i=o.add;o.add=function(a,l){return a=Number(a),this.$utils().p(l)===e?this.add(3*a,t):i.bind(this)(a,l)};var s=o.startOf;o.startOf=function(a,l){var c=this.$utils(),u=!!c.u(l)||l;if(c.p(a)===e){var d=this.quarter()-1;return u?this.month(3*d).startOf(t).startOf("day"):this.month(3*d+2).endOf(t).endOf("day")}return s.bind(this)(a,l)}}})});var hO=wi((Qst,eat)=>{(function(t,e){typeof Qst=="object"&&typeof eat<"u"?eat.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs=e()})(Qst,function(){"use strict";var t=1e3,e=6e4,n=36e5,r="millisecond",o="second",i="minute",s="hour",a="day",l="week",c="month",u="quarter",d="year",f="date",p="Invalid Date",m=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,h=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,g={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(O){var $=["th","st","nd","rd"],U=O%100;return"["+O+($[(U-20)%10]||$[U]||$[0])+"]"}},v=function(O,$,U){var V=String(O);return!V||V.length>=$?O:""+Array($+1-V.length).join(U)+O},y={s:v,z:function(O){var $=-O.utcOffset(),U=Math.abs($),V=Math.floor(U/60),K=U%60;return($<=0?"+":"-")+v(V,2,"0")+":"+v(K,2,"0")},m:function O($,U){if($.date()<U.date())return-O(U,$);var V=12*(U.year()-$.year())+(U.month()-$.month()),K=$.clone().add(V,c),se=U-K<0,le=$.clone().add(V+(se?-1:1),c);return+(-(V+(U-K)/(se?K-le:le-K))||0)},a:function(O){return O<0?Math.ceil(O)||0:Math.floor(O)},p:function(O){return{M:c,y:d,w:l,d:a,D:f,h:s,m:i,s:o,ms:r,Q:u}[O]||String(O||"").toLowerCase().replace(/s$/,"")},u:function(O){return O===void 0}},w="en",_={};_[w]=g;var S="$isDayjsObject",I=function(O){return O instanceof P||!(!O||!O[S])},C=function O($,U,V){var K;if(!$)return w;if(typeof $=="string"){var se=$.toLowerCase();_[se]&&(K=se),U&&(_[se]=U,K=se);var le=$.split("-");if(!K&&le.length>1)return O(le[0])}else{var Q=$.name;_[Q]=$,K=Q}return!V&&K&&(w=K),K||!V&&w},k=function(O,$){if(I(O))return O.clone();var U=typeof $=="object"?$:{};return U.date=O,U.args=arguments,new P(U)},T=y;T.l=C,T.i=I,T.w=function(O,$){return k(O,{locale:$.$L,utc:$.$u,x:$.$x,$offset:$.$offset})};var P=function(){function O(U){this.$L=C(U.locale,null,!0),this.parse(U),this.$x=this.$x||U.x||{},this[S]=!0}var $=O.prototype;return $.parse=function(U){this.$d=function(V){var K=V.date,se=V.utc;if(K===null)return new Date(NaN);if(T.u(K))return new Date;if(K instanceof Date)return new Date(K);if(typeof K=="string"&&!/Z$/i.test(K)){var le=K.match(m);if(le){var Q=le[2]-1||0,ne=(le[7]||"0").substring(0,3);return se?new Date(Date.UTC(le[1],Q,le[3]||1,le[4]||0,le[5]||0,le[6]||0,ne)):new Date(le[1],Q,le[3]||1,le[4]||0,le[5]||0,le[6]||0,ne)}}return new Date(K)}(U),this.init()},$.init=function(){var U=this.$d;this.$y=U.getFullYear(),this.$M=U.getMonth(),this.$D=U.getDate(),this.$W=U.getDay(),this.$H=U.getHours(),this.$m=U.getMinutes(),this.$s=U.getSeconds(),this.$ms=U.getMilliseconds()},$.$utils=function(){return T},$.isValid=function(){return this.$d.toString()!==p},$.isSame=function(U,V){var K=k(U);return this.startOf(V)<=K&&K<=this.endOf(V)},$.isAfter=function(U,V){return k(U)<this.startOf(V)},$.isBefore=function(U,V){return this.endOf(V)<k(U)},$.$g=function(U,V,K){return T.u(U)?this[V]:this.set(K,U)},$.unix=function(){return Math.floor(this.valueOf()/1e3)},$.valueOf=function(){return this.$d.getTime()},$.startOf=function(U,V){var K=this,se=!!T.u(V)||V,le=T.p(U),Q=function(R,X){var D=T.w(K.$u?Date.UTC(K.$y,X,R):new Date(K.$y,X,R),K);return se?D:D.endOf(a)},ne=function(R,X){return T.w(K.toDate()[R].apply(K.toDate("s"),(se?[0,0,0,0]:[23,59,59,999]).slice(X)),K)},ee=this.$W,ae=this.$M,q=this.$D,F="set"+(this.$u?"UTC":"");switch(le){case d:return se?Q(1,0):Q(31,11);case c:return se?Q(1,ae):Q(0,ae+1);case l:var z=this.$locale().weekStart||0,N=(ee<z?ee+7:ee)-z;return Q(se?q-N:q+(6-N),ae);case a:case f:return ne(F+"Hours",0);case s:return ne(F+"Minutes",1);case i:return ne(F+"Seconds",2);case o:return ne(F+"Milliseconds",3);default:return this.clone()}},$.endOf=function(U){return this.startOf(U,!1)},$.$set=function(U,V){var K,se=T.p(U),le="set"+(this.$u?"UTC":""),Q=(K={},K[a]=le+"Date",K[f]=le+"Date",K[c]=le+"Month",K[d]=le+"FullYear",K[s]=le+"Hours",K[i]=le+"Minutes",K[o]=le+"Seconds",K[r]=le+"Milliseconds",K)[se],ne=se===a?this.$D+(V-this.$W):V;if(se===c||se===d){var ee=this.clone().set(f,1);ee.$d[Q](ne),ee.init(),this.$d=ee.set(f,Math.min(this.$D,ee.daysInMonth())).$d}else Q&&this.$d[Q](ne);return this.init(),this},$.set=function(U,V){return this.clone().$set(U,V)},$.get=function(U){return this[T.p(U)]()},$.add=function(U,V){var K,se=this;U=Number(U);var le=T.p(V),Q=function(ae){var q=k(se);return T.w(q.date(q.date()+Math.round(ae*U)),se)};if(le===c)return this.set(c,this.$M+U);if(le===d)return this.set(d,this.$y+U);if(le===a)return Q(1);if(le===l)return Q(7);var ne=(K={},K[i]=e,K[s]=n,K[o]=t,K)[le]||1,ee=this.$d.getTime()+U*ne;return T.w(ee,this)},$.subtract=function(U,V){return this.add(-1*U,V)},$.format=function(U){var V=this,K=this.$locale();if(!this.isValid())return K.invalidDate||p;var se=U||"YYYY-MM-DDTHH:mm:ssZ",le=T.z(this),Q=this.$H,ne=this.$m,ee=this.$M,ae=K.weekdays,q=K.months,F=K.meridiem,z=function(X,D,G,ce){return X&&(X[D]||X(V,se))||G[D].slice(0,ce)},N=function(X){return T.s(Q%12||12,X,"0")},R=F||function(X,D,G){var ce=X<12?"AM":"PM";return G?ce.toLowerCase():ce};return se.replace(h,function(X,D){return D||function(G){switch(G){case"YY":return String(V.$y).slice(-2);case"YYYY":return T.s(V.$y,4,"0");case"M":return ee+1;case"MM":return T.s(ee+1,2,"0");case"MMM":return z(K.monthsShort,ee,q,3);case"MMMM":return z(q,ee);case"D":return V.$D;case"DD":return T.s(V.$D,2,"0");case"d":return String(V.$W);case"dd":return z(K.weekdaysMin,V.$W,ae,2);case"ddd":return z(K.weekdaysShort,V.$W,ae,3);case"dddd":return ae[V.$W];case"H":return String(Q);case"HH":return T.s(Q,2,"0");case"h":return N(1);case"hh":return N(2);case"a":return R(Q,ne,!0);case"A":return R(Q,ne,!1);case"m":return String(ne);case"mm":return T.s(ne,2,"0");case"s":return String(V.$s);case"ss":return T.s(V.$s,2,"0");case"SSS":return T.s(V.$ms,3,"0");case"Z":return le}return null}(X)||le.replace(":","")})},$.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},$.diff=function(U,V,K){var se,le=this,Q=T.p(V),ne=k(U),ee=(ne.utcOffset()-this.utcOffset())*e,ae=this-ne,q=function(){return T.m(le,ne)};switch(Q){case d:se=q()/12;break;case c:se=q();break;case u:se=q()/3;break;case l:se=(ae-ee)/6048e5;break;case a:se=(ae-ee)/864e5;break;case s:se=ae/n;break;case i:se=ae/e;break;case o:se=ae/t;break;default:se=ae}return K?se:T.a(se)},$.daysInMonth=function(){return this.endOf(c).$D},$.$locale=function(){return _[this.$L]},$.locale=function(U,V){if(!U)return this.$L;var K=this.clone(),se=C(U,V,!0);return se&&(K.$L=se),K},$.clone=function(){return T.w(this.$d,this)},$.toDate=function(){return new Date(this.valueOf())},$.toJSON=function(){return this.isValid()?this.toISOString():null},$.toISOString=function(){return this.$d.toISOString()},$.toString=function(){return this.$d.toUTCString()},O}(),E=P.prototype;return k.prototype=E,[["$ms",r],["$s",o],["$m",i],["$H",s],["$W",a],["$M",c],["$y",d],["$D",f]].forEach(function(O){E[O[1]]=function($){return this.$g($,O[0],O[1])}}),k.extend=function(O,$){return O.$i||(O($,P,k),O.$i=!0),k},k.locale=C,k.isDayjs=I,k.unix=function(O){return k(1e3*O)},k.en=_[w],k.Ls=_,k.p={},k})});var G0,t5=b(()=>{Lu();G0=class extends Uo{constructor(e){super(e);M(this,"lc_serializable",!0);M(this,"lc_namespace",["langchain_core","prompts",this._getPromptType()]);M(this,"inputVariables");M(this,"outputParser");M(this,"partialVariables");M(this,"metadata");M(this,"tags");let{inputVariables:n}=e;if(n.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}get lc_attributes(){return{partialVariables:void 0}}async mergePartialAndUserVariables(e){let n=this.partialVariables??{},r={};for(let[o,i]of Object.entries(n))typeof i=="string"?r[o]=i:r[o]=await i();return{...r,...e}}async invoke(e,n){let r={...this.metadata,...n?.metadata},o=[...this.tags??[],...n?.tags??[]];return this._callWithConfig(i=>this.formatPromptValue(i),e,{...n,tags:o,metadata:r,runType:"prompt"})}}});var dF,eoe=b(()=>{uJ();t5();dF=class extends G0{async formatPromptValue(t){return new pge(await this.format(t))}}});function kat(t){return typeof t=="function"}function zjr(t){return r5(t)?"array":typeof t}function Cat(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function KSn(t,e){return t!=null&&typeof t=="object"&&e in t}function Hjr(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}function Vjr(t,e){return Wjr.call(t,e)}function Kjr(t){return!Vjr(qjr,t)}function Zjr(t){return String(t).replace(/[&<>"'`=\/]/g,function(n){return Gjr[n]})}function eBr(t,e){if(!t)return[];var n=!1,r=[],o=[],i=[],s=!1,a=!1,l="",c=0;function u(){if(s&&!a)for(;i.length;)delete o[i.pop()];else i=[];s=!1,a=!1}var d,f,p;function m(k){if(typeof k=="string"&&(k=k.split(Jjr,2)),!r5(k)||k.length!==2)throw new Error("Invalid tags: "+k);d=new RegExp(Cat(k[0])+"\\s*"),f=new RegExp("\\s*"+Cat(k[1])),p=new RegExp("\\s*"+Cat("}"+k[1]))}m(e||sw.tags);for(var h=new noe(t),g,v,y,w,_,S;!h.eos();){if(g=h.pos,y=h.scanUntil(d),y)for(var I=0,C=y.length;I<C;++I)w=y.charAt(I),Kjr(w)?(i.push(o.length),l+=w):(a=!0,n=!0,l+=" "),o.push(["text",w,g,g+1]),g+=1,w===`
`&&(u(),l="",c=0,n=!1);if(!h.scan(d))break;if(s=!0,v=h.scan(Qjr)||"name",h.scan(Yjr),v==="="?(y=h.scanUntil(GSn),h.scan(GSn),h.scanUntil(f)):v==="{"?(y=h.scanUntil(p),h.scan(Xjr),h.scanUntil(f),v="&"):y=h.scanUntil(f),!h.scan(f))throw new Error("Unclosed tag at "+h.pos);if(v==">"?_=[v,y,g,h.pos,l,c,n]:_=[v,y,g,h.pos],c++,o.push(_),v==="#"||v==="^")r.push(_);else if(v==="/"){if(S=r.pop(),!S)throw new Error('Unopened section "'+y+'" at '+g);if(S[1]!==y)throw new Error('Unclosed section "'+S[1]+'" at '+g)}else v==="name"||v==="{"||v==="&"?a=!0:v==="="&&m(y)}if(u(),S=r.pop(),S)throw new Error('Unclosed section "'+S[1]+'" at '+h.pos);return nBr(tBr(o))}function tBr(t){for(var e=[],n,r,o=0,i=t.length;o<i;++o)n=t[o],n&&(n[0]==="text"&&r&&r[0]==="text"?(r[1]+=n[1],r[3]=n[3]):(e.push(n),r=n));return e}function nBr(t){for(var e=[],n=e,r=[],o,i,s=0,a=t.length;s<a;++s)switch(o=t[s],o[0]){case"#":case"^":n.push(o),r.push(o),n=o[4]=[];break;case"/":i=r.pop(),i[5]=o[2],n=r.length>0?r[r.length-1][4]:e;break;default:n.push(o)}return e}function noe(t){this.string=t,this.tail=t,this.pos=0}function n5(t,e){this.view=t,this.cache={".":this.view},this.parent=e}function qp(){this.templateCache={_cache:{},set:function(e,n){this._cache[e]=n},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}var Bjr,r5,Wjr,qjr,Gjr,Yjr,Jjr,GSn,Xjr,Qjr,sw,toe,Iat,ZSn=b(()=>{Bjr=Object.prototype.toString,r5=Array.isArray||function(e){return Bjr.call(e)==="[object Array]"};Wjr=RegExp.prototype.test;qjr=/\S/;Gjr={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};Yjr=/\s*/,Jjr=/\s+/,GSn=/\s*=/,Xjr=/\s*\}/,Qjr=/#|\^|\/|>|\{|&|=|!/;noe.prototype.eos=function(){return this.tail===""};noe.prototype.scan=function(e){var n=this.tail.match(e);if(!n||n.index!==0)return"";var r=n[0];return this.tail=this.tail.substring(r.length),this.pos+=r.length,r};noe.prototype.scanUntil=function(e){var n=this.tail.search(e),r;switch(n){case-1:r=this.tail,this.tail="";break;case 0:r="";break;default:r=this.tail.substring(0,n),this.tail=this.tail.substring(n)}return this.pos+=r.length,r};n5.prototype.push=function(e){return new n5(e,this)};n5.prototype.lookup=function(e){var n=this.cache,r;if(n.hasOwnProperty(e))r=n[e];else{for(var o=this,i,s,a,l=!1;o;){if(e.indexOf(".")>0)for(i=o.view,s=e.split("."),a=0;i!=null&&a<s.length;)a===s.length-1&&(l=KSn(i,s[a])||Hjr(i,s[a])),i=i[s[a++]];else i=o.view[e],l=KSn(o.view,e);if(l){r=i;break}o=o.parent}n[e]=r}return kat(r)&&(r=r.call(this.view)),r};qp.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};qp.prototype.parse=function(e,n){var r=this.templateCache,o=e+":"+(n||sw.tags).join(":"),i=typeof r<"u",s=i?r.get(o):void 0;return s==null&&(s=eBr(e,n),i&&r.set(o,s)),s};qp.prototype.render=function(e,n,r,o){var i=this.getConfigTags(o),s=this.parse(e,i),a=n instanceof n5?n:new n5(n,void 0);return this.renderTokens(s,a,r,e,o)};qp.prototype.renderTokens=function(e,n,r,o,i){for(var s="",a,l,c,u=0,d=e.length;u<d;++u)c=void 0,a=e[u],l=a[0],l==="#"?c=this.renderSection(a,n,r,o,i):l==="^"?c=this.renderInverted(a,n,r,o,i):l===">"?c=this.renderPartial(a,n,r,i):l==="&"?c=this.unescapedValue(a,n):l==="name"?c=this.escapedValue(a,n,i):l==="text"&&(c=this.rawValue(a)),c!==void 0&&(s+=c);return s};qp.prototype.renderSection=function(e,n,r,o,i){var s=this,a="",l=n.lookup(e[1]);function c(f){return s.render(f,n,r,i)}if(l){if(r5(l))for(var u=0,d=l.length;u<d;++u)a+=this.renderTokens(e[4],n.push(l[u]),r,o,i);else if(typeof l=="object"||typeof l=="string"||typeof l=="number")a+=this.renderTokens(e[4],n.push(l),r,o,i);else if(kat(l)){if(typeof o!="string")throw new Error("Cannot use higher-order sections without the original template");l=l.call(n.view,o.slice(e[3],e[5]),c),l!=null&&(a+=l)}else a+=this.renderTokens(e[4],n,r,o,i);return a}};qp.prototype.renderInverted=function(e,n,r,o,i){var s=n.lookup(e[1]);if(!s||r5(s)&&s.length===0)return this.renderTokens(e[4],n,r,o,i)};qp.prototype.indentPartial=function(e,n,r){for(var o=n.replace(/[^ \t]/g,""),i=e.split(`
`),s=0;s<i.length;s++)i[s].length&&(s>0||!r)&&(i[s]=o+i[s]);return i.join(`
`)};qp.prototype.renderPartial=function(e,n,r,o){if(r){var i=this.getConfigTags(o),s=kat(r)?r(e[1]):r[e[1]];if(s!=null){var a=e[6],l=e[5],c=e[4],u=s;l==0&&c&&(u=this.indentPartial(s,c,a));var d=this.parse(u,i);return this.renderTokens(d,n,r,u,o)}}};qp.prototype.unescapedValue=function(e,n){var r=n.lookup(e[1]);if(r!=null)return r};qp.prototype.escapedValue=function(e,n,r){var o=this.getConfigEscape(r)||sw.escape,i=n.lookup(e[1]);if(i!=null)return typeof i=="number"&&o===sw.escape?String(i):o(i)};qp.prototype.rawValue=function(e){return e[1]};qp.prototype.getConfigTags=function(e){return r5(e)?e:e&&typeof e=="object"?e.tags:void 0};qp.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!r5(e))return e.escape};sw={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(t){toe.templateCache=t},get templateCache(){return toe.templateCache}},toe=new qp;sw.clearCache=function(){return toe.clearCache()};sw.parse=function(e,n){return toe.parse(e,n)};sw.render=function(e,n,r,o){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+zjr(e)+'" was given as the first argument for mustache#render(template, view, partials)');return toe.render(e,n,r,o)};sw.escape=Zjr;sw.Scanner=noe;sw.Context=n5;sw.Writer=qp;Iat=sw});var rBr,o5,YSn,roe,JSn,XSn,Y0e,QSn,Yg,i5,s5,fF=b(()=>{Kk();ZSn();rBr={escape:t=>t},o5=t=>{let e=t.split(""),n=[],r=(i,s)=>{for(let a=s;a<e.length;a+=1)if(i.includes(e[a]))return a;return-1},o=0;for(;o<e.length;)if(e[o]==="{"&&o+1<e.length&&e[o+1]==="{")n.push({type:"literal",text:"{"}),o+=2;else if(e[o]==="}"&&o+1<e.length&&e[o+1]==="}")n.push({type:"literal",text:"}"}),o+=2;else if(e[o]==="{"){let i=r("}",o);if(i<0)throw new Error("Unclosed '{' in template.");n.push({type:"variable",name:e.slice(o+1,i).join("")}),o=i+1}else{if(e[o]==="}")throw new Error("Single '}' in template.");{let i=r("{}",o),s=(i<0?e.slice(o):e.slice(o,i)).join("");n.push({type:"literal",text:s}),o=i<0?e.length:i}}return n},YSn=(t,e=[])=>{let n=[];for(let r of t)if(r[0]==="name"){let o=r[1].includes(".")?r[1].split(".")[0]:r[1];n.push({type:"variable",name:o})}else if(["#","&","^",">"].includes(r[0])){if(n.push({type:"variable",name:r[1]}),r[0]==="#"&&r.length>4&&Array.isArray(r[4])){let o=[...e,r[1]],i=YSn(r[4],o);n.push(...i)}}else n.push({type:"literal",text:r[1]});return n},roe=t=>{let e=Iat.parse(t);return YSn(e)},JSn=(t,e)=>o5(t).reduce((n,r)=>{if(r.type==="variable"){if(r.name in e)return n+(typeof e[r.name]=="string"?e[r.name]:JSON.stringify(e[r.name]));throw new Error(`(f-string) Missing value for input ${r.name}`)}return n+r.text},""),XSn=(t,e)=>Iat.render(t,e,void 0,rBr),Y0e={"f-string":JSn,mustache:XSn},QSn={"f-string":o5,mustache:roe},Yg=(t,e,n)=>{try{return Y0e[e](t,n)}catch(r){throw fA(r,"INVALID_PROMPT_INPUT")}},i5=(t,e)=>QSn[e](t),s5=(t,e,n)=>{if(!(e in Y0e)){let r=Object.keys(Y0e);throw new Error(`Invalid template format. Got \`${e}\`;
should be one of ${r}`)}try{let r=Object.fromEntries(n.map(o=>[o,"foo"]));Array.isArray(t)?t.forEach(o=>{if(o.type==="text"&&"text"in o&&typeof o.text=="string")Yg(o.text,e,r);else if(o.type==="image_url"){if(typeof o.image_url=="string")Yg(o.image_url,e,r);else if(typeof o.image_url=="object"&&o.image_url!==null&&"url"in o.image_url&&typeof o.image_url.url=="string"){let i=o.image_url.url;Yg(i,e,r)}}else throw new Error(`Invalid message template received. ${JSON.stringify(o,null,2)}`)}):Yg(t,e,r)}catch(r){throw new Error(`Invalid prompt schema: ${r.message}`)}}});var dC,J0e=b(()=>{eoe();fF();dC=class ooe extends dF{constructor(n){super(n);M(this,"template");M(this,"templateFormat","f-string");M(this,"validateTemplate",!0);M(this,"additionalContentFields");if(n.templateFormat==="mustache"&&n.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,n),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),s5(this.template,this.templateFormat,r)}}static lc_name(){return"PromptTemplate"}_getPromptType(){return"prompt"}async format(n){let r=await this.mergePartialAndUserVariables(n);return Yg(this.template,this.templateFormat,r)}static fromExamples(n,r,o,i=`
`,s=""){let a=[s,...n,r].join(i);return new ooe({inputVariables:o,template:a})}static fromTemplate(n,r){let{templateFormat:o="f-string",...i}=r??{},s=new Set;return i5(n,o).forEach(a=>{a.type==="variable"&&s.add(a.name)}),new ooe({inputVariables:[...s],templateFormat:o,template:n,...i})}async partial(n){let r=this.inputVariables.filter(s=>!(s in n)),o={...this.partialVariables??{},...n},i={...this,inputVariables:r,partialVariables:o};return new ooe(i)}serialize(){if(this.outputParser!==void 0)throw new Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(n){if(!n.template)throw new Error("Prompt template must have a template");return new ooe({inputVariables:n.input_variables,template:n.template,templateFormat:n.template_format})}}});var ioe,Tat=b(()=>{uJ();t5();fF();ioe=class eCn extends G0{constructor(n){super(n);M(this,"lc_namespace",["langchain_core","prompts","image"]);M(this,"template");M(this,"templateFormat","f-string");M(this,"validateTemplate",!0);M(this,"additionalContentFields");if(this.template=n.template,this.templateFormat=n.templateFormat??this.templateFormat,this.validateTemplate=n.validateTemplate??this.validateTemplate,this.additionalContentFields=n.additionalContentFields,this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),s5([{type:"image_url",image_url:this.template}],this.templateFormat,r)}}static lc_name(){return"ImagePromptTemplate"}_getPromptType(){return"prompt"}async partial(n){let r=this.inputVariables.filter(s=>!(s in n)),o={...this.partialVariables??{},...n},i={...this,inputVariables:r,partialVariables:o};return new eCn(i)}async format(n){let r={};for(let[a,l]of Object.entries(this.template))typeof l=="string"?r[a]=Yg(l,this.templateFormat,n):r[a]=l;let o=n.url||r.url,i=n.detail||r.detail;if(!o)throw new Error("Must provide either an image URL.");if(typeof o!="string")throw new Error("url must be a string.");let s={url:o};return i&&(s.detail=i),s}async formatPromptValue(n){return new k6t(await this.format(n))}}});function Pat(t,e){let n=[];for(let r of Object.values(t))if(typeof r=="string")i5(r,e).forEach(o=>{o.type==="variable"&&n.push(o.name)});else if(Array.isArray(r))for(let o of r)typeof o=="string"?i5(o,e).forEach(i=>{i.type==="variable"&&n.push(i.name)}):typeof o=="object"&&n.push(...Pat(o,e));else typeof r=="object"&&r!==null&&n.push(...Pat(r,e));return Array.from(new Set(n))}function Aat(t,e,n){let r={};for(let[o,i]of Object.entries(t))if(typeof i=="string")r[o]=Yg(i,n,e);else if(Array.isArray(i)){let s=[];for(let a of i)typeof a=="string"?s.push(Yg(a,n,e)):typeof a=="object"&&s.push(Aat(a,e,n));r[o]=s}else typeof i=="object"&&i!==null?r[o]=Aat(i,e,n):r[o]=i;return r}var X0e,Eat=b(()=>{Lu();fF();X0e=class extends Uo{constructor(e){let n=e.templateFormat??"f-string",r=Pat(e.template,n);super({inputVariables:r,...e});M(this,"lc_namespace",["langchain_core","prompts","dict"]);M(this,"lc_serializable",!0);M(this,"template");M(this,"templateFormat");M(this,"inputVariables");this.template=e.template,this.templateFormat=n,this.inputVariables=r}static lc_name(){return"DictPromptTemplate"}async format(e){return Aat(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}}});function oBr(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function iBr(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:"image_url"in t&&(typeof t.image_url=="string"||typeof t.image_url=="object"&&t.image_url!==null&&"url"in t.image_url&&typeof t.image_url.url=="string")}function sBr(t){return typeof t.formatMessages=="function"}function aBr(t,e){if(sBr(t)||lv(t))return t;if(Array.isArray(t)&&t[0]==="placeholder"){let o=t[1];if(e?.templateFormat==="mustache"&&typeof o=="string"&&o.slice(0,2)==="{{"&&o.slice(-2)==="}}")return new Z0({variableName:o.slice(2,-2),optional:!0});if(typeof o=="string"&&o[0]==="{"&&o[o.length-1]==="}")return new Z0({variableName:o.slice(1,-1),optional:!0});throw new Error(`Invalid placeholder template for format ${e?.templateFormat??'"f-string"'}: "${t[1]}". Expected a variable name surrounded by ${e?.templateFormat==="mustache"?"double":"single"} curly braces.`)}let n=hb(t),r;if(typeof n.content=="string"?r=n.content:r=n.content.map(o=>"text"in o?{...o,text:o.text}:"image_url"in o?{...o,image_url:o.image_url}:o),n._getType()==="human")return Y0.fromTemplate(r,e);if(n._getType()==="ai")return rCn.fromTemplate(r,e);if(n._getType()==="system")return pF.fromTemplate(r,e);if(yf.isInstance(n))return nCn.fromTemplate(n.content,n.role,e);throw new Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function lBr(t){return t.constructor.lc_name()==="MessagesPlaceholder"}var eTe,Z0,tCn,Mat,nCn,Oat,Y0,rCn,pF,A_,soe=b(()=>{Kk();gf();Om();PY();yA();AY();gb();Lu();oi();uJ();t5();eoe();fF();J0e();Tat();Eat();eTe=class extends Uo{constructor(){super(...arguments);M(this,"lc_namespace",["langchain_core","prompts","chat"]);M(this,"lc_serializable",!0)}async invoke(e,n){return this._callWithConfig(r=>this.formatMessages(r),e,{...n,runType:"prompt"})}},Z0=class extends eTe{constructor(e){typeof e=="string"&&(e={variableName:e});super(e);M(this,"variableName");M(this,"optional");this.variableName=e.variableName,this.optional=e.optional??!1}static lc_name(){return"MessagesPlaceholder"}get inputVariables(){return[this.variableName]}async formatMessages(e){let n=e[this.variableName];if(this.optional&&!n)return[];if(!n){let o=new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw o.name="InputFormatError",o}let r;try{Array.isArray(n)?r=n.map(hb):r=[hb(n)]}catch(o){let i=typeof n=="string"?n:JSON.stringify(n,null,2),s=new Error([`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,`Received value: ${i}`,`Additional message: ${o.message}`].join(`
`));throw s.name="InputFormatError",s.lc_error_code=o.lc_error_code,s}return r}},tCn=class extends eTe{constructor(e){"prompt"in e||(e={prompt:e});super(e);M(this,"prompt");this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},Mat=class extends G0{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){return new mge(await this.formatMessages(t))}},nCn=class extends tCn{constructor(e,n){"prompt"in e||(e={prompt:e,role:n});super(e);M(this,"role");this.role=e.role}static lc_name(){return"ChatMessagePromptTemplate"}async format(e){return new yf(await this.prompt.format(e),this.role)}static fromTemplate(e,n,r){return new this(dC.fromTemplate(e,{templateFormat:r?.templateFormat}),n)}};Oat=class extends eTe{constructor(e,n){"prompt"in e||(e={prompt:e});super(e);M(this,"lc_namespace",["langchain_core","prompts","chat"]);M(this,"lc_serializable",!0);M(this,"inputVariables",[]);M(this,"additionalOptions",{});M(this,"prompt");M(this,"messageClass");M(this,"chatMessageClass");if(this.prompt=e.prompt,Array.isArray(this.prompt)){let r=[];this.prompt.forEach(o=>{"inputVariables"in o&&(r=r.concat(o.inputVariables))}),this.inputVariables=r}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=n??this.additionalOptions}static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}createMessage(e){let n=this.constructor;if(n._messageClass())return new(n._messageClass())({content:e});if(n.chatMessageClass){let r=n.chatMessageClass();return new r({content:e,role:this.getRoleFromMessageClass(r.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(e){switch(e){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(e,n){if(typeof e=="string")return new this(dC.fromTemplate(e,n));let r=[];for(let o of e)if(typeof o=="string")r.push(dC.fromTemplate(o,n));else if(o!==null)if(oBr(o)){let i="";typeof o.text=="string"&&(i=o.text??"");let s={...n,additionalContentFields:o};r.push(dC.fromTemplate(i,s))}else if(iBr(o)){let i=o.image_url??"",s,a=[];if(typeof i=="string"){let l;n?.templateFormat==="mustache"?l=roe(i):l=o5(i);let c=l.flatMap(u=>u.type==="variable"?[u.name]:[]);if((c?.length??0)>0){if(c.length>1)throw new Error(`Only one format variable allowed per image template.
Got: ${c}
From: ${i}`);a=[c[0]]}else a=[];i={url:i},s=new ioe({template:i,inputVariables:a,templateFormat:n?.templateFormat,additionalContentFields:o})}else if(typeof i=="object"){if("url"in i){let l;n?.templateFormat==="mustache"?l=roe(i.url):l=o5(i.url),a=l.flatMap(c=>c.type==="variable"?[c.name]:[])}else a=[];s=new ioe({template:i,inputVariables:a,templateFormat:n?.templateFormat,additionalContentFields:o})}else throw new Error("Invalid image template");r.push(s)}else typeof o=="object"&&r.push(new X0e({template:o,templateFormat:n?.templateFormat}));return new this({prompt:r,additionalOptions:n})}async format(e){if(this.prompt instanceof dF){let n=await this.prompt.format(e);return this.createMessage(n)}else{let n=[];for(let r of this.prompt){let o={};if(!("inputVariables"in r))throw new Error(`Prompt ${r} does not have inputVariables defined.`);for(let i of r.inputVariables)o||(o={[i]:e[i]}),o={...o,[i]:e[i]};if(r instanceof dF){let i=await r.format(o),s;"additionalContentFields"in r&&(s=r.additionalContentFields),i!==""&&n.push({...s,type:"text",text:i})}else if(r instanceof ioe){let i=await r.format(o),s;"additionalContentFields"in r&&(s=r.additionalContentFields),n.push({...s,type:"image_url",image_url:i})}else if(r instanceof X0e){let i=await r.format(o),s;"additionalContentFields"in r&&(s=r.additionalContentFields),n.push({...s,...i})}}return this.createMessage(n)}}async formatMessages(e){return[await this.format(e)]}},Y0=class extends Oat{static _messageClass(){return na}static lc_name(){return"HumanMessagePromptTemplate"}},rCn=class extends Oat{static _messageClass(){return cr}static lc_name(){return"AIMessagePromptTemplate"}},pF=class extends Oat{static _messageClass(){return sg}static lc_name(){return"SystemMessagePromptTemplate"}};A_=class Q0e extends Mat{constructor(n){super(n);M(this,"promptMessages");M(this,"validateTemplate",!0);M(this,"templateFormat","f-string");if(n.templateFormat==="mustache"&&n.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,n),this.validateTemplate){let r=new Set;for(let l of this.promptMessages)if(!(l instanceof bl))for(let c of l.inputVariables)r.add(c);let o=this.inputVariables,i=new Set(this.partialVariables?o.concat(Object.keys(this.partialVariables)):o),s=new Set([...i].filter(l=>!r.has(l)));if(s.size>0)throw new Error(`Input variables \`${[...s]}\` are not used in any of the prompt messages.`);let a=new Set([...r].filter(l=>!i.has(l)));if(a.size>0)throw new Error(`Input variables \`${[...a]}\` are used in prompt messages but not in the prompt template.`)}}static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}_getPromptType(){return"chat"}async _parseImagePrompts(n,r){return typeof n.content=="string"||(n.content=await Promise.all(n.content.map(async o=>{if(o.type!=="image_url")return o;let i="";typeof o.image_url=="string"?i=o.image_url:typeof o.image_url=="object"&&o.image_url!==null&&"url"in o.image_url&&typeof o.image_url.url=="string"&&(i=o.image_url.url);let s=await dC.fromTemplate(i,{templateFormat:this.templateFormat}).format(r);return typeof o.image_url=="object"&&o.image_url!==null&&"url"in o.image_url?o.image_url.url=s:o.image_url=s,o}))),n}async formatMessages(n){let r=await this.mergePartialAndUserVariables(n),o=[];for(let i of this.promptMessages)if(i instanceof bl)o.push(await this._parseImagePrompts(i,r));else{let s;this.templateFormat==="mustache"?s={...r}:s=i.inputVariables.reduce((l,c)=>{if(!(c in r)&&!(lBr(i)&&i.optional))throw fA(new Error(`Missing value for input variable \`${c.toString()}\``),"INVALID_PROMPT_INPUT");return l[c]=r[c],l},{});let a=await i.formatMessages(s);o=o.concat(a)}return o}async partial(n){let r=this.inputVariables.filter(s=>!(s in n)),o={...this.partialVariables??{},...n},i={...this,inputVariables:r,partialVariables:o};return new Q0e(i)}static fromTemplate(n,r){let o=new Y0({prompt:dC.fromTemplate(n,r)});return this.fromMessages([o])}static fromMessages(n,r){let o=n.reduce((a,l)=>a.concat(l instanceof Q0e?l.promptMessages:[aBr(l,r)]),[]),i=n.reduce((a,l)=>l instanceof Q0e?Object.assign(a,l.partialVariables):a,Object.create(null)),s=new Set;for(let a of o)if(!(a instanceof bl))for(let l of a.inputVariables)l in i||s.add(l);return new this({...r,inputVariables:[...s],promptMessages:o,partialVariables:i,templateFormat:r?.templateFormat})}}});var oCn=b(()=>{eoe();fF();J0e();soe()});var iCn=b(()=>{t5();soe()});var sCn=b(()=>{Lu();soe()});var a5=b(()=>{br();t5();eoe();fF();J0e();Tat();Eat();soe();oCn();iCn();sCn()});var uCn=b(()=>{LA();lg();Sd();EA()});var dCn=b(()=>{a4()});var $at=b(()=>{uCn();dCn();a5();LA();lg()});function lTe(){let t=Ar(ZN("chat"),{store:on}),e=(0,aTe.useMemo)(()=>{let r=[];for(let o of t)o.state==="ok"&&r.push({label:o.configuredModel.info.displayName||o.configuredModel.info.id,value:o.configuredModelId});return r},[t]),n=(0,aTe.useCallback)(r=>Q9(t,r),[t]);return{options:e,resolveSelectionId:n}}var aTe,Uat=b(()=>{mp();Se();Us();aTe=L(B())});var dkn={};sr(dkn,{ContextCompactor:()=>ilt});var ilt,fkn=b(()=>{pe();jq();oi();ilt=class t{constructor(){this.MIN_ITEM_SIZE=5e4;this.MAX_CONCURRENCY=3;this.TEMPERATURE=.1;this.MAX_ITEM_SIZE=5e5;this.BLOCK_TYPES=["note_context","active_note","url_content","selected_text","embedded_note","embedded_pdf","web_tab_context","active_web_tab","youtube_video_context"];this.PROMPT=`Summarize the following content, preserving:
- Key concepts and main ideas
- Important facts, names, and dates
- Technical details relevant for Q&A
Keep the summary concise but information-dense. Output only the summary.
Title: {title}
Path: {path}
Content:
{content}
Summary:`;this.URL_BASED_TYPES=["url_content","web_tab_context","active_web_tab","youtube_video_context"];this.chatModelManager=nw.getInstance()}static getInstance(){return t.instance||(t.instance=new t),t.instance}async compact(e){let n=e.length;j(`[ContextCompactor] Starting compaction of ${n} chars`);let r=this.parseItems(e);if(r.length===0)return this.noOpResult(e);let o=await this.summarizeItems(r);if(o.size===0)return this.noOpResult(e);let i=this.rebuild(e,r,o);return j(`[ContextCompactor] Done: ${n} -> ${i.length} chars (${((1-i.length/n)*100).toFixed(0)}% reduction)`),{content:i,wasCompacted:!0,originalCharCount:n,compactedCharCount:i.length,itemsProcessed:r.length,itemsSummarized:o.size}}noOpResult(e){return{content:e,wasCompacted:!1,originalCharCount:e.length,compactedCharCount:e.length,itemsProcessed:0,itemsSummarized:0}}parseItems(e){let n=[];for(let r of this.BLOCK_TYPES){let o=new RegExp(`<${r}>[\\s\\S]*?<\\/${r}>`,"g"),i;for(;(i=o.exec(e))!==null;){let s=this.parseBlock(i[0],r,i.index);s&&n.push(s)}}return n.sort((r,o)=>r.startIndex-o.startIndex),n.filter((r,o)=>!n.some((i,s)=>o!==s&&i.startIndex<=r.startIndex&&i.endIndex>=r.endIndex))}parseBlock(e,n,r){let o=c=>new RegExp(`<${c}>([^<]*)</${c}>`).exec(e)?.[1]||"",i=()=>/<content>([\s\S]*?)<\/content>/.exec(e)?.[1]||"",s=o("path")||o("url"),a=o("title")||s.split("/").pop()||"Untitled",l=i();return{type:n,path:s,title:a,content:l,metadata:{ctime:o("ctime"),mtime:o("mtime")},originalXml:e,startIndex:r,endIndex:r+e.length}}async summarizeItems(e){let n=new Map,r=e.map((o,i)=>({index:i,item:o})).filter(({item:o})=>o.content.length>=this.MIN_ITEM_SIZE);if(r.length===0)return n;j(`[ContextCompactor] Summarizing ${r.length} items`);for(let o=0;o<r.length;o+=this.MAX_CONCURRENCY){let i=r.slice(o,o+this.MAX_CONCURRENCY);(await Promise.all(i.map(async({index:a,item:l})=>{try{return{index:a,summary:await this.summarize(l)}}catch(c){return j(`[ContextCompactor] Failed to summarize item ${a}:`,c),{index:a,summary:null}}}))).forEach(({index:a,summary:l})=>{l&&n.set(a,l)})}return n.size<r.length*.5?(j("[ContextCompactor] High failure rate, aborting compaction"),new Map):n}async summarize(e){let n=e.content;n.length>this.MAX_ITEM_SIZE&&(n=n.slice(0,this.MAX_ITEM_SIZE)+`
[TRUNCATED]`);let r=this.PROMPT.replace("{title}",e.title).replace("{path}",e.path).replace("{content}",n),i=await(await this.chatModelManager.getChatModelWithTemperature(this.TEMPERATURE)).invoke([new na(r)]);return typeof i.content=="string"?i.content.trim():""}rebuild(e,n,r){let o=e;return Array.from(r.keys()).sort((i,s)=>s-i).forEach(i=>{let s=n[i],a=r.get(i),l=this.buildBlock(s,a);o=o.slice(0,s.startIndex)+l+o.slice(s.endIndex)}),o}buildBlock(e,n){let r=[`<${e.type}>`];if(e.title&&r.push(`<title>${e.title}</title>`),e.path){let o=this.URL_BASED_TYPES.includes(e.type)?"url":"path";r.push(`<${o}>${e.path}</${o}>`)}return e.metadata.ctime&&r.push(`<ctime>${e.metadata.ctime}</ctime>`),e.metadata.mtime&&r.push(`<mtime>${e.metadata.mtime}</mtime>`),r.push(`<content>[SUMMARIZED]
${n}</content>`),r.push(`</${e.type}>`),r.join(`
`)}}});var woe,qTe,boe,ult=b(()=>{woe=L(B());De();qTe=({tab:t,isSelected:e,onClick:n,isFirst:r,isLast:o,variant:i="page"})=>woe.default.createElement("div",{role:"tab",id:`tab-${t.id}`,"aria-controls":`tabpanel-${t.id}`,"aria-selected":e,tabIndex:0,onClick:n,onKeyDown:s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())},className:J("tw-flex tw-flex-row tw-items-center","tw-h-8","tw-px-2 tw-py-1","tw-gap-1.5","tw-cursor-pointer","tw-overflow-hidden","tw-whitespace-nowrap","tw-text-sm","tw-border tw-border-solid tw-border-border",i==="page"?"tw-rounded-b-[2px] tw-rounded-t-sm":"tw-rounded-md","tw-bg-primary","tw-transition-all tw-duration-300 tw-ease-in-out","hover:tw-border-interactive-accent","focus-visible:tw-outline-none focus-visible:tw-ring-1 focus-visible:tw-ring-ring",e&&["!tw-bg-interactive-accent","tw-text-on-accent","!tw-max-w-full","tw-transition-all tw-duration-300 tw-ease-in-out","tw-delay-100"],e&&i==="inline"&&"!tw-border-interactive-accent","lg:tw-max-w-32","md:tw-max-w-32")},woe.default.createElement("div",{className:J("tw-flex tw-items-center tw-justify-center","tw-size-4","tw-transition-transform tw-duration-200 tw-ease-in-out",e?"tw-max-w-[16px] tw-translate-x-0 tw-opacity-100":"tw-max-w-0 tw--translate-x-4 tw-opacity-0")},t.icon),woe.default.createElement("span",{className:J("tw-text-sm","tw-font-medium","tw-transition-all tw-duration-200 tw-ease-in-out","tw-overflow-hidden tw-whitespace-nowrap","tw-max-w-[100px] tw-translate-x-0 tw-opacity-100")},t.label)),boe=({id:t,children:e,isSelected:n,variant:r="page"})=>n?woe.default.createElement("div",{role:"tabpanel",id:`tabpanel-${t}`,"aria-labelledby":`tab-${t}`,className:J(r==="page"?"tw-mt-4 tw-rounded-lg tw-bg-secondary tw-p-4":"tw-mt-3","tw-transition-all tw-duration-200 tw-ease-in-out",n?"tw-translate-y-0 tw-opacity-100":"tw-translate-y-2 tw-opacity-0")},e):null});var T5,Rkn,Lkn,P5,_oe=b(()=>{T5=L(B()),Rkn=(0,T5.createContext)(void 0),Lkn=({plugin:t,children:e})=>T5.default.createElement(Rkn.Provider,{value:t},e),P5=()=>{let t=(0,T5.useContext)(Rkn);if(!t)throw new Error("usePlugin must be used inside <PluginProvider>");return t}});function yu({label:t,description:e,children:n,className:r,gated:o=!1,gateNotice:i}){let s=(0,mh.useRef)(null);return(0,mh.useEffect)(()=>{let a=s.current;a&&(o?a.setAttribute("inert",""):a.removeAttribute("inert"))},[o]),mh.default.createElement("div",{className:J("tw-space-y-2",r)},(t||e)&&mh.default.createElement("div",{className:"tw-space-y-1"},t&&mh.default.createElement("div",{className:"tw-text-xs tw-font-semibold tw-text-muted"},t),e&&mh.default.createElement("div",{className:"tw-text-sm tw-text-muted"},e)),o&&i&&mh.default.createElement("div",{className:"tw-flex tw-items-start tw-gap-2 tw-rounded-lg tw-border tw-border-solid tw-px-3 tw-py-2.5 tw-text-xs tw-text-warning tw-bg-warning/10 tw-border-warning/30"},mh.default.createElement(Wr,{className:"tw-mt-0.5 tw-size-4 tw-shrink-0"}),mh.default.createElement("div",null,i)),mh.default.createElement("div",{ref:s,className:J("tw-overflow-hidden tw-rounded-xl tw-border tw-border-solid tw-border-border tw-bg-primary tw-shadow-sm",o&&"tw-opacity-45")},mh.default.createElement("div",{className:"tw-divide-y tw-divide-border [&>*]:tw-px-4"},n)))}var mh,LF=b(()=>{mh=L(B());De();Re()});function JIn(t,e,n,r,o,i){let s=[],a=[];for(let l of t){let c=e[l.providerId];if(!c)continue;let u={configuredModel:l,provider:c,enabled:n.has(l.configuredModelId)},d=c.origin;if(d.kind==="agent"){d.agentType===r&&a.push(u);continue}if(o&&(d.kind==="byok"||d.kind==="copilot-plus")){if(i&&!i(c))continue;s.push(u)}}return{byokPlusCandidates:s,agentOriginCandidates:a}}function XIn(t,e,n){let r=[];for(let o of t){if(o.info.isEmbedding)continue;let i=e[o.providerId];i&&i.origin.kind!=="agent"&&r.push({configuredModel:o,provider:i,enabled:n.has(o.configuredModelId)})}return{byokPlusCandidates:r,agentOriginCandidates:[]}}function iHr(t,e){let n=t.info.id.indexOf("/");return n>0?t.info.id.slice(0,n):e.displayName}function YIn(t){let{configuredModel:e,enabled:n}=t,{displayName:r,id:o,description:i}=e.info;return{id:e.configuredModelId,label:r||o,description:i||void 0,wireId:o,enabled:n,isFree:kQ(o),capabilities:Uw(e.info)}}function Nlt(t,e){return e?t.label.toLowerCase().includes(e)||t.id.toLowerCase().includes(e)||(t.wireId?.toLowerCase().includes(e)??!1)||(t.description?.toLowerCase().includes(e)??!1):!0}function sHr(t){switch(t){case"byok":return"BYOK";case"copilot-plus":return"Copilot";case"agent":return"Agent Provided"}}function vPe(t,e,n,r){let o=n.trim().toLowerCase(),i=[],s=new Map;for(let c of t.byokPlusCandidates){let u=YIn(c);if(!Nlt(u,o))continue;let d=c.provider.providerId,f=s.get(d);f?f.rows.push(u):s.set(d,{label:c.provider.displayName,kind:c.provider.origin.kind,rows:[u]})}for(let[c,{label:u,kind:d,rows:f}]of s)i.push({group:{key:`byok:${c}`,label:u,rows:f},kind:d});let a=new Map;for(let c of t.agentOriginCandidates){let u=e?iHr(c.configuredModel,c.provider):c.provider.displayName,d=YIn(c);if(!Nlt(d,o))continue;let f=a.get(u);f?f.rows.push(d):a.set(u,{label:u,rows:[d]})}for(let[c,{rows:u}]of a)i.push({group:{key:`agent:${c}`,label:c,rows:u},kind:"agent"});if(e&&r){let c=gj.map(u=>({id:`__locked_copilot__${u.id}`,label:u.displayName||u.id,description:u.description,wireId:u.id,enabled:!1,locked:!0})).filter(u=>Nlt(u,o));c.length>0&&i.push({group:{key:"locked:copilot-plus",label:"Copilot",rows:c},kind:"copilot-plus"})}let l=new Set(i.map(c=>c.kind)).size>1;for(let c of i)c.kind==="copilot-plus"?(c.group.highlight=!0,c.group.badge="privacy",c.group.tooltip="Copilot license required"):l&&(c.group.badge=sHr(c.kind));return i.sort((c,u)=>+(u.kind==="copilot-plus")-+(c.kind==="copilot-plus")),i.map(c=>c.group)}var Rlt=b(()=>{Hf();mp()});var tT,aHr,QIn,e0n=b(()=>{Hf();pe();mp();Se();Us();tT=L(B());Rlt();aHr=Object.freeze([]),QIn=()=>{let t=Ey(),e=Ar(ux,{store:on}),n=Ar(fk,{store:on}),r=Ar(vj,{store:on}),[o,i]=tT.default.useState(""),s=tT.default.useMemo(()=>new Set(r.chat?.enabledModels??aHr),[r]),a=tT.default.useMemo(()=>XIn(e,n,s),[e,n,s]),l=tT.default.useMemo(()=>vPe(a,!1,o,!1),[a,o]),c=tT.default.useCallback((d,f)=>{(f?t.backendConfigRegistry.enableModel("chat",d):t.backendConfigRegistry.disableModel("chat",d)).catch(m=>H(`[QuickChat] toggle model ${d} failed`,m))},[t]);return tT.default.createElement(g3,{groups:l,onToggle:c,query:o,onQueryChange:i,searchPlaceholder:"Search chat models\u2026",emptyState:tT.default.createElement("span",null,"No models configured yet. Add a provider on the"," ",tT.default.createElement("span",{className:"tw-font-medium"},"Models (BYOK)")," tab to populate Quick Chat.")})}});var hC,lHr,cHr,t0n,n0n=b(()=>{Hf();pe();mp();hke();Se();Us();hC=L(B());Rlt();lHr=Object.freeze([]),cHr=t=>bS(t)!==null,t0n=({descriptor:t})=>{let e=Ey(),n=t.id,r=Ar(ux,{store:on}),o=Ar(fk,{store:on}),i=Ar(vj,{store:on}),[s,a]=hC.default.useState(""),l=hC.default.useMemo(()=>{let h=i[n]?.enabledModels??lHr;return new Set(h)},[i,n]),c=t.id==="opencode",u=hC.default.useMemo(()=>JIn(r,o,l,n,c,cHr),[r,o,l,n,c]),d=f3(o),f=hC.default.useMemo(()=>vPe(u,c,s,d),[u,c,s,d]),p=hC.default.useCallback((h,g)=>{(g?e.backendConfigRegistry.enableModel(n,h):e.backendConfigRegistry.disableModel(n,h)).catch(y=>H(`[AgentMode] toggle model ${h} for ${n} failed`,y))},[e,n]),m=t.id==="opencode"?hC.default.createElement("span",null,"No models configured yet. Add a provider on the"," ",hC.default.createElement("span",{className:"tw-font-medium"},"Models (BYOK)")," tab, or sign in to an opencode subscription, to curate models here."):hC.default.createElement("span",null,"No models reported yet. Sign in / install the ",t.displayName," CLI and reload, or open a chat session with this agent.");return hC.default.createElement(g3,{groups:f,onToggle:p,query:s,onQueryChange:a,searchPlaceholder:`Search ${t.displayName} models\u2026`,emptyState:m,defaultOpenGroupKey:f[0]?.key})}});var r0n={};sr(r0n,{AgentSettings:()=>dHr});function uHr(t){let e=t.parentElement;for(;e;){let n=getComputedStyle(e).overflowY;if(n==="auto"||n==="scroll")return e;e=e.parentElement}return null}var or,Llt,dHr,fHr,pHr,o0n=b(()=>{Hf();yt();pm();Iv();LF();ult();kS();_oe();Uat();pe();Se();aP();Re();or=L(B());e0n();n0n();Llt="quickchat";dHr=()=>{let t=xt(),e=P5(),[n,r]=or.default.useState(()=>x$()[0].id),o=or.default.useRef(null),i=or.default.useRef(null);or.default.useLayoutEffect(()=>{let d=o.current;if(!d||i.current===null)return;let f=uHr(d);if(f){let p=d.getBoundingClientRect().top-i.current;p!==0&&(f.scrollTop+=p)}i.current=null},[n]);let s=or.default.useCallback(d=>{i.current=o.current?.getBoundingClientRect().top??null,r(d)},[]),a=x$(),l=[...a.map(d=>({id:d.id,icon:or.default.createElement(d.Icon,{className:"tw-size-4"}),label:d.displayName})),{id:Llt,icon:or.default.createElement(BC,{className:"tw-size-4"}),label:"Quick Chat"}],c=l.some(d=>d.id===n)?n:l[0].id,u=a.some(d=>d.id===t.agentMode.activeBackend)?t.agentMode.activeBackend:a[0].id;return or.default.createElement("section",{className:"tw-space-y-4"},or.default.createElement(yu,{label:"Agents"},or.default.createElement(_o,{type:"select",title:"Default backend",description:"Used when you click + to start a new session and for auto-spawn on mount. Selecting a model from the model picker also updates this.",value:u,onChange:d=>En(f=>({agentMode:{...f.agentMode,activeBackend:d}})),options:a.map(d=>({label:d.displayName,value:d.id}))})),or.default.createElement("div",{className:"tw-flex tw-flex-col"},or.default.createElement("div",{ref:o,className:"tw-flex tw-flex-wrap tw-gap-1",role:"tablist"},l.map((d,f)=>or.default.createElement(qTe,{key:d.id,tab:d,isSelected:c===d.id,onClick:()=>s(d.id),isFirst:f===0,isLast:f===l.length-1,variant:"inline"}))),a.map(d=>or.default.createElement(boe,{key:d.id,id:d.id,isSelected:c===d.id,variant:"inline"},or.default.createElement(pHr,{descriptor:d,plugin:e}))),or.default.createElement(boe,{id:Llt,isSelected:c===Llt,variant:"inline"},or.default.createElement(fHr,null))))},fHr=()=>{let t=xt(),{options:e,resolveSelectionId:n}=lTe(),r=n(t.defaultModelKey);return or.default.createElement(yu,null,or.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-col tw-py-4"},or.default.createElement("span",{className:"tw-text-base tw-font-semibold"},"Quick Chat models"),or.default.createElement("span",{className:"tw-text-xs tw-text-muted"},"Models shown in the chat model picker. Add providers on the Models (BYOK) tab.")),or.default.createElement(_o,{type:"select",title:"Default model",description:"The model new chats start with. Pick from your enabled Quick Chat models.",value:r??"Select Model",onChange:i=>{i!=="Select Model"&&At("defaultModelKey",i)},options:r!==void 0?e:[{label:"Select Model",value:"Select Model"},...e],placeholder:"Model"}),or.default.createElement("div",{className:"tw-py-4"},or.default.createElement(QIn,null)))},pHr=({descriptor:t,plugin:e})=>{let n=xt(),r=t.SettingsPanel,o=e.agentSessionManager,i=MM(t,e),s=t.getResolvedBinaryPath?.(n)??null;or.default.useEffect(()=>{o&&i.kind==="ready"&&(o.getCachedModelCatalog(t.id)||o.preloadModels(t.id).catch(u=>H(`[AgentMode] preload ${t.id} failed`,u)))},[o,t.id,i.kind]);let a=t.Icon,l=RI(t,n),c=i.kind==="absent"?t.AbsentInstallActions:void 0;return or.default.createElement("div",{className:"tw-space-y-3"},l&&or.default.createElement("div",{className:"tw-flex tw-items-start tw-gap-2 tw-rounded-lg tw-border tw-border-solid tw-px-3 tw-py-2.5 tw-text-xs tw-text-normal tw-bg-warning/10 tw-border-warning/40"},or.default.createElement(Wr,{className:"tw-mt-0.5 tw-size-4 tw-shrink-0 tw-text-warning"}),or.default.createElement("div",{className:"tw-leading-relaxed"},or.default.createElement("span",{className:"tw-font-semibold"},"Cloud service.")," Self-Host Mode is on, but"," ",t.displayName," runs in the cloud \u2014 your prompts leave your machine for a third party. It stays available; use it only if you're comfortable with that.")),or.default.createElement(yu,null,or.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2 tw-py-4"},or.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-gap-2"},or.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-2"},or.default.createElement(a,{className:"tw-size-4 tw-shrink-0"}),or.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-col"},or.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},or.default.createElement("span",{className:"tw-text-base tw-font-semibold"},t.displayName),or.default.createElement(Gye,{state:i}),c&&or.default.createElement(ei,{variant:"accent",className:"tw-font-normal"},"Recommended")),s&&or.default.createElement(si,{className:"tw-max-w-[90%] tw-font-mono tw-text-xs tw-text-muted"},Rae(s)),c&&or.default.createElement("span",{className:"tw-text-xs tw-text-muted"},"Not installed \u2014 one download away."),(i.kind==="incompatible"||i.kind==="error")&&or.default.createElement("span",{className:"tw-text-xs tw-text-error"},i.message))),c?or.default.createElement(c,{plugin:e}):or.default.createElement(oe,{className:"tw-shrink-0",size:"default",variant:i.kind==="ready"?"secondary":"default",onClick:()=>t.openInstallUI(e)},"Configure")),c&&or.default.createElement("div",{className:"tw-text-xs tw-text-muted"},"Works with Copilot Plus or your own API keys \u2014 add providers on the BYOK tab.")),i.kind==="ready"&&o&&or.default.createElement(Oke,{descriptor:t,manager:o}),i.kind==="ready"&&or.default.createElement("div",{className:"tw-py-4"},or.default.createElement(t0n,{descriptor:t})),r&&or.default.createElement(r,{plugin:e,app:e.app})))}});var lTn,cTn=b(()=>{lTn=`
:root {
color-scheme: light;
--background-primary: #ffffff;
--background-secondary: #f6f7f8;
--text-normal: #242424;
--text-muted: #666666;
--text-accent: #5b5fc7;
--interactive-accent: #5b5fc7;
--background-modifier-border: #d8d8d8;
--code-background: #f3f3f3;
--callout-color: 91, 95, 199;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
background: var(--background-primary);
color: var(--text-normal);
font-family: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
font-size: 16px;
line-height: 1.65;
}
.publish-renderer {
width: min(100% - 2rem, 46rem);
margin: 0 auto;
padding: 3rem 0 5rem;
}
.markdown-rendered h1,
.markdown-rendered h2,
.markdown-rendered h3,
.markdown-rendered h4,
.markdown-rendered h5,
.markdown-rendered h6 {
margin: 1.8em 0 0.6em;
line-height: 1.25;
}
.markdown-rendered h1 {
font-size: 2rem;
}
.markdown-rendered h2 {
padding-bottom: 0.2em;
border-bottom: 1px solid var(--background-modifier-border);
font-size: 1.5rem;
}
.markdown-rendered h3 {
font-size: 1.25rem;
}
.markdown-rendered p,
.markdown-rendered ul,
.markdown-rendered ol,
.markdown-rendered blockquote,
.markdown-rendered pre,
.markdown-rendered table {
margin: 1em 0;
}
.markdown-rendered a {
color: var(--text-accent);
text-decoration-thickness: 0.08em;
text-underline-offset: 0.15em;
}
.markdown-rendered .internal-link {
color: inherit;
text-decoration: underline;
text-decoration-color: var(--background-modifier-border);
text-underline-offset: 0.15em;
}
.markdown-rendered blockquote {
margin-left: 0;
padding: 0.1em 1em;
border-left: 3px solid var(--background-modifier-border);
color: var(--text-muted);
}
.markdown-rendered code {
padding: 0.15em 0.35em;
border-radius: 0.25rem;
background: var(--code-background);
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
font-size: 0.9em;
}
.markdown-rendered pre {
overflow-x: auto;
padding: 1rem;
border-radius: 0.4rem;
background: var(--code-background);
}
.markdown-rendered pre code {
padding: 0;
background: transparent;
}
.markdown-rendered table {
width: 100%;
border-collapse: collapse;
}
.markdown-rendered th,
.markdown-rendered td {
padding: 0.5rem 0.7rem;
border: 1px solid var(--background-modifier-border);
text-align: left;
vertical-align: top;
}
.markdown-rendered th {
background: var(--background-secondary);
}
.markdown-rendered img,
.markdown-rendered svg {
max-width: 100%;
height: auto;
}
.markdown-rendered hr {
margin: 2rem 0;
border: 0;
border-top: 1px solid var(--background-modifier-border);
}
.markdown-rendered .task-list-item {
list-style: none;
}
.symposium-task-marker {
display: inline-block;
width: 1.4em;
margin-left: -1.4em;
}
.markdown-rendered .callout {
margin: 1rem 0;
padding: 0.8rem 1rem;
border: 1px solid rgba(var(--callout-color), 0.35);
border-left-width: 4px;
border-radius: 0.4rem;
background: rgba(var(--callout-color), 0.08);
}
.markdown-rendered .callout-title {
display: flex;
gap: 0.5rem;
align-items: center;
font-weight: 650;
}
.markdown-rendered .callout-content > :last-child {
margin-bottom: 0;
}
.markdown-rendered .markdown-embed,
.markdown-rendered .file-embed {
margin: 1rem 0;
padding: 0.75rem 1rem;
border: 1px solid var(--background-modifier-border);
border-radius: 0.4rem;
background: var(--background-secondary);
}
.markdown-rendered .canvas-minimap {
display: block;
width: 100%;
border-radius: 0.4rem;
background: var(--background-secondary);
}
.markdown-rendered .canvas-minimap path {
fill: none;
stroke: var(--text-muted);
stroke-width: 2;
}
.markdown-rendered .canvas-minimap rect {
fill: var(--background-primary);
stroke: var(--text-muted);
stroke-width: 2;
}
.markdown-rendered math[display="block"],
.markdown-rendered .math {
max-width: 100%;
overflow-x: auto;
}
.symposium-missing-asset {
display: inline-block;
padding: 0.2rem 0.45rem;
border: 1px dashed var(--background-modifier-border);
border-radius: 0.25rem;
color: var(--text-muted);
}
@media (max-width: 40rem) {
.publish-renderer {
width: min(100% - 1.25rem, 46rem);
padding-top: 1.5rem;
}
}
`.trim()});function gTn(t,e){let n=new TextEncoder().encode(e).byteLength;if(n>10485760)throw new $O(n);return Object.freeze({title:t,html:e,byteLength:n})}function yTn(t,e){let n=gTn(t,e);return ect(e),n}function ect(t){let e=new DOMParser().parseFromString(t,"text/html"),n=new Set;for(let o of e.querySelectorAll(QHr))n.add(`remove unsupported <${o.localName}>`);[...e.querySelectorAll("meta[http-equiv]")].some(o=>o.getAttribute("http-equiv")?.trim().toLowerCase()==="refresh")&&n.add("remove the automatic redirect");for(let o of e.querySelectorAll("*")){o.localName==="style"&&dTn(o.textContent??"")&&n.add("embed or remove the external CSS resource in <style>");for(let i of[...o.attributes]){let s=i.name.toLowerCase();if(s.startsWith("on")||eWr.has(s)){n.add(`remove "${i.name}" from <${o.localName}>`);continue}if((s==="style"||i.value.toLowerCase().includes("url("))&&dTn(i.value)){n.add(`embed or remove the external CSS resource in "${i.name}" on <${o.localName}>`);continue}hTn.has(s)&&!iWr(o,s,i.value)&&n.add(`embed or remove "${i.name}" on <${o.localName}>`)}}if(n.size>0)throw new jF([...n])}function dTn(t){let e=t.replace(nWr,"").replace(rWr,"");return tWr.test(e)}function iWr(t,e,n){let r=n.trim();if(!r)return!1;if(r.startsWith("#"))return!0;let o=t.localName.toLowerCase(),i=r.match(/^([a-z][a-z0-9+.-]*):/i)?.[1]?.toLowerCase();return o==="a"&&e==="href"?r.startsWith("//")||i==="http"||i==="https"||i==="mailto"||i==="tel":o==="img"&&e==="src"?DPe(r)&&!/^data:image\/svg\+xml/i.test(r):o==="image"&&(e==="href"||e==="xlink:href")?DPe(r)&&!/^data:image\/svg\+xml/i.test(r):e==="cite"?r.startsWith("//")||i==="http"||i==="https":!1}async function vTn(t,e,n,r){let o=await t.vault.read(e),i=r.win.createEl("article","markdown-preview-view markdown-rendered symposium-document"),s=mTn.MarkdownRenderer.render;await s(t,o,i,e.path,n),sWr(i),aWr(i),lWr(i),cWr(i);let a=i.cloneNode(!0);Qlt(a);let l=new TextEncoder().encode(pTn(r,e.basename,a)).byteLength;if(l>10485760)throw new $O(l);await uWr(i,t,e.path,l),Qlt(i);let c=e.basename,u=pTn(r,c,i);return gTn(c,u)}function sWr(t){t.querySelectorAll("mjx-container").forEach(e=>{let n=e.querySelector("mjx-assistive-mml math");n&&e.replaceWith(n.cloneNode(!0))})}function aWr(t){t.querySelectorAll("input.task-list-item-checkbox").forEach(e=>{let n=e.checked||e.hasAttribute("checked"),r=t.doc.win.createSpan({cls:"symposium-task-marker",text:n?"\u2611":"\u2610",attr:{role:"img","aria-label":n?"Completed task":"Open task"}});e.replaceWith(r)})}function lWr(t){t.querySelectorAll(XHr).forEach(e=>e.remove())}function cWr(t){t.querySelectorAll("a.internal-link").forEach(e=>{let n=t.doc.win.createSpan([...e.classList].filter(r=>r!=="is-unresolved").join(" "));n.classList.contains("internal-link")||n.classList.add("internal-link"),e.title&&(n.title=e.title),n.append(...e.childNodes),e.replaceWith(n)})}async function uWr(t,e,n,r){let o=[...t.querySelectorAll("img")].filter(a=>{let l=a.getAttribute("src")?.trim()??"";return!wTn(l)&&!DPe(l)});if(o.length===0)return;let i=dWr(e),s=r;for(let a of o){let l=a.getAttribute("src")?.trim()??"",c=Boe(a),u=fWr(a,e,n,i);if(!u){let _=Xlt(a,l);s+=Boe(_)-c;continue}let d=oWr+4*Math.ceil(u.stat.size/3),f=fTn(a,d),p=s-c+f;if(p>10485760)throw new $O(p);let m;try{m=await e.vault.readBinary(u)}catch{let _=Xlt(a,u.path);s+=Boe(_)-c;continue}let h=mWr(m);if(!h){let _=Xlt(a,u.path);s+=Boe(_)-c;continue}let g=`data:${h};base64,`,v=g.length+4*Math.ceil(m.byteLength/3),y=fTn(a,v),w=s-c+y;if(w>10485760)throw new $O(w);a.src=`${g}${Fv(m)}`,a.removeAttribute("data-path"),a.removeAttribute("data-src"),s=w}}function Boe(t){let e=t.cloneNode(!0);return Qlt(e),new TextEncoder().encode(e.outerHTML).byteLength}function fTn(t,e){let n=t.cloneNode(!0);return n.src=uTn,n.removeAttribute("data-path"),n.removeAttribute("data-src"),Boe(n)-uTn.length+e}function dWr(t){let e=new Map;for(let n of t.vault.getFiles())e.set(t.vault.getResourcePath(n),n);return e}function fWr(t,e,n,r){let o=[t.getAttribute("data-path"),t.getAttribute("data-src"),t.getAttribute("src")];for(let i of o){if(!i)continue;let s=r.get(i);if(s)return s;let a=yWr(i);if(gWr(a))continue;let l=a.replace(/^\/+/,"").split(/[?#]/,1)[0],c=e.metadataCache.getFirstLinkpathDest(l,n);if(c)return c;let u=e.vault.getAbstractFileByPath(l);if(pWr(u))return u}return null}function pWr(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.path=="string"&&typeof e.basename=="string"&&typeof e.extension=="string"}function mWr(t){let e=new Uint8Array(t,0,Math.min(t.byteLength,512));if(joe(e,[137,80,78,71,13,10,26,10]))return"image/png";if(joe(e,[255,216,255]))return"image/jpeg";if($Pe(e,"GIF87a")||$Pe(e,"GIF89a"))return"image/gif";if($Pe(e,"BM"))return"image/bmp";if($Pe(e,"RIFF")&&zoe(e,8,"WEBP"))return"image/webp";if(joe(e,[0,0,1,0]))return"image/x-icon";if(joe(e,[73,73,42,0])||joe(e,[77,77,0,42]))return"image/tiff";if(Jlt(e,["avif","avis"]))return"image/avif";if(Jlt(e,["heic","heix","hevc","hevx","heim","heis","hevm","hevs"]))return"image/heic";if(Jlt(e,["mif1","msf1"]))return"image/heif";let n=new TextDecoder().decode(e).trimStart();return/^(?:<\?xml[\s\S]*?\?>\s*)?(?:<!--[\s\S]*?-->\s*)*<svg[\s>]/i.test(n)?"image/svg+xml":null}function Jlt(t,e){if(!zoe(t,4,"ftyp"))return!1;let n=new DataView(t.buffer,t.byteOffset,4).getUint32(0);if(n<16)return!1;let r=Math.min(n,t.byteLength);if(e.some(o=>zoe(t,8,o)))return!0;for(let o=16;o+4<=r;o+=4)if(e.some(i=>zoe(t,o,i)))return!0;return!1}function joe(t,e){return e.every((n,r)=>t[r]===n)}function $Pe(t,e){return zoe(t,0,e)}function zoe(t,e,n){return t.byteLength<e+n.length?!1:[...n].every((r,o)=>t[e+o]===r.charCodeAt(0))}function Xlt(t,e){let n=t.doc.win.createSpan({cls:"symposium-missing-asset",text:`[Missing image: ${t.alt||e||"unknown"}]`});return t.replaceWith(n),n}function Qlt(t){for(let e of[t,...t.querySelectorAll("*")]){for(let n of[...e.attributes]){let r=n.name.toLowerCase();if(r.startsWith("on")||r==="style"||r==="srcdoc"||r==="srcset"||r==="contenteditable"||r==="referrerpolicy"){e.removeAttribute(n.name);continue}hTn.has(r)&&!hWr(e,r,n.value)&&e.removeAttribute(n.name)}e.tagName==="A"&&e.hasAttribute("target")&&e.setAttribute("rel","noopener noreferrer"),e.tagName==="IMG"&&wTn(e.getAttribute("src")?.trim()??"")&&e.setAttribute("referrerpolicy","no-referrer")}}function hWr(t,e,n){let r=n.trim();if(!r)return!1;if(r.startsWith("#"))return!0;if(r.startsWith("//"))return t.tagName==="A"&&e==="href"||t.tagName==="IMG"&&e==="src";let o=r.match(/^([a-z][a-z0-9+.-]*):/i)?.[1]?.toLowerCase();return t.tagName==="IMG"&&e==="src"?o==="http"||o==="https"||DPe(r):t.tagName==="A"&&e==="href"?o==="http"||o==="https"||o==="mailto"||o==="tel":e==="cite"?o==="http"||o==="https":!1}function wTn(t){return/^(?:https?:)?\/\//i.test(t)}function DPe(t){return/^data:image\/[a-z0-9.+-]+(?:;[a-z0-9=.+-]+)*;base64,[a-z0-9+/=\s]+$/i.test(t)}function gWr(t){return/^[a-z][a-z0-9+.-]*:/i.test(t)||t.startsWith("//")}function yWr(t){try{return decodeURIComponent(t)}catch{return t}}function pTn(t,e,n){return["<!doctype html>",'<html lang="en">',"<head>",'<meta charset="utf-8">','<meta name="viewport" content="width=device-width, initial-scale=1">',t.win.createEl("title",{text:e}).outerHTML,`<style id="symposium-obsidian-publish-baseline">${lTn}</style>`,"</head>",'<body><main class="publish-renderer">',n.outerHTML,"</main></body>","</html>"].join("")}var mTn,XHr,QHr,hTn,eWr,tWr,nWr,rWr,oWr,uTn,$O,jF,tct=b(()=>{cTn();i$();jV();mTn=require("obsidian"),XHr=["base","button","embed","form","iframe","input","link","meta","object","script","select","style","template","textarea","video","audio","applet","dialog","frame","frameset","fencedframe","foreignObject","animate","animateMotion","animateTransform","set",".collapse-indicator",".copy-code-button",".edit-block-button",".heading-collapse-indicator",".markdown-embed-link",".frontmatter",".metadata-container"].join(","),QHr=["applet","audio","base","button","dialog","embed","fencedframe","form","frame","frameset","iframe","input","link","object","portal","script","select","template","textarea","video","foreignObject","animate","animateMotion","animateTransform","set","html[manifest]"].join(","),hTn=new Set(["action","background","cite","formaction","href","manifest","poster","ping","src","xlink:href"]),eWr=new Set(["contenteditable","ping","srcdoc","srcset"]),tWr=/@import|url\s*\(|https?:|\/\/|\\|expression\s*\(|behavior\s*:/i,nWr=/\/\*[\s\S]*?\*\//g,rWr=/url\s*\(\s*(["']?)#[^\s)"']+\1\s*\)/gi,oWr=22,uTn="data:image/png;base64,A",$O=class t extends Error{constructor(n){super(`Symposium HTML is ${n} bytes; the limit is ${10485760} bytes.`);this.byteLength=n;this.name="SymposiumDocumentTooLargeError",Object.setPrototypeOf(this,t.prototype)}},jF=class t extends Error{constructor(e){let n=e.slice(0,8),r=e.length-n.length;super(`Symposium HTML is not publishable: ${n.join("; ")}${r>0?`; plus ${r} more`:""}.`),this.name="SymposiumDocumentUnsafeError",Object.setPrototypeOf(this,t.prototype)}}});var CTn={};sr(CTn,{consumeSymposiumAgentHandoff:()=>AWr});function kWr(t){let e=`${eW}/`,n=t.startsWith(e)?t.slice(e.length):"";if(!n||n.includes("/")||n.includes("\\")||!n.toLowerCase().endsWith(".html"))throw new fw(ict);return n}async function IWr(t){let{lstat:e}=Pe("fs/promises"),n=Pe("path"),r=n.resolve(t,".symposium"),o=n.join(r,"handoffs");try{let[i,s]=await Promise.all([e(r),e(o)]);if(!i.isDirectory()||!s.isDirectory())throw new Error("unsafe handoff root")}catch{throw new fw(bWr)}return o}function STn(t){try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t)}catch{throw new fw("Staged Symposium HTML must be valid UTF-8.")}}async function _Tn(t){let{unlink:e}=Pe("fs/promises");try{await e(t)}catch(n){if(n.code!=="ENOENT")throw new fw(_Wr)}}function oct(t){return t.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function xTn(t,e){return[...CWr,`frame-src ${t}`,`script-src ${e}`].join("; ")}function TWr(t){let e=xTn("'self'","'unsafe-inline'"),n=xTn("'none'","'none'"),r=`<meta http-equiv="Content-Security-Policy" content="${oct(n)}">${t}`;return`<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="${oct(e)}">
<meta name="referrer" content="no-referrer">
<title>Symposium local preview</title>
<style>html,body,iframe{border:0;height:100%;margin:0;padding:0;width:100%}body{overflow:hidden}iframe{display:block}</style>
</head>
<body>
<iframe title="Symposium HTML preview" sandbox="allow-same-origin" referrerpolicy="no-referrer" srcdoc="${oct(r)}"></iframe>
<script>
const frame=document.querySelector("iframe");
const block=(event)=>event.preventDefault();
const seal=()=>{
const previewDocument=frame.contentDocument;
if(!previewDocument)return;
for(const eventName of ["auxclick","click","contextmenu","dragstart","submit"]){
previewDocument.addEventListener(eventName,block,true);
}
};
frame.addEventListener("load",seal);
seal();
<\/script>
</body>
</html>
`}async function PWr(t){let{lstat:e,mkdtemp:n,readFile:r,rm:o,writeFile:i}=Pe("fs/promises"),{tmpdir:s}=Pe("os"),a=Pe("path"),{pathToFileURL:l}=Pe("url"),c=await n(a.join(s(),xWr)),u=a.join(c,SWr),d=TWr(t);try{await i(u,new TextEncoder().encode(d),{flag:"wx",mode:256})}catch(f){throw await o(c,{recursive:!0,force:!0}),f}return Object.freeze({html:t,previewPath:u,previewUrl:l(u).href,isPreviewCurrent:async()=>{try{return(await e(u)).isFile()?STn(Uint8Array.from(await r(u)))===d:!1}catch{return!1}},cleanup:()=>o(c,{recursive:!0,force:!0})})}async function AWr(t,e){let{lstat:n,readFile:r}=Pe("fs/promises"),o=Pe("path"),i=kWr(e),s=await IWr(t),a=o.join(s,i),l;try{let c=await n(a);if(!c.isFile())throw new fw(ict);if(c.size>10485760)throw new fw(`Symposium HTML is ${c.size} bytes; the limit is ${10485760} bytes.`);let u=await r(a);if(u.byteLength>10485760)throw new fw(`Symposium HTML is ${u.byteLength} bytes; the limit is ${10485760} bytes.`);l=STn(Uint8Array.from(u))}catch(c){throw await _Tn(a),c instanceof fw?c:new fw(ict)}try{ect(l)}catch(c){throw c instanceof jF?new fw(`${c.message} Edit this staged file and retry once: ${e}`):c}return await _Tn(a),PWr(l)}var fw,bWr,ict,_Wr,xWr,SWr,CWr,kTn=b(()=>{i$();tct();$n();fw=class t extends Error{constructor(e){super(e),this.name="SymposiumAgentHandoffError",Object.setPrototypeOf(this,t.prototype)}},bWr="The Symposium handoff folder must be an ordinary directory inside the current vault.",ict="Staged Symposium HTML must be one ordinary .html file inside the vault handoff folder.",_Wr="Copilot could not remove the staged Symposium HTML.",xWr="copilot-symposium-preview-",SWr="preview.html",CWr=["default-src 'none'","base-uri 'none'","connect-src 'none'","font-src data:","form-action 'none'","img-src data:","media-src data:","object-src 'none'","style-src 'unsafe-inline'"]});var PTn={};sr(PTn,{buildManagedOpencodeProviderIds:()=>TTn,wireAgentModelDiscovery:()=>DWr});function DWr(t,e){let n=new Map,r=new Map,o=!1,i=l=>{let c=e.getCachedModelCatalog(l.id),u=jWr(c);if(u===null)return;let d=u.map(m=>`${m.wireId} ${m.name} ${m.description??""}`).join(`
`);if(n.get(l.id)===d)return;let p=(r.get(l.id)??Promise.resolve()).catch(()=>{}).then(async()=>{o||(await FWr(t.modelManagement,l,u),n.set(l.id,d))}).catch(m=>{H(`[AgentMode] model discovery enroll failed for ${l.id}`,m)}).finally(()=>{r.get(l.id)===p&&r.delete(l.id)});r.set(l.id,p)},s=()=>{if(!o)for(let l of ss())i(l)},a=e.subscribeModelCache(s);return s(),()=>{o=!0,a()}}async function FWr(t,e,n){let r=e.id,o=n.map(d=>d.wireId),i=e.id==="opencode"?UWr(t,o):o,s={},a={};for(let d of n)d.name&&(s[d.wireId]=d.name),d.description&&(a[d.wireId]=d.description);if(i.length===0){j(`[AgentMode] model discovery: empty model list for ${r} \u2014 skipping enroll/sync (transient or fully-suppressed probe)`);return}if(t.providerRegistry.listByOrigin("agent").find(d=>d.origin.kind==="agent"&&d.origin.agentType===r)){await t.setup.agent.syncAgentModels({agentType:r,wireModelIds:i,fallbackDisplayNames:s,fallbackDescriptions:a});return}let c=e.id==="opencode"?i.slice(0,$Wr):void 0,u=await t.setup.agent.registerAgentProvider({agentType:r,providerType:LWr[r],displayName:e.displayName,apiKey:null,wireModelIds:i,autoEnrollModelIds:c,fallbackDisplayNames:s,fallbackDescriptions:a});j(`[AgentMode] model discovery: first enrollment for ${r} \u2014 ${u.configuredModelIds.length} model(s) configured, ${c?.length??u.configuredModelIds.length} enabled`)}function UWr(t,e){let n=[...t.providerRegistry.listByOrigin("byok"),...t.providerRegistry.listByOrigin("copilot-plus")],r=TTn(n);return Ake(e,r)}function TTn(t){let e=new Set;for(let n of t){if(n.origin.kind==="agent")continue;let r=bS(n);r&&e.add(r.id)}return e}function jWr(t){return t?.availableModels?t.availableModels.map(e=>({wireId:e.baseModelId,name:e.name,description:e.description})):null}var LWr,$Wr,ATn=b(()=>{pe();Hf();LWr={claude:"anthropic",codex:"openai-compatible",opencode:"openai-compatible"},$Wr=3});var BWr={};sr(BWr,{default:()=>zPe});module.exports=DTn(BWr);H5();_v();es();mw();gt();Se();es();mw();gt();gt();pe();var XS=class{static convert(e,n={}){let{includeSystemMessage:r=!0,mergeUserContent:o=!0,debug:i=!1}=n,s=[],a=e.layers.find(f=>f.id==="L1_SYSTEM"),l=e.layers.find(f=>f.id==="L2_PREVIOUS"),c=e.layers.find(f=>f.id==="L3_TURN"),u=e.layers.find(f=>f.id==="L4_STRIP"),d=e.layers.find(f=>f.id==="L5_USER");if(r&&a&&a.text){let f=[a.text];l&&l.text&&(f.push(`
## Context Library
The following notes are available for reference:
`+l.text),i&&j("[LayerToMessagesConverter] Added L2 (cumulative context) to system")),s.push({role:"system",content:f.join(`
`)}),i&&j("[LayerToMessagesConverter] Added L1 (System) + L2 (Cumulative) as stable prefix")}if(u&&u.text&&i&&j("[LayerToMessagesConverter] L4 (Strip) found but skipped (using LangChain memory)"),o){let f=[];if(c&&c.segments.length>0&&l){let p=new Set(l.segments.map(g=>g.id)),m=[],h=[];for(let g of c.segments)p.has(g.id)?m.push(g.id):h.push(g);if(m.length>0||h.length>0){let g=[];m.length>0&&g.push(`Context attached to this message:
`+m.map(v=>`- ${v}`).join(`
`)+`
Find them in the Context Library in the system prompt above.`),h.length>0&&g.push(h.map(v=>v.content).join(`
`)),f.push(g.join(`
`)),i&&j(`[LayerToMessagesConverter] Added L3: ${m.length} references, ${h.length} new items`)}}else c&&c.text&&(f.push(c.text),i&&j("[LayerToMessagesConverter] Added L3 (all new context)"));f.length>0&&d&&d.text&&f.push(`---
[User query]:`),d&&d.text&&(f.push(d.text),i&&j("[LayerToMessagesConverter] Added L5 (user message)")),f.length>0&&s.push({role:"user",content:f.join(`
`)})}else c&&c.text&&s.push({role:"user",content:c.text}),d&&d.text&&s.push({role:"user",content:d.text});return i&&(j(`[LayerToMessagesConverter] Converted envelope to ${s.length} messages`),s.forEach((f,p)=>{let m=f.content.substring(0,100);j(` Message ${p+1} [${f.role}]: ${m}...`)})),s}static extractUserContent(e){let n=e.layers.find(i=>i.id==="L3_TURN"),r=e.layers.find(i=>i.id==="L5_USER"),o=[];return n&&n.text&&o.push(n.text),r&&r.text&&o.push(r.text),o.join(`
`)}static extractFullContext(e){let n=e.layers.find(s=>s.id==="L2_PREVIOUS"),r=e.layers.find(s=>s.id==="L3_TURN"),o=e.layers.find(s=>s.id==="L5_USER"),i=[];return n&&n.text&&i.push(n.text),r&&r.text&&i.push(r.text),o&&o.text&&i.push(o.text),i.join(`
`)}static extractSystemMessage(e){return e.layers.find(r=>r.id==="L1_SYSTEM")?.text||""}static getLayerHashes(e){return e.layerHashes}};pe();ut();gt();pe();ut();PEe();var jM=class{constructor(e){this.chainManager=e}async handleResponse(e,n,r,o,i,s,a,l){if((e||l?.wasTruncated)&&!(r.signal.aborted&&r.signal.reason==="new-chat")){let p=n.contextEnvelope?.layers.find(v=>v.id==="L5_USER")?.text||n.originalMessage||n.message,m=a||e||"[Response truncated - no content generated]";await this.chainManager.memoryManager.saveContext({input:p},{output:m});let g={message:e||(l?.wasTruncated?"_[The model stopped at its maximum response length before generating any content.]_":""),sender:pl,isVisible:!0,timestamp:Cs(new Date),sources:s,responseMetadata:l};o(g),i("")}else r.signal.reason==="new-chat"&&i("");let u=this.chainManager.memoryManager.getMemory().chatHistory.messages;j(`Chat memory updated:
`,{turns:Array.isArray(u)?u.length:0});let d=2e3;try{let{parseToolCallMarkers:f}=await Promise.resolve().then(()=>(Get(),Kcn)),m=f(e).segments.map(g=>g.type==="text"?g.content:"").join("").trim();m||(m=e||"");let h=m.length>d?m.slice(0,d)+"... (truncated)":m;j(`Final AI response (truncated):
`,h)}catch{let f=typeof e=="string"?e:String(e??""),p=f.length>d?f.slice(0,d)+"... (truncated)":f;j(`Final AI response (truncated):
`,p)}return e}async handleError(e,n){let r=kt(e);H("Error during LLM invocation:",r);let o=Eie(e);if(o){n(o);return}let i=e?.response?.data?.error||r,s=i?.code||r,a="";e?.message?.includes("Invalid license key")?a="Invalid Copilot Plus license key. Please check your license key in settings.":s==="model_not_found"?a="You do not have access to this model or the model does not exist, please check with your API provider.":a=`${s}`,H(i),n(this.enhancedErrorMsg(a,r,e))}enhancedErrorMsg(e,n,r){let o=e.search("Troubleshooting URL");return e=o!==-1?e.slice(0,o):e,this.isAuthenticationError(r,n)&&(e=`Something went wrong. Please check if you have set your API key.
Path: Settings > Copilot > BYOK.
Or check model config
Error Details: `+e),e}isAuthenticationError(e,n){let r=e?.response,o=r?.data?.error??e?.error,i=r?.status??o?.status,s=typeof i=="string"?Number.parseInt(i,10):i,a=typeof o=="object"&&o!==null?o:void 0,l=(typeof a?.message=="string"?a.message:n).toLowerCase(),c=typeof a?.code=="string"?a.code.toLowerCase():"",u=typeof a?.type=="string"?a.type.toLowerCase():"";return s===401?!0:["api key","apikey","unauthorized","authentication","invalid authentication"].some(f=>l.includes(f)||c.includes(f)||u.includes(f))}};pe();function Art(t){let e=[];for(let n of t){if(!n)continue;let r=n;if(typeof r.type=="string"){let o=r.type;o==="human"?e.push({role:"user",content:r.content}):o==="ai"&&e.push({role:"assistant",content:r.content})}else if(r.content!==void 0){let o=VLr(r);o&&e.push({role:o,content:r.content})}}return e}function VLr(t){return t.role==="human"||t.role==="user"||t.sender==="user"?"user":t.role==="ai"||t.role==="assistant"||t.sender==="AI"?"assistant":null}function qLr(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&n.type==="text").map(n=>n.text||"").join(" ")||"[Image content]":String(t||"")}function Ogn(t){return t.map(e=>({role:e.role,content:qLr(e.content)}))}async function BM(t,e){let r=(await t.loadMemoryVariables({})).history||[],o=r.length?Art(r):[];for(let l of o)e.push({role:l.role,content:l.content});let i=0;for(let l of e)typeof l.content=="string"&&l.role==="system"&&(i+=l.content.length);let s=0;for(let l of o)typeof l.content=="string"&&(s+=l.content.length);let a=i+s;return a>2e6&&j("[Token Budget] Large payload detected (excluding user message):",{"L1+L2 (system)":`${Math.round(i/4e3)}k tokens`,"L4 (history)":`${Math.round(s/4e3)}k tokens (${o.length} msgs)`,total:`${Math.round(a/4e3)}k tokens`}),o}pe();var ic=class t{constructor(){this.tools=new Map}static getInstance(){return t.instance||(t.instance=new t),t.instance}register(e){this.tools.set(e.metadata.id,e)}registerAll(e){e.forEach(n=>this.register(n))}getAllTools(){return Array.from(this.tools.values())}getEnabledTools(e,n){let r=[];for(let[o,i]of this.tools){let{metadata:s,tool:a}=i;if(s.isAlwaysEnabled){(!s.requiresVault||n)&&r.push(a);continue}e.has(o)&&(!s.requiresVault||n)&&r.push(a)}return r}getToolsByCategory(){let e=new Map;for(let n of this.tools.values()){let r=n.metadata.category;e.has(r)||e.set(r,[]),e.get(r).push(n)}return e}getConfigurableTools(){return Array.from(this.tools.values()).filter(e=>!e.metadata.isAlwaysEnabled)}getCopilotCommandMappings(){let e=new Map;for(let n of this.tools.values()){let r=n.metadata.copilotCommands;if(r)for(let o of r){let i=o.toLowerCase();e.has(i)||e.set(i,n)}}return e}getToolMetadata(e){return this.tools.get(e)?.metadata}getToolDefinition(e){return this.tools.get(e)}clear(){this.tools.clear()}};var v3=null;function KLr(t){let e=new WeakSet;return JSON.stringify(t,(n,r)=>{if(typeof r=="object"&&r!==null){if(e.has(r))return"[Circular]";e.add(r)}return typeof r=="bigint"?r.toString():r},2)}function GLr(t,e){let n=[];e&&(n.push(`msg:${e.messageId??"N/A"} | conv:${e.conversationId??"N/A"} | v${e.version}`),n.push(""));let r=ic.getInstance(),o=new Set(r.getAllTools().map(u=>u.tool.name)),i=u=>{let d=[],f=/<(\w+)>([\s\S]*?)<\/\1>/g,p;for(;(p=f.exec(u))!==null;){let m=p[1],h=p[2];if(o.has(m)){let g=h.length>200?h.substring(0,200).trim()+"...[truncated]":h.trim();d.push({tool:m,preview:g})}}return d},s=u=>typeof u.content=="string"?u.content:Array.isArray(u.content)?u.content.filter(f=>f.type==="text").map(f=>f.text??"").join(`
`):"",a=Array.isArray(t)?t:[],l=0;for(let u=0;u<a.length;u++){let d=a[u],f=s(d);if(d.role==="system"){n.push("\u2501\u2501\u2501 SYSTEM MESSAGE \u2501\u2501\u2501"),n.push("");let p=e?.layers.find(h=>h.id==="L1_SYSTEM"),m=e?.layers.find(h=>h.id==="L2_PREVIOUS");if(p&&f.includes(p.text)){let h=p.hash.substring(0,8);n.push(`\u{1F512} L1_SYSTEM (${h}) [CACHEABLE]`);let g=f.indexOf(p.text)+p.text.length,v=p.text.length>300?p.text.substring(0,300)+"...[truncated]":p.text;if(n.push(v),n.push(""),m&&m.text){let _=m.hash.substring(0,8);n.push(`\u{1F512} L2_PREVIOUS (${_}) [CACHEABLE]`);let S=m.text.length>300?m.text.substring(0,300)+"...[truncated]":m.text;n.push(S),n.push("")}let y=f.substring(g),w=i(y);if(w.length>0){n.push("--- PER-TURN ADDITIONS (not cached) ---"),n.push("");for(let _ of w)n.push(`\u{1F4E6} TOOL: ${_.tool} (turn-specific RAG)`),n.push(_.preview),n.push("")}}else{let h=i(f);if(h.length>0){let g=f.match(/<(\w+)>/);if(g){let v=f.substring(0,g.index);if(v.trim()){let y=v.length>300?v.substring(0,300)+"...[truncated]":v;n.push(y),n.push("")}}n.push("--- PER-TURN ADDITIONS (not cached) ---"),n.push("");for(let v of h)n.push(`\u{1F4E6} TOOL: ${v.tool}`),n.push(v.preview),n.push("")}else{let g=f.length>300?f.substring(0,300)+"...[truncated]":f;n.push(g),n.push("")}}}else(d.role==="user"||d.role==="assistant")&&u<a.length-1&&l++}l>0&&(n.push("\u2501\u2501\u2501 CHAT HISTORY (L4) \u2501\u2501\u2501"),n.push(""),n.push(`${l} message(s)`),n.push(""));let c=a[a.length-1];if(c&&c.role==="user"){n.push("\u2501\u2501\u2501 USER MESSAGE \u2501\u2501\u2501"),n.push("");let u=s(c),d=i(u);if(d.length>0){n.push("--- PER-TURN TOOL RESULTS ---"),n.push("");for(let m of d)n.push(`\u{1F4E6} TOOL: ${m.tool}`),n.push(m.preview),n.push("")}let f=e?.layers.find(m=>m.id==="L3_TURN"),p=e?.layers.find(m=>m.id==="L5_USER");if(f&&f.text&&u.includes(f.text)){let m=f.hash.substring(0,8);n.push(`\u26A1 L3_TURN (${m})`);let h=f.text.length>300?f.text.substring(0,300)+"...[truncated]":f.text;n.push(h),n.push("")}if(p&&p.text&&u.includes(p.text)){let m=p.hash.substring(0,8);n.push(`\u26A1 L5_USER (${m})`),n.push(p.text),n.push("")}}return n.join(`
`)}function zM(t){let{messages:e,modelName:n,contextEnvelope:r}=t;try{v3={timestamp:new Date().toISOString(),modelName:n,serializedMessages:KLr(e),messagesArray:e,contextEnvelope:r}}catch{v3={timestamp:new Date().toISOString(),modelName:n,serializedMessages:String(e),messagesArray:e,contextEnvelope:r}}}function w3(){v3=null}async function $ke(){if(!v3)return;let{timestamp:t,modelName:e,serializedMessages:n,messagesArray:r,contextEnvelope:o}=v3,i=[`### Prompt \u2014 ${t}${e?` \u2014 ${e}`:""}`,"","**Actual Messages Sent to LLM:**","","```json",n,"```",""],s=GLr(r,o);i.push("**Layered Context Metadata:**"),i.push(""),i.push("```"),i.push(s),i.push("```"),i.push(""),Kie(i),v3=null}function Ngn(t){let e=t.response_metadata||{};return e.finish_reason==="length"?{wasTruncated:!0,message:"Response truncated due to token limit"}:e.stop_reason==="max_tokens"?{wasTruncated:!0,message:"Response truncated due to max_tokens limit"}:e.finishReason==="MAX_TOKENS"||e.finish_reason==="MAX_TOKENS"?{wasTruncated:!0,message:"Response truncated due to MAX_TOKENS limit"}:{wasTruncated:!1,message:null}}function Rgn(t){let e=t.response_metadata||{};if(e.tokenUsage){let n=e.tokenUsage;return{inputTokens:n.promptTokens,outputTokens:n.completionTokens,totalTokens:n.totalTokens}}if(e.usage){let n=e.usage;return{inputTokens:n.input_tokens||n.inputTokens||n.inputTokenCount||n.prompt_tokens,outputTokens:n.output_tokens||n.outputTokens||n.outputTokenCount||n.completion_tokens,totalTokens:n.total_tokens||n.totalTokens||(n.input_tokens||n.inputTokenCount||0)+(n.output_tokens||n.outputTokenCount||0)}}return t.usage_metadata?{inputTokens:t.usage_metadata.input_tokens,outputTokens:t.usage_metadata.output_tokens,totalTokens:t.usage_metadata.total_tokens}:null}function ZLr(t){return`<errorChunk>${t}</errorChunk>`}function Dke(t,e){let n=ZLr(t);return e?`${e}
${n}`:`
${n}`}oi();pe();function Ert(t,e,n){return new ig({content:n,tool_call_id:t,name:e})}function Fke(){let t=Date.now(),e=Math.random().toString(36).substring(2,11);return`call_${t}_${e}`}function Lgn(t,e){let n=e.index??0,r=t.get(n)||{name:"",args:""};e.id&&(r.id=e.id);let o=e.name??e.functionCall?.name;o&&(r.name+=o),e.args&&(r.args+=e.args),t.set(n,r)}function Uke(t){let e=[];for(let n of t.values()){if(!n.name)continue;let r={};if(n.args)try{r=JSON.parse(n.args)}catch{H(`[ToolCall] Failed to parse args for tool "${n.name}": ${n.args}`),r={}}e.push({id:n.id||Fke(),name:n.name,args:r})}return e}function $gn(t,e){return new cr({content:t,tool_calls:e.map(n=>({id:n.id,name:n.name,args:n.args,type:"tool_call"}))})}pe();var YLr=["<|im_end|>","<|im_start|>","<|eot_id|>","<|start_header_id|>","<|end_header_id|>","<end_of_turn>","<start_of_turn>","<|end|>","<|assistant|>","<|user|>","<|system|>","</s>","[INST]","[/INST]","<|endoftext|>","<|end\u2581of\u2581sentence|>","<|END_OF_TURN_TOKEN|>","<|START_OF_TURN_TOKEN|>"],JLr=new RegExp(YLr.map(t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),"g");function Mrt(t){return t.replace(JLr,"")}var Ug=class{constructor(e,n=!1){this.updateCurrentAiMessage=e;this.excludeThinking=n;this.hasOpenThinkBlock=!1;this.fullResponse="";this.errorResponse="";this.wasTruncated=!1;this.tokenUsage=null;this.hasHandledTextLevelThinkTag=!1;this.excludedThinkBlockStart=-1;this.toolCallChunks=new Map;this.accumulatedToolCalls=[];j(`[ThinkBlockStreamer] Created with excludeThinking=${n}`)}handleTextLevelThinkTags(){if(this.excludeThinking){this.handleExcludedThinkTags();return}let e=this.fullResponse.includes("</think>"),n=this.fullResponse.includes("<think>");e&&!n&&!this.hasHandledTextLevelThinkTag&&(this.hasHandledTextLevelThinkTag=!0,W("Detected </think> closing tag without opening <think> tag. This may indicate a misconfigured chat template in LM Studio. Adding opening tag."),this.fullResponse="<think>"+this.fullResponse)}handleExcludedThinkTags(){if(this.excludedThinkBlockStart>=0){let r=this.fullResponse.indexOf("</think>",this.excludedThinkBlockStart);if(r!==-1){let o=this.fullResponse.substring(0,this.excludedThinkBlockStart),i=this.fullResponse.substring(r+8);this.fullResponse=(o+i).trimStart(),this.excludedThinkBlockStart=-1}else this.fullResponse=this.fullResponse.substring(0,this.excludedThinkBlockStart);return}let e=this.fullResponse.indexOf("<think>");if(e!==-1){this.excludedThinkBlockStart=e;let r=this.fullResponse.indexOf("</think>",e);if(r!==-1){let o=this.fullResponse.substring(0,e),i=this.fullResponse.substring(r+8);this.fullResponse=(o+i).trimStart(),this.excludedThinkBlockStart=-1}else this.fullResponse=this.fullResponse.substring(0,e);return}let n=this.fullResponse.indexOf("</think>");n!==-1&&(this.fullResponse=this.fullResponse.substring(n+8).trimStart())}handleClaudeChunk(e){let n="",r=!1;for(let o of e)switch(o.type){case"text":n+=o.text;break;case"thinking":if(r=!0,this.excludeThinking)break;this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),o.thinking!==void 0&&(this.fullResponse+=o.thinking),this.updateCurrentAiMessage(this.fullResponse);break}return n&&this.hasOpenThinkBlock&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),n&&(this.fullResponse+=Mrt(n)),r}handleDeepseekChunk(e){return typeof e.content=="string"&&(this.fullResponse+=Mrt(e.content)),e.additional_kwargs?.reasoning_content?(this.excludeThinking||(this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),e.additional_kwargs.reasoning_content!==void 0&&(this.fullResponse+=e.additional_kwargs.reasoning_content)),!0):!1}handleOpenRouterChunk(e){return e.additional_kwargs?.delta?.reasoning?(this.excludeThinking||(this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),this.fullResponse+=e.additional_kwargs.delta.reasoning),!0):(typeof e.content=="string"&&e.content&&this.hasOpenThinkBlock&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),typeof e.content=="string"&&e.content&&(this.fullResponse+=e.content),!1)}handleToolCallChunks(e){let n=e.tool_call_chunks;if(!(!n||!Array.isArray(n)))for(let r of n){let o=r.index??0,i=this.toolCallChunks.get(o)||{name:"",args:""};r.id&&(i.id=r.id),r.name&&(i.name+=r.name),r.args&&(i.args+=r.args),this.toolCallChunks.set(o,i)}}processChunk(e){Ngn(e).wasTruncated&&(this.wasTruncated=!0);let r=Rgn(e);r&&(this.tokenUsage=r),this.handleToolCallChunks(e);let o=Array.isArray(e.content)||e.additional_kwargs?.delta?.reasoning||e.additional_kwargs?.reasoning_details&&Array.isArray(e.additional_kwargs.reasoning_details)&&e.additional_kwargs.reasoning_details.length>0||e.additional_kwargs?.reasoning_content;this.hasOpenThinkBlock&&!o&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),Array.isArray(e.content)?this.handleClaudeChunk(e.content):e.additional_kwargs?.reasoning_content?this.handleDeepseekChunk(e):o?this.handleOpenRouterChunk(e):this.handleDeepseekChunk(e),this.handleTextLevelThinkTags(),this.updateCurrentAiMessage(this.fullResponse)}processErrorChunk(e){this.errorResponse=Dke(e)}getToolCalls(){return this.accumulatedToolCalls.length>0?this.accumulatedToolCalls:Uke(this.toolCallChunks)}hasToolCalls(){return this.toolCallChunks.size>0||this.accumulatedToolCalls.length>0}setToolCalls(e){this.accumulatedToolCalls=e}buildAIMessage(){let e=this.getToolCalls();return $gn(this.fullResponse,e)}close(){return this.hasOpenThinkBlock&&(this.fullResponse+="</think>"),this.handleTextLevelThinkTags(),this.errorResponse&&(this.fullResponse+=this.errorResponse),this.updateCurrentAiMessage(this.fullResponse),{content:this.fullResponse,wasTruncated:this.wasTruncated,tokenUsage:this.tokenUsage}}};var one=class extends jM{async constructMessages(e){if(!e.contextEnvelope)throw new Error("[LLMChainRunner] Context envelope is required but not available. Cannot proceed with LLM chain.");j("[LLMChainRunner] Using envelope-based context");let n=XS.convert(e.contextEnvelope,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),r=[],o=n.find(a=>a.role==="system");o&&r.push(o);let i=this.chainManager.memoryManager.getMemory();await BM(i,r);let s=n.find(a=>a.role==="user");if(s)if(e.content&&Array.isArray(e.content)){let a=e.content.map(l=>l.type==="text"?{...l,text:s.content}:l);r.push({role:"user",content:a})}else r.push(s);return r}async run(e,n,r,o,i){let s=!1,a=this.chainManager.chatModelManager.getActiveModel();a?s=!a.capabilities?.includes("reasoning"):j("Could not determine model capabilities, defaulting to include thinking blocks");let l=new Ug(r,s);try{let d=await this.constructMessages(e),p=this.chainManager.chatModelManager.getChatModel()?.modelName;zM({messages:d,modelName:p,contextEnvelope:e.contextEnvelope}),j(`Final Request to AI:
`,d);let m=await Jf(()=>this.chainManager.chatModelManager.getChatModel().stream(d,{signal:n.signal}));for await(let h of m){if(n.signal.aborted){j("Stream iteration aborted",{reason:n.signal.reason});break}l.processChunk(h)}}catch(d){(d instanceof Error?d.name:"")==="AbortError"||n.signal.aborted?j("Stream aborted by user",{reason:n.signal.reason}):await this.handleError(d,p=>l.processErrorChunk(p))}let c=l.close(),u={wasTruncated:c.wasTruncated,tokenUsage:c.tokenUsage??void 0};return n.signal.aborted&&n.signal.reason==="new-chat"?(r(""),""):(await this.handleResponse(c.content,e,n,o,r,void 0,void 0,u),c.content)}};gt();ut();async function jke(t,e){let n=`Given the following conversation and a follow up question,
summarize the conversation as context and keep the follow up question unchanged, in its original language.
If the follow up question is unrelated to its preceding messages, return this follow up question directly.
If it is related, then combine the summary and the follow up question to construct a standalone question.
Make sure to keep any [[]] wrapped note titles in the question unchanged.
If there's nothing in the chat history, just return the follow up question.
Chat History:
{chat_history}
Follow Up Input: {question}
Standalone question:`,r=e.map(({role:o,content:i})=>`${o}: ${i}`).join(`
`);return await Jf(async()=>{let o=await N0.instance.getCurrentChainManager().chatModelManager.getChatModelWithTemperature(0),i="",s=await o.stream([{role:"user",content:n.replace("{chat_history}",r).replace("{question}",t)}]);for await(let l of s)i+=T2(l.content);let a=LEe(i);return Xdt(a)})}pe();pe();zu();Se();$M();ine();pe();nA();zu();ha();Se();S3();var h1r=20,eIe=class extends HM{constructor(n,r){super();this.app=n;this.options=r;this.lc_namespace=["miyo_semantic_retriever"];this.client=new jc,this.returnAll=!!r.returnAll,this.finalK=r.maxK>0?r.maxK:h1r,this.minSimilarityScore=r.minSimilarityScore??.1}async getRelevantDocuments(n,r){let o=await this.searchMiyo(n),i=this.deduplicateResults(o),a=this.filterByCopilotPatterns(i).slice(0,this.finalK);return Y().debug&&this.logDebugInfo(n,o,a),a}filterByCopilotPatterns(n){let r=pX(this.app),o=[],i=[];for(let s of n){let a=s.metadata.path;if(s.metadata.fromCurrentVault===!1){o.push(s);continue}r(a)?o.push(s):i.push(a)}if(Y().debug){let s=Array.from(new Set(i));j(`MiyoSemanticRetriever: inclusion/exclusion rules kept ${o.length}/${n.length} chunks`+(s.length>0?`; excluded ${s.join(", ")}`:""))}return o}async searchMiyo(n){try{let r=await this.client.resolveBaseUrl(Ci(Y())),o=Y(),i=this.returnAll||TKt(o)||N9e(this.app,o)?al:Math.min(this.finalK*2,al),s=this.buildSearchFilters();Y().debug&&j("MiyoSemanticRetriever: search params:",{baseUrl:r,limit:i,finalK:this.finalK,minSimilarityScore:this.minSimilarityScore,returnAll:this.returnAll,filters:s});let a=o.miyoSearchAll,l=a?void 0:Mp(this.app),u=(await this.client.search(r,l,n,i,s)).results||[],d=u.filter(f=>this.isScoreAboveThreshold(f));return Y().debug&&j(`MiyoSemanticRetriever: received ${u.length} results, ${d.length} after threshold`),d.map(f=>this.toDocument(f,a))}catch(r){return W(`MiyoSemanticRetriever: search failed: ${r}`),[]}}buildSearchFilters(){if(!this.options.timeRange)return;let{startTime:n,endTime:r}=this.options.timeRange;return[{field:"mtime",gte:n,lte:r}]}toDocument(n,r){let o=o$(this.app,n.path),i=!r||kKt(this.app,n.path),s=n.metadata??{},a=s.chunkId||(n.chunk_index!==void 0?`${o}#${n.chunk_index}`:void 0),l=typeof n.score=="number"?n.score.toFixed(2):"?";return new cu({pageContent:n.chunk_text??"",metadata:{...s,score:n.score,explanation:`miyo ${l}`,path:o,mtime:n.mtime,ctime:n.ctime,title:n.title??"",id:n.id,embeddingModel:n.embedding_model,tags:n.tags??[],extension:n.extension,created_at:n.created_at,nchars:n.nchars,chunkId:a,fromCurrentVault:i}})}isScoreAboveThreshold(n){let r=n.score;return typeof r!="number"||Number.isNaN(r)?!0:r>=this.minSimilarityScore}deduplicateResults(n){let r=new Map,o=i=>{let s=this.getDocumentKey(i);r.has(s)||r.set(s,i)};return n.forEach(o),Y().debug&&r.size!==n.length&&j(`MiyoSemanticRetriever: deduplicated semantic results from ${n.length} to ${r.size}`),Array.from(r.values())}logDebugInfo(n,r,o){j("*** MIYO SEMANTIC RETRIEVER DEBUG INFO: ***"),j("Query: ",n),j("Semantic Chunks: ",r),j("Deduplicated Chunks: ",o);let i=r.reduce((s,a)=>{let l=a.metadata?.score;return typeof l=="number"&&!Number.isNaN(l)?Math.max(s,l):s},0);j("Max Miyo Score: ",i)}getDocumentKey(n){let r=n.metadata??{};return r.chunkId||r.path||r.id||r.title||`${n.pageContent.slice(0,64)}::${n.pageContent.length}`}};Ust();gre();function k0e(t){return{minSimilarityScore:t.minSimilarityScore??.1,maxK:t.maxK,salientTerms:t.salientTerms??[],timeRange:t.timeRange,textWeight:t.textWeight,returnAll:t.returnAll??!1,useRerankerThreshold:t.useRerankerThreshold,tagTerms:t.tagTerms??[]}}var T_=class t{static async createRetriever(e,n,r){let o=r?{...Y(),...r}:Y(),i=k0e(n);if(t.shouldUseMiyo(o)){let a=t.createMiyoRetriever(e,n);return j("RetrieverFactory: Using MiyoSemanticRetriever (standalone)"),{retriever:a,type:"semantic",reason:"Miyo search is enabled"}}if(o.enableSemanticSearchV3){let a=new Bq(e,i);return j("RetrieverFactory: Using MergedSemanticRetriever (semantic search)"),{retriever:a,type:"semantic",reason:"Semantic search is enabled"}}let s=new cC(e,i);return j("RetrieverFactory: Using TieredLexicalRetriever (lexical search)"),{retriever:s,type:"lexical",reason:"Default lexical search"}}static createLexicalRetriever(e,n){return new cC(e,k0e(n))}static createSemanticRetriever(e,n){return t.shouldUseMiyo(Y())?t.createMiyoRetriever(e,n):new Bq(e,k0e(n))}static getRetrieverType(e){let n=e?{...Y(),...e}:Y();return t.shouldUseMiyo(n)||n.enableSemanticSearchV3?"semantic":"lexical"}static shouldUseMiyo(e){return Bu(e)==="miyo"}static isMiyoActive(){return t.shouldUseMiyo(Y())}static createMiyoRetriever(e,n){return new eIe(e,k0e(n))}};I0e();T0e();Brt();Se();ut();FV();var yre=class extends jM{async run(e,n,r,o,i){let s=!1,a=this.chainManager.chatModelManager.getActiveModel();a?s=!a.capabilities?.includes("reasoning"):j("Could not determine model capabilities, defaulting to include thinking blocks");let l=new Ug(r,s);try{let f=e.contextEnvelope;if(!f)throw new Error("[VaultQA] Context envelope is required but not available. Cannot proceed with VaultQA chain.");let m=f.layers.find(D=>D.id==="L5_USER")?.text||e.message,h=this.extractTagTerms(m);j("[VaultQA] Extracted tags before condensing:",h);let g=this.chainManager.memoryManager.getMemory(),v=await g.loadMemoryVariables({}),y=Die(v),w=m;y.length>0&&(j("[VaultQA] Condensing query with chat history for better retrieval"),w=await jke(m,y),j("[VaultQA] Standalone question:",w));let _=Y(),S=h.length>0,C=await new fO(this.chainManager.app,{salientTerms:S?[...h]:[],maxK:_.maxSourceChunks,returnAll:S}).getRelevantDocuments(w),k=T_.isMiyoActive(),T=await T_.createRetriever(this.chainManager.app,{minSimilarityScore:.01,maxK:_.maxSourceChunks,salientTerms:S?[...h]:[],tagTerms:h,returnAll:S},k?{enableMiyo:!1,enableSemanticSearchV3:!1}:{}),P=T.retriever;j(`VaultQA: Using ${T.type} retriever - ${T.reason}`);let E=await P.getRelevantDocuments(w),{filterResults:O,searchResults:$}=zq(C,E),U=[...O,...$],V=U.length>_.maxSourceChunks,K=U.slice(0,_.maxSourceChunks);this.chainManager.storeRetrieverDocuments(K);let se=K.map(D=>{let G=D.metadata?.title||"Untitled",ce=D.metadata?.path||G;return`<${XPe}>
<title>${G}</title>
<path>${ce}</path>
<content>
${DV(D.pageContent??"")}
</content>
</${XPe}>`}).join(`
`),le=[],Q=this.chainManager.chatModelManager.getChatModel(),ne=K.slice(0,Math.max(5,Math.min(20,K.length))).map(D=>({title:D.metadata?.title||D.metadata?.path||"Untitled",path:D.metadata?.path||D.metadata?.title||""})),ee=LSe(ne).join(`
`),ae=V?`
IMPORTANT: The retrieval limit of ${_.maxSourceChunks} documents was reached. ${U.length-_.maxSourceChunks} additional matching documents were omitted. Inform the user: "Note: The retrieval cap was reached \u2014 some matching documents were not included. Upgrade to Copilot Plus for more complete answers."`:"",q=`
Answer the question based only on the following context:
`+se+eun(ee,_.enableInlineCitations)+ae;j("[VaultQA] Using envelope-based context construction with LayerToMessagesConverter");let F=XS.convert(f,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),z=F.find(D=>D.role==="system");z&&le.push({role:VK(Q),content:z.content}),await BM(g,le);let N=F.find(D=>D.role==="user");if(N){let D=q+`
`+N.content;if(e.content&&Array.isArray(e.content)){let G=e.content.map(ce=>ce.type==="text"?{...ce,text:D}:{...ce});le.push({role:"user",content:G})}else le.push({role:"user",content:D})}let R=Q?.modelName;zM({messages:le,modelName:R,contextEnvelope:e.contextEnvelope}),j(`Final Request to AI:
`,le);let X=await Jf(()=>this.chainManager.chatModelManager.getChatModel().stream(le,{signal:n.signal}));for await(let D of X){if(n.signal.aborted){j("VaultQA stream iteration aborted",{reason:n.signal.reason});break}l.processChunk(D)}}catch(f){f.name==="AbortError"||n.signal.aborted?j("VaultQA stream aborted by user",{reason:n.signal.reason}):await this.handleError(f,p=>l.processErrorChunk(p))}let c=l.close(),u={wasTruncated:c.wasTruncated,tokenUsage:c.tokenUsage??void 0};if(n.signal.aborted&&n.signal.reason==="new-chat")return r(""),"";let d=this.addSourcestoResponse(c.content);return await this.handleResponse(d,e,n,o,r,void 0,void 0,u),d}addSourcestoResponse(e){let n=Y();if(!nun(e))return e;let r=this.chainManager.getRetrievedDocuments(),o=Vdt(r).map(i=>({title:i}));return RSe(e,o,n.enableInlineCitations)}extractTagTerms(e){return _3(e)}};Txe();gt();pe();ut();jV();var oF=require("obsidian"),uC=class{static async isImageUrl(e,n){try{let r,o=!1;try{let i=new URL(e),s=i.pathname,a=s.lastIndexOf("."),l=s.lastIndexOf("/");if(a>l&&a>-1&&(r=s.substring(a+1).toLowerCase()),r&&!this.IMAGE_EXTENSIONS.some(u=>u.toLowerCase()===`.${r}`))return H(`Unsupported image format from URL path: .${r}. Supported formats: ${this.IMAGE_EXTENSIONS.join(", ")}`,e),!1;try{let u=(await ks(e,{method:"HEAD",headers:{}})).headers.get("content-type");return u?.startsWith("image/")?!0:(W(`HEAD request succeeded for ${e} but Content-Type (${u}) is not image/*.`),!1)}catch(c){W(`HEAD request failed for URL: ${e}. Proceeding to heuristic check.`,c);let u=i.searchParams,f=[u.has("w")||u.has("width"),u.has("h")||u.has("height"),u.has("format"),u.has("fit"),u.has("quality"),i.pathname.includes("/image/"),i.pathname.includes("/images/"),i.pathname.includes("/img/"),u.has("auto"),u.has("crop")].filter(Boolean).length;return f>=2?(H(`Identified as image based on URL heuristics (indicator count: ${f}): ${e}`),!0):!1}}catch{o=!0;let i=e.lastIndexOf(".");if(i>-1)r=e.substring(i+1).toLowerCase();else return!1}if(o)if(r&&this.IMAGE_EXTENSIONS.some(i=>i.toLowerCase()===`.${r}`)){let i=n.getAbstractFileByPath(e);return i instanceof oF.TFile?i.stat.size>this.MAX_IMAGE_SIZE?(H(`Vault file too large: ${i.stat.size} bytes for path: ${e}`),!1):!0:(H(`File with image extension not found in vault: ${e}.`),!1)}else return r&&H(`Unsupported image format for potential vault path: .${r}. Supported formats: ${this.IMAGE_EXTENSIONS.join(", ")}`,e),!1;return H(`Could not determine image status for URL/path: ${e}`),!1}catch(r){return H(`Unexpected error in isImageUrl for "${e}":`,r),!1}}static async handleVaultImage(e,n){try{if(e.stat.size>this.MAX_IMAGE_SIZE)return H(`Image too large: ${e.stat.size} bytes, skipping: ${e.path}`),null;let r=await n.readBinary(e),o=await this.getMimeType(r,e.extension);if(!o.startsWith("image/"))return H(`Invalid MIME type: ${o}, skipping: ${e.path}`),null;let i=Fv(r);return`data:${o};base64,${i}`}catch(r){return H("Error processing vault image:",r),null}}static async handleWebImage(e){try{let n=await ks(e,{method:"GET",headers:{}});if(!n.ok)return H(`Failed to fetch image: ${n.statusText}, URL: ${e}`),null;let r=n.headers.get("content-type");if(!r?.startsWith("image/"))return H(`Invalid content type: ${r}, URL: ${e}`),null;let o=await n.arrayBuffer();if(o.byteLength>this.MAX_IMAGE_SIZE)return H(`Image too large: ${o.byteLength} bytes, URL: ${e}`),null;let i=Fv(o);return`data:${r};base64,${i}`}catch(n){return H("Error converting web image to base64:",n),null}}static async handleLocalImage(e,n){try{let r=decodeURIComponent(e.replace("app://","")),o=n.getAbstractFileByPath(r);if(!o||!(o instanceof oF.TFile))return H(`Local image not found: ${r}`),null;if(o.stat.size>this.MAX_IMAGE_SIZE)return H(`Image too large: ${o.stat.size} bytes, path: ${r}`),null;let i=await n.readBinary(o),s=await this.getMimeType(i,o.extension);if(!s.startsWith("image/"))return H(`Invalid MIME type: ${s}, path: ${r}`),null;let a=Fv(i);return`data:${s};base64,${a}`}catch(r){return H("Error processing local image:",r),null}}static async imageToBase64(e,n){if(e.startsWith("data:"))return e;if(e.startsWith("attachment:")){let o=e.substring(11),i=n.getAbstractFileByPath(o);return i instanceof oF.TFile?await this.handleVaultImage(i,n):(W(`Could not find attachment file in vault: ${o}`),null)}if(e.startsWith("app://"))return await this.handleLocalImage(e,n);let r=n.getAbstractFileByPath(e);return r instanceof oF.TFile?await this.handleVaultImage(r,n):await this.handleWebImage(e)}static async convertToBase64(e,n){let r=await this.imageToBase64(e,n);return r?{type:"image_url",image_url:{url:r}}:(H(`Failed to convert image to base64: ${e}`),null)}static async getMimeType(e,n){let r=new Uint8Array(e.slice(0,4));if(r[0]===255&&r[1]===216)return"image/jpeg";if(r[0]===137&&r[1]===80)return"image/png";if(r[0]===71&&r[1]===73)return"image/gif";if(r[0]===82&&r[1]===73)return"image/webp";if(r[0]===66&&r[1]===77)return"image/bmp";if(r[0]===60&&r[1]===115)throw new Error("SVG files are not supported");let o=this.MIME_TYPES[n.toLowerCase()];if(!o){let i=`Unsupported image extension: ${n}`;throw H(i),new Error(i)}return o}};uC.IMAGE_EXTENSIONS=[".jpg",".jpeg",".png",".gif",".webp",".bmp"],uC.MAX_IMAGE_SIZE=3*1024*1024,uC.MIME_TYPES={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp"};var iF=class t{static async processUrlBatch(e,n,r){try{let i=(await Promise.all(e.map(a=>t.processSingleUrl(a,n,r)))).filter(a=>a!==null),s=n.map(a=>`Image read failed for: ${a}`);return{successfulImages:i,failureDescriptions:s}}catch(o){return H("Error processing URL batch:",o),{successfulImages:[],failureDescriptions:e.map(i=>`Image read failed for: ${i}`)}}}static async processSingleUrl(e,n,r){try{if(!await uC.isImageUrl(e,r))return null;let o=await uC.convertToBase64(e,r);return o||(n.push(e),null)}catch(o){return H(`Failed to process image: ${e}`,o),n.push(e),null}}static async processChatImageBatch(e,n,r){try{let o=e.filter(l=>l.type==="image_url"&&!!l.image_url?.url),s=(await Promise.all(o.map(l=>t.processChatSingleImage(l,n,r)))).filter(l=>l!==null),a=n.map(l=>`Image read failed for: ${l}`);return{successfulImages:s,failureDescriptions:a}}catch(o){H("Error processing chat image batch:",o);let i=e.filter(s=>s.type==="image_url"&&!!s.image_url?.url).map(s=>s.image_url.url);return{successfulImages:[],failureDescriptions:i.map(s=>`Image read failed for: ${s}`)}}}static async processChatSingleImage(e,n,r){try{let o=await uC.convertToBase64(e.image_url.url,r);return o||(n.push(e.image_url.url),null)}catch(o){return H(`Failed to process chat image: ${e.image_url.url}`,o),n.push(e.image_url.url),null}}static showFailedImagesNotice(e){e.length>0&&new oF.Notice(`Failed to process images:
${e.join(`
`)}`)}};pe();vc();Se();Se();gt();pe();rk();function P0e(){return Cvt()||Y()?.userSystemPrompt||""}function pO(){let t=P0e();if(EN())return t;let n=vct;return t?`${n}
<user_custom_instructions>
${t}
</user_custom_instructions>`:n}async function H0(t){let e=pO();if(!t)return j("No UserMemoryManager provided to getSystemPromptWithMemory"),e;let n=await t.getUserMemoryPrompt();return n?`${n}
${e}`:e}var Hq=require("obsidian");De();pe();Se();Pa();var sF=class{diff(e,n,r={}){let o;typeof r=="function"?(o=r,r={}):"callback"in r&&(o=r.callback);let i=this.castInput(e,r),s=this.castInput(n,r),a=this.removeEmpty(this.tokenize(i,r)),l=this.removeEmpty(this.tokenize(s,r));return this.diffWithOptionsObj(a,l,r,o)}diffWithOptionsObj(e,n,r,o){var i;let s=y=>{if(y=this.postProcess(y,r),o){setTimeout(function(){o(y)},0);return}else return y},a=n.length,l=e.length,c=1,u=a+l;r.maxEditLength!=null&&(u=Math.min(u,r.maxEditLength));let d=(i=r.timeout)!==null&&i!==void 0?i:1/0,f=Date.now()+d,p=[{oldPos:-1,lastComponent:void 0}],m=this.extractCommon(p[0],n,e,0,r);if(p[0].oldPos+1>=l&&m+1>=a)return s(this.buildValues(p[0].lastComponent,n,e));let h=-1/0,g=1/0,v=()=>{for(let y=Math.max(h,-c);y<=Math.min(g,c);y+=2){let w,_=p[y-1],S=p[y+1];_&&(p[y-1]=void 0);let I=!1;if(S){let k=S.oldPos-y;I=S&&0<=k&&k<a}let C=_&&_.oldPos+1<l;if(!I&&!C){p[y]=void 0;continue}if(!C||I&&_.oldPos<S.oldPos?w=this.addToPath(S,!0,!1,0,r):w=this.addToPath(_,!1,!0,1,r),m=this.extractCommon(w,n,e,y,r),w.oldPos+1>=l&&m+1>=a)return s(this.buildValues(w.lastComponent,n,e))||!0;p[y]=w,w.oldPos+1>=l&&(g=Math.min(g,y-1)),m+1>=a&&(h=Math.max(h,y+1))}c++};if(o)(function y(){setTimeout(function(){if(c>u||Date.now()>f)return o(void 0);v()||y()},0)})();else for(;c<=u&&Date.now()<=f;){let y=v();if(y)return y}}addToPath(e,n,r,o,i){let s=e.lastComponent;return s&&!i.oneChangePerToken&&s.added===n&&s.removed===r?{oldPos:e.oldPos+o,lastComponent:{count:s.count+1,added:n,removed:r,previousComponent:s.previousComponent}}:{oldPos:e.oldPos+o,lastComponent:{count:1,added:n,removed:r,previousComponent:s}}}extractCommon(e,n,r,o,i){let s=n.length,a=r.length,l=e.oldPos,c=l-o,u=0;for(;c+1<s&&l+1<a&&this.equals(r[l+1],n[c+1],i);)c++,l++,u++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return u&&!i.oneChangePerToken&&(e.lastComponent={count:u,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=l,c}equals(e,n,r){return r.comparator?r.comparator(e,n):e===n||!!r.ignoreCase&&e.toLowerCase()===n.toLowerCase()}removeEmpty(e){let n=[];for(let r=0;r<e.length;r++)e[r]&&n.push(e[r]);return n}castInput(e,n){return e}tokenize(e,n){return Array.from(e)}join(e){return e.join("")}postProcess(e,n){return e}get useLongestToken(){return!1}buildValues(e,n,r){let o=[],i;for(;e;)o.push(e),i=e.previousComponent,delete e.previousComponent,e=i;o.reverse();let s=o.length,a=0,l=0,c=0;for(;a<s;a++){let u=o[a];if(u.removed)u.value=this.join(r.slice(c,c+u.count)),c+=u.count;else{if(!u.added&&this.useLongestToken){let d=n.slice(l,l+u.count);d=d.map(function(f,p){let m=r[c+p];return m.length>f.length?m:f}),u.value=this.join(d)}else u.value=this.join(n.slice(l,l+u.count));l+=u.count,u.added||(c+=u.count)}}return o}};function H_n(t,e){if(typeof t=="function")e.callback=t;else if(t)for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}var jst=class extends sF{constructor(){super(...arguments),this.tokenize=YFr}equals(e,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!e.includes(`
`))&&(e=e.trim()),(!r.newlineIsToken||!n.includes(`
`))&&(n=n.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(e.endsWith(`
`)&&(e=e.slice(0,-1)),n.endsWith(`
`)&&(n=n.slice(0,-1))),super.equals(e,n,r)}},W_n=new jst;function Bst(t,e,n){return n=H_n(n,{ignoreWhitespace:!0}),W_n.diff(t,e,n)}function YFr(t,e){e.stripTrailingCr&&(t=t.replace(/\r\n/g,`
`));let n=[],r=t.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let o=0;o<r.length;o++){let i=r[o];o%2&&!e.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n}var zst=class extends sF{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}},V_n=new zst;function Hst(t,e,n){return V_n.diff(t,e,n)}Re();var W0=require("obsidian"),Tt=L(B());yt();OP();function q_n(t){let e=[],n=[];return t.forEach(r=>{r.added||r.removed?n.push(r):(n.length>0&&(e.push(n),n=[]),e.push([r]))}),n.length>0&&e.push(n),e}ut();Hl();function JFr(t,e){let n=o=>o.split(/(\s+)/).filter(Boolean);return Hst(n(t),n(e)).map(o=>({value:o.value.join(""),added:o.added,removed:o.removed}))}function vre(t){let e=t.split(`
`);return e.length>0&&e[e.length-1]===""&&e.pop(),e}function K_n(t){let e=[],n=0;for(;n<t.length;){let r=t[n];if(!r.added&&!r.removed)vre(r.value).forEach(o=>{e.push({original:o,modified:o,isUnchanged:!0})}),n++;else if(r.removed){let o=t[n+1];if(o?.added){let i=vre(r.value),s=vre(o.value),a=Math.max(i.length,s.length);for(let l=0;l<a;l++)e.push({original:i[l]??null,modified:s[l]??null,isUnchanged:!1});n+=2}else vre(r.value).forEach(i=>{e.push({original:i,modified:null,isUnchanged:!1})}),n++}else r.added&&vre(r.value).forEach(o=>{e.push({original:null,modified:o,isUnchanged:!1})}),n++}return e}var G_n=(0,Tt.memo)(({original:t,modified:e,side:n})=>{let r=JFr(t,e);return Tt.default.createElement("span",null,r.map((o,i)=>{if(n==="original"){if(o.removed)return Tt.default.createElement("span",{key:i,className:"tw-bg-error tw-text-error"},o.value);if(o.added)return null}else{if(o.added)return Tt.default.createElement("span",{key:i,className:"tw-bg-success tw-text-success"},o.value);if(o.removed)return null}return Tt.default.createElement("span",{key:i},o.value)}))});G_n.displayName="WordDiffSpan";var wre=(0,Tt.memo)(({row:t,side:e})=>{let n=e==="original"?t.original:t.modified,r=e==="original"?t.modified:t.original;return n===null?Tt.default.createElement("span",{className:"tw-text-muted"},"\xA0"):t.isUnchanged?Tt.default.createElement("span",{className:"tw-text-normal"},n||"\xA0"):r!==null?Tt.default.createElement(G_n,{original:t.original,modified:t.modified,side:e}):Tt.default.createElement("span",{className:e==="original"?"tw-bg-error tw-text-error":"tw-bg-success tw-text-success"},n||"\xA0")});wre.displayName="DiffCell";var bre="obsidian-copilot-apply-view",A0e=class extends W0.ItemView{constructor(n){super(n);this.root=null;this.state=null;this.result=null}getViewType(){return bre}getDisplayText(){return"Preview Changes"}async setState(n){this.state=n,this.render()}async onOpen(){this.render()}async onClose(){this.root&&(this.root.unmount(),this.root=null),this.state?.resultCallback?.(this.result?this.result:"aborted")}render(){if(!this.state)return;let n=this.containerEl.children[1];n.empty();let r=n.createDiv();this.root||(this.root=Er(r,this.app)),this.root.render(Tt.default.createElement(XFr,{app:this.app,state:this.state,close:o=>{this.result=o,this.leaf.detach()}}))}},Z_n=(0,Tt.memo)(({block:t})=>{let e=(0,Tt.useMemo)(()=>K_n(t),[t]);return Tt.default.createElement("div",{className:"tw-grid tw-grid-cols-2 tw-gap-2"},Tt.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},e.map((n,r)=>Tt.default.createElement("div",{key:r,className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},Tt.default.createElement(wre,{row:n,side:"original"})))),Tt.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},e.map((n,r)=>Tt.default.createElement("div",{key:r,className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},Tt.default.createElement(wre,{row:n,side:"modified"})))))});Z_n.displayName="SideBySideBlock";var Y_n=(0,Tt.memo)(({block:t})=>{let e=t.some(r=>r.added||r.removed),n=(0,Tt.useMemo)(()=>K_n(t),[t]);return e?Tt.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Tt.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},Tt.default.createElement("div",{className:"tw-mb-1 tw-text-xs tw-font-medium tw-text-muted"},"Original"),Tt.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},n.map((r,o)=>r.original!==null?Tt.default.createElement("div",{key:o},Tt.default.createElement(wre,{row:r,side:"original"})):null))),Tt.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},Tt.default.createElement("div",{className:"tw-mb-1 tw-text-xs tw-font-medium tw-text-muted"},"Modified"),Tt.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},n.map((r,o)=>r.modified!==null?Tt.default.createElement("div",{key:o},Tt.default.createElement(wre,{row:r,side:"modified"})):null)))):Tt.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-px-2 tw-py-1 tw-font-mono tw-text-sm tw-text-normal"},t.map((r,o)=>Tt.default.createElement("span",{key:o},r.value)))});Y_n.displayName="SplitBlock";var XFr=({app:t,state:e,close:n})=>{let r=e.simple??!1,[o,i]=(0,Tt.useState)(()=>e.changes.map(y=>({...y,accepted:null}))),[s,a]=(0,Tt.useState)(()=>Y().diffViewMode??"split"),l=y=>{a(y),At("diffViewMode",y)},c=q_n(o),u=(0,Tt.useRef)([]);if(!e||!e.changes)return H("Invalid state:",e),Tt.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-col tw-items-center tw-justify-center"},Tt.default.createElement("div",{className:"tw-text-error"},"Error: Invalid state - missing changes"),Tt.default.createElement(oe,{onClick:()=>n("failed"),className:"tw-mt-4"},"Close"));let d=async()=>{try{let y=o.map(_=>_.accepted===null?{..._,accepted:!0}:_),w=await m(y);n(w?"accepted":"failed")}catch(y){H("Error applying changes:",y),new W0.Notice(`Error applying changes: ${y instanceof Error?y.message:String(y)}`),n("failed")}},f=async()=>{try{let y=o.map(_=>_.accepted===null?{..._,accepted:!1}:_),w=await m(y,!1);n(w?"rejected":"failed")}catch(y){H("Error applying changes:",y),new W0.Notice(`Error applying changes: ${y instanceof Error?y.message:String(y)}`),n("failed")}},p=async y=>{let w=t.vault.getAbstractFileByPath(y);if(w)return w;if(y.includes("/")){let _=y.split("/").slice(0,-1).join("/");await ao(t.vault,_)}return await t.vault.create(y,"")},m=async(y,w=!0)=>{let _=y.filter(I=>I.added?I.accepted===!0:I.removed?I.accepted===!1:!0).map(I=>I.value).join(""),S=await p(e.path);return!S||!(S instanceof W0.TFile)?(H("Error in getting file",e.path),new W0.Notice("Failed to create file"),!1):(await t.vault.modify(S,_),w&&new W0.Notice("Changes applied successfully"),!0)},h=y=>{if(!c)return;let w=-1;for(let _=y+1;_<c.length;_++){let S=c[_],I=S.some(k=>k.added||k.removed),C=S.some(k=>(k.added||k.removed)&&k.accepted===null);if(I&&C){w=_;break}}w!==-1&&u.current[w]&&u.current[w]?.scrollIntoView({behavior:"smooth",block:"center"})},g=y=>{i(w=>{let _=[...w],S=c?.[y];return S&&S.forEach(I=>{let C=_.findIndex(k=>k===I);C!==-1&&(_[C]={..._[C],accepted:!0})}),_}),window.setTimeout(()=>h(y),0)},v=y=>{i(w=>{let _=[...w],S=c?.[y];return S&&S.forEach(I=>{let C=_.findIndex(k=>k===I);C!==-1&&(_[C]={..._[C],accepted:!1})}),_}),window.setTimeout(()=>h(y),0)};return Tt.default.createElement("div",{className:"tw-relative tw-flex tw-h-full tw-flex-col"},Tt.default.createElement("div",{className:"tw-fixed tw-bottom-4 tw-left-1/2 tw-z-[9999] tw-flex tw-gap-2 tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-secondary tw-p-2 tw-shadow-lg"},Tt.default.createElement(oe,{variant:"destructive",size:"sm",onClick:xn(f)},Tt.default.createElement(pn,{className:"tw-size-4"}),"Reject"),Tt.default.createElement(oe,{variant:"success",size:"sm",onClick:xn(d)},Tt.default.createElement(Hr,{className:"tw-size-4"}),"Accept")),Tt.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-border-b tw-border-solid tw-border-border tw-p-2"},Tt.default.createElement("div",{className:"tw-text-sm tw-font-medium"},e.path),Tt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Tt.default.createElement("span",{className:J("tw-text-xs",s==="split"?"tw-font-medium tw-text-normal":"tw-text-muted")},"Split"),Tt.default.createElement(fp,{checked:s==="side-by-side",onCheckedChange:y=>l(y?"side-by-side":"split")}),Tt.default.createElement("span",{className:J("tw-text-xs",s==="side-by-side"?"tw-font-medium tw-text-normal":"tw-text-muted")},"Side-by-side"))),Tt.default.createElement("div",{className:"tw-flex-1 tw-overflow-auto tw-p-2"},c?.map((y,w)=>{let _=y.some(I=>I.added||I.removed),S=_?y.every(I=>!I.added&&!I.removed||I.accepted===!0)?"accepted":y.every(I=>!I.added&&!I.removed||I.accepted===!1)?"rejected":"undecided":"unchanged";return Tt.default.createElement("div",{key:w,ref:I=>u.current[w]=I,className:J("tw-mb-4 tw-overflow-hidden tw-rounded-md")},S==="accepted"?Tt.default.createElement("div",{className:"tw-flex-1 tw-whitespace-pre-wrap tw-px-2 tw-py-1 tw-font-mono tw-text-sm tw-text-normal"},y.filter(I=>!I.removed).map((I,C)=>Tt.default.createElement("div",{key:C},I.value))):S==="rejected"?Tt.default.createElement("div",{className:"tw-flex-1 tw-whitespace-pre-wrap tw-px-2 tw-py-1 tw-font-mono tw-text-sm tw-text-normal"},y.filter(I=>!I.added).map((I,C)=>Tt.default.createElement("div",{key:C},I.value))):s==="side-by-side"?Tt.default.createElement(Z_n,{block:y}):Tt.default.createElement(Y_n,{block:y}),!r&&_&&S==="undecided"&&Tt.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-end tw-border-[0px] tw-border-t tw-border-solid tw-border-border tw-p-2"},Tt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Tt.default.createElement(oe,{variant:"destructive",size:"sm",onClick:()=>v(w)},Tt.default.createElement(pn,{className:"tw-size-4"}),"Reject"),Tt.default.createElement(oe,{variant:"success",size:"sm",onClick:()=>g(w)},Tt.default.createElement(Hr,{className:"tw-size-4"}),"Accept"))),!r&&_&&(S==="accepted"||S==="rejected")&&Tt.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-end tw-border-[0px] tw-border-t tw-border-solid tw-border-border tw-p-2"},Tt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Tt.default.createElement("div",{className:"tw-mr-2 tw-text-sm tw-font-medium"},S==="accepted"?Tt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1 tw-text-success"},Tt.default.createElement(Hr,{className:"tw-size-4"}),Tt.default.createElement("div",null,"Accepted")):Tt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1 tw-text-error"},Tt.default.createElement(pn,{className:"tw-size-4"}),Tt.default.createElement("div",null,"Rejected"))),Tt.default.createElement(oe,{variant:"secondary",size:"sm",onClick:()=>{i(I=>{let C=[...I],k=c?.[w];return k&&k.forEach(T=>{let P=C.findIndex(E=>E===T);P!==-1&&(C[P]={...C[P],accepted:null})}),C})}},"Revert"))))})))};ap();bv();function gi(t){return cS(async e=>{let n=await t.func(e);return typeof n=="string"?n:JSON.stringify(n)},{name:t.name,description:t.description,schema:t.schema})}ut();Se();pe();async function X_n(t,e){let n=t.vault.getAbstractFileByPath(e);if(n&&n instanceof Hq.TFile)return n;if(n&&!(n instanceof Hq.TFile))throw new Error(`Path "${e}" exists but is not a file`);try{let r=e.includes("/")?e.split("/").slice(0,-1).join("/"):"";if(r&&await ao(t.vault,r),n=t.vault.getAbstractFileByPath(e),n&&n instanceof Hq.TFile)return n;if(n=await t.vault.create(e,""),!(n instanceof Hq.TFile))throw new Error(`Failed to create file: unexpected type returned for "${e}"`);return n}catch(r){let o=r instanceof Error?r.message:String(r);throw new Error(`Failed to get or create file "${e}": ${o}`)}}async function Q_n(t,e,n,r=!1){let o=await X_n(t,e),i=t.workspace.getActiveFile();o&&(!i||i.path!==e)&&await t.workspace.getLeaf().openFile(o);let s="";o&&(s=await t.vault.read(o));let a=Bst(s,n,{newlineIsToken:!0});return new Promise(l=>{t.workspace.getLeaf(!0).setViewState({type:bre,active:!0,state:{changes:a,path:e,simple:r,resultCallback:u=>{l(u)}}})})}var QFr=x.object({path:x.string().describe(`(Required) The path to the file to write to.
The path must end with explicit file extension, such as .md or .canvas .
Prefer to create new files in existing folders or root folder unless the user's request specifies otherwise.
The path must be relative to the root of the vault.`),content:x.union([x.string(),x.object({}).loose()]).describe(`(Required) The content to write to the file. Can be either a string or an object.
ALWAYS provide the COMPLETE intended content of the file, without any truncation or omissions.
You MUST include ALL parts of the file, even if they haven't been modified.
# For string content
* Use when writing text files like .md, .txt, etc.
# For object content
* Use when writing structured data files like .json, .canvas, etc.
* The object will be automatically converted to JSON string format
# Canvas JSON Format (JSON Canvas spec 1.0)
Required node fields: id, type, x, y, width, height
Node types: "text" (needs text), "file" (needs file), "link" (needs url), "group" (optional label)
Optional node fields: color (hex #FF0000 or preset "1"-"6"), subpath (file nodes, starts with #)
Required edge fields: id, fromNode, toNode
Optional edge fields: fromSide/toSide ("top"/"right"/"bottom"/"left"), fromEnd/toEnd ("none"/"arrow"), color, label
All IDs must be unique. Edge nodes must reference existing node IDs.
Example:
{
"nodes": [
{"id": "1", "type": "text", "text": "Hello", "x": 0, "y": 0, "width": 200, "height": 50},
{"id": "2", "type": "file", "file": "note.md", "subpath": "#heading", "x": 250, "y": 0, "width": 200, "height": 100, "color": "2"},
{"id": "3", "type": "group", "label": "Group", "x": 0, "y": 100, "width": 300, "height": 150}
],
"edges": [
{"id": "e1-2", "fromNode": "1", "toNode": "2", "fromSide": "right", "toSide": "left", "color": "3", "label": "links to"}
]
}`),confirmation:x.union([x.boolean(),x.string()]).optional().describe("(Optional) Hint for confirmation preference. Note: preview is always shown unless the user has enabled auto-accept in settings.")}),O0e=t=>gi({name:"writeFile",description:`Request to write content to a file at the specified path and show the changes in a Change Preview UI.
# Steps to find the the target path
1. Extract the target file information from user message and find out the file path from the context.
2. If target file is not specified, use the active note as the target file.
3. If still failed to find the target file or the file path, ask the user to specify the target file.
`,schema:QFr,func:async({path:e,content:n,confirmation:r=!0})=>{let o=$Ee(e);o!==e&&(W(`Filename too long, truncated for filesystem compatibility: "${e}" \u2192 "${o}"`),e=o);let i=typeof n=="string"?n:JSON.stringify(n,null,2);if(Y().autoAcceptEdits)try{let c=await X_n(t,e);return await t.vault.modify(c,i),{result:"accepted",message:"File changes applied without preview. Do not retry or attempt alternative approaches to modify this file in response to the current user request."}}catch(c){return{result:"failed",message:`Error writing to file without preview: ${c instanceof Error?c.message:String(c)}`}}let l=await Q_n(t,e,i);return{result:l,message:`File change result: ${l}. Do not retry or attempt alternative approaches to modify this file in response to the current user request.`}}}),e2r=x.object({path:x.string().describe("(Required) The path of the file to modify (relative to the root of the vault and include the file extension)."),oldText:x.string().describe(`(Required) The exact text to find and replace. Must match the file content exactly, including whitespace and indentation.
Fuzzy matching handles minor differences like trailing spaces or smart quotes, but the overall structure must be correct.
To make the match unique, include enough surrounding context lines (not just the changed line).`),newText:x.string().describe("(Required) The new text to replace the old text with. Can be empty string to delete the old text.")});function Wst(t){return t.replace(/\r\n/g,`
`).replace(/\r/g,`
`)}function M0e(t){return t.normalize("NFKC").split(`
`).map(e=>e.trimEnd()).join(`
`).replace(/[\u2018\u2019]/g,"'").replace(/[\u201C\u201D]/g,'"').replace(/[\u2010-\u2015\u2212]/g,"-").replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g," ")}function E0e(t,e){if(!e)return 0;let n=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)n++,r+=1;return n}function t2r(t){return t.charCodeAt(0)===65279?{content:t.slice(1),hasBOM:!0}:{content:t,hasBOM:!1}}function n2r(t,e,n){let r=E0e(t,e);if(r>0)return{found:!0,occurrences:r,workingContent:t,workingSearch:e,workingReplace:n,usedFuzzyMatch:!1};let o=M0e(t),i=M0e(e),s=E0e(o,i);if(s>0)return{found:!0,occurrences:s,workingContent:o,workingSearch:i,workingReplace:n,usedFuzzyMatch:!0};if(e.endsWith(`
`)){let a=e.slice(0,-1),l=n.endsWith(`
`)?n.slice(0,-1):n,c=E0e(t,a);if(c>0)return{found:!0,occurrences:c,workingContent:t,workingSearch:a,workingReplace:l,usedFuzzyMatch:!1};let u=M0e(a),d=E0e(o,u);if(d>0)return{found:!0,occurrences:d,workingContent:o,workingSearch:u,workingReplace:l,usedFuzzyMatch:!0}}return{found:!1,occurrences:0,workingContent:o,workingSearch:i,workingReplace:n,usedFuzzyMatch:!0}}function J_n(t,e,n){let r=n,o=0;for(let i=0;i<e.length;i++){let s=e[i].length,a=t[i]??"",l=a.length;if(r<=s){if(r===s)return o+l;let c=0,u=0;for(;u<a.length&&c<r;){let d=a[u].normalize("NFKC").length;if(c+d>r)break;c+=d,u++}return o+u}r-=s+1,o+=l+1}return o}function r2r(t,e,n){let{content:r,hasBOM:o}=t2r(t),i=(r.match(/\r\n/g)||[]).length,s=(r.match(/(?<!\r)\n/g)||[]).length,a=i>s,l=Wst(r),c=Wst(e),u=Wst(n),d=n2r(l,c,u);if(!d.found)return{ok:!1,reason:"NOT_FOUND"};if(d.occurrences>1)return{ok:!1,reason:"AMBIGUOUS",occurrences:d.occurrences};let f,p;if(d.usedFuzzyMatch){let h=l.split(`
`),g=d.workingContent.split(`
`),v=d.workingContent.indexOf(d.workingSearch);if(f=J_n(h,g,v),p=J_n(h,g,v+d.workingSearch.length),f>=p)return{ok:!1,reason:"NOT_FOUND"};if(M0e(l.substring(f,p))!==d.workingSearch)return{ok:!1,reason:"NOT_FOUND"}}else f=l.indexOf(d.workingSearch),p=f+d.workingSearch.length;let m=l.substring(0,f)+d.workingReplace+l.substring(p);return a&&(m=m.replace(/\n/g,`\r
`)),o&&(m="\uFEFF"+m),{ok:!0,content:m}}var exn=t=>gi({name:"editFile",description:"Request to make a targeted change to an existing file by specifying the exact text to find and its replacement. Use this tool for precise, surgical edits to specific parts of a file.",schema:e2r,func:async({path:e,oldText:n,newText:r})=>{let o=$Ee(e),i=t.vault.getAbstractFileByPath(o);if(!i||!(i instanceof Hq.TFile))return{result:"failed",message:`File not found at path: ${o}. Please check the file path and try again.`};try{let s=await t.vault.read(i),a=r2r(s,n,r);if(!a.ok)return a.reason==="NOT_FOUND"?{result:"failed",message:`Could not find the specified text in ${o}. The oldText must match the file content \u2014 try including more surrounding context lines to locate the right spot.`}:{result:"failed",message:`Found ${a.occurrences} occurrences of the search text in ${o}. The text must be unique \u2014 add more surrounding context to make it unambiguous.`};let l=a.content;if(s===l)return{result:"accepted",message:`No changes made to ${o}. The replacement produced identical content. Use writeFile if the file needs a broader rewrite.`};if(Y().autoAcceptEdits)return await t.vault.modify(i,l),{result:"accepted",message:"File changes applied without preview. Do not retry or attempt alternative approaches to modify this file in response to the current user request."};let u=await Q_n(t,o,l,!0);return{result:u,message:`File change result: ${u}. Do not retry or attempt alternative approaches to modify this file in response to the current user request.`}}catch(s){return{result:"failed",message:`Error modifying ${o}: ${s}. Please check the file path and try again.`}}}});Ixe();OSe();Se();var txn=require("obsidian"),o2r="obsidian",i2r=["/Applications/Obsidian.app/Contents/MacOS/obsidian","/Applications/Obsidian.app/Contents/MacOS/Obsidian"],s2r=15e3,a2r=1048576;function Vst(){let t=txn.Platform;return!!(t.isDesktopApp??t.isDesktop)}function l2r(){let t=window;if(typeof t.require!="function")throw new Error("Node require is unavailable in this runtime. Obsidian CLI commands require the desktop app.");return t.require}function c2r(){let e=l2r()("child_process");if(typeof e.execFile!="function")throw new Error("Failed to resolve child_process.execFile");return e.execFile}function u2r(t){return t.replace(/\n/g,"\\n").replace(/\t/g,"\\t")}function d2r(){let e=window.process?.env;return e?[e.OBSIDIAN_CLI_BINARY,e.OBSIDIAN_CLI_PATH].map(r=>r?.trim()||"").filter(Boolean):[]}function f2r(t){let e=t?.trim();if(e)return[e];let n=[...d2r(),o2r,...i2r];return Array.from(new Set(n.map(r=>r.trim()).filter(Boolean)))}function p2r(t){let e=[],n=t.vault?.trim();n&&e.push(`vault=${n}`),e.push(t.command);let r=Object.entries(t.params||{});r.sort(([o],[i])=>o.localeCompare(i));for(let[o,i]of r)if(i!=null){if(typeof i=="boolean"){i&&e.push(o);continue}e.push(`${o}=${u2r(String(i))}`)}return e}function m2r(t){return typeof t=="number"?t:null}async function h2r(t,e,n,r,o,i,s){let a=Date.now();return await new Promise(l=>{t(n,r,{timeout:o,maxBuffer:i,windowsHide:!0},(c,u,d)=>{let f=Date.now()-a;if(c){l({command:e,args:r,binary:n,attemptedBinaries:[...s],ok:!1,stdout:u||"",stderr:d||"",exitCode:m2r(c.code),errorCode:c.code??null,signal:c.signal??null,durationMs:f});return}l({command:e,args:r,binary:n,attemptedBinaries:[...s],ok:!0,stdout:u||"",stderr:d||"",exitCode:0,errorCode:null,signal:null,durationMs:f})})})}async function V0(t){let e=t.command?.trim();if(!e)throw new Error("Obsidian CLI command is required");if(!Vst())throw new Error("Obsidian CLI commands are only supported in desktop Obsidian.");let n=p2r({...t,command:e}),r=t.timeoutMs??s2r,o=t.maxBufferBytes??a2r,i=c2r(),s=f2r(t.binary),a=[],l=null;for(let c of s){a.push(c);let u=await h2r(i,e,c,n,r,o,a);if(l=u,u.ok||u.errorCode!=="ENOENT")return u}if(l)return l;throw new Error("Obsidian CLI execution failed before process spawn.")}async function nxn(t){return await V0({command:"daily:read",vault:t})}async function rxn(t){return await V0({command:"random:read",vault:t})}ha();ap();function g2r(t){return typeof t=="object"&&t!==null&&"children"in t&&"path"in t}function y2r(t){return typeof t=="object"&&t!==null&&"path"in t&&!("children"in t)}function v2r(t){let e=t.split(".");return e.length>1&&e.pop()?.toLowerCase()||""}function qst(t,e,n=!0){let r=[],o={},i={},{inclusions:s,exclusions:a}=Fi();for(let c of e.children)if(y2r(c)){if(ii(t,c,s,a)){n&&r.push(c.name);let u=v2r(c.name)||"unknown";u&&(o[u]=(o[u]||0)+1)}}else if(g2r(c)){let u=qst(t,c,n);if(Object.keys(u).length>0&&(i[c.name]=u[c.name],u[c.name].extensionCounts))for(let[d,f]of Object.entries(u[c.name].extensionCounts))o[d]=(o[d]||0)+f}let l={};return Object.keys(o).length>0&&(l.extensionCounts=o),n&&r.length>0&&(l.files=r),Object.keys(i).length>0&&(l.subFolders=i),Object.keys(l).length===0?{}:e.name?{[e.name]:l}:{vault:l}}var oxn=(t,e)=>gi({name:"getFileTree",description:"Get the file tree as a nested structure of folders and files",schema:x.object({}),func:async()=>{let n=qst(t,e,!0),r=`A JSON represents the file tree as a nested structure:
* The root object has a key "vault" which contains a FileTreeNode object.
* Each FileTreeNode has these properties:
* files: An array of filenames in the current directory (if any files exist)
* subFolders: An object mapping folder names to their FileTreeNode objects (if any subfolders exist)
* extensionCounts: An object with counts of file extensions in this folder and all subfolders
`,o=JSON.stringify(n);if(o.length>5e5){let i=qst(t,e,!1);return r+JSON.stringify(i)}return r+o}});ap();var Wq=require("obsidian");pe();Se();Is();ut();oi();var mO=class{constructor(e){this.recentConversationsContent="";this.savedMemoriesContent="";this.isUpdatingMemory=!1;this.app=e}async loadMemory(){try{let e=O2(),n=this.app.vault.getAbstractFileByPath(this.getRecentConversationFilePath(e));n instanceof Wq.TFile?this.recentConversationsContent=await this.app.vault.read(n):(this.recentConversationsContent="",j("[UserMemoryManager] Recent Conversations file not found, skipping memory load"));let r=this.app.vault.getAbstractFileByPath(this.getSavedMemoriesFilePath(e));r instanceof Wq.TFile?this.savedMemoriesContent=await this.app.vault.read(r):(this.savedMemoriesContent="",j("[UserMemoryManager] Saved Memories file not found, skipping saved memory load"))}catch(e){H("[UserMemoryManager] Error reading memory files:",e),this.recentConversationsContent="",this.savedMemoriesContent=""}}addRecentConversation(e,n){if(!Y().enableRecentConversations){W("[UserMemoryManager] Recent history referencing is disabled, skipping analysis");return}if(e.length===0){W("[UserMemoryManager] No messages to analyze for user memory");return}this.updateMemory(e,n).catch(o=>{H("[UserMemoryManager] Background user memory operation failed:",o)})}async updateSavedMemory(e,n){if(!Y().enableSavedMemory)return{error:"Saved memory is disabled, skipping save"};if(!e||e.trim()==="")return{error:"No content provided for saved memory"};if(!n)return{error:"No chat model available, skipping save"};try{let o=O2();await this.ensureMemoryFolderExists(o);let i=this.getSavedMemoriesFilePath(o);return{...await this.updateSavedMemoryFile(i,e,n),filePath:i}}catch(o){return{error:"Error saving memory: "+(o instanceof Error?o.message:String(o))}}}async getUserMemoryPrompt(){await this.loadMemory();try{let e=Y(),n="";return e.enableRecentConversations&&this.recentConversationsContent&&(n+=`<recent_conversations>
${this.recentConversationsContent}
</recent_conversations>
The current time is ${this.getTimestamp()}.
<recent_conversations> are the recent conversations between you and the user.
You can use it to provide more context for your responses.
Only use the recent conversations if they are relevant to the current conversation.`),e.enableSavedMemory&&this.savedMemoriesContent&&(n+=`<saved_memories>
${this.savedMemoriesContent}
</saved_memories>
<saved_memories> are important memories that the user explicitly asked you to remember.
Use these memories to provide more personalized and contextually relevant responses.`),n.length>0?n:null}catch(e){return H("[UserMemoryManager] Error reading user memory content:",e),null}}getTimestamp(){let e=new Date,n=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),s=String(e.getMinutes()).padStart(2,"0");return`${n}-${r}-${o} ${i}:${s}`}async createConversationSection(e,n){let{title:r,summary:o}=await this.extractTitleAndSummary(e,n),i=this.getTimestamp(),s=`## ${r}
`;return s+=`**Time:** ${i}
`,s+=`**Summary:** ${o}
`,s}async updateMemory(e,n){if(this.isUpdatingMemory){j("[UserMemoryManager] Memory update already in progress, skipping.");return}this.isUpdatingMemory=!0;try{if(!n){H("[UserMemoryManager] No chat model available, skipping memory update");return}if(e.length===0){j("[UserMemoryManager] No messages available, skipping memory update");return}let r=await this.createConversationSection(e,n),o=O2();await this.ensureMemoryFolderExists(o),await this.addToRecentConversationsFile(this.getRecentConversationFilePath(o),r)}catch(r){H("[UserMemoryManager] Error analyzing chat messages for user memory:",r)}finally{this.isUpdatingMemory=!1}}async ensureMemoryFolderExists(e){await ao(this.app.vault,e)}getRecentConversationFilePath(e=O2()){return`${e}/Recent Conversations.md`}getSavedMemoriesFilePath(e=O2()){return`${e}/Saved Memories.md`}async updateSavedMemoryFile(e,n,r){let o=this.app.vault.getAbstractFileByPath(e),i=o instanceof Wq.TFile?await this.app.vault.read(o):"";if(!r)return{error:"No chat model available, skipping memory update"};let s=`You maintain a user's long-term personal memory list as concise bullet points.
You task is to update the user's memory list with the new statement.
Rules:
- Keep only stable, evergreen facts or preferences that will help future conversations.
- Remove duplicates and near-duplicates by merging them into one concise statement.
- If the new statement conflicts with older ones, keep the most recent truth and remove obsolete/conflicting entries.
- Prefer short, specific, and unambiguous phrasing.
- Preserve the language used in the input memories.
- Output only the memory content with each as a bullet point.
# OUTPUT FORMAT
Return the updated memory list with each as a bullet point.
- memory item 1
- memory item 2
- memory item 3
...
`,a=`<current_memories>
${i.trim()}
</current_memories>
<new_statement>
${n.trim()}
</new_statement>
`,l=[new sg(s),new na(a)],c=null;try{c=(await r.invoke(l)).text??""}catch(u){return{error:"LLM call failed while updating saved memories: "+(u instanceof Error?u.message:String(u))}}return c==null||c.trim()===""?{error:"Empty content returned from LLM"}:(o instanceof Wq.TFile?await this.app.vault.modify(o,c):await this.app.vault.create(e,c),{content:c})}async addToRecentConversationsFile(e,n){let r=this.app.vault.getAbstractFileByPath(e);if(r instanceof Wq.TFile){let o=await this.app.vault.read(r),i;if(o.trim()==="")i=`${n.trim()}
`;else{let s=this.parseExistingConversations(o);s.push(n);let l=Y().maxRecentConversations;s.length>l&&s.splice(0,s.length-l),i=`${s.map(u=>u.trim()).join(`
`)}
`}await this.app.vault.modify(r,i)}else{let o=`${n.trim()}
`;await this.app.vault.create(e,o)}}parseExistingConversations(e){let n=e.split(`
`),r=[],o=[];for(let i of n)i.trim().startsWith("## ")?(o.length>0&&r.push(o.join(`
`).trim()),o=[i]):o.length>0&&o.push(i);return o.length>0&&r.push(o.join(`
`).trim()),r}extractJsonFromResponse(e){let n=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);if(n)return n[1].trim();let r=e.match(/\{[\s\S]*\}/);return r?r[0]:e}async extractTitleAndSummary(e,n){let r=e.map(a=>`${a.sender}: ${a.message}`).join(`
`),o=`Your task is to analyze a conversation and generate both a title and a summary.
# OUTPUT FORMAT
You must return your response in the following JSON format:
{
"title": "Brief 2-8 word title capturing the main user intent",
"summary": "2-3 sentence summary at most including key details (e.g. user facts mentioned entities), and key conclusions if there are any."
}
# RULES
* Use the same language as the conversation`,i=`<conversation_text>
${r}
</conversation_text>
Generate a title and summary for this conversation:`,s=[new sg(o),new na(i)];try{let l=(await n.invoke(s)).text,c=this.extractJsonFromResponse(l);try{let u=JSON.parse(c);return{title:u.title||"Untitled Conversation",summary:u.summary||"No summary available"}}catch(u){return H("[UserMemoryManager] Failed to parse LLM response as JSON:",u),{title:"Untitled Conversation",summary:"Summary generation failed"}}}catch(a){return H("[UserMemoryManager] Failed to extract title and summary:",a),{title:"Untitled Conversation",summary:"Summary generation failed"}}}};pe();jq();var w2r=x.object({statement:x.string().min(1).describe("The user statement for explicitly updating saved memories")}),N0e=t=>gi({name:"updateMemory",description:"Update the user memory when the user explicitly asks to update the memory",schema:w2r,func:async({statement:e})=>{try{let n=new mO(t),r=nw.getInstance().getChatModel(),o=await n.updateSavedMemory(e,r);return o.error?{success:!1,message:o.error}:{success:!0,message:`Memory updated successfully into ${o.filePath}: ${o.content}`}}catch(n){return H("[updateMemoryTool] Error updating memory:",n),{success:!1,message:`Failed to save memory: ${n instanceof Error?n.message:String(n)}`}}}});var _re=require("obsidian");ap();pe();var Kst=200;function R0e(t){return t.replace(/\\/g,"/").toLowerCase()}function b2r(t){return t.replace(/\.[^/.]+$/,"")}function _2r(t,e){if(e.length===0)return!1;let r=R0e(t).split("/").filter(Boolean);if(r.length<e.length)return!1;let o=r.slice(-e.length);for(let i=0;i<e.length;i+=1){let s=e[i];if(!s)return!1;let a=o[i];if(i===o.length-1){let l=b2r(a);if(!a.includes(s)&&!l.includes(s))return!1}else if(!a.includes(s))return!1}return!0}function Gst(t){return/\.[^/]+$/.test(t)}async function x2r(t,e){let n=w=>{let _=t.vault.getAbstractFileByPath(w);return _ instanceof _re.TFile?_:null},r=e.trim(),o=r.match(/^\s*\[\[([\s\S]+?)\]\]\s*$/),s=(o?o[1]:r).trim(),[a]=s.split("|"),[l]=a.split("#"),c=l.trim(),u=Array.from(new Set([r,s,c].map(w=>w.trim()).filter(Boolean)));for(let w of u){let _=n(w);if(_)return{type:"resolved",file:_};if(!Gst(w))for(let S of[".md",".canvas"]){let I=n(`${w}${S}`);if(I)return{type:"resolved",file:I}}}let d=t.metadataCache,f=c.trim();if(d&&f){let w=new Set([f]);if(!Gst(f))for(let _ of[".md",".canvas"])w.add(`${f}${_}`);for(let _ of w){let S=d.getFirstLinkpathDest?.(_,"");if(S instanceof _re.TFile)return{type:"resolved",file:S}}}if(!f)return{type:"not_found"};let p=t.vault.getMarkdownFiles?.()??[];if(p.length===0)return{type:"not_found"};let m=R0e(f),h=new Set([m]);if(!Gst(f))for(let w of[".md",".canvas"])h.add(R0e(`${f}${w}`));for(let w of p){let _=R0e(w.path);if(h.has(_))return{type:"resolved",file:w}}let g=f.split("/").pop();if(g){let w=g.toLowerCase(),_=p.filter(S=>S.basename.toLowerCase()===w);if(_.length===1)return{type:"resolved",file:_[0]};if(_.length>1)return{type:"not_unique",matches:_}}let v=m.split("/").filter(Boolean);if(v.length===0)return{type:"not_found"};let y=p.filter(w=>_2r(w.path,v));return y.length===1?{type:"resolved",file:y[0]}:y.length>1?{type:"not_unique",matches:y}:{type:"not_found"}}async function S2r(t,e){try{return await t.vault.read(e)}catch(n){return W(`readNote: failed to read ${e.path}`,n),""}}function C2r(t){let e=new Map,n=t.vault.getMarkdownFiles?.()??[];for(let r of n)if(r instanceof _re.TFile){let o=e.get(r.basename)??[];o.push(r),e.set(r.basename,o)}return e}function k2r(t,e,n,r){let o=e.trim();if(!o)return[];let i=new Map,s=t.metadataCache.getFirstLinkpathDest?.(o,n);if(s instanceof _re.TFile&&i.set(s.path,s),!/\.[^./]+$/.test(o)){let a=o.split("/").pop()??o,l=r.get(a)??[];for(let c of l)i.set(c.path,c)}return Array.from(i.values())}function I2r(t,e,n){if(!e)return[];let r=/\[\[([^\]]+)\]\]/g,o=new Map,i=null,s;for(;(s=r.exec(e))!==null;){if(s.index>0&&e[s.index-1]==="!")continue;let a=s[1]?.trim();if(!a)continue;let[l,c]=a.split("|"),[u,d]=l.split("#"),f=u?.trim();if(!f)continue;let p=`${f}|${c??""}|${d??""}`;if(o.has(p))continue;i||(i=C2r(t));let m=k2r(t,f,n.path,i);o.set(p,{linkText:f,displayText:c?.trim()||f,section:d?.trim()||void 0,candidates:m.map(h=>({path:h.path,title:h.basename})),unresolved:m.length===0?!0:void 0})}return Array.from(o.values())}function T2r(t,e){let n=e.split(/\r?\n/),r=n.length===1&&n[0]===""?0:n.length;if(r===0)return[{id:`${t.path}#L1-1`,notePath:t.path,chunkIndex:0,content:"",heading:""}];let o=Math.ceil(r/Kst),i=[];for(let s=0;s<o;s++){let a=s*Kst,l=Math.min((s+1)*Kst,r),c=n.slice(a,l),u=c.find(f=>/^#+\s+/.test(f.trim())),d=u?u.trim().replace(/^#+\s+/,""):"";i.push({id:`${t.path}#L${a+1}-${l}`,notePath:t.path,chunkIndex:s,content:c.join(`
`).trimEnd(),heading:d})}return i}var P2r=t=>{if(t===void 0)return 0;let e=typeof t=="string"?Number(t.trim()):t;return!Number.isInteger(e)||e<0?null:e},A2r=x.object({notePath:x.string().min(1).describe("Full path to the note (relative to the vault root) that needs to be read, such as 'Projects/plan.md'."),chunkIndex:x.union([x.number().int().min(0),x.string()]).optional().describe("0-based chunk index to read. Omit to read the first chunk.")}),ixn=t=>gi({name:"readNote",description:"Read a single note in search v3 sized chunks. Use only when you already know the exact note path and need its contents.",schema:A2r,func:async({notePath:e,chunkIndex:n})=>{let r=P2r(n),o=e.trim();if(o.startsWith("/"))return{notePath:o,status:"invalid_path",message:"Provide the note path relative to the vault root without a leading slash."};if(r===null)return{notePath:o,status:"invalid_chunk_index",message:"chunkIndex must be a non-negative integer (0-based). Omit it to read the first chunk."};let i=await x2r(t,o);if(i.type==="not_found")return W(`readNote: note not found or not a file (${o})`),{notePath:o,status:"not_found",message:`Note "${o}" was not found or is not a readable file.`};if(i.type==="not_unique")return W(`readNote: ambiguous note path "${o}" matched multiple files`,i.matches.map(m=>m.path)),{notePath:o,status:"not_unique",message:`Multiple notes match "${o}". Provide a more specific path.`,candidates:i.matches.map(m=>({path:m.path,title:m.basename}))};let s=i.file,a=s.path,l=await S2r(t,s),c=T2r(s,l),u=c.length;if(u===0)return{notePath:a,status:"empty",message:`No readable content was found in "${a}".`};if(r>=u)return{notePath:a,status:"out_of_range",message:`Chunk index ${r} exceeds available chunks (last index ${u-1}).`,totalChunks:u};let d=c[r];j(`readNote: returning chunk ${d.chunkIndex} of ${u} for ${a}`);let f=d.chunkIndex<u-1,p=I2r(t,d.content,s);return{notePath:a,noteTitle:s.basename,heading:d.heading,chunkId:d.id,chunkIndex:d.chunkIndex,totalChunks:u,hasMore:f,nextChunkIndex:f?d.chunkIndex+1:null,content:d.content,mtime:s.stat.mtime,linkedNotes:p.length>0?p:void 0}}});ap();function L0e(t,e,n,r){let o=t.trim();return o.length>0?o:n==="ENOENT"?`CLI binary not found. Tried: ${r.length>0?r.join(", "):"unknown"}. Ensure Obsidian CLI is installed or set OBSIDIAN_CLI_BINARY/OBSIDIAN_CLI_PATH.`:n!==null?`Obsidian CLI failed with error code ${String(n)}`:e!==null?`Obsidian CLI failed with exit code ${e}`:"Obsidian CLI command failed for an unknown reason"}function aF(t){throw new Error(L0e(t.stderr,t.exitCode,t.errorCode,t.attemptedBinaries))}var yos=gi({name:"obsidianDailyRead",description:"Read the current daily note via Obsidian CLI and return the note content as plain text.",schema:x.object({vault:x.string().optional().describe("Optional vault name to target. Omit to use the active/default vault resolution from Obsidian CLI.")}),func:async({vault:t})=>{let e=await nxn(t);if(!e.ok)throw new Error(`Failed to read daily note via Obsidian CLI: ${L0e(e.stderr,e.exitCode,e.errorCode,e.attemptedBinaries)}`);return{type:"obsidian_cli_daily_read",command:e.command,vault:t||null,content:e.stdout,durationMs:e.durationMs}}}),sxn=gi({name:"obsidianRandomRead",description:"Read a random note via Obsidian CLI and return the note content as plain text.",schema:x.object({vault:x.string().optional().describe("Optional vault name to target. Omit to use the active/default vault resolution from Obsidian CLI.")}),func:async({vault:t})=>{let e=await rxn(t);if(!e.ok)throw new Error(`Failed to read random note via Obsidian CLI: ${L0e(e.stderr,e.exitCode,e.errorCode,e.attemptedBinaries)}`);return{type:"obsidian_cli_random_read",command:e.command,vault:t||null,content:e.stdout,durationMs:e.durationMs}}});ap();function Vq(t){return Object.fromEntries(Object.entries(t).filter(([e,n])=>e!=="command"&&e!=="vault"&&n!==void 0))}var E2r=x.object({command:x.enum(["daily","daily:read","daily:path"]).describe("daily \u2014 create today's daily note (applies configured template). daily:read \u2014 read today's daily note content. daily:path \u2014 get the vault-relative file path."),vault:x.string().optional().describe("Optional vault name to target. Omit to use the active vault.")}),axn=gi({name:"obsidianDailyNote",description:"Create or read today's daily note, or get its vault path, via the official Obsidian CLI. Use readNote for reading specific notes by path. Use obsidianRandomRead for picking a random note.",schema:E2r,func:async t=>{let{command:e,vault:n}=t,r=Vq(t),o=await V0({command:e,vault:n,params:r});o.ok||aF(o);let i=e==="daily:read"?o.stdout:o.stdout.trim();return{type:"obsidian_cli_daily_note",command:o.command,vault:n??null,content:i,durationMs:o.durationMs}}}),M2r=x.object({command:x.enum(["properties","property:read"]).describe("properties \u2014 list property names vault-wide or key-value pairs for a specific note. property:read \u2014 read a single property value from a note."),name:x.string().optional().describe("For property:read: the property name to read (required). For properties vault-wide: filter to this property name."),file:x.string().optional().describe("Target file by name (without extension)."),path:x.string().optional().describe("Target file by vault-relative path."),counts:x.boolean().optional().describe("Include occurrence counts alongside property names (vault-wide mode)."),sort:x.string().optional().describe("Sort order for vault-wide listing. Use 'count' to sort by occurrence count."),total:x.boolean().optional().describe("Return only the total property count."),vault:x.string().optional().describe("Optional vault name to target. Omit to use the active vault.")}),lxn=gi({name:"obsidianProperties",description:"Read frontmatter properties from your vault via the official Obsidian CLI: list all property names used vault-wide, or read specific property values from a note.",schema:M2r,func:async t=>{let{command:e,vault:n}=t;if(e==="property:read"&&!t.name)throw new Error("name is required for property:read");let r=Vq(t),o=await V0({command:e,vault:n,params:r});return o.ok||aF(o),{type:"obsidian_cli_properties",command:o.command,vault:n??null,content:o.stdout.trim(),durationMs:o.durationMs}}}),O2r=x.object({command:x.literal("tasks").describe('Must be exactly "tasks". Lists tasks across the vault with optional filters.'),file:x.string().optional().describe("Filter tasks by file name."),path:x.string().optional().describe("Filter tasks by vault-relative file path."),todo:x.boolean().optional().describe("Show only incomplete (todo) tasks."),done:x.boolean().optional().describe("Show only completed tasks."),status:x.string().optional().describe("Filter by a specific status character (e.g. '/' for in-progress)."),daily:x.boolean().optional().describe("Show tasks from today's daily note only."),verbose:x.boolean().optional().describe("Group tasks by file with line numbers."),total:x.boolean().optional().describe("Return only the total task count."),vault:x.string().optional().describe("Optional vault name to target. Omit to use the active vault.")}),cxn=gi({name:"obsidianTasks",description:"List tasks across your vault via the official Obsidian CLI with filters for completion status, file, daily note, and more.",schema:O2r,func:async t=>{let{command:e,vault:n}=t,r=Vq(t),o=await V0({command:e,vault:n,params:r});return o.ok||aF(o),{type:"obsidian_cli_tasks",command:o.command,vault:n??null,content:o.stdout.trim(),durationMs:o.durationMs}}}),N2r=x.object({command:x.enum(["backlinks","links","orphans","unresolved"]).describe("backlinks \u2014 list notes that link TO a given file. links \u2014 list outgoing links FROM a file. orphans \u2014 list files with no incoming links. unresolved \u2014 list wikilinks that don't resolve to any file."),file:x.string().optional().describe("Target file by name (for backlinks and links commands)."),path:x.string().optional().describe("Target file by vault-relative path (for backlinks and links commands)."),counts:x.boolean().optional().describe("Include link counts per source file (for backlinks and unresolved)."),verbose:x.boolean().optional().describe("Include source file for each entry (for unresolved)."),total:x.boolean().optional().describe("Return only the count."),all:x.boolean().optional().describe("Include non-markdown files such as images and PDFs (for orphans)."),vault:x.string().optional().describe("Optional vault name to target. Omit to use the active vault.")}),uxn=gi({name:"obsidianLinks",description:"Query the vault link graph via the official Obsidian CLI: list backlinks to a file, outgoing links from a file, orphaned notes with no incoming links, or unresolved wikilinks.",schema:N2r,func:async t=>{let{command:e,vault:n}=t,r=Vq(t),o=await V0({command:e,vault:n,params:r});return o.ok||aF(o),{type:"obsidian_cli_links",command:o.command,vault:n??null,content:o.stdout.trim(),durationMs:o.durationMs}}}),R2r=x.object({command:x.enum(["templates","template:read"]).describe("templates \u2014 list all available template names. template:read \u2014 read a template's content with variable resolution."),name:x.string().optional().describe("Template name to read. Required for template:read."),vault:x.string().optional().describe("Optional vault name to target. Omit to use the active vault.")}),dxn=gi({name:"obsidianTemplates",description:"List available templates or read template content via the official Obsidian CLI. Use before creating notes to find the right template.",schema:R2r,func:async t=>{let{command:e,vault:n}=t;if(e==="template:read"&&!t.name)throw new Error("name is required for template:read");let r=Vq(t),o=await V0({command:e,vault:n,params:r});return o.ok||aF(o),{type:"obsidian_cli_templates",command:o.command,vault:n??null,content:o.stdout.trim(),durationMs:o.durationMs}}}),L2r=x.object({command:x.enum(["bases","base:views","base:query","base:create"]).describe("bases \u2014 list all Base files in the vault. base:views \u2014 list views defined in a Base file. base:query \u2014 query data from a Base view. base:create \u2014 create a new item (row) in a Base."),file:x.string().optional().describe("Target Base file by name (without extension). Used for base:views, base:query, and base:create."),path:x.string().optional().describe("Target Base file by vault-relative path. Alternative to file= for base:views, base:query, and base:create."),view:x.string().optional().describe("View name. For base:query: view to query. For base:create: view to add item to."),name:x.string().optional().describe("New file name for the created item. For base:create only."),content:x.string().optional().describe("Initial content for the created item. For base:create only."),format:x.string().optional().describe("Output format for base:query (e.g., 'csv'). Omit for default text output."),total:x.boolean().optional().describe("Return only the count."),vault:x.string().optional().describe("Optional vault name to target. Omit to use the active vault.")}),$2r=["base:views","base:query","base:create"],fxn=gi({name:"obsidianBases",description:"Interact with Obsidian Base (database) files via the official Obsidian CLI: list all bases, list views in a base, query data from a base view, or create a new item in a base.",schema:L2r,func:async t=>{let{command:e,vault:n}=t;if($2r.includes(e)&&!t.file&&!t.path)throw new Error(`file or path is required for ${e}`);let r=Vq(t),o=await V0({command:e,vault:n,params:r});return o.ok||aF(o),{type:"obsidian_cli_bases",command:o.command,vault:n??null,content:o.stdout.trim(),durationMs:o.durationMs}}});gt();_v();pe();Se();ut();var D2r="https://api.firecrawl.dev/v2/search",F2r="https://api.perplexity.ai/chat/completions",mxn="https://api.supadata.ai/v1/transcript",U2r=2e3,pxn=6e4;function hxn(){let t=Y();switch(t.selfHostSearchProvider){case"perplexity":return!!t.perplexityApiKey;case"firecrawl":default:return!!t.firecrawlApiKey}}async function j2r(t,e){let n=Date.now(),r=await bh(D2r,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({query:t,limit:5})});if(!r.ok){let u=await r.text();throw new Error(`Firecrawl search failed (${r.status}): ${u}`)}let i=(await r.json())?.data,s=Array.isArray(i)?i:Array.isArray(i?.web)?i.web:[],a=[],l=[];for(let u of s){let d=u.title||"Untitled",f=u.description||"",p=u.url||"";a.push(`### ${d}
${f}
Source: ${p}`),p&&l.push(p)}let c=Date.now()-n;return j(`[selfHostWebSearch] Firecrawl: ${s.length} results in ${c}ms`),{content:a.join(`
`),citations:l}}async function B2r(t,e){let n=await bh(F2r,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({model:"sonar",messages:[{role:"user",content:t}]})});if(!n.ok){let s=await n.text();throw new Error(`Perplexity Sonar search failed (${n.status}): ${s}`)}let r=await n.json(),o=r?.choices?.[0]?.message?.content??"",i=Array.isArray(r?.citations)?r.citations:[];return{content:o,citations:i}}async function gxn(t){let e=Y();switch(e.selfHostSearchProvider){case"perplexity":return B2r(t,e.perplexityApiKey);case"firecrawl":default:return j2r(t,e.firecrawlApiKey)}}async function $0e(t){let e=Date.now(),n=Y().supadataApiKey,r=`${mxn}?url=${encodeURIComponent(t)}&mode=auto&text=true`,o=await bh(r,{method:"GET",headers:{"x-api-key":n,Accept:"application/json"}});if(o.status===200){let s=await o.json(),a=Date.now()-e;return j(`[selfHostYoutube4llm] transcript received in ${a}ms`),{response:{transcript:s.content||""},elapsed_time_ms:a}}if(o.status===201||o.status===202){let a=(await o.json()).job_id;if(!a)throw new Error("Supadata returned async status but no job_id");return await z2r(a,n,e)}let i=await o.text();throw new Error(`Supadata transcript request failed (${o.status}): ${i}`)}async function z2r(t,e,n){let r=Date.now()+pxn,o=`${mxn}/${t}`;for(;Date.now()<r;){await new Promise(a=>window.setTimeout(a,U2r));let i=await bh(o,{method:"GET",headers:{"x-api-key":e,Accept:"application/json"}});if(i.status===200){let a=await i.json(),l=Date.now()-n;return j(`[selfHostYoutube4llm] async transcript completed in ${l}ms`),{response:{transcript:a.content||""},elapsed_time_ms:l}}if(i.status===202)continue;let s=await i.text();throw H(`[selfHostYoutube4llm] poll failed (${i.status}): ${s}`),new Error(`Supadata poll failed (${i.status}): ${s}`)}throw new Error(`Supadata transcript timed out after ${pxn}ms`)}pe();zu();vc();Se();ap();pe();vc();Se();Ixe();ut();async function yxn(t,e,n){try{if(!t||!t.name)return{toolName:t?.name||"unknown",result:"Error: Invalid tool call - missing tool name",success:!1};let o=e.find(u=>u.name===t.name);if(!o){let u=e.map(d=>d.name).join(", ");return{toolName:t.name,result:`Error: Tool '${t.name}' not found. Available tools: ${u}. Make sure you have the tool enabled in the Agent settings.`,success:!1}}let s=ic.getInstance().getToolMetadata(t.name);if(s?.isPlusOnly&&!await ch(void 0,{trigger:"tool_call"})&&!UM())return{toolName:t.name,result:`Error: ${Zst(t.name)} requires a Copilot Plus subscription`,success:!1};let a={...t.args};s?.requiresUserMessageContent&&n&&(a._userMessageContent=n);let l=12e4;typeof s?.timeoutMs=="number"&&(l=s.timeoutMs);let c;return!l||l===1/0?c=await d0.callTool(o,a):c=await Promise.race([d0.callTool(o,a),new Promise((u,d)=>window.setTimeout(()=>d(new Error(`Tool execution timed out after ${l}ms`)),l))]),c==null?(W(`Tool ${t.name} returned null/undefined result`),{toolName:t.name,result:JSON.stringify({message:"Tool executed but returned no result",status:"empty"}),success:!0}):{toolName:t.name,result:typeof c=="string"?c:JSON.stringify(c),success:!0}}catch(o){let i=kt(o);return i.includes("schema")?H(`[ToolCall] Schema validation failed for "${t.name}". Args: ${JSON.stringify(t.args,null,2)}`):H(`[ToolCall] Error executing "${t.name}": ${i}`),{toolName:t.name,result:`Error: ${i}`,success:!1}}}function Zst(t){return t==="localSearch"?Y().enableSemanticSearchV3?"vault search (semantic)":"vault search (index-free)":{webSearch:"web search",getFileTree:"file tree",getCurrentTime:"current time",getTimeRangeMs:"time range",getTimeInfoByEpoch:"time info",convertTimeBetweenTimezones:"timezone converter",startPomodoro:"pomodoro timer",pomodoroTool:"pomodoro timer",youtubeTranscription:"YouTube transcription",indexVault:"vault indexing",indexTool:"index",writeFile:"file editor",editFile:"file editor",obsidianDailyNote:"daily note (CLI)",obsidianRandomRead:"random note (CLI)",obsidianProperties:"properties (CLI)",obsidianTasks:"tasks (CLI)",obsidianLinks:"links (CLI)",obsidianTemplates:"templates (CLI)",obsidianBases:"bases (CLI)"}[t]||t}function vxn(t){return{localSearch:"\u{1F50D}",webSearch:"\u{1F310}",getFileTree:"\u{1F4C1}",getCurrentTime:"\u{1F552}",getTimeRangeMs:"\u{1F4C5}",getTimeInfoByEpoch:"\u{1F570}\uFE0F",convertTimeBetweenTimezones:"\u{1F30D}",youtubeTranscription:"\u{1F4FA}",indexVault:"\u{1F4DA}",indexTool:"\u{1F4DA}",writeFile:"\u270F\uFE0F",editFile:"\u{1F504}",readNote:"\u{1F50D}",obsidianDailyNote:"\u{1F4C5}",obsidianRandomRead:"\u{1F3B2}",obsidianProperties:"\u{1F3F7}\uFE0F",obsidianTasks:"\u2705",obsidianLinks:"\u{1F517}",obsidianTemplates:"\u{1F4C4}",obsidianBases:"\u{1F5C4}\uFE0F"}[t]||"\u{1F527}"}function wxn(t,e){let n=Zst(t.name),r=vxn(t.name),o=Object.keys(t.args).length>0?JSON.stringify(t.args,null,2):"(no parameters)";j(`${r} [Iteration ${e}] ${n.toUpperCase()}`),j("Parameters:",o),j("---")}function bxn(t,e){if(t==="localSearch")return;let n=Zst(t),r=vxn(t),o=e.success?"\u2705 SUCCESS":"\u274C FAILED";j(`${r} ${n.toUpperCase()} RESULT: ${o}`);let i=300,s=String(e.result??"");s.length>i?j(`Result: ${s.substring(0,i)}... (truncated, ${s.length} chars total)`):s.length>0&&j("Result:",s)}function qq(t){let e=new Map;for(let n of t){let r=n.path||n.title,o=e.get(r);(!o||n.score>o.score)&&e.set(r,n)}return Array.from(e.values()).sort((n,r)=>r.score-n.score)}FV();gre();I0e();S3();T0e();function H2r(t){let e=new Set,n=[],r=o=>{if(typeof o!="string")return;let i=o.toLowerCase().trim();i&&!e.has(i)&&(e.add(i),n.push(o.trim()))};return t.originalQuery&&typeof t.originalQuery=="string"&&r(t.originalQuery),(t.salientTerms||[]).forEach(r),(t.expandedQueries||[]).forEach(r),n}var W2r=x.object({query:x.string().min(1).describe("The search query to find relevant notes"),salientTerms:x.array(x.string()).describe("Keywords extracted from the user's query for BM25 full-text search. Must be from original query."),timeRange:x.object({startTime:x.number().optional().describe("Start time as epoch milliseconds"),endTime:x.number().optional().describe("End time as epoch milliseconds")}).optional().describe("Optional time range filter. Use epoch milliseconds from getTimeRangeMs result."),_preExpandedQuery:x.object({originalQuery:x.string(),salientTerms:x.array(x.string()),expandedQueries:x.array(x.string()),recallTerms:x.array(x.string())}).optional().describe("Internal: pre-expanded query data injected by the system to avoid double expansion")});async function _xn({app:t,timeRange:e,query:n,salientTerms:r,forceLexical:o=!1,preExpandedQuery:i}){let s=Y(),a=r.filter(E=>E.startsWith("#")),l=a.length>0?a:(()=>{try{return[...n.matchAll(/#[\p{L}\p{N}_/-]+/gu)].map(E=>E[0])}catch{return[...n.matchAll(/#[a-z0-9_/-]+/gi)].map(E=>E[0])}})(),c=l.length>0,u=e!==void 0||c,d=u?al:s.maxSourceChunks;j(`lexicalSearch effectiveMaxK: ${d} (expanded: ${u}), forceLexical: ${o}`);let f=i?{...i,queries:[i.originalQuery,...i.expandedQueries||[]].filter(Boolean)}:void 0,p=new fO(t,{salientTerms:r,timeRange:e,maxK:d,returnAll:u}),m=await p.getRelevantDocuments(n);j(`lexicalSearch filterRetriever returned ${m.length} filter docs`);let h=[],g;if(!p.hasTimeRange()){let E={minSimilarityScore:u?0:.1,maxK:d,salientTerms:r,textWeight:tAe,returnAll:u,useRerankerThreshold:.5,tagTerms:l,preExpandedQuery:f},O,$;if(o)O=T_.createLexicalRetriever(t,E),$="lexical (forced)";else{let U=await T_.createRetriever(t,E);O=U.retriever,$=U.type}if(j(`lexicalSearch using ${$} retriever`),h=await O.getRelevantDocuments(n),O instanceof cC){let U=O.getLastQueryExpansion();U&&(g={originalQuery:U.originalQuery,salientTerms:U.salientTerms,expandedQueries:U.expandedQueries,recallTerms:H2r(U)})}}let{filterResults:v,searchResults:y}=zq(m,h),w=(E,O)=>({title:E.metadata.title||"Untitled",content:E.pageContent,path:E.metadata.path||"",score:E.metadata.rerank_score??E.metadata.score??0,rerank_score:E.metadata.rerank_score??E.metadata.score??0,includeInContext:E.metadata.includeInContext??!0,source:E.metadata.source,mtime:E.metadata.mtime??null,ctime:E.metadata.ctime??null,chunkId:E.metadata.chunkId??null,isChunk:E.metadata.isChunk??!1,explanation:E.metadata.explanation??null,isFilterResult:O,matchType:O?E.metadata.source||"filter":void 0}),_=v.map(E=>w(E,!0)),S=y.map(E=>w(E,!1));j(`lexicalSearch found ${_.length} filter + ${S.length} search documents for query: "${n}"`),e&&j(`Time range search from ${new Date(e.startTime).toISOString()} to ${new Date(e.endTime).toISOString()}`);let I=S.map(E=>({title:E.title||E.path||"Untitled",path:E.path||E.title||"",score:E.rerank_score||E.score||0})),C=qq(I),k=new Map;for(let E of S){let O=(E.path||E.title).toLowerCase(),$=k.get(O);(!$||(E.rerank_score||0)>($.rerank_score||0))&&k.set(O,E)}let T=C.map(E=>k.get((E.path||E.title).toLowerCase())).filter(Boolean);return{type:"local_search",documents:[..._,...T].slice(0,d),queryExpansion:g}}function V2r(t){if(!t)return;let{startTime:e,endTime:n}=t;if(!e||!n||e<=0||n<=0){j("localSearch: Ignoring invalid time range (missing, zero, or negative values)");return}if(e>n){j("localSearch: Ignoring inverted time range (start > end)");return}return{startTime:e,endTime:n}}async function q2r({app:t,query:e,salientTerms:n,timeRange:r}){let o=n.filter(m=>m.startsWith("#")),i=r!==void 0||o.length>0,s=i?al:Y().maxSourceChunks,a=new fO(t,{salientTerms:n,timeRange:r,maxK:s,returnAll:i}),l=await a.getRelevantDocuments(e),c=[];a.hasTimeRange()||(c=await T_.createMiyoRetriever(t,{minSimilarityScore:i?0:.1,maxK:s,salientTerms:n,textWeight:tAe,returnAll:i,useRerankerThreshold:.5,tagTerms:o}).getRelevantDocuments(e)),j(`miyoSearch: ${l.length} filter + ${c.length} miyo docs for query: "${e}"`);let{filterResults:u,searchResults:d}=zq(l,c),f=(m,h)=>({title:m.metadata.title||"Untitled",content:m.pageContent,path:m.metadata.path||"",score:m.metadata.rerank_score??m.metadata.score??0,rerank_score:m.metadata.rerank_score??m.metadata.score??0,includeInContext:m.metadata.includeInContext??!0,source:m.metadata.source,mtime:m.metadata.mtime??null,ctime:m.metadata.ctime??null,chunkId:m.metadata.chunkId??null,isChunk:m.metadata.isChunk??!1,explanation:m.metadata.explanation??null,isFilterResult:h,matchType:h?m.metadata.source||"filter":void 0});return{type:"local_search",documents:[...u.map(m=>f(m,!0)),...d.map(m=>f(m,!1))].slice(0,s)}}var D0e=t=>gi({name:"localSearch",description:"Search for notes in the vault based on query, salient terms, and optional time range",schema:W2r,func:async({timeRange:e,query:n,salientTerms:r,_preExpandedQuery:o})=>{let i=V2r(e);if(T_.isMiyoActive())return j("localSearch: Using Miyo search path"),await q2r({app:t,query:n,salientTerms:r,timeRange:i});let s=r.filter(c=>c.startsWith("#"));if(i!==void 0||s.length>0)return j("localSearch: Forcing lexical search (time range or tags present)"),await _xn({app:t,timeRange:i,query:n,salientTerms:r,forceLexical:!0,preExpandedQuery:o});let l=T_.getRetrieverType();return j(`localSearch: Using ${l} retriever via factory`),await _xn({app:t,timeRange:i,query:n,salientTerms:r,preExpandedQuery:o})}}),Xos=gi({name:"indexVault",description:"Index the vault to the Copilot index",schema:x.object({}),func:async()=>{let t=Y();if(t.enableSemanticSearchV3)try{let n=await(await Promise.resolve().then(()=>(El(),nd))).default.getInstance().indexVaultToVectorStore(),r=Bu(t)==="miyo",o=r?`Requested a Miyo folder scan for this vault.
`:`Semantic search index refreshed with ${n} documents.
`;return{success:!0,message:r?o+"Miyo will handle chunking and indexing for the registered folder.":o+`Semantic search index has been refreshed with ${n} documents.`,documentCount:n}}catch(e){return{success:!1,message:`Failed to index with semantic search: ${e instanceof Error?e.message:String(e)}`}}else return{success:!0,message:"Tiered lexical retriever uses on-demand indexing. No manual indexing required."}}}),K2r=x.object({query:x.string().min(1).describe("The search query to search the internet"),chatHistory:x.array(x.object({role:x.enum(["user","assistant"]),content:x.string()})).describe("Previous conversation turns for context (usually empty array)")}),F0e=gi({name:"webSearch",description:"Search the INTERNET (NOT vault notes) when user explicitly asks for web/online information",schema:K2r,func:async({query:t,chatHistory:e})=>{try{let n=await jke(t,e),r,o;if(UM()&&hxn()){let s=await gxn(n);r=s.content,o=s.citations}else{let s=await Gi.getInstance().webSearch(n);r=s.response.choices[0].message.content,o=s.response.citations||[]}return[{type:"web_search",content:r,citations:o,instruction:run()}]}catch(n){return H(`Error processing web search query ${t}:`,n),{error:`Web search failed: ${n}`}}}});ap();var Yst=5e5,G2r=500,xxn=50,Z2r=x.object({includeInline:x.boolean().optional().describe("Include inline tags in addition to frontmatter tags. Defaults to true."),maxEntries:x.number().int().min(1).max(5e3).optional().describe("Maximum number of tag entries to return, sorted by occurrences. Responses are capped at ~500KB.")}).describe("Parameters for retrieving the tag list.");function Y2r(t){return t?.metadataCache?t.metadataCache:null}function Sxn(t){let e={};if(!t)return e;for(let[n,r]of Object.entries(t)){let o=n?.trim();if(!o)continue;let i=o.replace(/^#+/,"").trim().toLowerCase();if(!i)continue;let s=`#${i}`;if(s==="#")continue;let a=Number.isFinite(r)?Math.max(0,Math.floor(r)):0;e[s]=(e[s]||0)+a}return e}function J2r(t,e,n){let r=t,o=Sxn(r.getFrontmatterTags?.()),i=e?Sxn(r.getTags?.()):{},s=new Set([...Object.keys(o),...e?Object.keys(i):[]]),a=[],l=0;for(let u of s){let d=o[u]??0,f=e?Math.max(0,i[u]??0):0,p=0,m=d;e&&(f>=d?(p=f-d,m=f):f>0&&(p=f,m=d+p)),m!==0&&(l+=m,a.push({tag:u,occurrences:m,frontmatterOccurrences:d,inlineOccurrences:p}))}a.sort((u,d)=>d.occurrences===u.occurrences?u.tag.localeCompare(d.tag):d.occurrences-u.occurrences);let c=a.slice(0,n);return{totalUniqueTags:a.length,returnedTagCount:c.length,totalOccurrences:l,includedSources:e?["frontmatter","inline"]:["frontmatter"],truncated:c.length<a.length,tags:c}}function X2r(t){let e=t,n=JSON.stringify(e);if(n.length<=Yst)return e;let r=e.tags.length;for(;n.length>Yst&&r>xxn;)r=Math.max(xxn,Math.floor(r/2)),e={...e,tags:t.tags.slice(0,r),returnedTagCount:r,truncated:!0},n=JSON.stringify(e);return n.length>Yst?{totalUniqueTags:t.totalUniqueTags,returnedTagCount:0,totalOccurrences:t.totalOccurrences,includedSources:t.includedSources,truncated:!0,tags:[],note:"Tag list exceeded the size limit. Request a narrower scope or specify a smaller maxEntries value."}:e}function Cxn(t){return`A JSON object lists the vault tags and their occurrence counts:
* totalUniqueTags: number of unique tags indexed across the vault
* returnedTagCount: number of tag entries included in this response
* totalOccurrences: total tag occurrences across included sources
* includedSources: sources represented in the counts (frontmatter, inline)
* truncated: whether the list was shortened due to limits
* tags: array of tag objects { tag, occurrences, frontmatterOccurrences, inlineOccurrences }
${JSON.stringify(t)}`}var kxn=t=>gi({name:"getTagList",description:"Get the list of tags in the vault with occurrence statistics.",schema:Z2r,func:async e=>{let n=Y2r(t),r=e?.includeInline??!0,o=e?.maxEntries??G2r;if(!n)return Cxn({totalUniqueTags:0,returnedTagCount:0,totalOccurrences:0,includedSources:r?["frontmatter","inline"]:["frontmatter"],truncated:!1,tags:[],note:"Metadata cache is unavailable. Try again after the vault finishes indexing."});let i=J2r(n,r,o),s=X2r(i);return Cxn(s)}});var Axn=L(Ixn(),1),xre=L(hO(),1);var Zo;(function(t){t[t.AM=0]="AM",t[t.PM=1]="PM"})(Zo||(Zo={}));var lc;(function(t){t[t.SUNDAY=0]="SUNDAY",t[t.MONDAY=1]="MONDAY",t[t.TUESDAY=2]="TUESDAY",t[t.WEDNESDAY=3]="WEDNESDAY",t[t.THURSDAY=4]="THURSDAY",t[t.FRIDAY=5]="FRIDAY",t[t.SATURDAY=6]="SATURDAY"})(lc||(lc={}));var Zg;(function(t){t[t.JANUARY=1]="JANUARY",t[t.FEBRUARY=2]="FEBRUARY",t[t.MARCH=3]="MARCH",t[t.APRIL=4]="APRIL",t[t.MAY=5]="MAY",t[t.JUNE=6]="JUNE",t[t.JULY=7]="JULY",t[t.AUGUST=8]="AUGUST",t[t.SEPTEMBER=9]="SEPTEMBER",t[t.OCTOBER=10]="OCTOBER",t[t.NOVEMBER=11]="NOVEMBER",t[t.DECEMBER=12]="DECEMBER"})(Zg||(Zg={}));function Txn(t,e){e=e.add(1,"day"),lF(t,e),Kq(t,e)}function P_(t,e){t.assign("day",e.date()),t.assign("month",e.month()+1),t.assign("year",e.year())}function U0e(t,e){t.assign("hour",e.hour()),t.assign("minute",e.minute()),t.assign("second",e.second()),t.assign("millisecond",e.millisecond()),t.get("hour")<12?t.assign("meridiem",Zo.AM):t.assign("meridiem",Zo.PM)}function lF(t,e){t.imply("day",e.date()),t.imply("month",e.month()+1),t.imply("year",e.year())}function Kq(t,e){t.imply("hour",e.hour()),t.imply("minute",e.minute()),t.imply("second",e.second()),t.imply("millisecond",e.millisecond())}var tat=L(hO(),1);var Q2r={ACDT:630,ACST:570,ADT:-180,AEDT:660,AEST:600,AFT:270,AKDT:-480,AKST:-540,ALMT:360,AMST:-180,AMT:-240,ANAST:720,ANAT:720,AQTT:300,ART:-180,AST:-240,AWDT:540,AWST:480,AZOST:0,AZOT:-60,AZST:300,AZT:240,BNT:480,BOT:-240,BRST:-120,BRT:-180,BST:60,BTT:360,CAST:480,CAT:120,CCT:390,CDT:-300,CEST:120,CET:{timezoneOffsetDuringDst:2*60,timezoneOffsetNonDst:60,dstStart:t=>Pxn(t,Zg.MARCH,lc.SUNDAY,2),dstEnd:t=>Pxn(t,Zg.OCTOBER,lc.SUNDAY,3)},CHADT:825,CHAST:765,CKT:-600,CLST:-180,CLT:-240,COT:-300,CST:-360,CT:{timezoneOffsetDuringDst:-5*60,timezoneOffsetNonDst:-6*60,dstStart:t=>gO(t,Zg.MARCH,lc.SUNDAY,2,2),dstEnd:t=>gO(t,Zg.NOVEMBER,lc.SUNDAY,1,2)},CVT:-60,CXT:420,ChST:600,DAVT:420,EASST:-300,EAST:-360,EAT:180,ECT:-300,EDT:-240,EEST:180,EET:120,EGST:0,EGT:-60,EST:-300,ET:{timezoneOffsetDuringDst:-4*60,timezoneOffsetNonDst:-5*60,dstStart:t=>gO(t,Zg.MARCH,lc.SUNDAY,2,2),dstEnd:t=>gO(t,Zg.NOVEMBER,lc.SUNDAY,1,2)},FJST:780,FJT:720,FKST:-180,FKT:-240,FNT:-120,GALT:-360,GAMT:-540,GET:240,GFT:-180,GILT:720,GMT:0,GST:240,GYT:-240,HAA:-180,HAC:-300,HADT:-540,HAE:-240,HAP:-420,HAR:-360,HAST:-600,HAT:-90,HAY:-480,HKT:480,HLV:-210,HNA:-240,HNC:-360,HNE:-300,HNP:-480,HNR:-420,HNT:-150,HNY:-540,HOVT:420,ICT:420,IDT:180,IOT:360,IRDT:270,IRKST:540,IRKT:540,IRST:210,IST:330,JST:540,KGT:360,KRAST:480,KRAT:480,KST:540,KUYT:240,LHDT:660,LHST:630,LINT:840,MAGST:720,MAGT:720,MART:-510,MAWT:300,MDT:-360,MESZ:120,MEZ:60,MHT:720,MMT:390,MSD:240,MSK:180,MST:-420,MT:{timezoneOffsetDuringDst:-6*60,timezoneOffsetNonDst:-7*60,dstStart:t=>gO(t,Zg.MARCH,lc.SUNDAY,2,2),dstEnd:t=>gO(t,Zg.NOVEMBER,lc.SUNDAY,1,2)},MUT:240,MVT:300,MYT:480,NCT:660,NDT:-90,NFT:690,NOVST:420,NOVT:360,NPT:345,NST:-150,NUT:-660,NZDT:780,NZST:720,OMSST:420,OMST:420,PDT:-420,PET:-300,PETST:720,PETT:720,PGT:600,PHOT:780,PHT:480,PKT:300,PMDT:-120,PMST:-180,PONT:660,PST:-480,PT:{timezoneOffsetDuringDst:-7*60,timezoneOffsetNonDst:-8*60,dstStart:t=>gO(t,Zg.MARCH,lc.SUNDAY,2,2),dstEnd:t=>gO(t,Zg.NOVEMBER,lc.SUNDAY,1,2)},PWT:540,PYST:-180,PYT:-240,RET:240,SAMT:240,SAST:120,SBT:660,SCT:240,SGT:480,SRT:-180,SST:-660,TAHT:-600,TFT:300,TJT:300,TKT:780,TLT:540,TMT:300,TVT:720,ULAT:480,UTC:0,UYST:-120,UYT:-180,UZT:300,VET:-210,VLAST:660,VLAT:660,VUT:660,WAST:120,WAT:60,WEST:60,WESZ:60,WET:0,WEZ:0,WFT:720,WGST:-120,WGT:-180,WIB:420,WIT:540,WITA:480,WST:780,WT:0,YAKST:600,YAKT:600,YAPT:600,YEKST:360,YEKT:360};function gO(t,e,n,r,o=0){let i=0,s=0;for(;s<r;)i++,new Date(t,e-1,i).getDay()===n&&s++;return new Date(t,e-1,i,o)}function Pxn(t,e,n,r=0){let o=n===0?7:n,i=new Date(t,e-1+1,1,12),s=i.getDay()===0?7:i.getDay(),a;return s===o?a=7:s<o?a=7+s-o:a=s-o,i.setDate(i.getDate()-a),new Date(t,e-1,i.getDate(),r)}function j0e(t,e,n={}){if(t==null)return null;if(typeof t=="number")return t;let r=n[t]??Q2r[t];return r==null?null:typeof r=="number"?r:e==null?null:(0,tat.default)(e).isAfter(r.dstStart(e.getFullYear()))&&!(0,tat.default)(e).isAfter(r.dstEnd(e.getFullYear()))?r.timezoneOffsetDuringDst:r.timezoneOffsetNonDst}xre.default.extend(Axn.default);var yO=class{constructor(e){e=e??new Date,e instanceof Date?this.instant=e:(this.instant=e.instant??new Date,this.timezoneOffset=j0e(e.timezone,this.instant))}getDateWithAdjustedTimezone(){return new Date(this.instant.getTime()+this.getSystemTimezoneAdjustmentMinute(this.instant)*6e4)}getSystemTimezoneAdjustmentMinute(e,n){(!e||e.getTime()<0)&&(e=new Date);let r=-e.getTimezoneOffset(),o=n??this.timezoneOffset??r;return r-o}},Yo=class t{constructor(e,n){if(this._tags=new Set,this.reference=e,this.knownValues={},this.impliedValues={},n)for(let o in n)this.knownValues[o]=n[o];let r=(0,xre.default)(e.instant);this.imply("day",r.date()),this.imply("month",r.month()+1),this.imply("year",r.year()),this.imply("hour",12),this.imply("minute",0),this.imply("second",0),this.imply("millisecond",0)}get(e){return e in this.knownValues?this.knownValues[e]:e in this.impliedValues?this.impliedValues[e]:null}isCertain(e){return e in this.knownValues}getCertainComponents(){return Object.keys(this.knownValues)}imply(e,n){return e in this.knownValues?this:(this.impliedValues[e]=n,this)}assign(e,n){return this.knownValues[e]=n,delete this.impliedValues[e],this}delete(e){delete this.knownValues[e],delete this.impliedValues[e]}clone(){let e=new t(this.reference);e.knownValues={},e.impliedValues={};for(let n in this.knownValues)e.knownValues[n]=this.knownValues[n];for(let n in this.impliedValues)e.impliedValues[n]=this.impliedValues[n];return e}isOnlyDate(){return!this.isCertain("hour")&&!this.isCertain("minute")&&!this.isCertain("second")}isOnlyTime(){return!this.isCertain("weekday")&&!this.isCertain("day")&&!this.isCertain("month")&&!this.isCertain("year")}isOnlyWeekdayComponent(){return this.isCertain("weekday")&&!this.isCertain("day")&&!this.isCertain("month")}isDateWithUnknownYear(){return this.isCertain("month")&&!this.isCertain("year")}isValidDate(){let e=this.dateWithoutTimezoneAdjustment();return!(e.getFullYear()!==this.get("year")||e.getMonth()!==this.get("month")-1||e.getDate()!==this.get("day")||this.get("hour")!=null&&e.getHours()!=this.get("hour")||this.get("minute")!=null&&e.getMinutes()!=this.get("minute"))}toString(){return`[ParsingComponents {
tags: ${JSON.stringify(Array.from(this._tags).sort())},
knownValues: ${JSON.stringify(this.knownValues)},
impliedValues: ${JSON.stringify(this.impliedValues)}},
reference: ${JSON.stringify(this.reference)}]`}dayjs(){return(0,xre.default)(this.date())}date(){let e=this.dateWithoutTimezoneAdjustment(),n=this.reference.getSystemTimezoneAdjustmentMinute(e,this.get("timezoneOffset"));return new Date(e.getTime()+n*6e4)}addTag(e){return this._tags.add(e),this}addTags(e){for(let n of e)this._tags.add(n);return this}tags(){return new Set(this._tags)}dateWithoutTimezoneAdjustment(){let e=new Date(this.get("year"),this.get("month")-1,this.get("day"),this.get("hour"),this.get("minute"),this.get("second"),this.get("millisecond"));return e.setFullYear(this.get("year")),e}static createRelativeFromReference(e,n){let r=(0,xre.default)(e.instant);for(let i in n)r=r.add(n[i],i);let o=new t(e);return n.hour||n.minute||n.second?(U0e(o,r),P_(o,r),e.timezoneOffset!==null&&o.assign("timezoneOffset",-e.instant.getTimezoneOffset())):(Kq(o,r),e.timezoneOffset!==null&&o.imply("timezoneOffset",-e.instant.getTimezoneOffset()),n.d?(o.assign("day",r.date()),o.assign("month",r.month()+1),o.assign("year",r.year())):n.week?(o.assign("day",r.date()),o.assign("month",r.month()+1),o.assign("year",r.year()),o.imply("weekday",r.day())):(o.imply("day",r.date()),n.month?(o.assign("month",r.month()+1),o.assign("year",r.year())):(o.imply("month",r.month()+1),n.year?o.assign("year",r.year()):o.imply("year",r.year())))),o}},q0=class t{constructor(e,n,r,o,i){this.reference=e,this.refDate=e.instant,this.index=n,this.text=r,this.start=o||new Yo(e),this.end=i}clone(){let e=new t(this.reference,this.index,this.text);return e.start=this.start?this.start.clone():null,e.end=this.end?this.end.clone():null,e}date(){return this.start.date()}tags(){let e=new Set(this.start.tags());if(this.end)for(let n of this.end.tags())e.add(n);return e}toString(){let e=Array.from(this.tags()).sort();return`[ParsingResult {index: ${this.index}, text: '${this.text}', tags: ${JSON.stringify(e)} ...}]`}};function nat(t,e,n="\\s{0,5},?\\s{0,5}"){let r=e.replace(/\((?!\?)/g,"(?:");return`${t}${r}(?:${n}${r}){0,10}`}function eUr(t){let e;return t instanceof Array?e=[...t]:t instanceof Map?e=Array.from(t.keys()):e=Object.keys(t),e}function Bd(t){return`(?:${eUr(t).sort((n,r)=>r.length-n.length).join("|").replace(/\./g,"\\.")})`}var Exn=L(hO(),1);function B0e(t){return t<100&&(t>50?t=t+1900:t=t+2e3),t}function vO(t,e,n){let r=(0,Exn.default)(t),o=r;o=o.month(n-1),o=o.date(e),o=o.year(r.year());let i=o.add(1,"y"),s=o.add(-1,"y");return Math.abs(i.diff(r))<Math.abs(o.diff(r))?o=i:Math.abs(s.diff(r))<Math.abs(o.diff(r))&&(o=s),o.year()}var iat={sunday:0,sun:0,"sun.":0,monday:1,mon:1,"mon.":1,tuesday:2,tue:2,"tue.":2,wednesday:3,wed:3,"wed.":3,thursday:4,thurs:4,"thurs.":4,thur:4,"thur.":4,thu:4,"thu.":4,friday:5,fri:5,"fri.":5,saturday:6,sat:6,"sat.":6},sat={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},rw={...sat,jan:1,"jan.":1,feb:2,"feb.":2,mar:3,"mar.":3,apr:4,"apr.":4,jun:6,"jun.":6,jul:7,"jul.":7,aug:8,"aug.":8,sep:9,"sep.":9,sept:9,"sept.":9,oct:10,"oct.":10,nov:11,"nov.":11,dec:12,"dec.":12},rat={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12},oat={first:1,second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,tenth:10,eleventh:11,twelfth:12,thirteenth:13,fourteenth:14,fifteenth:15,sixteenth:16,seventeenth:17,eighteenth:18,nineteenth:19,twentieth:20,"twenty first":21,"twenty-first":21,"twenty second":22,"twenty-second":22,"twenty third":23,"twenty-third":23,"twenty fourth":24,"twenty-fourth":24,"twenty fifth":25,"twenty-fifth":25,"twenty sixth":26,"twenty-sixth":26,"twenty seventh":27,"twenty-seventh":27,"twenty eighth":28,"twenty-eighth":28,"twenty ninth":29,"twenty-ninth":29,thirtieth:30,"thirty first":31,"thirty-first":31},Oxn={second:"second",seconds:"second",minute:"minute",minutes:"minute",hour:"hour",hours:"hour",day:"d",days:"d",week:"week",weeks:"week",month:"month",months:"month",quarter:"quarter",quarters:"quarter",year:"year",years:"year"},Sre={s:"second",sec:"second",second:"second",seconds:"second",m:"minute",min:"minute",mins:"minute",minute:"minute",minutes:"minute",h:"hour",hr:"hour",hrs:"hour",hour:"hour",hours:"hour",d:"d",day:"d",days:"d",w:"w",week:"week",weeks:"week",mo:"month",mon:"month",mos:"month",month:"month",months:"month",qtr:"quarter",quarter:"quarter",quarters:"quarter",y:"year",yr:"year",year:"year",years:"year",...Oxn},Nxn=`(?:${Bd(rat)}|[0-9]+|[0-9]+\\.[0-9]+|half(?:\\s{0,2}an?)?|an?\\b(?:\\s{0,2}few)?|few|several|the|a?\\s{0,2}couple\\s{0,2}(?:of)?)`;function tUr(t){let e=t.toLowerCase();return rat[e]!==void 0?rat[e]:e==="a"||e==="an"||e=="the"?1:e.match(/few/)?3:e.match(/half/)?.5:e.match(/couple/)?2:e.match(/several/)?7:parseFloat(e)}var Gq=`(?:${Bd(oat)}|[0-9]{1,2}(?:st|nd|rd|th)?)`;function Zq(t){let e=t.toLowerCase();return oat[e]!==void 0?oat[e]:(e=e.replace(/(?:st|nd|rd|th)$/i,""),parseInt(e))}var wO="(?:[1-9][0-9]{0,3}\\s{0,2}(?:BE|AD|BC|BCE|CE)|[1-2][0-9]{3}|[5-9][0-9]|2[0-5])";function bO(t){if(/BE/i.test(t))return t=t.replace(/BE/i,""),parseInt(t)-543;if(/BCE?/i.test(t))return t=t.replace(/BCE?/i,""),-parseInt(t);if(/(AD|CE)/i.test(t))return t=t.replace(/(AD|CE)/i,""),parseInt(t);let e=parseInt(t);return B0e(e)}var Rxn=`(${Nxn})\\s{0,3}(${Bd(Sre)})`,Mxn=new RegExp(Rxn,"i"),nUr=`(${Nxn})\\s{0,3}(${Bd(Oxn)})`,Lxn="\\s{0,5},?(?:\\s*and)?\\s{0,5}",K0=nat("(?:(?:about|around)\\s{0,3})?",Rxn,Lxn),_O=nat("(?:(?:about|around)\\s{0,3})?",nUr,Lxn);function ow(t){let e={},n=t,r=Mxn.exec(n);for(;r;)rUr(e,r),n=n.substring(r[0].length).trim(),r=Mxn.exec(n);return Object.keys(e).length==0?null:e}function rUr(t,e){if(e[0].match(/^[a-zA-Z]+$/))return;let n=tUr(e[1]),r=Sre[e[2].toLowerCase()];t[r]=n}var Hi=class{constructor(){this.cachedInnerPattern=null,this.cachedPattern=null}innerPatternHasChange(e,n){return this.innerPattern(e)!==n}patternLeftBoundary(){return"(\\W|^)"}pattern(e){return this.cachedInnerPattern&&!this.innerPatternHasChange(e,this.cachedInnerPattern)?this.cachedPattern:(this.cachedInnerPattern=this.innerPattern(e),this.cachedPattern=new RegExp(`${this.patternLeftBoundary()}${this.cachedInnerPattern.source}`,this.cachedInnerPattern.flags),this.cachedPattern)}extract(e,n){let r=n[1]??"";n.index=n.index+r.length,n[0]=n[0].substring(r.length);for(let o=2;o<n.length;o++)n[o-1]=n[o];return this.innerExtract(e,n)}};var oUr=new RegExp(`(?:(?:within|in|for)\\s*)?(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${K0})(?=\\W|$)`,"i"),iUr=new RegExp(`(?:within|in|for)\\s*(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${K0})(?=\\W|$)`,"i"),sUr=new RegExp(`(?:within|in|for)\\s*(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${_O})(?=\\W|$)`,"i"),Cre=class extends Hi{constructor(e){super(),this.strictMode=e}innerPattern(e){return this.strictMode?sUr:e.option.forwardDate?oUr:iUr}innerExtract(e,n){if(n[0].match(/^for\s*the\s*\w+/))return null;let r=ow(n[1]);return r?Yo.createRelativeFromReference(e.reference,r):null}};var aUr=new RegExp(`(?:on\\s{0,3})?(${Gq})(?:\\s{0,3}(?:to|\\-|\\\u2013|until|through|till)?\\s{0,3}(${Gq}))?(?:-|/|\\s{0,3}(?:of)?\\s{0,3})(${Bd(rw)})(?:(?:-|/|,?\\s{0,3})(${wO}(?!\\w)))?(?=\\W|$)`,"i"),$xn=1,Dxn=2,lUr=3,Fxn=4,kre=class extends Hi{innerPattern(){return aUr}innerExtract(e,n){let r=e.createParsingResult(n.index,n[0]),o=rw[n[lUr].toLowerCase()],i=Zq(n[$xn]);if(i>31)return n.index=n.index+n[$xn].length,null;if(r.start.assign("month",o),r.start.assign("day",i),n[Fxn]){let s=bO(n[Fxn]);r.start.assign("year",s)}else{let s=vO(e.refDate,i,o);r.start.imply("year",s)}if(n[Dxn]){let s=Zq(n[Dxn]);r.end=r.start.clone(),r.end.assign("day",s)}return r}};var cUr=new RegExp(`(${Bd(rw)})(?:-|/|\\s*,?\\s*)(${Gq})(?!\\s*(?:am|pm))\\s*(?:(?:to|\\-)\\s*(${Gq})\\s*)?(?:(?:-|/|\\s*,\\s*|\\s+)(${wO}))?(?=\\W|$)(?!\\:\\d)`,"i"),uUr=1,Uxn=2,aat=3,lat=4,Ire=class extends Hi{constructor(e){super(),this.shouldSkipYearLikeDate=e}innerPattern(){return cUr}innerExtract(e,n){let r=rw[n[uUr].toLowerCase()],o=Zq(n[Uxn]);if(o>31||this.shouldSkipYearLikeDate&&!n[aat]&&!n[lat]&&n[Uxn].match(/^2[0-5]$/))return null;let i=e.createParsingComponents({day:o,month:r}).addTag("parser/ENMonthNameMiddleEndianParser");if(n[lat]){let l=bO(n[lat]);i.assign("year",l)}else{let l=vO(e.refDate,o,r);i.imply("year",l)}if(!n[aat])return i;let s=Zq(n[aat]),a=e.createParsingResult(n.index,n[0]);return a.start=i,a.end=i.clone(),a.end.assign("day",s),a}};var dUr=new RegExp(`((?:in)\\s*)?(${Bd(rw)})\\s*(?:[,-]?\\s*(${wO})?)?(?=[^\\s\\w]|\\s+[^0-9]|\\s+$|$)`,"i"),fUr=1,pUr=2,jxn=3,Tre=class extends Hi{innerPattern(){return dUr}innerExtract(e,n){let r=n[pUr].toLowerCase();if(n[0].length<=3&&!sat[r])return null;let o=e.createParsingResult(n.index+(n[fUr]||"").length,n.index+n[0].length);o.start.imply("day",1),o.start.addTag("parser/ENMonthNameParser");let i=rw[r];if(o.start.assign("month",i),n[jxn]){let s=bO(n[jxn]);o.start.assign("year",s)}else{let s=vO(e.refDate,1,i);o.start.imply("year",s)}return o}};var mUr=new RegExp(`([0-9]{4})[-\\.\\/\\s](?:(${Bd(rw)})|([0-9]{1,2}))[-\\.\\/\\s]([0-9]{1,2})(?=\\W|$)`,"i"),hUr=1,gUr=2,Bxn=3,yUr=4,Pre=class extends Hi{constructor(e){super(),this.strictMonthDateOrder=e}innerPattern(){return mUr}innerExtract(e,n){let r=parseInt(n[hUr]),o=parseInt(n[yUr]),i=n[Bxn]?parseInt(n[Bxn]):rw[n[gUr].toLowerCase()];if(i<1||i>12){if(this.strictMonthDateOrder)return null;o>=1&&o<=12&&([i,o]=[o,i])}return o<1||o>31?null:{day:o,month:i,year:r}}};var vUr=new RegExp("([0-9]|0[1-9]|1[012])/([0-9]{4})","i"),wUr=1,bUr=2,Are=class extends Hi{innerPattern(){return vUr}innerExtract(e,n){let r=parseInt(n[bUr]),o=parseInt(n[wUr]);return e.createParsingComponents().imply("day",1).assign("month",o).assign("year",r)}};function _Ur(t,e,n,r){return new RegExp(`${t}${e}(\\d{1,4})(?:(?:\\.|:|\uFF1A)(\\d{1,2})(?:(?::|\uFF1A)(\\d{2})(?:\\.(\\d{1,6}))?)?)?(?:\\s*(a\\.m\\.|p\\.m\\.|am?|pm?))?${n}`,r)}function xUr(t,e){return new RegExp(`^(${t})(\\d{1,4})(?:(?:\\.|\\:|\\\uFF1A)(\\d{1,2})(?:(?:\\.|\\:|\\\uFF1A)(\\d{1,2})(?:\\.(\\d{1,6}))?)?)?(?:\\s*(a\\.m\\.|p\\.m\\.|am?|pm?))?${e}`,"i")}var zxn=2,Yq=3,z0e=4,H0e=5,Ere=6,W0e=class{constructor(e=!1){this.cachedPrimaryPrefix=null,this.cachedPrimarySuffix=null,this.cachedPrimaryTimePattern=null,this.cachedFollowingPhase=null,this.cachedFollowingSuffix=null,this.cachedFollowingTimePatten=null,this.strictMode=e}patternFlags(){return"i"}primaryPatternLeftBoundary(){return"(^|\\s|T|\\b)"}primarySuffix(){return"(?!/)(?=\\W|$)"}followingSuffix(){return"(?!/)(?=\\W|$)"}pattern(e){return this.getPrimaryTimePatternThroughCache()}extract(e,n){let r=this.extractPrimaryTimeComponents(e,n);if(!r)return n[0].match(/^\d{4}/)?(n.index+=4,null):(n.index+=n[0].length,null);let o=n.index+n[1].length,i=n[0].substring(n[1].length),s=e.createParsingResult(o,i,r);n.index+=n[0].length;let a=e.text.substring(n.index),c=this.getFollowingTimePatternThroughCache().exec(a);return i.match(/^\d{3,4}/)&&c&&(c[0].match(/^\s*([+-])\s*\d{2,4}$/)||c[0].match(/^\s*([+-])\s*\d{2}\W\d{2}/))?null:!c||c[0].match(/^\s*([+-])\s*\d{3,4}$/)?this.checkAndReturnWithoutFollowingPattern(s):(s.end=this.extractFollowingTimeComponents(e,c,s),s.end&&(s.text+=c[0]),this.checkAndReturnWithFollowingPattern(s))}extractPrimaryTimeComponents(e,n,r=!1){let o=e.createParsingComponents(),i=0,s=null,a=parseInt(n[zxn]);if(a>100){if(this.strictMode||n[Yq]!=null)return null;i=a%100,a=Math.floor(a/100)}if(a>24)return null;if(n[Yq]!=null){if(n[Yq].length==1&&!n[Ere])return null;i=parseInt(n[Yq])}if(i>=60)return null;if(a>12&&(s=Zo.PM),n[Ere]!=null){if(a>12)return null;let l=n[Ere][0].toLowerCase();l=="a"&&(s=Zo.AM,a==12&&(a=0)),l=="p"&&(s=Zo.PM,a!=12&&(a+=12))}if(o.assign("hour",a),o.assign("minute",i),s!==null?o.assign("meridiem",s):a<12?o.imply("meridiem",Zo.AM):o.imply("meridiem",Zo.PM),n[H0e]!=null){let l=parseInt(n[H0e].substring(0,3));if(l>=1e3)return null;o.assign("millisecond",l)}if(n[z0e]!=null){let l=parseInt(n[z0e]);if(l>=60)return null;o.assign("second",l)}return o}extractFollowingTimeComponents(e,n,r){let o=e.createParsingComponents();if(n[H0e]!=null){let l=parseInt(n[H0e].substring(0,3));if(l>=1e3)return null;o.assign("millisecond",l)}if(n[z0e]!=null){let l=parseInt(n[z0e]);if(l>=60)return null;o.assign("second",l)}let i=parseInt(n[zxn]),s=0,a=-1;if(n[Yq]!=null?s=parseInt(n[Yq]):i>100&&(s=i%100,i=Math.floor(i/100)),s>=60||i>24)return null;if(i>=12&&(a=Zo.PM),n[Ere]!=null){if(i>12)return null;let l=n[Ere][0].toLowerCase();l=="a"&&(a=Zo.AM,i==12&&(i=0,o.isCertain("day")||o.imply("day",o.get("day")+1))),l=="p"&&(a=Zo.PM,i!=12&&(i+=12)),r.start.isCertain("meridiem")||(a==Zo.AM?(r.start.imply("meridiem",Zo.AM),r.start.get("hour")==12&&r.start.assign("hour",0)):(r.start.imply("meridiem",Zo.PM),r.start.get("hour")!=12&&r.start.assign("hour",r.start.get("hour")+12)))}return o.assign("hour",i),o.assign("minute",s),a>=0?o.assign("meridiem",a):r.start.isCertain("meridiem")&&r.start.get("hour")>12?r.start.get("hour")-12>i?o.imply("meridiem",Zo.AM):i<=12&&(o.assign("hour",i+12),o.assign("meridiem",Zo.PM)):i>12?o.imply("meridiem",Zo.PM):i<=12&&o.imply("meridiem",Zo.AM),o.date().getTime()<r.start.date().getTime()&&o.imply("day",o.get("day")+1),o}checkAndReturnWithoutFollowingPattern(e){if(e.text.match(/^\d$/)||e.text.match(/^\d\d\d+$/)||e.text.match(/\d[apAP]$/))return null;let n=e.text.match(/[^\d:.](\d[\d.]+)$/);if(n){let r=n[1];if(this.strictMode||r.includes(".")&&!r.match(/\d(\.\d{2})+$/)||parseInt(r)>24)return null}return e}checkAndReturnWithFollowingPattern(e){if(e.text.match(/^\d+-\d+$/))return null;let n=e.text.match(/[^\d:.](\d[\d.]+)\s*-\s*(\d[\d.]+)$/);if(n){if(this.strictMode)return null;let r=n[1],o=n[2];if(o.includes(".")&&!o.match(/\d(\.\d{2})+$/))return null;let i=parseInt(o),s=parseInt(r);if(i>24||s>24)return null}return e}getPrimaryTimePatternThroughCache(){let e=this.primaryPrefix(),n=this.primarySuffix();return this.cachedPrimaryPrefix===e&&this.cachedPrimarySuffix===n?this.cachedPrimaryTimePattern:(this.cachedPrimaryTimePattern=_Ur(this.primaryPatternLeftBoundary(),e,n,this.patternFlags()),this.cachedPrimaryPrefix=e,this.cachedPrimarySuffix=n,this.cachedPrimaryTimePattern)}getFollowingTimePatternThroughCache(){let e=this.followingPhase(),n=this.followingSuffix();return this.cachedFollowingPhase===e&&this.cachedFollowingSuffix===n?this.cachedFollowingTimePatten:(this.cachedFollowingTimePatten=xUr(e,n),this.cachedFollowingPhase=e,this.cachedFollowingSuffix=n,this.cachedFollowingTimePatten)}};var Mre=class extends W0e{constructor(e){super(e)}followingPhase(){return"\\s*(?:\\-|\\\u2013|\\~|\\\u301C|to|until|through|till|\\?)\\s*"}primaryPrefix(){return"(?:(?:at|from)\\s*)??"}primarySuffix(){return"(?:\\s*(?:o\\W*clock|at\\s*night|in\\s*the\\s*(?:morning|afternoon)))?(?!/)(?=\\W|$)"}extractPrimaryTimeComponents(e,n){let r=super.extractPrimaryTimeComponents(e,n);if(!r)return r;if(n[0].endsWith("night")){let o=r.get("hour");o>=6&&o<12?(r.assign("hour",r.get("hour")+12),r.assign("meridiem",Zo.PM)):o<6&&r.assign("meridiem",Zo.AM)}if(n[0].endsWith("afternoon")){r.assign("meridiem",Zo.PM);let o=r.get("hour");o>=0&&o<=6&&r.assign("hour",r.get("hour")+12)}return n[0].endsWith("morning")&&(r.assign("meridiem",Zo.AM),r.get("hour")<12&&r.assign("hour",r.get("hour"))),r.addTag("parser/ENTimeExpressionParser")}};function xO(t){let e={};for(let n in t)e[n]=-t[n];return e}function Hxn(t,e){let n=t.clone(),r=t.dayjs();for(let o in e)r=r.add(e[o],o);return("day"in e||"d"in e||"week"in e||"month"in e||"year"in e)&&(n.imply("day",r.date()),n.imply("month",r.month()+1),n.imply("year",r.year())),("second"in e||"minute"in e||"hour"in e)&&(n.imply("second",r.second()),n.imply("minute",r.minute()),n.imply("hour",r.hour())),n}var SUr=new RegExp(`(${K0})\\s{0,5}(?:ago|before|earlier)(?=\\W|$)`,"i"),CUr=new RegExp(`(${_O})\\s{0,5}(?:ago|before|earlier)(?=\\W|$)`,"i"),Ore=class extends Hi{constructor(e){super(),this.strictMode=e}innerPattern(){return this.strictMode?CUr:SUr}innerExtract(e,n){let r=ow(n[1]);if(!r)return null;let o=xO(r);return Yo.createRelativeFromReference(e.reference,o)}};var kUr=new RegExp(`(${K0})\\s{0,5}(?:later|after|from now|henceforth|forward|out)(?=(?:\\W|$))`,"i"),IUr=new RegExp(`(${_O})\\s{0,5}(later|after|from now)(?=\\W|$)`,"i"),TUr=1,Nre=class extends Hi{constructor(e){super(),this.strictMode=e}innerPattern(){return this.strictMode?IUr:kUr}innerExtract(e,n){let r=ow(n[TUr]);return r?Yo.createRelativeFromReference(e.reference,r):null}};var V0e=class{refine(e,n){return n.filter(r=>this.isValid(e,r))}},iw=class{refine(e,n){if(n.length<2)return n;let r=[],o=n[0],i=null;for(let s=1;s<n.length;s++){i=n[s];let a=e.text.substring(o.index+o.text.length,i.index);if(!this.shouldMergeResults(a,o,i,e))r.push(o),o=i;else{let l=o,c=i,u=this.mergeResults(a,l,c,e);e.debug(()=>{console.log(`${this.constructor.name} merged ${l} and ${c} into ${u}`)}),o=u}}return o!=null&&r.push(o),r}};var Rre=class extends iw{shouldMergeResults(e,n,r){return!n.end&&!r.end&&e.match(this.patternBetween())!=null}mergeResults(e,n,r){if(!n.start.isOnlyWeekdayComponent()&&!r.start.isOnlyWeekdayComponent()&&(r.start.getCertainComponents().forEach(i=>{n.start.isCertain(i)||n.start.imply(i,r.start.get(i))}),n.start.getCertainComponents().forEach(i=>{r.start.isCertain(i)||r.start.imply(i,n.start.get(i))})),n.start.date().getTime()>r.start.date().getTime()){let i=n.start.dayjs(),s=r.start.dayjs();r.start.isOnlyWeekdayComponent()&&s.add(7,"days").isAfter(i)?(s=s.add(7,"days"),r.start.imply("day",s.date()),r.start.imply("month",s.month()+1),r.start.imply("year",s.year())):n.start.isOnlyWeekdayComponent()&&i.add(-7,"days").isBefore(s)?(i=i.add(-7,"days"),n.start.imply("day",i.date()),n.start.imply("month",i.month()+1),n.start.imply("year",i.year())):r.start.isDateWithUnknownYear()&&s.add(1,"years").isAfter(i)?(s=s.add(1,"years"),r.start.imply("year",s.year())):n.start.isDateWithUnknownYear()&&i.add(-1,"years").isBefore(s)?(i=i.add(-1,"years"),n.start.imply("year",i.year())):[r,n]=[n,r]}let o=n.clone();return o.start=n.start,o.end=r.start,o.index=Math.min(n.index,r.index),n.index<r.index?o.text=n.text+e+r.text:o.text=r.text+e+n.text,o}};var Lre=class extends Rre{patternBetween(){return/^\s*(to|-|–|until|through|till)\s*$/i}};function cat(t,e){let n=t.clone(),r=t.start,o=e.start;if(n.start=Wxn(r,o),t.end!=null||e.end!=null){let i=t.end==null?t.start:t.end,s=e.end==null?e.start:e.end,a=Wxn(i,s);if(t.end==null&&a.date().getTime()<n.start.date().getTime()){let l=a.dayjs().add(1,"day");a.isCertain("day")?P_(a,l):lF(a,l)}n.end=a}return n}function Wxn(t,e){let n=t.clone();return e.isCertain("hour")?(n.assign("hour",e.get("hour")),n.assign("minute",e.get("minute")),e.isCertain("second")?(n.assign("second",e.get("second")),e.isCertain("millisecond")?n.assign("millisecond",e.get("millisecond")):n.imply("millisecond",e.get("millisecond"))):(n.imply("second",e.get("second")),n.imply("millisecond",e.get("millisecond")))):(n.imply("hour",e.get("hour")),n.imply("minute",e.get("minute")),n.imply("second",e.get("second")),n.imply("millisecond",e.get("millisecond"))),e.isCertain("timezoneOffset")&&n.assign("timezoneOffset",e.get("timezoneOffset")),e.isCertain("meridiem")?n.assign("meridiem",e.get("meridiem")):e.get("meridiem")!=null&&n.get("meridiem")==null&&n.imply("meridiem",e.get("meridiem")),n.get("meridiem")==Zo.PM&&n.get("hour")<12&&(e.isCertain("hour")?n.assign("hour",n.get("hour")+12):n.imply("hour",n.get("hour")+12)),n.addTags(t.tags()),n.addTags(e.tags()),n}var $re=class extends iw{shouldMergeResults(e,n,r){return(n.start.isOnlyDate()&&r.start.isOnlyTime()||r.start.isOnlyDate()&&n.start.isOnlyTime())&&e.match(this.patternBetween())!=null}mergeResults(e,n,r){let o=n.start.isOnlyDate()?cat(n,r):cat(r,n);return o.index=n.index,o.text=n.text+e+r.text,o}};var Jq=class extends $re{patternBetween(){return new RegExp("^\\s*(T|at|after|before|on|of|,|-|\\.|\u2219|:)?\\s*$")}};var PUr=new RegExp("^\\s*,?\\s*\\(?([A-Z]{2,4})\\)?(?=\\W|$)","i"),Dre=class{constructor(e){this.timezoneOverrides=e}refine(e,n){let r=e.option.timezones??{};return n.forEach(o=>{let i=e.text.substring(o.index+o.text.length),s=PUr.exec(i);if(!s)return;let a=s[1].toUpperCase(),l=o.start.date()??o.refDate??new Date,c={...this.timezoneOverrides,...r},u=j0e(a,l,c);if(u==null)return;e.debug(()=>{console.log(`Extracting timezone: '${a}' into: ${u} for: ${o.start}`)});let d=o.start.get("timezoneOffset");d!==null&&u!=d&&(o.start.isCertain("timezoneOffset")||a!=s[1])||o.start.isOnlyDate()&&a!=s[1]||(o.text+=s[0],o.start.isCertain("timezoneOffset")||o.start.assign("timezoneOffset",u),o.end!=null&&!o.end.isCertain("timezoneOffset")&&o.end.assign("timezoneOffset",u))}),n}};var AUr=new RegExp("^\\s*(?:\\(?(?:GMT|UTC)\\s?)?([+-])(\\d{1,2})(?::?(\\d{2}))?\\)?","i"),EUr=1,MUr=2,OUr=3,Fre=class{refine(e,n){return n.forEach(function(r){if(r.start.isCertain("timezoneOffset"))return;let o=e.text.substring(r.index+r.text.length),i=AUr.exec(o);if(!i)return;e.debug(()=>{console.log(`Extracting timezone: '${i[0]}' into : ${r}`)});let s=parseInt(i[MUr]),a=parseInt(i[OUr]||"0"),l=s*60+a;l>14*60||(i[EUr]==="-"&&(l=-l),r.end!=null&&r.end.assign("timezoneOffset",l),r.start.assign("timezoneOffset",l),r.text+=i[0])}),n}};var SO=class{refine(e,n){if(n.length<2)return n;let r=[],o=n[0];for(let i=1;i<n.length;i++){let s=n[i];if(s.index>=o.index+o.text.length){r.push(o),o=s;continue}let a=null,l=null;s.text.length>o.text.length?(a=s,l=o):(a=o,l=s),e.debug(()=>{console.log(`${this.constructor.name} remove ${l} by ${a}`)}),o=a}return o!=null&&r.push(o),r}};var Vxn=L(hO(),1);var Ure=class{refine(e,n){return e.option.forwardDate&&n.forEach(r=>{let o=(0,Vxn.default)(e.refDate);if(r.start.isOnlyTime()&&o.isAfter(r.start.dayjs())&&(o=o.add(1,"day"),lF(r.start,o),r.end&&r.end.isOnlyTime()&&(lF(r.end,o),r.start.dayjs().isAfter(r.end.dayjs())&&(o=o.add(1,"day"),lF(r.end,o))),e.debug(()=>{console.log(`${this.constructor.name} adjusted ${r} time result (${r.start})`)})),r.start.isOnlyWeekdayComponent()&&o.isAfter(r.start.dayjs())&&(o.day()>=r.start.get("weekday")?o=o.day(r.start.get("weekday")+7):o=o.day(r.start.get("weekday")),r.start.imply("day",o.date()),r.start.imply("month",o.month()+1),r.start.imply("year",o.year()),e.debug(()=>{console.log(`${this.constructor.name} adjusted ${r} weekday (${r.start})`)}),r.end&&r.end.isOnlyWeekdayComponent()&&(o.day()>r.end.get("weekday")?o=o.day(r.end.get("weekday")+7):o=o.day(r.end.get("weekday")),r.end.imply("day",o.date()),r.end.imply("month",o.month()+1),r.end.imply("year",o.year()),e.debug(()=>{console.log(`${this.constructor.name} adjusted ${r} weekday (${r.end})`)}))),r.start.isDateWithUnknownYear()&&o.isAfter(r.start.dayjs()))for(let i=0;i<3&&o.isAfter(r.start.dayjs());i++)r.start.imply("year",r.start.get("year")+1),e.debug(()=>{console.log(`${this.constructor.name} adjusted ${r} year (${r.start})`)}),r.end&&!r.end.isCertain("year")&&(r.end.imply("year",r.end.get("year")+1),e.debug(()=>{console.log(`${this.constructor.name} adjusted ${r} month (${r.start})`)}))}),n}};var jre=class extends V0e{constructor(e){super(),this.strictMode=e}isValid(e,n){return n.text.replace(" ","").match(/^\d*(\.\d*)?$/)?(e.debug(()=>{console.log(`Removing unlikely result '${n.text}'`)}),!1):n.start.isValidDate()?n.end&&!n.end.isValidDate()?(e.debug(()=>{console.log(`Removing invalid result: ${n} (${n.end})`)}),!1):this.strictMode?this.isStrictModeValid(e,n):!0:(e.debug(()=>{console.log(`Removing invalid result: ${n} (${n.start})`)}),!1)}isStrictModeValid(e,n){return n.start.isOnlyWeekdayComponent()?(e.debug(()=>{console.log(`(Strict) Removing weekday only component: ${n} (${n.end})`)}),!1):n.start.isOnlyTime()&&(!n.start.isCertain("hour")||!n.start.isCertain("minute"))?(e.debug(()=>{console.log(`(Strict) Removing uncertain time component: ${n} (${n.end})`)}),!1):!0}};var NUr=new RegExp("([0-9]{4})\\-([0-9]{1,2})\\-([0-9]{1,2})(?:T([0-9]{1,2}):([0-9]{1,2})(?::([0-9]{1,2})(?:\\.(\\d{1,4}))?)?(Z|([+-]\\d{2}):?(\\d{2})?)?)?(?=\\W|$)","i"),RUr=1,LUr=2,$Ur=3,qxn=4,DUr=5,Kxn=6,Gxn=7,FUr=8,Zxn=9,Yxn=10,Bre=class extends Hi{innerPattern(){return NUr}innerExtract(e,n){let r=e.createParsingComponents({year:parseInt(n[RUr]),month:parseInt(n[LUr]),day:parseInt(n[$Ur])});if(n[qxn]!=null&&(r.assign("hour",parseInt(n[qxn])),r.assign("minute",parseInt(n[DUr])),n[Kxn]!=null&&r.assign("second",parseInt(n[Kxn])),n[Gxn]!=null&&r.assign("millisecond",parseInt(n[Gxn])),n[FUr]!=null)){let o=0;if(n[Zxn]){let i=parseInt(n[Zxn]),s=0;n[Yxn]!=null&&(s=parseInt(n[Yxn])),o=i*60,o<0?o-=s:o+=s}r.assign("timezoneOffset",o)}return r.addTag("parser/ISOFormatParser")}};var zre=class extends iw{mergeResults(e,n,r){let o=r.clone();return o.index=n.index,o.text=n.text+e+o.text,o.start.assign("weekday",n.start.get("weekday")),o.end&&o.end.assign("weekday",n.start.get("weekday")),o}shouldMergeResults(e,n,r){return n.start.isOnlyWeekdayComponent()&&!n.start.isCertain("hour")&&r.start.isCertain("day")&&e.match(/^,?\s*$/)!=null}};function Jxn(t,e=!1){return t.parsers.unshift(new Bre),t.refiners.unshift(new zre),t.refiners.unshift(new Fre),t.refiners.unshift(new SO),t.refiners.push(new Dre),t.refiners.push(new SO),t.refiners.push(new Ure),t.refiners.push(new jre(e)),t}var uSn=L(hO(),1);var Xq=L(hO(),1);function Xxn(t){let e=(0,Xq.default)(t.instant),n=new Yo(t,{});return P_(n,e),U0e(n,e),t.timezoneOffset!==null&&n.assign("timezoneOffset",e.utcOffset()),n.addTag("casualReference/now"),n}function Qxn(t){let e=(0,Xq.default)(t.instant),n=new Yo(t,{});return P_(n,e),Kq(n,e),n.addTag("casualReference/today"),n}function eSn(t){return UUr(t,1).addTag("casualReference/yesterday")}function UUr(t,e){return nSn(t,-e)}function tSn(t){return nSn(t,1).addTag("casualReference/tomorrow")}function nSn(t,e){let n=(0,Xq.default)(t.instant),r=new Yo(t,{});return n=n.add(e,"day"),P_(r,n),Kq(r,n),r}function rSn(t,e=22){let n=(0,Xq.default)(t.instant),r=new Yo(t,{});return P_(r,n),r.imply("hour",e),r.imply("meridiem",Zo.PM),r.addTag("casualReference/tonight"),r}function oSn(t,e=20){let n=new Yo(t,{});return n.imply("meridiem",Zo.PM),n.imply("hour",e),n.addTag("casualReference/evening"),n}function iSn(t){let e=new Yo(t,{}),n=(0,Xq.default)(t.instant);return n.hour()>2&&Txn(e,n),e.assign("hour",0),e.imply("minute",0),e.imply("second",0),e.imply("millisecond",0),e.addTag("casualReference/midnight"),e}function sSn(t,e=6){let n=new Yo(t,{});return n.imply("meridiem",Zo.AM),n.imply("hour",e),n.imply("minute",0),n.imply("second",0),n.imply("millisecond",0),n.addTag("casualReference/morning"),n}function aSn(t,e=15){let n=new Yo(t,{});return n.imply("meridiem",Zo.PM),n.imply("hour",e),n.imply("minute",0),n.imply("second",0),n.imply("millisecond",0),n.addTag("casualReference/afternoon"),n}function lSn(t){let e=new Yo(t,{});return e.imply("meridiem",Zo.AM),e.imply("hour",12),e.imply("minute",0),e.imply("second",0),e.imply("millisecond",0),e.addTag("casualReference/noon"),e}var jUr=/(now|today|tonight|tomorrow|tmr|tmrw|yesterday|last\s*night)(?=\W|$)/i,Hre=class extends Hi{innerPattern(e){return jUr}innerExtract(e,n){let r=(0,uSn.default)(e.refDate),o=n[0].toLowerCase(),i=e.createParsingComponents();switch(o){case"now":i=Xxn(e.reference);break;case"today":i=Qxn(e.reference);break;case"yesterday":i=eSn(e.reference);break;case"tomorrow":case"tmr":case"tmrw":i=tSn(e.reference);break;case"tonight":i=rSn(e.reference);break;default:o.match(/last\s*night/)&&(r.hour()>6&&(r=r.add(-1,"day")),P_(i,r),i.imply("hour",0));break}return i.addTag("parser/ENCasualDateParser"),i}};var BUr=/(?:this)?\s{0,3}(morning|afternoon|evening|night|midnight|midday|noon)(?=\W|$)/i,Wre=class extends Hi{innerPattern(){return BUr}innerExtract(e,n){let r=null;switch(n[1].toLowerCase()){case"afternoon":r=aSn(e.reference);break;case"evening":case"night":r=oSn(e.reference);break;case"midnight":r=iSn(e.reference);break;case"morning":r=sSn(e.reference);break;case"noon":case"midday":r=lSn(e.reference);break}return r&&r.addTag("parser/ENCasualTimeParser"),r}};function dSn(t,e,n){let r=t.getDateWithAdjustedTimezone(),o=zUr(r,e,n),i=new Yo(t);return i=Hxn(i,{day:o}),i.assign("weekday",e),i}function zUr(t,e,n){let r=t.getDay();switch(n){case"this":return q0e(t,e);case"last":return fSn(t,e);case"next":return r==lc.SUNDAY?e==lc.SUNDAY?7:e:r==lc.SATURDAY?e==lc.SATURDAY?7:e==lc.SUNDAY?8:1+e:e<r&&e!=lc.SUNDAY?q0e(t,e):q0e(t,e)+7}return HUr(t,e)}function HUr(t,e){let n=fSn(t,e),r=q0e(t,e);return r<-n?r:n}function q0e(t,e){let n=t.getDay(),r=e-n;return r<0&&(r+=7),r}function fSn(t,e){let n=t.getDay(),r=e-n;return r>=0&&(r-=7),r}var WUr=new RegExp(`(?:(?:\\,|\\(|\\\uFF08)\\s*)?(?:on\\s*?)?(?:(this|last|past|next)\\s*)?(${Bd(iat)})(?:\\s*(?:\\,|\\)|\\\uFF09))?(?:\\s*(this|last|past|next)\\s*week)?(?=\\W|$)`,"i"),VUr=1,qUr=2,KUr=3,Vre=class extends Hi{innerPattern(){return WUr}innerExtract(e,n){let r=n[qUr].toLowerCase(),o=iat[r],i=n[VUr],s=n[KUr],a=i||s;a=a||"",a=a.toLowerCase();let l=null;return a=="last"||a=="past"?l="last":a=="next"?l="next":a=="this"&&(l="this"),dSn(e.reference,o,l)}};var pSn=L(hO(),1);var GUr=new RegExp(`(this|last|past|next|after\\s*this)\\s*(${Bd(Sre)})(?=\\s*)(?=\\W|$)`,"i"),ZUr=1,YUr=2,qre=class extends Hi{innerPattern(){return GUr}innerExtract(e,n){let r=n[ZUr].toLowerCase(),o=n[YUr].toLowerCase(),i=Sre[o];if(r=="next"||r.startsWith("after")){let l={};return l[i]=1,Yo.createRelativeFromReference(e.reference,l)}if(r=="last"||r=="past"){let l={};return l[i]=-1,Yo.createRelativeFromReference(e.reference,l)}let s=e.createParsingComponents(),a=(0,pSn.default)(e.reference.instant);return o.match(/week/i)?(a=a.add(-a.get("d"),"d"),s.imply("day",a.date()),s.imply("month",a.month()+1),s.imply("year",a.year())):o.match(/month/i)?(a=a.add(-a.date()+1,"d"),s.imply("day",a.date()),s.assign("year",a.year()),s.assign("month",a.month()+1)):o.match(/year/i)&&(a=a.add(-a.date()+1,"d"),a=a.add(-a.month(),"month"),s.imply("day",a.date()),s.imply("month",a.month()+1),s.assign("year",a.year())),s}};var JUr=new RegExp("([^\\d]|^)([0-3]{0,1}[0-9]{1})[\\/\\.\\-]([0-3]{0,1}[0-9]{1})(?:[\\/\\.\\-]([0-9]{4}|[0-9]{2}))?(\\W|$)","i"),XUr=1,QUr=5,mSn=2,hSn=3,uat=4,Kre=class{constructor(e){this.groupNumberMonth=e?hSn:mSn,this.groupNumberDay=e?mSn:hSn}pattern(){return JUr}extract(e,n){let r=n.index+n[XUr].length,o=n.index+n[0].length-n[QUr].length;if(r>0&&e.text.substring(0,r).match("\\d/?$")||o<e.text.length&&e.text.substring(o).match("^/?\\d"))return;let i=e.text.substring(r,o);if(i.match(/^\d\.\d$/)||i.match(/^\d\.\d{1,2}\.\d{1,2}\s*$/)||!n[uat]&&i.indexOf("/")<0)return;let s=e.createParsingResult(r,i),a=parseInt(n[this.groupNumberMonth]),l=parseInt(n[this.groupNumberDay]);if((a<1||a>12)&&a>12)if(l>=1&&l<=12&&a<=31)[l,a]=[a,l];else return null;if(l<1||l>31)return null;if(s.start.assign("day",l),s.start.assign("month",a),n[uat]){let c=parseInt(n[uat]),u=B0e(c);s.start.assign("year",u)}else{let c=vO(e.refDate,l,a);s.start.imply("year",c)}return s}};var ejr=new RegExp(`(this|last|past|next|after|\\+|-)\\s*(${K0})(?=\\W|$)`,"i"),tjr=new RegExp(`(this|last|past|next|after|\\+|-)\\s*(${_O})(?=\\W|$)`,"i"),Gre=class extends Hi{constructor(e=!0){super(),this.allowAbbreviations=e}innerPattern(){return this.allowAbbreviations?ejr:tjr}innerExtract(e,n){let r=n[1].toLowerCase(),o=ow(n[2]);if(!o)return null;switch(r){case"last":case"past":case"-":o=xO(o);break}return Yo.createRelativeFromReference(e.reference,o)}};function njr(t){return t.text.match(/^[+-]/i)!=null}function gSn(t){return t.text.match(/^-/i)!=null}var Zre=class extends iw{shouldMergeResults(e,n,r){return e.match(/^\s*$/i)?njr(r)||gSn(r):!1}mergeResults(e,n,r,o){let i=ow(r.text);gSn(r)&&(i=xO(i));let s=Yo.createRelativeFromReference(new yO(n.start.date()),i);return new q0(n.reference,n.index,`${n.text}${e}${r.text}`,s)}};function ySn(t){return t.text.match(/\s+(before|from)$/i)!=null}function rjr(t){return t.text.match(/\s+(after|since)$/i)!=null}var Yre=class extends iw{patternBetween(){return/^\s*$/i}shouldMergeResults(e,n,r){return!e.match(this.patternBetween())||!ySn(n)&&!rjr(n)?!1:!!r.start.get("day")&&!!r.start.get("month")&&!!r.start.get("year")}mergeResults(e,n,r){let o=ow(n.text);ySn(n)&&(o=xO(o));let i=Yo.createRelativeFromReference(new yO(r.start.date()),o);return new q0(r.reference,n.index,`${n.text}${e}${r.text}`,i)}};var ojr=new RegExp(`^\\s*(${wO})`,"i"),ijr=1,Jre=class{refine(e,n){return n.forEach(function(r){if(!r.start.isDateWithUnknownYear())return;let o=e.text.substring(r.index+r.text.length),i=ojr.exec(o);if(!i)return;e.debug(()=>{console.log(`Extracting year: '${i[0]}' into : ${r}`)});let s=bO(i[ijr]);r.end!=null&&r.end.assign("year",s),r.start.assign("year",s),r.text+=i[0]}),n}};var cF=class{createCasualConfiguration(e=!1){let n=this.createConfiguration(!1,e);return n.parsers.push(new Hre),n.parsers.push(new Wre),n.parsers.push(new Tre),n.parsers.push(new qre),n.parsers.push(new Gre),n}createConfiguration(e=!0,n=!1){let r=Jxn({parsers:[new Kre(n),new Cre(e),new kre,new Ire(n),new Vre,new Are,new Mre(e),new Ore(e),new Nre(e)],refiners:[new Jq]},e);return r.parsers.unshift(new Pre(e)),r.refiners.unshift(new Yre),r.refiners.unshift(new Zre),r.refiners.unshift(new SO),r.refiners.push(new Jq),r.refiners.push(new Jre),r.refiners.push(new Lre),r}};var Qq=class t{constructor(e){this.defaultConfig=new cF,e=e||this.defaultConfig.createCasualConfiguration(),this.parsers=[...e.parsers],this.refiners=[...e.refiners]}clone(){return new t({parsers:[...this.parsers],refiners:[...this.refiners]})}parseDate(e,n,r){let o=this.parse(e,n,r);return o.length>0?o[0].start.date():null}parse(e,n,r){let o=new dat(e,n,r),i=[];return this.parsers.forEach(s=>{let a=t.executeParser(o,s);i=i.concat(a)}),i.sort((s,a)=>s.index-a.index),this.refiners.forEach(function(s){i=s.refine(o,i)}),i}static executeParser(e,n){let r=[],o=n.pattern(e),i=e.text,s=e.text,a=o.exec(s);for(;a;){let l=a.index+i.length-s.length;a.index=l;let c=n.extract(e,a);if(!c){s=i.substring(a.index+1),a=o.exec(s);continue}let u=null;c instanceof q0?u=c:c instanceof Yo?(u=e.createParsingResult(a.index,a[0]),u.start=c):u=e.createParsingResult(a.index,a[0],c);let d=u.index,f=u.text;e.debug(()=>console.log(`${n.constructor.name} extracted (at index=${d}) '${f}'`)),r.push(u),s=i.substring(d+f.length),a=o.exec(s)}return r}},dat=class{constructor(e,n,r){this.text=e,this.reference=new yO(n),this.option=r??{},this.refDate=this.reference.instant}createParsingComponents(e){return e instanceof Yo?e:new Yo(this.reference,e)}createParsingResult(e,n,r,o){let i=typeof n=="string"?n:this.text.substring(e,n),s=r?this.createParsingComponents(r):null,a=o?this.createParsingComponents(o):null;return new q0(this.reference,e,i,s,a)}debug(e){this.option.debug&&(this.option.debug instanceof Function?this.option.debug(e):this.option.debug.debug(e))}};var fat=new cF,vSn=new Qq(fat.createCasualConfiguration(!1)),sjr=new Qq(fat.createConfiguration(!0,!1)),nls=new Qq(fat.createCasualConfiguration(!0));var wSn=vSn;function pat(t,e,n){return wSn.parse(t,e,n)}function bSn(t,e,n){return wSn.parseDate(t,e,n)}TEe();ap();pe();function mat(t){let e=t.match(/^(?:UTC|GMT)?([-+]?\d{1,2})(?::(\d{2}))?$/i);if(!e)throw new Error(`Invalid timezone offset format: ${t}. Use formats like '+8', '-5', '+5:30', 'UTC+8', 'GMT-5'`);let n=parseInt(e[1]),r=parseInt(e[2]||"0");if(Math.abs(n)>14||r>=60)throw new Error(`Invalid timezone offset: ${t}. Hours must be between -14 and +14, minutes must be less than 60`);let o=n>=0?"+":"",i=r>0?`:${r.toString().padStart(2,"0")}`:"";return`UTC${o}${n}${i}`}async function cjr(t){let e=Wn.now();if(t)try{let i=mat(t),s=e.setZone(i);if(!s.isValid)throw new Error(`Failed to apply timezone offset: ${t}`);e=s}catch(i){throw new Error(`${i.message}`)}let n=e.toJSDate(),r=e.offset,o=e.offsetNameShort||"Unknown";return{epoch:Math.floor(n.getTime()),isoString:n.toISOString(),userLocaleString:e.toLocaleString(Wn.DATETIME_FULL),localDateString:e.toISODate()||"",timezoneOffset:r,timezone:o}}var _Sn=gi({name:"getCurrentTime",description:"Get the current time in local timezone or at a specified UTC offset. Returns epoch time, ISO string, and formatted strings.",schema:x.object({timezoneOffset:x.string().optional().describe(`Optional UTC offset. IMPORTANT: Must be a numeric offset, NOT a timezone name.
EXAMPLES OF CORRECT USAGE:
- "what time is it" \u2192 No parameter (uses local time)
- "what time is it in Tokyo" \u2192 timezoneOffset: "+9"
- "what time is it in Beijing" \u2192 timezoneOffset: "+8"
- "what time is it in New York" \u2192 timezoneOffset: "-5" (or "-4" during DST)
- "what time is it in Mumbai" \u2192 timezoneOffset: "+5:30"
SUPPORTED FORMATS:
- Simple: "+8", "-5", "+5:30"
- With prefix: "UTC+8", "GMT-5", "UTC+5:30"
COMMON TIMEZONE OFFSETS:
- Tokyo: UTC+9
- Beijing/Singapore: UTC+8
- Mumbai: UTC+5:30
- Dubai: UTC+4
- London: UTC+0 (UTC+1 during BST)
- New York: UTC-5 (UTC-4 during DST)
- Los Angeles: UTC-8 (UTC-7 during DST)`)}),func:async({timezoneOffset:t})=>cjr(t)}),xSn={jan:1,january:1,feb:2,february:2,mar:3,march:3,apr:4,april:4,may:5,jun:6,june:6,jul:7,july:7,aug:8,august:8,sep:9,sept:9,september:9,oct:10,october:10,nov:11,november:11,dec:12,december:12};function ujr(t,e){let n=t.match(/^(last|past|previous|prior)\s+(\d+)\s+(days?|weeks?|months?|years?)$/i);if(!n)return;let[,,r,o]=n,i=parseInt(r);if(i<=0)return;let s=o.replace(/s$/,""),a=e.startOf("day");return{start:a.minus({[s+"s"]:i}),end:a}}function djr(t,e){switch(t){case"yesterday":return{start:e.minus({days:1}).startOf("day"),end:e.minus({days:1}).endOf("day")};case"last week":return{start:e.minus({weeks:1}).startOf("week"),end:e.minus({weeks:1}).endOf("week")};case"this week":return{start:e.startOf("week"),end:e.endOf("week")};case"next week":return{start:e.plus({weeks:1}).startOf("week"),end:e.plus({weeks:1}).endOf("week")};case"last month":return{start:e.minus({months:1}).startOf("month"),end:e.minus({months:1}).endOf("month")};case"this month":return{start:e.startOf("month"),end:e.endOf("month")};case"next month":return{start:e.plus({months:1}).startOf("month"),end:e.plus({months:1}).endOf("month")};case"last year":return{start:e.minus({years:1}).startOf("year"),end:e.minus({years:1}).endOf("year")};case"this year":return{start:e.startOf("year"),end:e.endOf("year")};case"next year":return{start:e.plus({years:1}).startOf("year"),end:e.plus({years:1}).endOf("year")};case"last quarter":return{start:e.minus({quarters:1}).startOf("quarter"),end:e.minus({quarters:1}).endOf("quarter")};case"this quarter":return{start:e.startOf("quarter"),end:e.endOf("quarter")};case"next quarter":return{start:e.plus({quarters:1}).startOf("quarter"),end:e.plus({quarters:1}).endOf("quarter")}}}function fjr(t,e){let n=t.match(/(?:the\s+)?week\s+of\s+(.+)/i);if(!n)return;let r=n[1],o=pat(r,e.toJSDate(),{forwardDate:!1});if(o.length===0)return;let i=Wn.fromJSDate(o[0].start.date()).startOf("week"),s=i.endOf("week");return i>e&&(i=i.minus({years:1}),s=s.minus({years:1})),{start:i,end:s}}function pjr(t,e){let n=t.match(/^(jan|january|feb|february|mar|march|apr|april|may|jun|june|jul|july|aug|august|sep|sept|september|oct|october|nov|november|dec|december)$/i);if(!n)return;let r=xSn[n[1]],o=e.year;r>e.month&&o--;let i=Wn.fromObject({year:o,month:r,day:1}),s=i.endOf("month");return i>e&&(i=i.minus({years:1}),s=s.minus({years:1})),{start:i,end:s}}function mjr(t,e){let n=t.match(/^(?:(?:the\s+)?(?:year|yr)(?:\s+(?:of|in))?\s+)?(\d{4})$/i);if(!n)return;let r=parseInt(n[1]),o=Wn.fromObject({year:r,month:1,day:1}),i=Wn.fromObject({year:r,month:12,day:31});return o>e&&(o=o.minus({years:1}),i=i.minus({years:1})),{start:o,end:i}}function hjr(t,e){let n=t.match(/^(?:(?:q|Q)(\d{1})\s+(\d{4})|(\d{4})\s+(?:q|Q)(\d{1}))$/),r=t.match(/^(?:q|Q)(\d{1})$/),o,i;if(n)o=parseInt(n[1]||n[4]),i=parseInt(n[2]||n[3]);else if(r){o=parseInt(r[1]),i=e.year;let c=Math.floor((e.month-1)/3)+1;o>c&&i--}else return;if(o<1||o>4)return;let s=(o-1)*3+1,a=Wn.fromObject({year:i,month:s,day:1}).startOf("day"),l=a.plus({months:3}).minus({days:1}).endOf("day");return a>e&&(a=a.minus({years:1}),l=l.minus({years:1})),{start:a,end:l}}function gjr(t,e){let n=t.match(/^(jan|january|feb|february|mar|march|apr|april|may|jun|june|jul|july|aug|august|sep|sept|september|oct|october|nov|november|dec|december)\s+(\d{4})$/i);if(!n)return;let r=xSn[n[1].toLowerCase()],o=parseInt(n[2]),i=Wn.fromObject({year:o,month:r,day:1}).startOf("day"),s=i.endOf("month");return i>e&&(i=i.minus({years:1}),s=s.minus({years:1})),{start:i,end:s}}function yjr(t){let e=Wn.now(),n=t.toLowerCase().replace("@vault","").trim(),r=ujr(n,e)||djr(n,e)||fjr(n,e)||pjr(n,e)||gjr(n,e)||hjr(n,e)||mjr(n,e);if(r)return{startTime:r.start.toMillis(),endTime:r.end.toMillis()};let o=pat(t,e.toJSDate(),{forwardDate:!1});if(o.length>0){let i=Wn.fromJSDate(o[0].start.date()).startOf("day"),s=o[0].end?Wn.fromJSDate(o[0].end.date()).endOf("day"):i.endOf("day");return i>e&&(i.minus({years:1}),s.minus({years:1})),{startTime:i.toMillis(),endTime:s.toMillis()}}W(`Unable to parse time expression: ${t}`)}function vjr(t){let e=t.toJSDate(),n=t.offset,r=t.offsetNameShort||"Unknown";return{epoch:Math.floor(e.getTime()),isoString:e.toISOString(),userLocaleString:t.toLocaleString(Wn.DATETIME_FULL),localDateString:t.toISODate()||"",timezoneOffset:n,timezone:r}}var SSn=gi({name:"getTimeRangeMs",description:"Convert natural language time expressions to date ranges for use with localSearch",schema:x.object({timeExpression:x.string().describe(`Natural language time expression to convert to a date range.
COMMON EXPRESSIONS:
- Relative past: "yesterday", "last week", "last month", "last year"
- Relative ranges: "this week", "this month", "this year"
- Specific dates: "July 1", "July 1 2023", "2023-07-01"
- Date ranges: "from July 1 to July 15", "between May and June"
- Time periods: "last 7 days", "past 30 days", "previous 3 months"
IMPORTANT: This tool is typically used as the first step before localSearch when searching notes by time.
EXAMPLE WORKFLOW:
1. User: "what did I do last week"
2. First call getTimeRangeMs with timeExpression: "last week"
3. Then use the returned time range with localSearch`)}),func:async({timeExpression:t})=>{let e=yjr(t);return e||{error:`Unable to parse time expression: ${t}`}}});function wjr(t){let e=t.toString().length===10?t*1e3:t,n=Wn.fromMillis(e);return vjr(n)}var CSn=gi({name:"getTimeInfoByEpoch",description:"Convert a Unix timestamp (in seconds or milliseconds) to detailed time information",schema:x.object({epoch:x.number().describe("Unix timestamp in seconds or milliseconds")}),func:async({epoch:t})=>wjr(t)});async function bjr(t,e,n){let r=mat(e),o=mat(n);try{let i=Wn.now().setZone(r),s=bSn(t,i.toJSDate());if(!s)throw new Error(`Could not parse time: ${t}`);let a=Wn.fromJSDate(s,{zone:r}),l=a.setZone(o);if(!l.isValid)throw new Error("Invalid timezone conversion");let c=l.toJSDate(),u=l.offset;return{epoch:Math.floor(c.getTime()),isoString:c.toISOString(),userLocaleString:l.toLocaleString(Wn.DATETIME_FULL),localDateString:l.toISODate()||"",timezoneOffset:u,timezone:l.offsetNameShort||o,originalTime:a.toLocaleString(Wn.TIME_SIMPLE)+" "+a.offsetNameShort,convertedTime:l.toLocaleString(Wn.TIME_SIMPLE)+" "+l.offsetNameShort}}catch(i){throw new Error(`Failed to convert time: ${i.message}`)}}var kSn=gi({name:"convertTimeBetweenTimezones",description:"Convert a specific time from one timezone to another using UTC offsets",schema:x.object({time:x.string().describe(`Time to convert. Supports various formats:
- 12-hour: "6pm", "3:30 PM", "11:45 am"
- 24-hour: "18:00", "15:30", "23:45"
- Relative: "noon", "midnight"`),fromOffset:x.string().describe(`Source UTC offset. Must be numeric, not timezone name.
Examples: "-8" for PT, "+0" for London, "+8" for Beijing`),toOffset:x.string().describe(`Target UTC offset. Must be numeric, not timezone name.
Examples: "+9" for Tokyo, "-5" for NY, "+5:30" for Mumbai
EXAMPLE USAGE:
- "what time is 6pm PT in Tokyo" \u2192 time: "6pm", fromOffset: "-8", toOffset: "+9"
- "convert 3:30 PM EST to London time" \u2192 time: "3:30 PM", fromOffset: "-5", toOffset: "+0"
- "what is 9am Beijing time in New York" \u2192 time: "9am", fromOffset: "+8", toOffset: "-5"`)}),func:async({time:t,fromOffset:e,toOffset:n})=>bjr(t,e,n)});_v();vc();Se();ut();ap();pe();var ISn=5e4,TSn=gi({name:"youtubeTranscription",description:"Get transcripts of YouTube videos when the user provides YouTube URLs",schema:x.object({_userMessageContent:x.string().optional().describe("Internal: user message content injected by the system")}),func:async t=>{let{_userMessageContent:e}=t;if(typeof e!="string")return{success:!1,message:"Invalid input: User message must be a string"};if(e.length>ISn)return{success:!1,message:`Input too long: Maximum allowed length is ${ISn} characters`};let n=Zdt(e);if(n.length===0)return{success:!1,message:"No YouTube URLs found in the user prompt. URLs must be in the user prompt instead of the context notes."};let r=await Promise.all(n.map(async i=>{try{let s=UM()&&Y().supadataApiKey?await $0e(i):await Gi.getInstance().youtube4llm(i);return s.response.transcript?{url:i,success:!0,transcript:s.response.transcript,elapsed_time_ms:s.elapsed_time_ms}:{url:i,success:!1,message:"Transcript not available. Only English videos with auto transcript enabled are supported"}}catch(s){return H(`Error transcribing YouTube video ${i}:`,s),{url:i,success:!1,message:"An error occurred while transcribing the YouTube video"}}}));return{success:r.some(i=>i.success),results:r,total_urls:n.length}}});function _jr(t){return[{tool:D0e(t),metadata:{id:"localSearch",displayName:"Vault Search",description:"Search through your vault notes",category:"search",copilotCommands:["@vault"],customPromptInstructions:`For localSearch (searching notes based on their contents in the vault):
- You MUST always provide both "query" (string) and "salientTerms" (array of strings)
- salientTerms MUST be extracted from the user's original query - never invent new terms
- They are keywords used for BM25 full-text search to find notes containing those exact words
- Treat every token that begins with "#" as a high-priority salient term. Keep the leading "#" and the full tag hierarchy (e.g., "#project/phase1").
- Include tagged terms alongside other meaningful words; never strip hashes or rewrite tags into plain words.
- Extract meaningful content words from the query (nouns, verbs, names, etc.)
- Exclude common words like "what", "I", "do", "the", "a", etc.
- Exclude time expressions like "last month", "yesterday", "last week"
- Preserve the original language - do NOT translate terms to English
Evaluating search results and re-searching:
- Results include a relevance quality summary: high (score \u22650.7), medium (0.3-0.7), low (<0.3)
- If most results are low relevance or miss key concepts from the user's question:
1. Try searching again with synonyms or related terms
2. Use more specific phrasing if query was too broad
3. Use more general phrasing if query was too narrow
- Example: "machine learning algorithms" returned low results \u2192 try "ML models", "neural networks", or "AI techniques"
Examples:
- Query "piano learning practice" \u2192 query: "piano learning practice", salientTerms: ["piano", "learning", "practice"]
- Query "#projectx status update" \u2192 query: "#projectx status update", salientTerms: ["#projectx", "status", "update"]
- Query "\u94A2\u7434\u5B66\u4E60" (Chinese) \u2192 query: "\u94A2\u7434\u5B66\u4E60", salientTerms: ["\u94A2\u7434", "\u5B66\u4E60"] (preserve original language)
For time-based searches (e.g., "what did I do last week"):
1. First call getTimeRangeMs with timeExpression: "last week"
2. Then use localSearch with the returned timeRange, query matching the user's question, and salientTerms: [] (empty for generic time queries)
For time-based searches with meaningful terms (e.g., "python debugging notes from yesterday"):
1. First call getTimeRangeMs with timeExpression: "yesterday"
2. Then use localSearch with the returned timeRange, query: "python debugging notes", salientTerms: ["python", "debugging", "notes"]
For broad searches:
- If the user wants a comprehensive list, use getFileTree to get all note titles as reference. This helps verify search completeness and identify notes the search may have missed.`}},{tool:F0e,metadata:{id:"webSearch",displayName:"Web Search",description:"Search the INTERNET (NOT vault notes) when user explicitly asks for web/online information",category:"search",copilotCommands:["@websearch","@web"],customPromptInstructions:`For webSearch:
- ONLY use when the user's query contains explicit web-search intent like:
* "web search", "internet search", "online search"
* "Google", "search online", "look up online", "search the web"
- Always provide an empty chatHistory array
Example: "search the web for python tutorials" \u2192 query: "python tutorials", chatHistory: []`}},{tool:_Sn,metadata:{id:"getCurrentTime",displayName:"Get Current Time",description:"Get the current time in any timezone",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For time queries (IMPORTANT: Always use UTC offsets, not timezone names):
- If the user mentions a specific city, country, or timezone name (e.g., "Tokyo", "Japan", "JST"), you MUST convert it to the correct UTC offset and pass it via the timezoneOffset parameter (e.g., "+9").
- Only omit timezoneOffset when the user asks for the current local time without naming any location or timezone.
- If you cannot confidently determine the offset from the user request, ask the user to clarify before calling the tool.
Examples:
- "what time is it" (local time) \u2192 call with no parameters
- "what time is it in Tokyo" (UTC+9) \u2192 timezoneOffset: "+9"
- "what time is it in New York" (UTC-5 or UTC-4 depending on DST) \u2192 timezoneOffset: "-5"`}},{tool:CSn,metadata:{id:"getTimeInfoByEpoch",displayName:"Get Time Info",description:"Convert epoch timestamp to human-readable format",category:"time",isAlwaysEnabled:!0}},{tool:SSn,metadata:{id:"getTimeRangeMs",displayName:"Get Time Range",description:"Convert time expressions to date ranges",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For time-based queries:
- Use this tool to convert time expressions like "last week", "yesterday", "last month" to proper time ranges
- This is typically the first step before using localSearch with a time range
Example: For "last week" \u2192 timeExpression: "last week"`}},{tool:kSn,metadata:{id:"convertTimeBetweenTimezones",displayName:"Convert Timezones",description:"Convert time between different timezones",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For timezone conversions:
Example: "what time is 6pm PT in Tokyo" (PT is UTC-8 or UTC-7, Tokyo is UTC+9) \u2192 time: "6pm", fromOffset: "-8", toOffset: "+9"`}},{tool:ixn(t),metadata:{id:"readNote",displayName:"Read Note",description:"Read a specific note in sequential chunks using its own line-chunking logic.",category:"file",requiresVault:!0,isAlwaysEnabled:!0,customPromptInstructions:`For readNote:
- Decide based on the user's request: only call this tool when the question requires reading note content.
- If the user asks about a note title that is already mentioned in the current or previous turns of the conversation, or linked in <active_note> or <note_context> blocks, call readNote directly\u2014do not use localSearch to look it up. Even if the note title mention is partial but similar to what you have seen in the context, try to infer the correct note path from context. Skip the tool when a note is irrelevant to the user query.
- If the user asks about notes linked from that note, read the original note first, then follow the "linkedNotes" paths returned in the tool result to inspect those linked notes.
- Always start with chunk 0 (omit chunkIndex or set it to 0). Only request the next chunk if the previous chunk did not answer the question.
- Pass vault-relative paths without a leading slash. If a call fails, adjust the path (for example, add ".md" or use an alternative candidate) and retry only if necessary.
- Every tool result may include a "linkedNotes" array. If the user needs information from those linked notes, call readNote again with one of the provided candidate paths, starting again at chunk 0. Do not expand links you don't need.
- Stop calling readNote as soon as you have the required information.
- Always call getFileTree to get the exact note path if it is not provided in the context before calling readNote.
Examples:
- First chunk: notePath: "Projects/launch-plan.md" (chunkIndex omitted or 0)
- Next chunk: notePath: "Projects/launch-plan.md", chunkIndex: 1`}},{tool:O0e(t),metadata:{id:"writeFile",displayName:"Write to File",description:"Create or rewrite files in your vault",category:"file",requiresVault:!0,timeoutMs:0,copilotCommands:["@composer"],customPromptInstructions:`For writeFile:
- NEVER display the file content directly in your response
- Always pass the complete file content to the tool
- Include the full path to the file
- You MUST explicitly call writeFile for any intent of updating or creating files
- Do not call writeFile tool again if the result is not accepted
- Do not call writeFile tool if no change needs to be made
- Always create new notes in root folder or folders the user explicitly specifies
- When creating a new note in a folder, you MUST use getFileTree to get the exact folder path first
Examples:
- Basic: path: "path/to/note.md", content: "FULL CONTENT OF THE NOTE"
- Skip confirmation: path: "path/to/note.md", content: "FULL CONTENT", confirmation: false`}},{tool:exn(t),metadata:{id:"editFile",displayName:"Edit File",description:"Make a targeted, single-match edit to an existing file",category:"file",requiresVault:!0,timeoutMs:0,customPromptInstructions:`For editFile:
- Use for targeted edits; use writeFile for major rewrites or new files
- oldText must uniquely identify the location \u2014 include surrounding context lines if needed
- The tool automatically handles minor whitespace/quote differences (fuzzy matching)
- Call once per edit; for multiple edits call the tool multiple times
Example: Add "Bob Johnson" to attendees in notes/meeting.md:
path: "notes/meeting.md"
oldText: "## Attendees\\n- John Smith\\n- Jane Doe"
newText: "## Attendees\\n- John Smith\\n- Jane Doe\\n- Bob Johnson"`}},{tool:TSn,metadata:{id:"youtubeTranscription",displayName:"YouTube Transcription",description:"Get transcripts from YouTube videos",category:"media",isPlusOnly:!0,requiresUserMessageContent:!0,customPromptInstructions:`For youtubeTranscription:
- Use when user provides YouTube URLs
- No parameters needed - the tool will process URLs from the conversation`}}]}function xjr(t){ic.getInstance().register({tool:oxn(t,t.vault.getRoot()),metadata:{id:"getFileTree",displayName:"File Tree",description:"Browse vault file structure",category:"file",isAlwaysEnabled:!0,requiresVault:!0,isBackground:!0,customPromptInstructions:`For getFileTree:
- Use to browse the vault's file structure including paths of notes and folders
- Always call this tool to explore the exact path of notes or folders when you are not given the exact path.
- DO NOT use this tool to look up note contents or metadata - use localSearch or readNote instead.
- No parameters needed
Example queries that should use getFileTree:
- "Create a new note in the projects folder" \u2192 call getFileTree to get the exact folder path
- "Create a new note using the quick note template" \u2192 call getFileTree to look up the template path
- "How many files are in the projects folder" \u2192 call getFileTree to list all files`}})}function Sjr(t){ic.getInstance().register({tool:kxn(t),metadata:{id:"getTagList",displayName:"Tag List",description:"List vault tags with occurrence statistics",category:"file",isAlwaysEnabled:!0,requiresVault:!0,isBackground:!0,customPromptInstructions:`For getTagList:
- Use to inspect existing tags before suggesting new ones or reorganizing notes.
- Omit parameters to include both frontmatter and inline tags.
- Set includeInline to false when you only need frontmatter-defined tags.
- Use maxEntries to limit output for very large vaults.
Examples:
- Default (all tags): call with no parameters
- Frontmatter only: includeInline: false`}})}function Cjr(t){ic.getInstance().register({tool:N0e(t),metadata:{id:"updateMemory",displayName:"Update Memory",description:"Save information to user memory when the user explicitly asks to remember something or update the memory",category:"memory",copilotCommands:["@memory"],isAlwaysEnabled:!0,customPromptInstructions:`For updateMemory:
- Use this tool to update the memory when the user explicitly asks to update the memory
- DO NOT use for general information - only for personal facts, preferences, or specific things the user wants stored
Example: statement: "I'm studying Japanese and I'm preparing for JLPT N3"`}})}function kjr(){let t=ic.getInstance();t.register({tool:axn,metadata:{id:"obsidianDailyNote",displayName:"Daily Note",description:"Create or read today's daily note, or get its path",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianDailyNote:
- Use for daily note operations: creating, reading content, or getting the file path.
- Use readNote for reading specific notes by path. Use obsidianDailyNote only for today's daily note.
- daily \u2014 create today's daily note. Applies the user's configured daily note template automatically. Use this when the user asks to create or set up today's daily note.
- daily:read \u2014 read today's daily note content.
- daily:path \u2014 get the vault-relative file path (useful for follow-up readNote calls).
- For past or future daily notes (e.g. "yesterday's daily note"): NEVER ask the user for the date \u2014 use the time tools. Workflow: (1) call getCurrentTime to resolve the date, (2) call daily:path to discover the date format and folder, (3) call obsidianTemplates with command=templates to list available template names, then call template:read with the name that matches (e.g. "Daily Note Template"), (4) use writeFile to create the note at the resolved path with the template content, replacing variables like {{date}} with the target date. If templates returns an error or no daily template is found, ask the user for their template path and use readNote to read it.
- To add content to a daily note, use writeFile or editFile.
- Use \\n for newlines and \\t for tabs in content strings.
- For arbitrary file writes beyond daily notes, use writeFile or editFile instead.
- If the user names a specific vault, pass it using the vault parameter.`}}),t.register({tool:sxn,metadata:{id:"obsidianRandomRead",displayName:"Random Note",description:"Read a random note using the official Obsidian CLI",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianRandomRead:
- Use when the user explicitly asks for a random note or random note content.
- If the user names a specific vault, pass it using the vault parameter.
- Do not use when the user asks for a specific note; use readNote/getFileTree for specific targets.`}}),t.register({tool:lxn,metadata:{id:"obsidianProperties",displayName:"Properties",description:"Read frontmatter properties from notes or list all property names in the vault",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianProperties:
- Use to inspect frontmatter properties across the vault or within a specific note.
- properties (no file/path): list all property names used vault-wide. Add counts=true for occurrence counts. Add sort=count to sort by frequency.
- properties with file= or path=: list that note's key-value property pairs.
- property:read: read a single property value from a specific note. Requires name parameter.
- file= resolves like a wikilink (name only, no path or extension). path= uses exact vault-relative path.
- Do not use for full note content \u2014 use readNote for that.
- To modify properties, use writeFile or editFile to update the frontmatter YAML.`}}),t.register({tool:cxn,metadata:{id:"obsidianTasks",displayName:"Tasks",description:"List tasks across the vault with filters for status, file, and daily note",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianTasks:
- ALWAYS use this tool when the user asks about tasks, todos, or checkboxes. Do NOT use localSearch for task queries.
- Use to list and filter tasks across the vault.
- todo=true: show only incomplete tasks. done=true: show only completed tasks.
- status="x": filter by specific status character (e.g., "/" for in-progress, "x" for done, " " for open).
- daily=true: show tasks from today's daily note only.
- verbose=true: group tasks by file with line numbers.
- total=true: return only the task count.
- file= resolves like a wikilink (name only). path= uses exact vault-relative path.
- For time-based task queries (e.g. "tasks from last month"): use verbose=true to get tasks grouped by file, then filter results by file dates or daily note filenames to match the time range.`}}),t.register({tool:uxn,metadata:{id:"obsidianLinks",displayName:"Links",description:"Query the vault link graph: backlinks, outgoing links, orphans, unresolved",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianLinks:
- Use to explore the vault's link graph.
- backlinks: list notes that link TO a given file. Use file= or path= to target a note. Add counts=true for link counts.
- links: list outgoing links FROM a given file. Use file= or path= to target a note.
- orphans: list all notes with no incoming links. Use total=true for just the count. Add all=true to include non-markdown files.
- unresolved: list wikilinks that don't resolve to any existing file. Use counts=true for occurrence counts, verbose=true to see source files.
- file= resolves like a wikilink (name only). path= uses exact vault-relative path. Without either, targets the active file.`}}),t.register({tool:dxn,metadata:{id:"obsidianTemplates",displayName:"Templates",description:"List available templates or read template content",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianTemplates:
- Use 'templates' to list all available templates when you need to find the right template for a task.
- Use 'template:read' with a template name to get its content with variables resolved. Requires name parameter.
- This is useful for creating daily notes from templates \u2014 read the template first, then use writeFile to populate the note.`}}),t.register({tool:fxn,metadata:{id:"obsidianBases",displayName:"Bases",description:"List Base files, views, query data, or create new items in Obsidian Bases",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianBases:
- Use to explore and manage structured data in Obsidian Base (.base) database files.
- bases: list all Base files in the vault. Use total=true for just the count.
- base:views: list the views defined in a Base file. Requires file= or path=.
- base:query: query data from a specific Base view. Requires file= or path=, optionally view= and format= (e.g., format=csv).
- base:create: create a new item (row) in a Base. Requires file= or path=. Optional: view= (target view), name= (file name for the item), content= (initial note content).
- The created item appears as a new note that matches the Base's filter criteria.
- Use base:query first to understand the Base's structure and existing data before creating items.
- If the Base filters by a specific tag or folder, ensure the new item will match those filters.
Base file YAML reference (for creating new .base files with writeFile):
- filters: MUST be either a single string OR an object with and/or/not keys. NEVER use a bare YAML list.
- Single filter: filters: 'file.hasTag("book")'
- Multiple filters: filters: { and: ['file.hasTag("book")', 'status == "reading"'] }
- Negation: filters: { not: ['file.hasTag("archived")'] }
- Bare lists like "filters: - 'expr'" are INVALID and will cause parse errors.
- formulas: computed properties. Functions: date(), now(), today(), if(cond, true, false), duration(). Duration fields: .days, .hours, .minutes. Example: days_left: 'if(due, (date(due) - today()).days, "")'
- properties: display config per property (displayName, width, hidden).
- views: table (default), cards, list, or map. Each view can have its own filters, order (property display list), groupBy, summaries.
- Property types: note properties (from frontmatter), file properties (file.name, file.mtime, file.ctime, file.tags, file.links, file.backlinks), formula properties (formula.my_formula).
- YAML quoting: single-quote formulas containing double quotes: 'if(done, "Yes", "No")'. Quote strings with special chars (:, {, }, [, ]).
- Embed in notes with ![[MyBase.base]] or ![[MyBase.base#View Name]].
- VALIDATION: After creating or editing a .base file, ALWAYS call obsidianBases with base:views to verify it parses correctly. If it returns an error, fix the YAML with writeFile and re-validate. Do not stop until validation passes.`}})}function e5(t){let e=ic.getInstance(),n=Y(),r=e.getToolMetadata("getFileTree")!==void 0,o=t!==void 0,i=e.getToolMetadata("updateMemory")!==void 0,s=n.enableSavedMemory;(e.getAllTools().length===0||r!==o||i!==s)&&(e.clear(),t&&(e.registerAll(_jr(t)),xjr(t),Sjr(t),n.enableSavedMemory&&Cjr(t)),Vst()&&kjr())}ut();ut();OSe();var K0e=class{constructor(e,n){this.toolManager=e;this.writeFileTool=n;this.buffer=""}findCompleteBlock(e){let n=/<writeFile>[\s\S]*?<\/writeFile>/,r=e.match(n);return!r||r.index===void 0?null:{block:r[0],endIdx:r.index+r[0].length}}async*processChunk(e){let n="";if(Array.isArray(e.content))for(let o of e.content)o.type==="text"&&o.text!=null&&(n+=typeof o.text=="string"?o.text:"");else e.content!=null&&(n=typeof e.content=="string"?e.content:"");n&&(this.buffer+=n),yield e;let r=this.findCompleteBlock(this.buffer);for(;r;){let{block:o,endIdx:i}=r,s=o.match(/<path>([\s\S]*?)<\/path>/),a=o.match(/<content>([\s\S]*?)<\/content>/),l=s?s[1].trim():void 0,c=a?a[1].trim():void 0;try{let u=await this.toolManager.callTool(this.writeFileTool,{path:l,content:c}),d=S0.format("writeFile",u);yield{...e,content:`
${d}
`}}catch(u){yield{...e,content:`
Error: ${u?.message??String(u)}
`}}this.buffer=this.buffer.substring(i),r=this.findCompleteBlock(this.buffer)}}};FV();pe();FV();function PSn(t){if(!Array.isArray(t)||t.length===0)return{high:0,medium:0,low:0,total:0,averageScore:0};let e=0,n=0,r=0,o=0;for(let i of t){let s=i.rerank_score??i.score??0;o+=s,s>=.7?e++:s>=.3?n++:r++}return{high:e,medium:n,low:r,total:t.length,averageScore:o/t.length}}function ASn(t){let e=[];return t.high>0&&e.push(`${t.high} high`),t.medium>0&&e.push(`${t.medium} medium`),t.low>0&&e.push(`${t.low} low`),e.length===0?"[Relevance: no results]":`[Relevance: ${e.join(", ")}]`}function hat(t){if(!Array.isArray(t))return"";let e=t.filter(r=>r.includeInContext!==!1);return e.length===0?"No relevant documents found.":e.map((r,o)=>{let i=r.title||"Untitled",s=r.path||"",a=r.__sourceId||r.collection_name||r.source_id||o+1,l=null;if(r.mtime){let c=new Date(r.mtime);isNaN(c.getTime())||(l=c.toISOString())}return`<document>
<id>${a}</id>
<title>${i}</title>${s&&s!==i?`
<path>${s}</path>`:""}${l?`
<modified>${l}</modified>`:""}
<content>
${r.content||""}
</content>
</document>`}).filter(r=>r.length>0).join(`
`)}function ESn(t){try{let e=JSON.parse(t);return Array.isArray(e)?hat(e):"Invalid search results format."}catch(e){return W("Failed to format localSearch result string:",e),"Error processing search results."}}function MSn(t){return Array.isArray(t)?t.map(e=>({title:e.title||e.path||"Untitled",path:e.path||e.title||"",score:e.rerank_score||e.score||0,explanation:e.explanation||null})):[]}function G0e(t){if(typeof t=="number"){let e=new Date(t);return isNaN(e.getTime())?"":e.toISOString()}if(typeof t=="string"){let e=new Date(t);return isNaN(e.getTime())?"":e.toISOString()}return""}function Ijr(t){if(!t)return"";let e=[],n=t;try{if(Array.isArray(n.lexicalMatches)&&n.lexicalMatches.length>0){let r=new Set,o=new Set;for(let a of n.lexicalMatches)typeof a?.field=="string"&&r.add(a.field),typeof a?.query=="string"&&o.add(a.query);let i=Array.from(r).join("/"),s=Array.from(o).slice(0,3).join(", ");e.push(`Lexical(${i}): ${s}${o.size>3?", ...":""}`)}if(typeof n.semanticScore=="number"&&n.semanticScore>0&&e.push(`Semantic: ${(n.semanticScore*100).toFixed(1)}%`),n.folderBoost&&typeof n.folderBoost.boostFactor=="number"){let r=n.folderBoost,o=r.folder||"root";e.push(`Folder +${r.boostFactor.toFixed(2)} (${o})`)}if(n.graphConnections&&typeof n.graphConnections=="object"){let r=n.graphConnections,o=[];(r.backlinks??0)>0&&o.push(`${r.backlinks} backlinks`),(r.coCitations??0)>0&&o.push(`${r.coCitations} co-cites`),(r.sharedTags??0)>0&&o.push(`${r.sharedTags} tags`),typeof r.score=="number"?e.push(`Graph ${r.score.toFixed(1)}${o.length?` (${o.join(", ")})`:""}`):o.length&&e.push(`Graph (${o.join(", ")})`)}if(n.graphBoost&&typeof n.graphBoost.boostFactor=="number"&&!n.graphConnections){let r=n.graphBoost;e.push(`Graph +${r.boostFactor.toFixed(2)} (${r.connections} connections)`)}typeof n.baseScore=="number"&&typeof n.finalScore=="number"&&n.baseScore!==n.finalScore&&e.push(`Score: ${n.baseScore.toFixed(4)}\u2192${n.finalScore.toFixed(4)}`)}catch{}return e.join(" | ")}function OSn(t,e,n=1){let r=n,o=[];if(t.length>0){let i=t.map(s=>{let a=s.__sourceId||r++,l=s.title||"Untitled",c=s.path||"",u=s.matchType||s.source||"filter",d=G0e(s.mtime);return`<document>
<id>${a}</id>
<title>${l}</title>
<path>${c}</path>
<matchType>${u}</matchType>${d?`
<modified>${d}</modified>`:""}
<content>
${s.content||""}
</content>
</document>`}).join(`
`);o.push(`<filterResults>
${i}
</filterResults>`)}if(e.length>0){let i=e.map(s=>{let a=s.__sourceId||r++,l=s.title||"Untitled",c=s.path||"",u=G0e(s.mtime);return`<document>
<id>${a}</id>
<title>${l}</title>${c&&c!==l?`
<path>${c}</path>`:""}${u?`
<modified>${u}</modified>`:""}
<content>
${s.content||""}
</content>
</document>`}).join(`
`);o.push(`<searchResults>
${i}
</searchResults>`)}return o.length===0?"No relevant documents found.":o.join(`
`)}var Tjr=new Set(["time-filtered","tag-match"]);function NSn(t){return!Array.isArray(t)||t.length===0?!1:t.every(e=>e.source!=null&&Tjr.has(e.source))}function RSn(t){return Array.isArray(t)?t.some(e=>e.source==="time-filtered"):!1}function gat(t,e=300){if(!Array.isArray(t)||t.length===0)return"";let n=t.map(r=>{let o=r.title||"Untitled",i=r.path||"",s=G0e(r.mtime),l=DV(r.content||"").slice(0,e),c=i?`
<path>${i}</path>`:"",u=s?`
<modified>${s}</modified>`:"",d=l?`
<snippet>${l}</snippet>`:"";return`<file>
<title>${o}</title>${c}${u}${d}
</file>`}).join(`
`);return`<additionalMatches count="${t.length}" note="These results contain titles and metadata only. To read the full content of a note, call the readNote tool with its path.">
${n}
</additionalMatches>`}function LSn(t){if(!Array.isArray(t)||t.length===0){j("Search Results: (none)");return}let e=0,n=t.map(l=>{let c=G0e(l.mtime),u=typeof l.rerank_score=="number"?l.rerank_score:l.score||0,d=(Number.isFinite(u)?u:0).toFixed(4),f=l.chunkId||l.path||"",p=Ijr(l.explanation),m=l.includeInContext!==!1;return m&&e++,{path:f,in:m?"Y":"",mtime:c,score:d,explanation:p}}),r=n.length;j(`Search Results (debug table): ${r} rows; in-context ${e}/${r}`);let o=l=>String(l||"").replace(/\|/g,"\\|"),i="| PATH | IN | MTIME | SCORE | EXPLANATION |",s="| --- | :-: | --- | ---: | --- |",a=n.map(l=>`| ${o(l.path)} | ${l.in} | ${l.mtime||""} | ${l.score} | ${o(l.explanation)} |`);Kie(["",`Results: ${r} rows; in-context ${e}/${r}`,"",i,s,...a,""])}function $Sn(t,e){return[t,e].map(r=>r?.trim()).filter(r=>!!r).join(`
`)}function DSn(t,e){let n=t?`
${t}
`:"";return`<localSearch${e?` timeRange="${e}"`:""}>${n}</localSearch>`}function yat(t,e){let n=t.trim();return n?`${n}
${e}`:e}function FSn(t,e){let n=e.trim();return!n||t.includes(n)?t:yat(t,`[User query]:
${n}`)}function USn(t,e){let n=e?.trim();if(!n)return t;let o=t.lastIndexOf("[User query]:");if(o===-1){let a=t.trimEnd(),l=a.length>0?`
`:"";return`${a}${l}${n}`}let i=t.slice(0,o).trimEnd(),s=t.slice(o).trimStart();return`${i}
${n}
${s}`}function jSn(t){let e=[],n=0;for(;n<t.length;){let r=t.indexOf("![",n);if(r===-1)break;let o=Ejr(t,r+2);if(o===null){n=r+2;continue}let i=o+1;for(;i<t.length&&Z0e(t[i]);)i++;if(t[i]!=="("){n=i;continue}let s=Mjr(t,i);if(s===null){n=i+1;continue}let a=Pjr(t.slice(i+1,s));a&&e.push(a),n=s+1}return e}function Pjr(t){let e=t.trim();if(e.length===0)return null;if(e.startsWith("<")){let r=Ojr(e,0);if(r===null)return null;let o=e.slice(1,r).trim();return o.length>0?o:null}let n=Ajr(e).trim();return n.length>0?n:null}function Ajr(t){let e=t.trimEnd();if(e.length===0)return"";let n=e[e.length-1];if(n==='"'||n==="'"){let o=Njr(e,n,e.length-1);if(o!==null){let i=e.slice(0,o);if(i.length>0&&Z0e(i[i.length-1]))return i.trimEnd()}}if(n===")"){let r=Rjr(e);if(r!==null){let o=e.slice(0,r);if(o.length>0&&Z0e(o[o.length-1]))return o.trimEnd()}}return e}function Ejr(t,e){let n=e,r=0;for(;n<t.length;){let o=t[n];if(o==="\\"){n+=2;continue}if(o==="["){r++,n++;continue}if(o==="]"){if(r===0)return n;r--,n++;continue}n++}return null}function Mjr(t,e){let n=e+1,r=1,o=!0,i=!1;for(;n<t.length;){let s=t[n];if(i){if(s==="\\"){n+=2;continue}if(s===">"){i=!1,o=!1,n++;continue}n++;continue}if(o){if(Z0e(s)){n++;continue}if(s==="<"){i=!0,n++;continue}o=!1}if(s==="\\"){n+=2;continue}if(s==="("){r++,n++;continue}if(s===")"){if(r--,r===0)return n;n++;continue}n++}return null}function Ojr(t,e){for(let n=e+1;n<t.length;n++){let r=t[n];if(r==="\\"){n++;continue}if(r===">")return n}return null}function Njr(t,e,n){for(let r=n-1;r>=0;r--)if(t[r]===e&&!BSn(t,r))return r;return null}function Rjr(t){if(t.length===0||t[t.length-1]!==")")return null;let e=0;for(let n=t.length-1;n>=0;n--){let r=t[n];if(!((r===")"||r==="(")&&BSn(t,n))){if(r===")"){e++;continue}if(r==="("&&(e--,e===0))return n}}return null}function BSn(t,e){let n=0;for(let r=e-1;r>=0&&t[r]==="\\";r--)n++;return n%2===1}function Z0e(t){return t===" "||t===" "||t===`
`||t==="\r"}nY();oi();var CO=class extends jM{constructor(){super(...arguments);this.lastCitationSources=null}getAvailableToolsForPlanning(){let n=ic.getInstance();return n.getAllTools().length===0&&e5(this.chainManager.app),n.getAllTools().map(o=>o.tool).filter(o=>o.name==="getCurrentTime"||o.name==="convertTimeBetweenTimezones"||o.name==="getTimeInfoByEpoch"||o.name==="getTimeRangeMs"||o.name==="getFileTree")}async planToolCalls(n,r,o=!1){let i=this.getAvailableToolsForPlanning(),s=r;if(typeof s.bindTools!="function")return W("[CopilotPlus] Model does not support native tool calling, skipping tool planning"),{toolCalls:[],salientTerms:this.extractSalientTermsFromQuery(n)};let a=s.bindTools(i),c=`You are a helpful AI assistant. Analyze the user's message and determine if any tools should be called.
Guidelines:
- Use tools when the user's request requires external information or computation
- For time-related queries, use getTimeRangeMs to convert time expressions to timestamps
- Use getFileTree ONLY when the user wants to discover or list notes/folders in the vault \u2014 not to read content already in context${o?`
- The user has an active note attached in this turn. Its content is already available; do NOT call getFileTree merely because the user says 'this note' or 'this file'. Only call getFileTree when the user explicitly wants to discover OTHER notes, list folders, or verify paths.`:""}
- If no tools are needed, respond with your analysis
After analyzing, extract key search terms from the user's message that would be useful for searching notes:
- Extract meaningful nouns, topics, and specific concepts
- Preserve the EXACT words and language from the user's message (works for any language)
- Exclude time expressions (those are handled by tools)
Include your extracted terms as: [SALIENT_TERMS: term1, term2, term3]`,u=[{role:VK(r),content:c},{role:"user",content:n}];j("[CopilotPlus] Requesting tool planning with native tool calling...");let d;{let g=await Jf(()=>a.stream(u)),v;for await(let y of g)v=v?v.concat(y):y;if(!v)throw new Error("[CopilotPlus] Received empty response from planning model");d=new cr({content:v.content,tool_calls:v.tool_calls,additional_kwargs:v.additional_kwargs})}let f=d.tool_calls||[],p=typeof d.content=="string"?d.content:JSON.stringify(d.content);j("[CopilotPlus] Native tool calls:",f.length);let{salientTerms:m}=this.extractPlanningFieldsFromResponse(p,n),h=[];for(let g of f){let v=i.find(y=>y.name===g.name);v?(h.push({tool:v,args:g.args}),j(`[CopilotPlus] Tool call: ${g.name}`,g.args)):W(`[CopilotPlus] Tool '${g.name}' not found in available tools`)}return{toolCalls:h,salientTerms:m}}extractPlanningFieldsFromResponse(n,r){let o,i=n.match(/\[SALIENT_TERMS:\s*([^\]]+?)\s*\]/i);if(i){let s=i[1].split(",").map(a=>a.trim()).filter(a=>a.length>0);o=s.length>0?s:this.extractSalientTermsFromQuery(r)}else o=this.extractSalientTermsFromQuery(r);return{salientTerms:o}}extractSalientTermsFromQuery(n){return n.split(/[\s\p{P}]+/u).filter(r=>r.length>=3).slice(0,10)}async processAtCommands(n,r,o){let i=n.toLowerCase(),s=this.removeAtCommands(n),a=[...r];if(i.includes("@vault")&&(a.some(c=>c.tool.name==="localSearch")||a.push({tool:D0e(this.chainManager.app),args:{query:s,salientTerms:o.salientTerms,timeRange:o.timeRange}})),(i.includes("@websearch")||i.includes("@web"))&&!a.some(c=>c.tool.name==="webSearch")){let u=await N0.instance.getCurrentChainManager().memoryManager.getMemory().loadMemoryVariables({}),d=Die(u);a.push({tool:F0e,args:{query:s,chatHistory:d}})}return i.includes("@memory")&&(a.some(c=>c.tool.name==="updateMemory")||a.push({tool:N0e(this.chainManager.app),args:{statement:s}})),a}removeAtCommands(n){return n.split(" ").filter(r=>!gV.includes(r.toLowerCase())).join(" ").trim()}async processImageUrls(n){let r=[],o=await iF.processUrlBatch(n,r,this.chainManager.app.vault);return iF.showFailedImagesNotice(r),o}async processChatInputImages(n){let r=[],o=await iF.processChatImageBatch(n,r,this.chainManager.app.vault);return iF.showFailedImagesNotice(r),o}async extractImagesFromContextBlock(n,r){let i=new RegExp(`<${r.tagName}>([\\s\\S]*?)<\\/${r.tagName}>`).exec(n);if(!i)return[];let s=i[1],l=/<content>([\s\S]*?)<\/content>/.exec(s),c=l?Y2t(l[1]):"";if(!c)return[];let d=new RegExp(`<${r.identifierTag}>(.*?)<\\/${r.identifierTag}>`).exec(s),f=d?d[1]:void 0;j(`[CopilotPlus] Extracting images from ${r.displayName}:`,f||`no ${r.identifierTag}`);let p=r.useForResolution?f:void 0;return this.extractEmbeddedImages(c,p)}async extractEmbeddedImages(n,r){let o=/!\[\[(.*?\.(png|jpg|jpeg|gif|webp|bmp|svg))\]\]/g,i=[],s=[...n.matchAll(o)];for(let l of s){let c=l[1];if(r){let u=this.chainManager.app.metadataCache.getFirstLinkpathDest(c,r);u?i.push(u.path):(W(`Could not resolve embedded image: ${c} from source: ${r}`),i.push(c))}else i.push(c)}let a=jSn(n);for(let l of a){if(!l)continue;if(l.match(/^https?:\/\//)){i.push(l);continue}let c=l.replace(/^\.\//,"").replace(/^\//,"");if(r){let u=this.chainManager.app.metadataCache.getFirstLinkpathDest(c,r);u?i.push(u.path):i.push(c)}else i.push(c)}return i}async buildMessageContent(n,r){let o=[],i=[],s=Y(),a=[];if(s.passMarkdownImages){let d=r.contextEnvelope;if(!d)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot extract images.");let f=d.layers.find(p=>p.id==="L3_TURN");if(f){let p=[{tagName:"active_note",identifierTag:"path",displayName:"active note",useForResolution:!0},{tagName:"active_web_tab",identifierTag:"url",displayName:"active web tab",useForResolution:!1}];for(let m of p){let h=await this.extractImagesFromContextBlock(f.text,m);h.length>0&&a.push({urls:h,type:"embedded"})}}}for(let d of a){let f=await this.processImageUrls(d.urls);i.push(...f.successfulImages),o.push(...f.failureDescriptions)}let l=r.content;if(l&&l.length>0){let d=await this.processChatInputImages(l);i.push(...d.successfulImages),o.push(...d.failureDescriptions)}let c=n;o.length>0&&(c=`${n}
Note:
${o.join(`
`)}
`);let u=[{type:"text",text:c}];return i.length>0&&u.push(...i),u}hasCapability(n,r){let o=n,i=o.modelName||o.model||"";return this.chainManager.chatModelManager.findModelByName(i)?.capabilities?.includes(r)??!1}isMultimodalModel(n){return this.hasCapability(n,"vision")}appendComposerInstructionsIfNeeded(n,r){if(!r.message||!r.message.includes("@composer"))return n;let o=`<OUTPUT_FORMAT>
${wct}
</OUTPUT_FORMAT>`;return`${n}
${o}`}async streamMultimodalResponse(n,r,o,i,s,a,l){let c=this.chainManager.memoryManager.getMemory(),u=this.chainManager.chatModelManager.getChatModel(),d=this.isMultimodalModel(u),f=[],p=r.contextEnvelope;if(!p)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot proceed with CopilotPlus chain.");j("[CopilotPlus] Using envelope-based context construction");let m=XS.convert(p,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),h=m.find(_=>_.role==="system");h&&f.push({role:VK(u),content:h.content}),await BM(c,f);let g=m.find(_=>_.role==="user");if(g){let _,S=o.length>0,I=k=>{let T="[User query]:";if(k.includes(T))return k;let P=k.trimEnd(),E=[];P.length>0&&E.push(P);let O=a.trim()||r.originalMessage?.trim()||"";return O.length>0?E.push(`${T}
${O}`):E.push(T),E.join(`
`)};if(S){let k=this.formatAllToolOutputs(o),T=I(g.content);_=yat(k,T);let P=tun(Y().enableInlineCitations);P&&(_=USn(_,P))}else _=I(g.content);if(n.includes("<OUTPUT_FORMAT>")&&!_.includes("<OUTPUT_FORMAT>")){let k=n.match(/<OUTPUT_FORMAT>[\s\S]*?<\/OUTPUT_FORMAT>/);k&&(_+=`
`+k[0])}let C=d?await this.buildMessageContent(_,r):_;f.push({role:"user",content:C})}j("Final request to AI",{messages:f.length});let v=u?.modelName;zM({messages:f,modelName:v,contextEnvelope:r.contextEnvelope});let y=new K0e(d0,O0e(this.chainManager.app)),w=await Jf(()=>this.chainManager.chatModelManager.getChatModel().stream(f,{signal:i.signal}));for await(let _ of w){if(i.signal.aborted){j("CopilotPlus multimodal stream iteration aborted",{reason:i.signal.reason});break}for await(let S of y.processChunk(_))s.processChunk(S)}}async run(n,r,o,i,s){let{updateLoadingMessage:a}=s,l=this.chainManager.chatModelManager.getChatModel(),u=!this.hasCapability(l,"reasoning"),d=new Ug(o,u),f=[];if(!await ch(this.chainManager.app,{trigger:"legacy_chat_turn",isCopilotPlus:!0})){await this.handleError(new Error("Invalid license key"),_=>d.processErrorChunk(_));let w=d.close().content;return this.handleResponse(w,n,r,i,o,void 0)}try{j("==== Step 1: Planning tools ====");let w,_=n.contextEnvelope;if(!_)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot proceed with CopilotPlus chain.");let I=_.layers.find($=>$.id==="L5_USER")?.text||n.originalMessage||"";try{let $=this.chainManager.chatModelManager.getChatModel(),V=!!_.layers.find(ne=>ne.id==="L3_TURN")?.segments?.some(ne=>ne.metadata?.source==="current_turn"&&/<active_note[\s>]/.test(ne.content)),K=await this.planToolCalls(I,$,V),se,le=K.toolCalls.find(ne=>ne.tool.name==="getTimeRangeMs");if(le){let ne=await d0.callTool(le.tool,le.args),ee=ae=>ae?.startTime?.epoch!==void 0&&ae?.endTime?.epoch!==void 0?{startTime:ae.startTime.epoch,endTime:ae.endTime.epoch}:ae;if(typeof ne=="string")try{let ae=JSON.parse(ne);ae.error||(se=ee(ae))}catch{W("[CopilotPlus] Failed to parse getTimeRangeMs result:",ne)}else if(ne){let ae=ne;ae.error||(se=ee(ae))}j("[CopilotPlus] Executed getTimeRangeMs, result:",se)}let Q=K.toolCalls.filter(ne=>ne.tool.name==="getTimeRangeMs"&&se?(j("Skipping getTimeRangeMs - already executed during planning"),!1):!0);w=await this.processAtCommands(I,Q,{salientTerms:K.salientTerms,timeRange:se})}catch($){return this.handleResponse(Udt($),n,r,i,o)}let C=n.contextEnvelope?.layers.find($=>$.id==="L5_USER")?.text,k=this.removeAtCommands(C||n.originalMessage||n.message),{toolOutputs:T,sources:P}=await this.executeToolCalls(w,a);f=P;let E=T.filter($=>$.output!=null),O=this.appendComposerInstructionsIfNeeded(k,n);j("Invoking LLM with envelope-based context construction"),await this.streamMultimodalResponse(O,n,E,r,d,k,a)}catch(w){a?.(gh.DEFAULT),w instanceof Error&&w.name==="AbortError"||r.signal.aborted?j("CopilotPlus stream aborted by user",{reason:r.signal.reason}):await this.handleError(w,_=>d.processErrorChunk(_))}if(r.signal.aborted&&r.signal.reason==="new-chat")return o(""),"";let m=d.close(),h=m.content,g={wasTruncated:m.wasTruncated,tokenUsage:m.tokenUsage??void 0},v=Y(),y=this.lastCitationSources&&this.lastCitationSources.length>0?this.lastCitationSources:(f||[]).map(w=>({title:w.title,path:w.path}));return h=RSe(h,y,v.enableInlineCitations),await this.handleResponse(h,n,r,i,o,f,void 0,g),h}async executeToolCalls(n,r){let o=[],i=[],s=n.some(a=>a.tool.name==="localSearch");for(let a of n){if(a.tool.name==="getFileTree"&&s){j("Skipping getFileTree since localSearch is already active");continue}j(`Step 2: Calling tool: ${a.tool.name}`),a.tool.name==="localSearch"?r?.(gh.READING_FILES):a.tool.name==="webSearch"?r?.(gh.SEARCHING_WEB):a.tool.name==="getFileTree"&&r?.(gh.READING_FILE_TREE);let l=await d0.callTool(a.tool,a.args);if(a.tool.name==="localSearch"){let u={result:typeof l=="string"?l:JSON.stringify(l),success:l!=null},d=this.getTimeExpression(n),f=this.processLocalSearchResult(u,d);i.push(...f.sources),o.push({tool:a.tool.name,output:f.formattedForLLM})}else o.push({tool:a.tool.name,output:l})}return{toolOutputs:o,sources:qq(i)}}getTimeExpression(n){let r=n.find(o=>o.tool.name==="getTimeRangeMs");return r?r.args.timeExpression:""}prepareLocalSearchResult(n,r){let o=Y(),s=n.filter(P=>P.includeInContext!==!1),a=PSn(s),l=ASn(a),c=NSn(s),u=RSn(s),d,f;if(u){let P=[...s].sort((E,O)=>(O.mtime||0)-(E.mtime||0));d=P.slice(0,o.maxSourceChunks),f=P.slice(o.maxSourceChunks)}else c?(d=[],f=s):s.length>o.maxSourceChunks?(d=s.slice(0,o.maxSourceChunks),f=s.slice(o.maxSourceChunks)):(d=s,f=[]);let p=d.reduce((P,E)=>P+(E.content?E.content.length:0),0),m=d;if(p>nAe){let P=nAe/p;j("Truncating document contents to fit context length. Truncation ratio:",P),m=d.map(E=>({...E,content:E.content?.slice(0,Math.floor((E.content?.length||0)*P))||""}))}let h=m.map((P,E)=>({...P,__sourceId:E+1,content:DV(P.content||"")})),g=h.filter(P=>P.isFilterResult===!0),v=h.filter(P=>P.isFilterResult!==!0),w=g.length>0?OSn(g,v):d.length===0&&f.length>0?gat(f):hat(h);d.length>0&&f.length>0?(u?j(`Time-dominant search: ${d.length} recent notes (full content), ${f.length} older notes (metadata-only)`):j(`Two-tier search: ${d.length} full-content docs, ${f.length} metadata-only docs`),w=`${w}
${gat(f)}`):c&&j(`Tag-only search: ${f.length} notes (metadata-only)`);let _=h.slice(0,Math.min(20,h.length)).map(P=>({title:P.title||P.path||"Untitled",path:P.path||P.title||""})),S=LSe(_);this.lastCitationSources=h.slice(0,Math.min(20,h.length)).map(P=>({title:P.title||P.path||"Untitled",path:P.path||void 0}));let I=Qcn(S,o.enableInlineCitations).trim(),k=$Sn("Answer the question based only on the following context:",w),T=I?`${l}
${k}
${I}`:`${l}
${k}`;return DSn(T,r)}processLocalSearchResult(n,r){let o=[],i,s;if(!n.success)return i=`<localSearch>
Search failed.
</localSearch>`,s=`Search failed: ${n.result}`,{formattedForLLM:i,formattedForDisplay:s,sources:o};try{let a=JSON.parse(n.result),l=a&&typeof a=="object"&&a.type==="local_search"&&Array.isArray(a.documents)?a.documents:null;if(!Array.isArray(l))return i=`<localSearch>
Invalid search results format.
</localSearch>`,s="Search results were in an unexpected format.",{formattedForLLM:i,formattedForDisplay:s,sources:o};LSn(l),o=MSn(l),i=this.prepareLocalSearchResult(l,r||""),s=S0.format("localSearch",i)}catch(a){W("Failed to parse localSearch results:",a);let l=ESn(n.result);i=r?`<localSearch timeRange="${r}">
${l}
</localSearch>`:`<localSearch>
${l}
</localSearch>`,s=S0.format("localSearch",i)}return{formattedForLLM:i,formattedForDisplay:s,sources:o}}async getSystemPrompt(){return H0(this.chainManager.userMemoryManager)}formatAllToolOutputs(n){return n.length===0?"":`# Additional context:
`+n.map(o=>{let i=typeof o.output=="string"?o.output:JSON.stringify(o.output);return`<${o.tool}>
${i}
</${o.tool}>`}).join(`
`)}};gt();pe();vc();Se();ut();oi();pe();function xat(t){return t.map(e=>e.content).filter(e=>e&&e.trim().length>0).join(`
`)}var uF=class{constructor(e){this.modelName=e}buildToolSpecificInstructions(e){let n=[];for(let o of e)o.customPromptInstructions&&n.push(o.customPromptInstructions);let r=this.buildCopilotCommandInstructions(e);return r&&n.push(r),n.length>0?n.join(`
`):""}buildCopilotCommandInstructions(e){let n=[];for(let r of e)if(!(!r.copilotCommands||r.copilotCommands.length===0))for(let o of r.copilotCommands)n.push(`- ${o}: call the tool named ${r.id}`);return n.length===0?null:["When the user explicitly includes a Copilot command alias (e.g., @vault) in their message, treat it as a direct request to call the mapped tool before proceeding.","Honor these aliases exactly (case-insensitive):",...n,"If the referenced tool is unavailable, explain that the command cannot be fulfilled instead of ignoring it."].join(`
`)}enhanceSystemPrompt(e,n,r,o){let i=this.buildSystemPromptSections(e,n,r,o);return xat(i)}buildSystemPromptSections(e,n,r,o){let i=o||[],s=this.buildToolSpecificInstructions(i).trim(),l=[{id:"base-system-prompt",label:"System prompt with memory",source:"src/system-prompts/systemPromptBuilder.ts#getSystemPromptWithMemory",content:e.trimEnd()},{id:"autonomous-agent-intro",label:"Autonomous agent introduction",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildSystemPromptSections",content:`# Autonomous Agent Mode
You are now in autonomous agent mode. You can use tools to gather information and complete tasks step by step.
Tools are provided via native function calling - use them when needed to complete tasks.
`}],c=n.trim();return c.length>0&&l.push({id:"tool-descriptions",label:"Tool descriptions (native tool calling via bindTools)",source:"Native tool calling - schemas provided via bindTools()",content:`Available tools:
${c}`}),l.push({id:"tool-usage-guidelines",label:"Tool usage guidelines",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildSystemPromptSections",content:`# Tool Usage Guidelines
## Time-based Queries
When users ask about temporal periods (e.g., "what did I do last month", "show me notes from last week"), you MUST:
1. First call getTimeRangeMs to convert the time expression to a proper time range
2. Then use localSearch with the timeRange parameter from step 1
3. For salientTerms, ONLY use words that exist in the user's original query (excluding time expressions)
Example for "what did I do last month":
1. Call getTimeRangeMs with timeExpression: "last month"
2. Use localSearch with query matching the user's question
3. salientTerms: [] - empty because "what", "I", "do" are not meaningful search terms
Example for "meetings about project X last week":
1. Call getTimeRangeMs with timeExpression: "last week"
2. Use localSearch with query "meetings about project X"
3. salientTerms: ["meetings", "project", "X"] - these words exist in the original query
## File-related Queries
### Handle ambiguity in folder/note paths
When user mentions a folder name (e.g., "meetings folder") or a note name (e.g., "meeting note template") without providing an exact path,
you MUST first call getFileTree to find the folder or notes best matching the user's query.
If multiple results or no result, you should ask the user to provide a more specific path.
`}),s.length>0&&l.push({id:"tool-specific-instructions",label:"Tool-specific instructions",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildToolSpecificInstructions",content:s}),l.push({id:"general-guidelines",label:"General guidelines",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildSystemPromptSections",content:`## Answer Source Priority (CRITICAL)
You are the user's personal knowledge assistant. Always ground your answers in real sources rather than your own training data. Follow this priority chain:
1. **Explicit context first.** If the user has attached notes, documents, URLs, YouTube transcripts, tweets, or any other content to the conversation, use that content as your primary source. The user added it for a reason.
2. **Vault second.** For any question that could plausibly be answered by the user's notes, search the vault (localSearch). The user's own writing, meeting notes, journal entries, and saved references are highly valuable.
3. **Web third.** If the vault has no relevant results, or the question is about external/current information the vault is unlikely to contain, search the web.
4. **Your own knowledge last.** Only fall back on your training data when all of the above have been exhausted or are clearly inapplicable (e.g., explaining a general concept, writing code, or creative tasks that don't need source material).
When in doubt, search the vault. It is always better to check and find nothing than to skip the search and miss relevant notes.
## General Guidelines
- NEVER mention tool names like "localSearch", "webSearch", etc. in your responses. Use natural language like "searching your vault", "searching the web", etc.
You can use multiple tools in sequence. After each tool execution, you'll receive the results and can decide whether to use more tools or provide your final response.
Always explain your reasoning before using tools. Be conversational and clear about what you're doing.
When you've gathered enough information, provide your final response without any tool calls.
## Citation Integrity (CRITICAL)
- ONLY cite sources from tools you ACTUALLY called and received results from
- NEVER fabricate or hallucinate search results, web searches, or any tool outputs
- If you did not call a tool, do not claim you did or cite results from it
- Each citation must correspond to a real document or result returned by a tool in this conversation`}),l}enhanceUserMessage(e,n){return e}needsSpecialHandling(){return!1}},vat=class extends uF{isGPT5Model(){return this.modelName.includes("gpt-5")||this.modelName.includes("gpt5")}buildSystemPromptSections(e,n,r,o){let i=super.buildSystemPromptSections(e,n,r,o),s=r||[],a=s.includes("writeFile")||s.includes("editFile"),l=[];this.isGPT5Model()?l.push(`GPT-5 SPECIFIC RULES:
- Use maximum 2 tool calls initially, then provide an answer
- Call each tool ONCE per unique query
- For optional parameters: OMIT them entirely if not needed (don't pass empty strings/null)
- For localSearch: OMIT timeRange if not doing time-based search`):l.push("CRITICAL FOR GPT MODELS: You MUST use tools when the user's request requires them. Do not just describe what you plan to do - actually call the tools."),a&&l.push(`\u{1F6A8} FILE EDITING WITH COMPOSER TOOLS \u{1F6A8}
When user asks you to edit or modify a file, you MUST:
1. Determine if it's a small edit (use editFile) or major rewrite (use writeFile)
2. Call the tool immediately - do not just describe what you plan to do
For editFile, pass the exact text to find and its replacement:
- path: vault-relative file path
- oldText: exact text to find (include surrounding context lines to make it unique)
- newText: replacement text (empty string to delete)
\u274C WRONG: "I'll help you add item 4 to the list. Let me update that for you." [No tool call = FAILURE]
\u2705 CORRECT: Actually call editFile or writeFile with proper parameters`),l.push("FINAL REMINDER FOR GPT MODELS: If the user asks you to search, find, edit, or modify anything, you MUST call the appropriate tool immediately. Do not wait for another turn.");let c=l.join(`
`);return i.push({id:"gpt-specific-guidelines",label:"GPT-specific guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#GPTModelAdapter.buildSystemPromptSections",content:c}),i}enhanceUserMessage(e,n){return n?this.getBaseEnhancement(e,n):e}getBaseEnhancement(e,n){if(!n)return e;let r=e.toLowerCase(),o=r.includes("find")||r.includes("search")||r.includes("my notes"),i=r.includes("edit")||r.includes("modify")||r.includes("update")||r.includes("change")||r.includes("fix")||r.includes("add")||r.includes("typo");return o?`${e}
REMINDER: Call the localSearch tool now.`:i?`${e}
\u{1F6A8} GPT REMINDER: Use editFile for small edits (oldText/newText parameters) or writeFile for full rewrites.`:e}needsSpecialHandling(){return!0}},wat=class extends uF{isThinkingModel(){return this.modelName.includes("claude-3-7-sonnet")||this.modelName.includes("claude-sonnet-4")||this.modelName.includes("claude-3.7-sonnet")||this.modelName.includes("claude-4-sonnet")||this.modelName.includes("claude-opus-4")}isClaudeSonnet4(){return this.modelName.includes("claude-sonnet-4")||this.modelName.includes("claude-4-sonnet")||this.modelName.includes("claude-sonnet-4-20250514")}buildSystemPromptSections(e,n,r,o){let i=super.buildSystemPromptSections(e,n,r,o);if(!this.isThinkingModel())return i;let s=[`IMPORTANT FOR CLAUDE THINKING MODELS:
- You are a thinking model with internal reasoning capability
- Your thinking process will be automatically wrapped in <think> tags - do not manually add thinking tags
- Call tools AFTER your thinking is complete
- Do not provide final answers before using tools - use tools first, then provide your response based on the results
CORRECT FLOW FOR THINKING MODELS:
1. Think through the problem (this happens automatically)
2. Use tools to gather information
3. Wait for tool results
4. Provide final response based on gathered information
INCORRECT: Providing a final answer before using tools
CORRECT: Using tools first, then providing answer based on results`];return this.isClaudeSonnet4()&&s.push(`\u{1F6A8} CRITICAL INSTRUCTIONS FOR CLAUDE SONNET 4 - AUTONOMOUS AGENT MODE \u{1F6A8}
\u26A0\uFE0F WARNING: You have a specific tendency to write complete responses immediately after tool calls. This BREAKS the autonomous agent pattern!
\u{1F504} CORRECT AUTONOMOUS AGENT ITERATION PATTERN:
1. User asks question
2. Brief sentence about what you'll do (1 sentence max)
3. Use tools to gather information
4. \u270B STOP after tool calls - Do not write anything else
5. Wait for tool results (system provides them)
6. Evaluate results and either: Use more tools OR provide final answer
\u2705 IDEAL RESPONSE FLOW:
- Brief action statement (1 sentence)
- Tool calls
- STOP (wait for results)
- Brief transition statement (1 sentence)
- More tool calls OR final answer
\u{1F3AF} CORRECT PATTERN:
I'll search your vault for piano practice information.
[Call localSearch tool]
[RESPONSE ENDS HERE - NO MORE TEXT]
\u274C WRONG PATTERN (DO NOT DO THIS):
[Call tool]
Based on the search results, here's a complete practice plan...
[This is FORBIDDEN - you haven't received results yet!]
\u{1F511} KEY UNDERSTANDING FOR CLAUDE 4:
- Brief 1-sentence explanations BEFORE tool calls are good
- Each response is ONE STEP in a multi-step process
- After tool calls, STOP and wait for the system to provide results
- Your thinking is automatically handled in <think> blocks
\u26A1 AUTONOMOUS AGENT RULES FOR CLAUDE 4:
1. If you need tools: Brief sentence + tool calls, then STOP
2. If you receive tool results: Evaluate if you need more tools
3. If you need more tools: Brief sentence + more tool calls, then STOP
4. If you have enough info: THEN provide your final response
REMEMBER: One brief sentence before tools is perfect. Nothing after tool calls.`),i.push({id:"claude-thinking-guidelines",label:"Claude thinking model guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#ClaudeModelAdapter.buildSystemPromptSections",content:s.join(`
`)}),i}needsSpecialHandling(){return this.isThinkingModel()}},bat=class extends uF{buildSystemPromptSections(e,n,r,o){let i=super.buildSystemPromptSections(e,n,r,o),l=[`\u{1F6A8} CRITICAL INSTRUCTIONS FOR GEMINI - AUTONOMOUS AGENT MODE \u{1F6A8}
You MUST use tools to complete tasks. DO NOT ask the user questions about how to proceed.
${(r||[]).includes("localSearch")?`
When the user mentions "my notes" or "my vault", use the localSearch tool.
\u274C WRONG:
"Let's start by searching your notes. What kind of information should I look for?"
\u2705 CORRECT: Call localSearch immediately with the user's topic as the query`:""}`.trim()];return l.push(`GEMINI SPECIFIC RULES:
1. When user mentions "my notes" about X \u2192 use localSearch with query "X"
2. DO NOT ask clarifying questions about search terms
3. DO NOT wait for permission to use tools
4. Use tools based on the user's request
\u{1F6A8} CRITICAL: SEQUENTIAL vs PARALLEL TOOL CALLS \u{1F6A8}
When one tool's OUTPUT is needed as INPUT to another tool, you MUST make them in SEPARATE responses:
1. Call the FIRST tool
2. STOP and wait for the result
3. In the NEXT response, use the result from step 1 in the SECOND tool call
\u274C WRONG (DO NOT DO THIS):
User: "Recap my last week"
- Call getTimeRangeMs AND localSearch together with made-up timeRange values
- This is WRONG because you're hallucinating the timeRange values!
\u2705 CORRECT (DO THIS):
User: "Recap my last week"
- FIRST: Call getTimeRangeMs with timeExpression "last week"
- WAIT for result
- SECOND: Call localSearch using the actual timeRange from the result
RULE: NEVER make up or guess parameter values. If you need a tool's output, call that tool FIRST, then WAIT for the result.
Remember: The user has already told you what to do. Execute it NOW with the available tools.`),i.push({id:"gemini-specific-guidelines",label:"Gemini-specific guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#GeminiModelAdapter.buildSystemPromptSections",content:l.join(`
`)}),i}enhanceUserMessage(e,n){return n?`${e}
REMINDER: Use the tools immediately. Do not ask questions. For "my notes", use localSearch.`:e}needsSpecialHandling(){return!0}},_at=class extends uF{buildSystemPromptSections(e,n,r,o){let i=super.buildSystemPromptSections(e,n,r,o);return i.push({id:"copilot-plus-guidelines",label:"Copilot Plus model guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#CopilotPlusModelAdapter.buildSystemPromptSections",content:`\u{1F6A8} CRITICAL: NO HALLUCINATED TOOL CALLS OR SOURCES \u{1F6A8}
You are a Copilot Plus model. You MUST follow these rules strictly:
## Tool Call Integrity
- You can ONLY reference results from tools you have ACTUALLY called in this conversation
- NEVER claim to have performed a web search unless you called the webSearch tool AND received results
- NEVER claim to have searched notes unless you called localSearch AND received results
- If you want to search the web, you MUST call the webSearch tool first - do not make up results
## Citation Rules
- Every citation [1], [2], etc. MUST correspond to a real source returned by a tool
- Do NOT invent sources like "General web search results for X" unless webSearch was actually called
- If you only called localSearch, your citations can ONLY reference notes from that search
- Count your actual tool calls - if you only made 1 tool call, you cannot have citations from multiple different tools
## Before Writing Citations
Ask yourself: "Did I actually call this tool and receive this result?"
- If YES: You may cite it
- If NO: Do NOT cite it or claim you did
REMEMBER: It is better to say "I only searched your notes, not the web" than to fabricate web search results.
## Formatting Guidelines
- AVOID using markdown tables - they often render poorly in chat interfaces
- Instead of tables, use bullet points, numbered lists, or simple formatted text
- Only use tables when the user explicitly requests tabular format`}),i}needsSpecialHandling(){return!0}},Xre=class{static createAdapter(e){let n=(e.modelName||e.model||"").toLowerCase();if(j(`Creating model adapter for: ${n}`),n.includes("gpt")){let r=new vat(n);return r.isGPT5Model()?j("Using GPTModelAdapter with GPT-5 specific enhancements"):j("Using GPTModelAdapter"),r}return n.includes("claude")?(j("Using ClaudeModelAdapter"),new wat(n)):n.includes("gemini")||n.includes("google/gemini")?(j("Using GeminiModelAdapter"),new bat(n)):n.includes("copilot-plus")?(j("Using CopilotPlusModelAdapter"),new _at(n)):(j("Using BaseModelAdapter (default)"),new uF(n))}};function zSn(t){let e=["find","search","look for","look up","my notes","in my vault","from my vault","check the web","search online","from the internet","current time","what time","timer","youtube","video","transcript"],n=t.toLowerCase();return e.some(r=>n.includes(r))}function Ljr(t){let{systemSections:e,rawHistory:n,adapterName:r,originalUserMessage:o,enhancedUserMessage:i}=t,s=[...e];if(n&&n.length>0){let l=Art(n);if(l.length>0){let u=Ogn(l).map((d,f)=>`${f+1}. ${d.role.toUpperCase()}
${d.content}`);s.push({id:"chat-history",label:"Restored chat history from memory",source:"src/LLMProviders/chainRunner/utils/chatHistoryUtils.ts#processRawChatHistory",content:u.join(`
`)})}}s.push({id:"user-original-message",label:"Original user message",source:"Chat input",content:o});let a=i===o?" (unchanged)":"";return s.push({id:"user-enhanced-message",label:`User message after ${r}.enhanceUserMessage${a}`,source:`src/LLMProviders/chainRunner/utils/modelAdapter.ts#${r}.enhanceUserMessage`,content:i}),s}function $jr(t){return t.map(e=>`${`[Section: ${e.label} | Source: ${e.source}]`}
${e.content}`).join(`
`)}function HSn(t){let e=Ljr(t),n=$jr(e),r=xat(t.systemSections);return{sections:e,annotatedPrompt:n,systemPrompt:r}}async function Djr(t){let{chainManager:e,adapter:n,basePrompt:r,toolDescriptions:o,toolNames:i,toolMetadata:s,userMessage:a}=t,l=n.buildSystemPromptSections(r,o,i,s),u=await e.memoryManager.getMemory().loadMemoryVariables({}),d=Array.isArray(u.history)?u.history:[],f=a.originalMessage||a.message,p=zSn(a.message),m=n.enhanceUserMessage(a.message,p);return HSn({systemSections:l,rawHistory:d,adapterName:n.constructor?.name||"ModelAdapter",originalUserMessage:f,enhancedUserMessage:m})}async function Fjr(t){return H0(t.userMemoryManager)}async function WSn(t){let{chainManager:e,adapter:n,availableTools:r,toolDescriptions:o,userMessage:i}=t,s=ic.getInstance(),a=r.map(u=>u.name),l=r.map(u=>s.getToolMetadata(u.name)).filter(u=>u!==void 0),c=await Fjr(e);return Djr({chainManager:e,adapter:n,basePrompt:c,toolDescriptions:o,toolNames:a,toolMetadata:l,userMessage:i})}NSe();function Ujr(t,e){let n=new Set(t.toLowerCase().split(/\s+/).filter(Boolean)),r=new Set(e.toLowerCase().split(/\s+/).filter(Boolean));if(n.size===0&&r.size===0)return 1;if(n.size===0||r.size===0)return 0;let o=0;for(let l of n)r.has(l)&&o++;let i=n.size+r.size-o,s=o/i,a=o/Math.min(n.size,r.size);return Math.max(s,a)}function Sat(t,e,n=.6){for(let r of e)if(Ujr(t,r)>=n)return r;return null}var jjr=/^(user|assistant|system)\s*$/;function VSn(t){return t&&t.split(`
`).filter(e=>!jjr.test(e)).join(`
`)}var qSn=`## Agent Behavior
- You have a limited number of tool calls. Use them wisely.
- NEVER search for the same or very similar query twice. If results were insufficient, try substantially different terms.
- After 1-2 searches, synthesize an answer from the results you have. Do not keep searching unless the results are clearly insufficient.
- If you have enough information to answer, respond directly without calling any more tools.`,Qre=class extends CO{constructor(){super(...arguments);this.llmFormattedMessages=[];this.lastDisplayedContent="";this.reasoningState=Gcn();this.reasoningTimerInterval=null;this.accumulatedContent="";this.allReasoningSteps=[];this.abortHandledByTimer=!1}getAvailableTools(){let n=Y(),r=ic.getInstance();r.getAllTools().length===0&&e5(this.chainManager.app);let o=new Set(n.autonomousAgentEnabledToolIds||[]);return r.getEnabledTools(o,!!this.chainManager.app?.vault)}startReasoningTimer(n,r){this.reasoningState={status:"reasoning",startTime:Date.now(),elapsedSeconds:0,steps:[]},this.accumulatedContent="",this.allReasoningSteps=[],this.abortHandledByTimer=!1;let o=["Understanding your question","Analyzing your request","Processing your query","Thinking about this","Considering your question","Working on this","Pondering the possibilities","Diving into your request","Let me think about this","Exploring your question","Getting my thoughts together","Examining the details","Looking into this","Mulling this over","On it","Firing up the neurons","Connecting the dots","Brewing some ideas","Spinning up the gears","Warming up the engines","Crunching the details","Putting on my thinking cap","Consulting my notes","Gathering my thoughts","Rolling up my sleeves"],i=o[Math.floor(Math.random()*o.length)];this.addReasoningStep(i),this.reasoningTimerInterval=window.setInterval(()=>{if(r?.signal.aborted&&this.reasoningState.status==="reasoning"){this.stopReasoningTimer(),this.reasoningState.status="complete",this.abortHandledByTimer=!0;let s=this.buildReasoningBlockMarkup(),a="The response was interrupted.",l=s?s+`
`+a:a;n(l);return}if(this.reasoningState.startTime&&this.reasoningState.status==="reasoning"){this.reasoningState.elapsedSeconds=Math.floor((Date.now()-this.reasoningState.startTime)/1e3);let s=this.buildReasoningBlockMarkup(),a=s?s+(this.accumulatedContent?`
`+this.accumulatedContent:""):this.accumulatedContent;n(a)}},100)}addReasoningStep(n,r,o=!1){let i={timestamp:Date.now(),summary:n,toolName:r};this.allReasoningSteps.push(i),!o&&(this.reasoningState.steps.push(i),this.reasoningState.steps.length>4&&this.reasoningState.steps.shift())}stopReasoningTimer(){this.reasoningTimerInterval&&(window.clearInterval(this.reasoningTimerInterval),this.reasoningTimerInterval=null),this.reasoningState.status="collapsed"}buildReasoningBlockMarkup(){if(this.reasoningState.status==="complete"||this.reasoningState.status==="collapsed"){let n={...this.reasoningState,steps:this.allReasoningSteps};return Zet(n)}return Zet(this.reasoningState)}static async generateSystemPrompt(n,r,o){let i=await H0(o),s=ic.getInstance(),l=n.map(u=>s.getToolMetadata(u.name)).filter(u=>u!==void 0).filter(u=>u.customPromptInstructions).map(u=>`For ${u.displayName}: ${u.customPromptInstructions}`).join(`
`),c=[i];return l&&c.push(`## Tool Guidelines
${l}`),c.push(qSn),c.join(`
`)}async buildToolPromptDebugReport(n){let r=this.getAvailableTools(),o=Xre.createAdapter(this.chainManager.chatModelManager.getChatModel()),i=r.map(s=>`${s.name}: ${s.description}`).join(`
`);return WSn({chainManager:this.chainManager,adapter:o,availableTools:r,toolDescriptions:i,userMessage:n})}applyCiCOrderingToLocalSearchResult(n,r){return FSn(n,r)}async run(n,r,o,i,s){this.llmFormattedMessages=[],this.lastDisplayedContent="";let a=await ch(this.chainManager.app,{trigger:"legacy_chat_turn",isAutonomousAgent:!0}),l=this.chainManager.chatModelManager.getChatModel(),c=Xre.createAdapter(l),u=new Ug(o,!0);if(!a){await this.handleError(new Error("Invalid license key"),h=>u.processErrorChunk(h));let m=u.close().content;return this.handleResponse(m,n,r,i,o,void 0)}let d=l?.modelName;if(!n.contextEnvelope)throw new Error("[Agent] Context envelope is required but not available. Cannot proceed with autonomous agent.");j("[Agent] Using native tool calling with ReAct pattern");let p=await this.prepareAgentConversation(n,l,s.updateLoadingMessage);try{this.startReasoningTimer(o,r);let m=await this.runReActLoop({boundModel:p.loopDeps.boundModel,chatModel:l,tools:p.loopDeps.availableTools,messages:p.messages,originalPrompt:p.originalUserPrompt,abortController:r,updateCurrentAiMessage:o,processLocalSearchResult:p.loopDeps.processLocalSearchResult,applyCiCOrderingToLocalSearchResult:p.loopDeps.applyCiCOrderingToLocalSearchResult,adapter:c});if(this.abortHandledByTimer)return this.lastDisplayedContent="","";let h=qq(m.sources);return p.messages.length>0&&zM({messages:[...p.messages],modelName:d,contextEnvelope:n.contextEnvelope}),await this.handleResponse(m.finalResponse,n,r,i,o,h.length>0?h:void 0,this.llmFormattedMessages.join(`
`),m.responseMetadata),this.lastDisplayedContent="",m.finalResponse}catch(m){if(this.stopReasoningTimer(),m.name==="AbortError"||r.signal.aborted)return j("Autonomous agent stream aborted by user",{reason:r.signal.reason}),"";H("Autonomous agent failed, falling back to regular Plus mode:",m);try{return await new CO(this.chainManager).run(n,r,o,i,s)}catch(h){H("Fallback to regular Plus mode also failed:",h),this.lastDisplayedContent&&u.processChunk({content:this.lastDisplayedContent});let g=kt(m),v=`
Fallback to regular Plus mode also failed: `+kt(h);await this.handleError(new Error(g+v),w=>u.processErrorChunk(w));let y=u.close().content;return this.handleResponse(y,n,r,i,o,void 0,y)}}}async prepareAgentConversation(n,r,o){let i=[],s=this.getAvailableTools(),a=r.modelName||r.model||"unknown";if(typeof r.bindTools!="function")throw new Error(`Model ${a} does not support native tool calling (bindTools not available). Agent mode requires a model with tool calling support.`);let l=r.bindTools(s),c={availableTools:s,boundModel:l,processLocalSearchResult:this.processLocalSearchResult.bind(this),applyCiCOrderingToLocalSearchResult:this.applyCiCOrderingToLocalSearchResult.bind(this)},u=n.contextEnvelope,d=XS.convert(u,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),f=this.chainManager.memoryManager.getMemory(),p=d.find(C=>C.role==="system"),m=ic.getInstance(),g=s.map(C=>m.getToolMetadata(C.name)).filter(C=>C!==void 0).filter(C=>C.customPromptInstructions).map(C=>`For ${C.displayName}: ${C.customPromptInstructions}`).join(`
`),v=[p?.content||"",g?`
## Tool Guidelines
${g}`:"",qSn].filter(Boolean).join(`
`);v&&i.push(new sg({content:v}));let _=u.layers.find(C=>C.id==="L5_USER")?.text||""||n.originalMessage||n.message,S=[];await BM(f,S);for(let C of S)C.role==="user"?i.push(new na(C.content)):i.push(new cr(C.content));let I=d.find(C=>C.role==="user");if(I){let k=this.isMultimodalModel(r)?await this.buildMessageContent(I.content,n):I.content;i.push(new na(k))}return{messages:i,collectedSources:[],originalUserPrompt:_,loopDeps:c}}async runReActLoop(n){let{boundModel:r,tools:o,messages:i,originalPrompt:s,abortController:a,updateCurrentAiMessage:l,processLocalSearchResult:c,applyCiCOrderingToLocalSearchResult:u}=n,d=Y().autonomousAgentMaxIterations,f=[],p=Date.now(),m=[],h=0,g=0,v;for(;g<d&&!a.signal.aborted;){let C=Date.now()-p;if(C>=rAe){W(`Agent loop timed out after ${Math.round(C/1e3)}s`);break}g++;let{content:k,aiMessage:T,streamingResult:P}=await this.streamModelResponse(r,i,a,l);v={wasTruncated:P.wasTruncated,tokenUsage:P.tokenUsage??void 0};let E=k?.trim();j(`[Agent] Iteration ${g} model output:`,E?E.slice(0,200):"(empty)");let O=T.tool_calls||[];if(j(`[Agent] Iteration ${g}: ${O.length} tool call(s)`),O.length===0){j(`[Agent] Iteration ${g}: Final response (no tool calls)`),this.stopReasoningTimer(),this.reasoningState.status="complete",i.push(T);let le=k;if(!le||le.trim()===""){let F=T.tool_call_chunks??[];W(`[Agent] Empty response detected (iteration ${g}). Content length: ${k?.length??0}, tool_call_chunks from model: ${F.length}, parsed tool_calls: ${O.length}. This may indicate tool calls were dropped or the model produced only thinking tokens.`),le="The model did not produce a response. Please try again or switch to a different model."}let Q=this.buildReasoningBlockMarkup(),ne=20,ee=5,ae="";for(let F=0;F<le.length&&!a.signal.aborted;F+=ne){ae+=le.slice(F,F+ne);let z=Q?Q+`
`+ae:ae;l(z),F+ne<le.length&&await new Promise(N=>window.setTimeout(N,ee))}let q=Q?Q+`
`+le:le;return l(q),{finalResponse:q,sources:f,responseMetadata:v}}let $=VSn(k),U=new cr({content:$,tool_calls:T.tool_calls});if(i.push(U),g>1&&$&&$.trim().length>0){let le=Ycn($);le&&this.addReasoningStep(le)}let V=[],K=[],se=[];for(let le of O){if(le.name==="localSearch"){let Q=le.args?.query;if(Q){let ne=Sat(Q,m)??Sat(Q,K);if(ne){j(`[Agent] Dedup: "${Q}" (similar to: "${ne}")`),i.push(Ert(le.id||Fke(),le.name,`You already searched for a similar query: "${ne}". Synthesize your answer from existing results.`));continue}K.push(Q),se.push(Q)}else se.push(null)}else se.push(null);V.push(le)}for(let le=0;le<V.length;le++){let Q=V[le];if(a.signal.aborted)break;let ne={name:Q.name,args:Q.args},ee=Yet(Q.name,ne.args);this.addReasoningStep(ee,Q.name),wxn(ne,g);let ae=await yxn(ne,o,s),q;if(Q.name==="localSearch"&&ae.success){let N=c(ae);f.push(...N.sources),q={titles:N.sources.map(R=>R.title),count:N.sources.length},ae.result=u(N.formattedForLLM,s||"")}if(bxn(Q.name,ae),Q.name==="localSearch"&&ae.success){let N=se[le];N&&m.push(N)}let F=Zcn(Q.name,ae,q,ne.args);(!ae.success||q)&&this.addReasoningStep(F,Q.name);let z=Ert(Q.id||Fke(),Q.name,ae.result);i.push(z)}if(V.length===0&&O.length>0){if(h++,j(`[Agent] All ${O.length} tool call(s) skipped as duplicates (${h} consecutive)`),h>=2){j("[Agent] Model stuck in search loop, forcing synthesis without tools"),this.addReasoningStep("Synthesizing answer from search results"),i.push(new na(`You have already searched and found relevant results. Do not call any tools. Answer the following question now based ONLY on the search results above:
`+s));let le=await this.streamModelResponse(n.chatModel,i,a,l);v={wasTruncated:le.streamingResult.wasTruncated,tokenUsage:le.streamingResult.tokenUsage??void 0},this.stopReasoningTimer(),this.reasoningState.status="complete";let Q=this.buildReasoningBlockMarkup(),ne=le.content||"Unable to synthesize a response from the search results.",ee=Q?Q+`
`+ne:ne;return l(ee),{finalResponse:ee,sources:f,responseMetadata:v}}}else h=0}this.stopReasoningTimer(),this.reasoningState.status="complete";let y=this.buildReasoningBlockMarkup();if(a.signal.aborted){if(j("Agent reasoning interrupted by user"),this.abortHandledByTimer)return{finalResponse:"",sources:f,responseMetadata:v};let C="The response was interrupted.";return{finalResponse:y?y+`
`+C:C,sources:f,responseMetadata:v}}let w=Date.now()-p,_=w>=rAe;_?W(`Agent loop timed out after ${Math.round(w/1e3)}s`):W(`Agent reached max iterations (${d})`);let S=_?"I've reached the time limit for reasoning. Here's what I found so far based on the search results.":"I've reached the maximum number of tool calls. Here's what I found so far based on the search results.";return{finalResponse:y?y+`
`+S:S,sources:f,responseMetadata:v}}async streamModelResponse(n,r,o,i){let s=new Map,a=new Ug(()=>{},!0),l="";try{let c=await Jf(()=>n.stream(r,{signal:o.signal}));for await(let g of c){if(o.signal.aborted)break;let v=g;if(v.response_metadata?.finish_reason==="MALFORMED_FUNCTION_CALL")throw W("Backend returned MALFORMED_FUNCTION_CALL - falling back to non-agent mode"),new Error("MALFORMED_FUNCTION_CALL: Model does not support native tool calling");let w=v.tool_call_chunks;if(w&&Array.isArray(w))for(let S of w)Lgn(s,S);let _=typeof v.content=="string"?v.content:"";_&&(l+=_),a.processChunk(v)}let u=a.close(),d=u.content,f=l.trim(),p=d.trim();f&&!p&&j(`[Agent] Model produced content that was entirely stripped (likely think blocks): ${f.slice(0,300)}`);let m=Uke(s),h=new cr({content:d,tool_calls:m.map(g=>({id:g.id,name:g.name,args:g.args,type:"tool_call"}))});return{content:d,aiMessage:h,streamingResult:u}}catch(c){if(H(`Stream error: ${c.message}`),c.name==="AbortError"||o.signal.aborted){let u=a.close();return{content:u.content,aiMessage:new cr({content:u.content}),streamingResult:u}}throw c}}};pe();Se();ut();mp();iy();a5();jq();var l5=[{tag:"note_context",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"active_note",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"embedded_note",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"vault_note",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"retrieved_document",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"url_content",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"web_tab_context",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"active_web_tab",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"youtube_video_context",sourceType:"youtube",recoverable:!0,sourceExtractor:"url"},{tag:"twitter_content",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"embedded_pdf",sourceType:"pdf",recoverable:!0,sourceExtractor:"name"},{tag:"selected_text",sourceType:"selected_text",recoverable:!1,sourceExtractor:null},{tag:"web_selected_text",sourceType:"selected_text",recoverable:!1,sourceExtractor:null},{tag:"localSearch",sourceType:"note",recoverable:!0,sourceExtractor:null}],tTe=new Map;for(let t of l5)tTe.set(t.tag,t);function mF(t){return tTe.get(t)?.sourceType??"unknown"}function nTe(t){return tTe.get(t)?.recoverable??!1}function c5(t,e){let n=tTe.get(e);if(!n?.sourceExtractor)return"";let r=n.sourceExtractor;return new RegExp(`<${r}>([^<]+)</${r}>`).exec(t)?.[1]??""}function aoe(t){let e=/<content>([\s\S]*?)<\/content>/.exec(t);return e?e[1]:t}var Jg={previewCharsPerSection:500,maxSections:20,verbatimThreshold:5e3};function hF(t,e=500,n=20){let r=t.split(/(?=^#{1,6}\s+)/m).filter(a=>a.trim());if(r.length<=1)return Nat(t,e*4);let o=r.slice(0,n),i=r.length>n,s=o.map(a=>{let l=a.trim().split(`
`),c=l[0],u=l.slice(1).join(`
`).trim();return u.length<=e?a.trim():`${c}
${Nat(u,e)}`}).join(`
`);return i?`${s}
[... ${r.length-n} more sections omitted ...]`:s}function Nat(t,e){if(t.length<=e)return t;let n=t.slice(0,e),r=/[.!?]\s+/g,o=-1,i;for(;(i=r.exec(n))!==null;)i.index>e*.5&&(o=i.index+1);if(o>0)return n.slice(0,o)+" ...";let s=n.lastIndexOf(`
`);if(s>e*.5)return n.slice(0,s)+`
...`;let a=n.lastIndexOf(" ");return a>e*.8?n.slice(0,a)+" ...":n+"..."}function rTe(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function cBr(){return["localSearch","note_context","active_note","retrieved_document","url_content","youtube_video_context"].map(e=>({pattern:new RegExp(`<${e}[^>]*>[\\s\\S]*?</${e}>`,"g"),tag:e}))}var uBr=cBr(),u5="Tool 'readNote' result: ";function dBr(t,e){if(t[e]!=="{")return null;let n=0,r=!1,o=!1;for(let i=e;i<t.length;i++){let s=t[i];if(o){o=!1;continue}if(s==="\\"&&r){o=!0;continue}if(s==='"'){r=!r;continue}if(!r){if(s==="{")n++;else if(s==="}"&&(n--,n===0))return{json:t.slice(e,i+1),endPos:i+1}}}return null}function d5(t,e={}){return Array.isArray(t)?t.map(n=>n.type==="text"&&typeof n.text=="string"?{...n,text:aCn(n.text,e)}:n):typeof t=="string"?aCn(t,e):t}function aCn(t,e={}){let n=e.verbatimThreshold??Jg.verbatimThreshold,r=t;for(let{pattern:o,tag:i}of uBr)o.lastIndex=0,r=r.replace(o,s=>s.length<n?s:pBr(s,i,e));return r=fBr(r,n,e),r}function fBr(t,e,n){let r="",o=0;for(;o<t.length;){let i=t.indexOf(u5,o);if(i===-1){r+=t.slice(o);break}r+=t.slice(o,i);let s=i+u5.length,a=dBr(t,s);if(!a){r+=u5,o=s;continue}try{let l=JSON.parse(a.json);if(l.content&&l.content.length>e){let c=hBr(l,n);r+=`${u5}${JSON.stringify(c)}`}else r+=u5+a.json}catch{r+=u5+a.json}o=a.endPos}return r}function pBr(t,e,n={}){if(!nTe(e))return t;if(e==="localSearch")return mBr(t,n);let r=c5(t,e),o=aoe(t),i=mF(e),s=n.previewCharsPerSection??Jg.previewCharsPerSection,a=n.maxSections??Jg.maxSections,l=hF(o,s,a);return`<prior_context source="${rTe(r)}" type="${i}">
${l}
</prior_context>`}function mBr(t,e={}){let n=e.previewCharsPerSection??Jg.previewCharsPerSection,r=/<document>([\s\S]*?)<\/document>/g,o=[],i;for(;(i=r.exec(t))!==null;){let a=i[1],l=/<path>([^<]+)<\/path>/.exec(a),c=/<title>([^<]+)<\/title>/.exec(a),u=/<content>([\s\S]*?)<\/content>/.exec(a),d=l?.[1]??"",f=c?.[1]??d.split("/").pop()??"Untitled",p=u?.[1]??"",m=p.length>n?p.slice(0,n)+"...":p;o.push({path:d,title:f,preview:m.trim()})}if(o.length===0){let a=aoe(t);return`<prior_context source="localSearch" type="note">
${hF(a,n,e.maxSections??Jg.maxSections)}
</prior_context>`}let s=o.map((a,l)=>`${l+1}. [[${a.title}]] (${a.path})
${a.preview}`).join(`
`);return`<prior_context source="localSearch" type="note">
[${o.length} search results - use localSearch to re-query]
${s}
</prior_context>`}function hBr(t,e={}){let{content:n,notePath:r,noteTitle:o,...i}=t;if(!n||typeof n!="string")return t;let s=e.previewCharsPerSection??Jg.previewCharsPerSection,a=e.maxSections??Jg.maxSections,l=hF(n,s,a);return{...i,notePath:r,noteTitle:o,content:`[COMPACTED - use readNote to get full content]
${l}`,_wasCompacted:!0}}pe();Se();a5();br();SL();Om();yA();oi();var gBr=class extends av{addUserMessage(t){return this.addMessage(new na(t))}addAIMessage(t){return this.addMessage(new cr(t))}async addMessages(t){for(let e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},Rat=class extends gBr{constructor(e){super(...arguments);M(this,"lc_namespace",["langchain","stores","message","in_memory"]);M(this,"messages",[]);this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}};br();var oTe=class{},lCn=(t,e)=>{if(e!==void 0)return t[e];let n=Object.keys(t);if(n.length===1)return t[n[0]]},iTe=(t,e)=>{let n=lCn(t,e);if(!n){let r=Object.keys(t);throw new Error(`input values have ${r.length} keys, you must specify an input key or pass only 1 key as input`)}return n},Lat=(t,e)=>{let n=lCn(t,e);if(!n&&n!==""){let r=Object.keys(t);throw new Error(`output values have ${r.length} keys, you must specify an output key or pass only 1 key as output`)}return n};var J0=class extends oTe{constructor(e){super();M(this,"chatHistory");M(this,"returnMessages",!1);M(this,"inputKey");M(this,"outputKey");this.chatHistory=e?.chatHistory??new Rat,this.returnMessages=e?.returnMessages??this.returnMessages,this.inputKey=e?.inputKey??this.inputKey,this.outputKey=e?.outputKey??this.outputKey}async saveContext(e,n){await this.chatHistory.addUserMessage(iTe(e,this.inputKey)),await this.chatHistory.addAIMessage(Lat(n,this.outputKey))}async clear(){await this.chatHistory.clear()}};$at();oi();oi();oi();var Dat=class extends J0{constructor(e){super({chatHistory:e?.chatHistory,returnMessages:e?.returnMessages??!1,inputKey:e?.inputKey,outputKey:e?.outputKey});M(this,"humanPrefix","Human");M(this,"aiPrefix","AI");M(this,"memoryKey","history");this.humanPrefix=e?.humanPrefix??this.humanPrefix,this.aiPrefix=e?.aiPrefix??this.aiPrefix,this.memoryKey=e?.memoryKey??this.memoryKey}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){let n=await this.chatHistory.getMessages();return this.returnMessages?{[this.memoryKey]:n}:{[this.memoryKey]:Mm(n,this.humanPrefix,this.aiPrefix)}}};oi();var Fat=class extends J0{constructor(e){super({returnMessages:e?.returnMessages??!1,chatHistory:e?.chatHistory,inputKey:e?.inputKey,outputKey:e?.outputKey});M(this,"humanPrefix","Human");M(this,"aiPrefix","AI");M(this,"memoryKey","history");M(this,"k",5);this.humanPrefix=e?.humanPrefix??this.humanPrefix,this.aiPrefix=e?.aiPrefix??this.aiPrefix,this.memoryKey=e?.memoryKey??this.memoryKey,this.k=e?.k??this.k}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){let n=await this.chatHistory.getMessages();return this.returnMessages?{[this.memoryKey]:n.slice(-this.k*2)}:{[this.memoryKey]:Mm(n.slice(-this.k*2),this.humanPrefix,this.aiPrefix)}}};$M();$at();SL();oi();oi();oi();var loe=class t{constructor(){this.initMemory(),zr(()=>{let e=this.memory?.chatHistory;this.initMemory(e)})}static getInstance(){return t.instance||(t.instance=new t),t.instance}initMemory(e){let n=Y().contextTurns;this.memory=new Fat({k:n*2,memoryKey:"history",inputKey:"input",returnMessages:!0,chatHistory:e}),this.debug&&j("Memory initialized with context turns:",n)}getMemory(){return this.memory}async clearChatMemory(){this.debug&&j("Clearing chat memory"),await this.memory.clear()}async loadMemoryVariables(){let e=await this.memory.loadMemoryVariables({});return this.debug&&j("Loaded memory variables:",e),e}async saveContext(e,n){let r=typeof n=="string"?d5(n):{...n,output:d5(n.output)};this.debug&&j("Saving to memory - Input:",e,"Output (compacted):",r),await this.memory.saveContext(e,r)}};Se();a5();var coe=class t{constructor(){this.initChatPrompt(),this.initQAPrompt(),zr(()=>{this.initChatPrompt(),this.initQAPrompt()})}static getInstance(){return t.instance||(t.instance=new t),t.instance}initChatPrompt(){let e=this.escapeTemplateString(pO());this.chatPrompt=A_.fromMessages([pF.fromTemplate(e),new Z0("history"),Y0.fromTemplate("{input}")])}initQAPrompt(){let e=`{system_message}
Answer the question with as detailed as possible based only on the following context:
{context}
Question: {question}
`;this.qaPrompt=A_.fromMessages([pF.fromTemplate(e)])}escapeTemplateString(e){return e.replace(/\{/g,"{{").replace(/\}/g,"}}")}getChatPrompt(){return this.chatPrompt}async getQAPrompt({question:e,context:n,systemMessage:r}){return await this.qaPrompt.format({question:e,context:n,system_message:r})}};var uoe=class{constructor(e,n){this.retrievedDocuments=[];this.pendingModelError=null;this.app=e,this.modelManagement=n,this.memoryManager=loe.getInstance(),this.chatModelManager=nw.getInstance(),this.promptManager=coe.getInstance(),this.userMemoryManager=new mO(e),this.initialize().catch(r=>H("ChainManager initialize failed",r)),zr(()=>{this.createChainWithNewModel().catch(r=>H("createChainWithNewModel failed",r))}),n.providerRegistry.subscribe(()=>{this.createChainWithNewModel().catch(r=>H("createChainWithNewModel after provider change failed",r))}),n.backendConfigRegistry.subscribe(()=>{this.createChainWithNewModel().catch(r=>H("createChainWithNewModel after chat backend change failed",r))})}getRetrievedDocuments(){return this.retrievedDocuments}async initialize(){await this.createChainWithNewModel()}validateChainType(e){if(e==null)throw new Error("No chain type set")}validateChatModel(){if(this.pendingModelError)throw this.pendingModelError;if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){let e="Chat model is not initialized properly, check your API key in Copilot setting and make sure you have API access.";throw new YF(e)}}storeRetrieverDocuments(e){this.retrievedDocuments=e}async createChainWithNewModel(e={},n=!0){let r,o=B_();try{let i=L2();if(n){let s=await FNe(this.modelManagement,i||void 0);if(!s.ok)throw new YF("No chat model enabled. Enable a model under Settings \u2192 Basic \u2192 Agents \u2192 Quick Chat, or add one on the Models (BYOK) tab.");r=s.configuredModelId,await this.chatModelManager.setChatModelFromBridged(s.customModel),this.pendingModelError=null}this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())?(this.validateChainType(o),e.refreshIndex&&await this.refreshVaultIndex()):H("createChainWithNewModel: skipping chain-type housekeeping \u2014 no chat model set."),j(`Setting chat model to configuredModelId=${r}`)}catch(i){this.pendingModelError=i instanceof Error?i:new Error(String(i)),H(`createChainWithNewModel failed: ${i}`),j(`configuredModelId: ${r??L2()}`)}}getChainRunner(){let e=B_(),n=Y();switch(e){case"llm_chain":return new one(this);case"vault_qa":return new yre(this);case"copilot_plus":return n.enableAutonomousAgent?new Qre(this):new CO(this);default:throw new Error(`Unsupported chain type: ${String(e)}`)}}async refreshVaultIndex(){if(!Y().enableSemanticSearchV3)return;await(await Promise.resolve().then(()=>(El(),nd))).default.getInstance().indexVaultToVectorStore(!1)}async runChain(e,n,r,o,i={}){let{ignoreSystemMessage:s=!1}=i,a=e.contextEnvelope?.layers.find(u=>u.id==="L5_USER")?.text;j(`Step 0: Initial user message:
`,a||e.originalMessage||e.message),this.validateChatModel();let l=this.chatModelManager.getChatModel();if(s||HK(l)){let u=A_.fromMessages([new Z0("history"),Y0.fromTemplate("{input}")]);HK(l)&&(u=A_.fromMessages([[ar,pO()||""],u])),this.createChainWithNewModel({prompt:u},!1).catch(d=>H("createChainWithNewModel failed",d))}return await this.getChainRunner().run(e,n,r,o,i)}};var N0=class t{constructor(e,n){this.chainMangerInstance=new uoe(e,n),lft(()=>{this.getCurrentChainManager().createChainWithNewModel()}),cft(()=>{let r=Y(),o=r.enableSemanticSearchV3&&r.indexVaultToVectorStore==="ON MODE SWITCH"&&(B_()==="vault_qa"||B_()==="copilot_plus");this.getCurrentChainManager().createChainWithNewModel({refreshIndex:o})})}static getInstance(e,n){return t.instance||(t.instance=new t(e,n)),t.instance}getCurrentChainManager(){return this.chainMangerInstance}};es();nN();pe();Py();var sTe=class t{constructor(e){this.memoryCache=new Map;this.cacheDir=e}static getInstance(e=".copilot/file-content-cache"){return t.instance||(t.instance=new t(e)),t.instance}async ensureCacheDir(e){await e.adapter.exists(this.cacheDir)||(j("Creating file cache directory:",this.cacheDir),await e.adapter.mkdir(this.cacheDir))}getCacheKey(e,n){let r=`${e.path}:${e.stat.size}:${e.stat.mtime}${n?`:${n}`:""}`;return jl(r)}getCachePath(e){return`${this.cacheDir}/${e}.md`}async get(e,n){try{let r=this.memoryCache.get(n);if(r)return j("Memory cache hit for file:",n),r.content;let o=this.getCachePath(n);if(await e.adapter.exists(o)){j("File cache hit:",n);let i=await e.adapter.read(o),s,a=i.trim();if(a.startsWith("{")&&a.endsWith("}")||a.startsWith("[")&&a.endsWith("]"))try{s=JSON.parse(i)}catch{s=i}else s=i;let l={content:s,timestamp:Date.now()};return this.memoryCache.set(n,l),l.content}return j("Cache miss for file:",n),null}catch(r){return H("Error reading from file cache:",r),null}}async set(e,n,r){try{await this.ensureCacheDir(e);let o=this.getCachePath(n),i=Date.now(),s={content:r,timestamp:i};this.memoryCache.set(n,s);let a;typeof r=="string"?a=r:a=JSON.stringify(r,null,2),await e.adapter.write(o,a),j("Cached file content:",n)}catch(o){H("Error writing to file cache:",o)}}async remove(e,n){try{this.memoryCache.delete(n);let r=this.getCachePath(n);await e.adapter.exists(r)&&(await e.adapter.remove(r),j("Removed file from cache:",n))}catch(r){H("Error removing file from cache:",r)}}async clear(e){try{if(this.memoryCache.clear(),await e.adapter.exists(this.cacheDir)){let n=await e.adapter.list(this.cacheDir);j("Clearing file cache, removing files:",n.files.length);for(let r of n.files)await e.adapter.remove(r)}}catch(n){H("Error clearing file cache:",n)}}};pe();var pCn=require("obsidian");yt();hl();IZ();RP();xI();var yi=L(B());Pa();De();Re();pe();var fC=L(B());function fCn(){return fC.default.createElement("ul",{className:"tw-m-0 tw-px-4 tw-text-sm"},fC.default.createElement("li",null,fC.default.createElement("span",{className:"tw-font-medium tw-text-accent"},"{}")," represents the selected text."),fC.default.createElement("li",null,fC.default.createElement("span",{className:"tw-font-medium tw-text-accent"},"{[[Note Title]]}")," represents a note."),fC.default.createElement("li",null,fC.default.createElement("span",{className:"tw-font-medium tw-text-accent"},"{activeNote}")," represents the active note."),fC.default.createElement("li",null,fC.default.createElement("span",{className:"tw-font-medium tw-text-accent"},"{#tag1, #tag2}")," represents ALL notes with ANY of the specified tags in their property (an OR operation)."))}Og();Uat();function wBr({commands:t,command:e,onConfirm:n,onCancel:r}){let{options:o,resolveSelectionId:i}=lTe(),[s,a]=(0,yi.useState)(()=>({...e,modelKey:e.modelKey?i(e.modelKey)||e.modelKey:""})),[l,c]=(0,yi.useState)({}),u=(f,p)=>{a(m=>({...m,[f]:p})),c(m=>({...m,[f]:void 0}))},d=()=>{let f={},p=cSe(s.title,t,e.title);if(p&&(f.title=p),s.content.trim()||(f.content="Prompt is required"),Object.keys(f).length>0){c(f);return}n(s)};return yi.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4 tw-p-4"},yi.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},yi.default.createElement($h,{htmlFor:"title"},"Name"),yi.default.createElement(Ir,{id:"title",value:s.title,onChange:f=>u("title",f.target.value),placeholder:"Enter command name"}),l.title&&yi.default.createElement("div",{className:"tw-text-sm tw-text-error"},l.title)),yi.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},yi.default.createElement($h,{htmlFor:"content"},"Prompt"),yi.default.createElement(fCn,null),yi.default.createElement(If,{id:"content",value:s.content,onChange:f=>u("content",f.target.value),placeholder:"Enter command prompt",className:"tw-min-h-[200px]"}),l.content&&yi.default.createElement("div",{className:"tw-text-sm tw-text-error"},l.content)),yi.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},yi.default.createElement($h,{htmlFor:"modelKey"},"Model (Optional)"),yi.default.createElement("div",{className:"tw-group tw-relative tw-w-full"},yi.default.createElement("select",{value:s.modelKey,onChange:f=>{let p=f.target.value;if(!p){u("modelKey","");return}if(!o.find(h=>h.value===p)){H(`Model ${p} not found`),u("modelKey","");return}u("modelKey",f.target.value)},className:J("tw-w-full tw-appearance-none","tw-flex tw-h-9 tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-dropdown tw-px-3 tw-py-1 tw-pr-8","tw-text-sm !tw-shadow tw-transition-colors","focus:tw-outline-none focus:tw-ring-1 focus:tw-ring-ring","disabled:tw-cursor-not-allowed disabled:tw-opacity-50","hover:tw-bg-interactive-hover hover:tw-text-normal")},yi.default.createElement("option",{value:""},"Inherit from chat model"),o.map(f=>yi.default.createElement("option",{key:f.value,value:f.value.toString()},f.label))),yi.default.createElement("div",{className:J("tw-pointer-events-none tw-absolute tw-inset-y-0 tw-right-0 tw-flex tw-items-center tw-pr-2","tw-transition-colors group-hover:[&>svg]:tw-text-normal")},yi.default.createElement(Bs,{className:"tw-size-4"})))),yi.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},yi.default.createElement(Wl,{id:"showInContextMenu",checked:s.showInContextMenu,onCheckedChange:f=>u("showInContextMenu",f)}),yi.default.createElement($h,{htmlFor:"showInContextMenu"},"Show in context menu")),yi.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},yi.default.createElement(Wl,{id:"showInSlashMenu",checked:s.showInSlashMenu,onCheckedChange:f=>u("showInSlashMenu",f)}),yi.default.createElement($h,{htmlFor:"showInSlashMenu"},"Show in slash menu")),yi.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},yi.default.createElement(oe,{variant:"secondary",onClick:r},"Cancel"),yi.default.createElement(oe,{variant:"default",onClick:d},"Save")))}var kO=class extends pCn.Modal{constructor(n,r,o,i){super(n);this.commands=r;this.command=o;this.onUpdate=i;this.setTitle("Edit Command")}onOpen(){let{contentEl:n}=this;this.root=Er(n,this.app);let r=o=>{this.onUpdate(o),this.close()};this.root.render(yi.default.createElement(wBr,{commands:this.commands,command:this.command,onConfirm:r,onCancel:()=>this.close()}))}onClose(){this.root.unmount()}};rD();x0();c_();var cTe=`
You are an AI assistant designed to execute user instructions with precision. Your responses should be:
- Direct and focused: Address only what is explicitly requested
- Concise: Avoid unnecessary elaboration unless the user asks for details
- Context-aware: When text is selected or highlighted, treat it as the primary target for any requested action
- Action-oriented: Prioritize completing the task over explaining the process
Key principles:
- Follow instructions literally and completely
- Assume selected/highlighted text is the focus unless told otherwise
- Use all provided context: Consider any additional information, examples, or constraints the user provides to better complete the task
- Add explanations only when explicitly requested or when clarification is essential
- Maintain the user's preferred format and style
Response format: Match the format implied by the user's request (e.g., if they ask for a list, provide a list; if they ask for a rewrite, provide only the rewritten text).
`;function uTe(t,e){if(!e)return t;let n=t.includes("{}"),r=/\{activenote\}/i.test(t),o=[];return n||o.push("{}"),r||o.push("{activeNote}"),o.length>0?t+`
${o.join(`
`)}`:t}es();Og();var zd=L(B());Re();var kCn=require("obsidian");var Oi=L(B());De();var ul=L(B());function dTe(t,e,n){return Math.min(Math.max(t,e),n)}function fTe(t={}){let{initialPosition:e={x:0,y:0},bounds:n="window",dragRef:r,getPosition:o,onPositionChange:i,writeToDom:s=!0}=t,[a,l]=(0,ul.useState)(e),[c,u]=(0,ul.useState)(!1),d=(0,ul.useRef)(null),f=r??d,p=(0,ul.useRef)(e),m=(0,ul.useRef)({x:0,y:0}),h=(0,ul.useRef)(null),g=(0,ul.useRef)(null),v=(0,ul.useRef)(null),y=(0,ul.useRef)(!0),w=(0,ul.useCallback)(k=>{if(!s)return;let T=f.current;T&&T.setCssProps({"--copilot-drag-x":`${k.x}px`,"--copilot-drag-y":`${k.y}px`})},[f,s]),_=(0,ul.useCallback)(k=>{let T=k.x,P=k.y,E=f.current;if(n==="window"&&E){let $=E.win,U=E.getBoundingClientRect(),V=$.innerWidth-U.width,K=$.innerHeight-U.height;T=dTe(T,0,Math.max(0,V)),P=dTe(P,0,Math.max(0,K))}else if(n==="parent"&&E?.parentElement){let $=E.getBoundingClientRect(),U=E.parentElement.getBoundingClientRect(),V=U.left,K=U.top,se=U.right-$.width,le=U.bottom-$.height;T=dTe(T,V,Math.max(V,se)),P=dTe(P,K,Math.max(K,le))}let O={x:T,y:P};return p.current=O,w(O),i?.(O),O},[n,f,w,i]),S=(0,ul.useCallback)(()=>{if(g.current!=null)return;let k=f.current?.win??window;g.current=k.requestAnimationFrame(()=>{g.current=null;let T=h.current;T&&(h.current=null,_(T))})},[_,f]);(0,ul.useLayoutEffect)(()=>{w(p.current)},[w]);let I=(0,ul.useCallback)(k=>{let T=p.current,P=typeof k=="function"?k(T):k;p.current=P,l(P),w(P),i?.(P)},[w,i]),C=(0,ul.useCallback)(k=>{if(k.button!==0||(k.preventDefault(),v.current))return;u(!0);let T=o?o():p.current;p.current=T,w(T),m.current={x:k.clientX-T.x,y:k.clientY-T.y};let P=f.current?.doc??activeDocument,E=P.defaultView??window,O=P.body;O.classList.add("tw-select-none","tw-cursor-grabbing");let $=K=>{h.current={x:K.clientX-m.current.x,y:K.clientY-m.current.y},S()},U=K=>{if(v.current!==U)return;P.removeEventListener("mousemove",$,!0),P.removeEventListener("mouseup",V,!0),g.current!=null&&(E.cancelAnimationFrame(g.current),g.current=null);let se=h.current;h.current=null;let le=se?_(se):p.current;O.classList.remove("tw-select-none","tw-cursor-grabbing"),v.current=null,K&&y.current&&(l(le),u(!1))},V=()=>{U(!0)};v.current=U,P.addEventListener("mousemove",$,!0),P.addEventListener("mouseup",V,!0)},[_,f,o,S,w]);return(0,ul.useEffect)(()=>()=>{y.current=!1,v.current?.(!1)},[]),(0,ul.useLayoutEffect)(()=>{w(p.current)}),{position:a,setPosition:I,isDragging:c,dragRef:f,handleMouseDown:C}}var qf=L(B());function mCn(t){let{enabled:e=!0,getRect:n,getConstraints:r,onResize:o}=t,[i,s]=(0,qf.useState)(!1),a=(0,qf.useRef)(null),l=(0,qf.useRef)(null),c=(0,qf.useRef)(null),u=(0,qf.useRef)(null),d=(0,qf.useRef)(null),f=(0,qf.useRef)(o);(0,qf.useEffect)(()=>{f.current=o},[o]);let p=(0,qf.useRef)(r);(0,qf.useEffect)(()=>{p.current=r},[r]);let m=(0,qf.useCallback)(h=>g=>{if(!e)return;let v=n();if(!v)return;let w=g.currentTarget?.doc??activeDocument;l.current=w,c.current=w.defaultView??window,a.current={direction:h,startClientX:g.clientX,startClientY:g.clientY,width:v.width,height:v.height,left:v.left,top:v.top,right:v.right},s(!0),g.preventDefault(),g.stopPropagation()},[e,n]);return(0,qf.useEffect)(()=>{if(!i)return;let h=a.current;if(!h)return;let g=h.direction,v=g==="right"?"ew-resize":g==="bottom"?"ns-resize":g==="bottom-left"?"nesw-resize":"nwse-resize",y=l.current??activeDocument,w=c.current??window,_=y.body;_.setCssProps({"--copilot-resize-cursor":v}),_.classList.add("tw-select-none","tw-cursor-[var(--copilot-resize-cursor)]");let S=()=>{u.current!==null&&(w.cancelAnimationFrame(u.current),u.current=null)},I=()=>{let E=d.current;E&&(d.current=null,f.current(E))},C=()=>{u.current===null&&(u.current=w.requestAnimationFrame(()=>{u.current=null,I()}))},k=E=>{let O=a.current;if(!O)return;let $=E.clientX-O.startClientX,U=E.clientY-O.startClientY,V=p.current?.()??{minWidth:0,minHeight:0},K=V.minWidth,se=V.minHeight,le=V.maxWidth??Number.POSITIVE_INFINITY,Q=V.maxHeight??Number.POSITIVE_INFINITY,ne=O.width,ee=O.height,ae,q;(g==="right"||g==="bottom-right")&&(ne=Math.min(le,Math.max(K,O.width+$))),g==="bottom-left"&&(ne=Math.min(le,Math.max(K,O.width-$)),ae=O.right-ne,q=O.top),(g==="bottom"||g==="bottom-right"||g==="bottom-left")&&(ee=Math.min(Q,Math.max(se,O.height+U))),d.current=ae===void 0?{width:ne,height:ee}:{width:ne,height:ee,x:ae,y:q},C()},T=()=>{S(),I(),y.removeEventListener("mousemove",k,!0),y.removeEventListener("mouseup",P,!0),_.classList.remove("tw-select-none","tw-cursor-[var(--copilot-resize-cursor)]"),_.setCssProps({"--copilot-resize-cursor":""}),a.current=null,s(!1)},P=()=>{T()};return y.addEventListener("mousemove",k,!0),y.addEventListener("mouseup",P,!0),()=>{S(),d.current=null,a.current=null,y.removeEventListener("mousemove",k,!0),y.removeEventListener("mouseup",P,!0),_.classList.remove("tw-select-none","tw-cursor-[var(--copilot-resize-cursor)]"),_.setCssProps({"--copilot-resize-cursor":""})}},[i]),{isResizing:i,handleResizeStart:m}}var jat=L(B());De();function hCn({onMouseDown:t,className:e}){return jat.createElement("div",{className:J("tw-flex tw-h-4 tw-items-center tw-justify-center","tw-cursor-grab active:tw-cursor-grabbing","hover:tw-bg-[color-mix(in_srgb,var(--background-modifier-hover)_20%,transparent)]",e),onMouseDown:t},jat.createElement("div",{className:"tw-h-[5px] tw-w-16 tw-rounded-sm tw-bg-[color-mix(in_srgb,var(--text-muted)_40%,transparent)] hover:tw-bg-[color-mix(in_srgb,var(--text-muted)_65%,transparent)]"}))}var Bat=L(B());Re();De();yt();function gCn({onClose:t,className:e}){return Bat.createElement(oe,{className:J("tw-absolute tw-right-2 tw-top-1 tw-rounded tw-p-1 tw-text-normal",e),variant:"ghost2",onClick:t,title:"Close","aria-label":"Close"},Bat.createElement(pn,{className:"tw-size-4"}))}var vCn="data-copilot-draggable-modal",yCn=`[${vCn}="true"]`;function wCn({open:t,onClose:e,children:n,className:r,initialPosition:o,width:i="min(500px, 90vw)",resizable:s=!1,minHeight:a=260,closeOnEscapeFromOutside:l=!1,anchorBottom:c}){let{position:u,setPosition:d,dragRef:f,handleMouseDown:p,isDragging:m}=fTe({initialPosition:o||{x:typeof window<"u"?(window.innerWidth-500)/2:100,y:typeof window<"u"?(window.innerHeight-400)/2:100},bounds:null}),h=(0,Oi.useRef)(!1),g=(0,Oi.useRef)(null),v=(0,Oi.useCallback)(U=>{let V=U.currentTarget.doc,K=U.clientX,se=U.clientY;g.current?.();let le=()=>{V.removeEventListener("mousemove",Q,!0),V.removeEventListener("mouseup",ne,!0),g.current===le&&(g.current=null)},Q=ee=>{Math.abs(ee.clientX-K)<2&&Math.abs(ee.clientY-se)<2||(h.current=!0,le())},ne=()=>le();V.addEventListener("mousemove",Q,!0),V.addEventListener("mouseup",ne,!0),g.current=le,p(U)},[p]),[y,w]=(0,Oi.useState)(null),[_,S]=(0,Oi.useState)(null),[I,C]=(0,Oi.useState)(t);t&&!I?(C(!0),w(null),S(null)):!t&&I&&C(!1),(0,Oi.useEffect)(()=>{t&&(g.current?.(),g.current=null,h.current=!1,o&&d(o))},[t]),(0,Oi.useEffect)(()=>()=>{g.current?.(),g.current=null},[]),(0,Oi.useLayoutEffect)(()=>{if(!t||!s||y!==null&&_!==null)return;let U=f.current;if(!U)return;let V=U.getBoundingClientRect(),K=typeof window<"u"?Math.floor(window.innerHeight*.85):V.height;y===null&&w(Math.min(K,Math.max(a,V.height))),_===null&&S(V.width)},[t,s,y,_,a,f]);let k=y===null?null:Math.max(y,a);(0,Oi.useLayoutEffect)(()=>{if(c===void 0||h.current||k===null)return;let U=Math.max(12,c-k);Math.abs(u.y-U)<1||d({x:u.x,y:U})},[c,k,u.x,u.y,d]),(0,Oi.useLayoutEffect)(()=>{if(c!==void 0||h.current||k===null)return;let V=(f.current?.win??window).innerHeight-12-k,K=Math.max(12,Math.min(u.y,V));Math.abs(u.y-K)<1||d({x:u.x,y:K})},[c,k,u.x,u.y,d,f]);let T=(0,Oi.useCallback)(()=>f.current?.getBoundingClientRect()??null,[f]),P=(0,Oi.useCallback)(()=>{let U=typeof window<"u"?Math.floor(window.innerHeight*.85):Number.POSITIVE_INFINITY;return{minWidth:300,minHeight:a,maxHeight:U}},[a]),E=(0,Oi.useCallback)(U=>{h.current=!0,w(V=>V===U.height?V:U.height),S(V=>V===U.width?V:U.width),typeof U.x=="number"&&d(V=>V.x===U.x?V:{...V,x:U.x})},[d]),{isResizing:O,handleResizeStart:$}=mCn({enabled:s,getRect:T,getConstraints:P,onResize:E});return(0,Oi.useEffect)(()=>{if(!t)return;let U=f.current?.doc??activeDocument,V=K=>{if(K.key!=="Escape"||K.defaultPrevented)return;let se=f.current;if(!se)return;let le=U.activeElement,Q=le instanceof Element?le.closest(yCn):null;if(Q){if(Q!==se)return;K.preventDefault(),K.stopPropagation(),e();return}if(!l)return;let ne=Array.from(U.querySelectorAll(yCn));ne[ne.length-1]===se&&(K.preventDefault(),K.stopPropagation(),e())};return U.addEventListener("keydown",V),()=>{U.removeEventListener("keydown",V)}},[t,e,f,l]),t?Oi.default.createElement("div",{ref:f,[vCn]:"true",className:J("tw-fixed tw-z-popover","tw-left-[var(--copilot-drag-x,0px)] tw-top-[var(--copilot-drag-y,0px)]","tw-flex tw-flex-col","tw-border tw-border-solid tw-border-border tw-bg-primary",s?"tw-rounded-t-lg tw-shadow-2xl":"tw-rounded-lg tw-shadow-2xl","tw-max-h-[85vh]",s&&"tw-group",m&&"tw-cursor-grabbing tw-select-none",O&&"tw-select-none",r),style:{width:s&&_!==null?_:i,...s&&k!==null?{height:k}:{}}},Oi.default.createElement("div",{className:"tw-relative tw-flex-none"},Oi.default.createElement(hCn,{onMouseDown:v}),Oi.default.createElement(gCn,{onClose:e})),Oi.default.createElement("div",{className:"tw-flex tw-min-h-0 tw-flex-1 tw-flex-col tw-overflow-hidden"},n),s&&Oi.default.createElement(Oi.default.Fragment,null,Oi.default.createElement("div",{className:"tw-absolute tw-bottom-0 tw-left-0 tw-h-1 tw-w-full tw-cursor-ns-resize",onMouseDown:$("bottom")}),Oi.default.createElement("div",{className:"quick-ask-resize-indicator-left tw-absolute tw-bottom-0 tw-left-0 tw-size-3 tw-cursor-nesw-resize",onMouseDown:$("bottom-left")}),Oi.default.createElement("div",{className:"quick-ask-resize-indicator-right tw-absolute tw-bottom-0 tw-right-0 tw-z-[10] tw-size-3 tw-cursor-nwse-resize",onMouseDown:$("bottom-right")}))):null}var pTe=L(B());Re();De();function bCn({icon:t,label:e,className:n}){let r=t===null?null:t!==void 0?t:pTe.createElement(wy,{className:"tw-size-4 tw-text-muted"});return pTe.createElement("div",{className:J("tw-flex tw-flex-none tw-items-center tw-justify-center tw-gap-2","tw-px-4 tw-py-2",n)},r,pTe.createElement("span",{className:"tw-truncate tw-text-sm tw-font-medium tw-text-normal"},e))}var cc=L(B());De();xI();Re();yt();var gF=L(B());function _Cn({content:t,renderMarkdown:e,className:n}){let r=gF.useRef(null),o=gF.useRef(0);return gF.useEffect(()=>{let i=r.current;if(!i)return;let s=++o.current,a=i.doc.win.createDiv();i.replaceChildren(),e(t,a).then(()=>{s===o.current&&(i.replaceChildren(...Array.from(a.childNodes)),a.classList.contains("markdown-rendered")&&i.classList.add("markdown-rendered"))}).catch(()=>{s===o.current&&(i.textContent=t)})},[t,e]),gF.createElement("div",{ref:r,className:n})}function xCn({state:t,editable:e=!1,value:n,onChange:r,placeholder:o="Ready to generate...",className:i,minHeight:s="180px",disableAutoGrow:a=!1,renderMarkdown:l}){let c=cc.useRef(null),[u,d]=cc.useState(!1),f=t.type==="result"&&!t.isStreaming,p=!!l&&f&&!u,m=t.type==="loading"||t.type==="result"&&t.isStreaming,[h,g]=cc.useState(m);m&&!h?(g(!0),d(!1)):!m&&h&&g(!1),cc.useEffect(()=>{t.type==="result"&&t.isStreaming&&c.current&&(c.current.scrollTop=c.current.scrollHeight)},[t]);let v="",y=!0;if(t.type==="idle"?(v="",y=!0):t.type==="loading"?(v="loading...",y=!0):t.type==="result"&&(v=e&&n!==void 0?n:t.text,y=t.isStreaming||!e),p&&l){let _=e&&n!==void 0?n:t.text;return cc.createElement("div",{className:J("tw-flex tw-min-h-0 tw-flex-1 tw-flex-col tw-px-4 tw-py-2",i)},cc.createElement("div",{className:"tw-relative tw-min-h-0 tw-flex-1 tw-overflow-auto tw-rounded-md tw-border tw-border-solid tw-px-3 tw-py-2"},cc.createElement(_Cn,{content:_,renderMarkdown:l,className:"tw-pr-6 tw-text-sm"}),e&&cc.createElement(oe,{variant:"ghost2",size:"icon",className:"tw-absolute tw-right-1 tw-top-1 tw-size-6 tw-opacity-60 hover:tw-opacity-100",onClick:()=>d(!0),title:"Edit content"},cc.createElement(EG,{className:"tw-size-3"}))))}let w=!!l&&f&&u;return a?cc.createElement("div",{className:J("tw-flex tw-min-h-0 tw-flex-1 tw-flex-col tw-px-4 tw-py-2",i)},cc.createElement("div",{className:"tw-relative tw-min-h-0 tw-flex-1"},cc.createElement("textarea",{ref:c,value:v,onChange:_=>r?.(_.target.value),placeholder:o,disabled:y,className:J("tw-min-w-fit tw-overflow-auto tw-border-solid","tw-absolute tw-inset-0 tw-w-full tw-resize-none tw-rounded-md tw-border tw-bg-transparent tw-py-2 tw-pl-3 tw-pr-8 tw-text-base tw-shadow-sm placeholder:tw-text-muted focus-visible:tw-outline-none focus-visible:tw-ring-1 focus-visible:tw-ring-ring disabled:tw-cursor-not-allowed disabled:tw-opacity-50 md:tw-text-sm",y&&"tw-cursor-default tw-opacity-70")}),w&&cc.createElement(oe,{variant:"ghost2",size:"icon",className:"tw-absolute tw-right-2 tw-top-2 tw-z-[1] tw-size-6 tw-opacity-60 hover:tw-opacity-100",onClick:()=>d(!1),title:"Preview rendered content"},cc.createElement(rG,{className:"tw-size-3"})))):cc.createElement("div",{className:J("tw-flex-1 tw-px-4 tw-py-2",i)},cc.createElement(If,{ref:c,value:v,onChange:_=>r?.(_.target.value),placeholder:o,disabled:y,className:J("tw-min-h-[120px] tw-resize-y",y&&"tw-cursor-default tw-opacity-70"),style:{minHeight:s}}))}var f5=L(B());De();xI();yt();Re();function SCn({value:t,onChange:e,onSubmit:n,onClear:r,placeholder:o="Enter follow-up instructions...",className:i,showClear:s=!0,disabled:a=!1,hint:l,autoFocus:c=!1}){let u=d=>{if(!(d.nativeEvent.isComposing||d.key==="Process")&&d.key==="Enter"&&!d.shiftKey&&!d.metaKey&&!d.ctrlKey&&!d.altKey){if(!n)return;d.preventDefault(),n()}};return f5.createElement("div",{className:J("tw-relative tw-flex-none tw-px-4 tw-py-2",i)},f5.createElement(If,{value:t,onChange:d=>e(d.target.value),onKeyDown:u,placeholder:o,disabled:a,autoFocus:c,className:"tw-min-h-[36px] tw-resize-none tw-py-2 tw-pr-8"}),l&&f5.createElement("span",{className:"tw-pointer-events-none tw-absolute tw-bottom-4 tw-right-6 tw-text-xs tw-text-muted"},l),s&&t&&r&&!l&&f5.createElement(oe,{type:"button",variant:"ghost2",size:"fit",onClick:r,disabled:a,className:"tw-absolute tw-right-6 tw-top-4 tw-text-muted","aria-label":"Clear input"},f5.createElement(pn,{className:"tw-size-4"})))}w_e();RP();Lh();var _s=L(B()),doe=require("obsidian");Re();De();yt();var IO="tw-size-3",bBr=()=>doe.Platform.isMacOS?_s.createElement("span",{className:"tw-ml-1 tw-inline-flex tw-items-center tw-gap-0.5 tw-opacity-80"},_s.createElement(ET,{className:IO}),_s.createElement(W_,{className:IO})):_s.createElement("span",{className:"tw-ml-1 tw-inline-flex tw-items-center tw-gap-0.5 tw-text-xs tw-opacity-80"},"Ctrl",_s.createElement(W_,{className:IO})),_Br=()=>doe.Platform.isMacOS?_s.createElement("span",{className:"tw-ml-1 tw-inline-flex tw-items-center tw-gap-0.5 tw-opacity-80"},_s.createElement(ET,{className:IO}),_s.createElement(U2,{className:IO}),_s.createElement(W_,{className:IO})):_s.createElement("span",{className:"tw-ml-1 tw-inline-flex tw-items-center tw-gap-0.5 tw-text-xs tw-opacity-80"},"Ctrl",_s.createElement(U2,{className:IO}),_s.createElement(W_,{className:IO}));function CCn({state:t,onStop:e,onCopy:n,onInsert:r,onReplace:o,onSubmit:i,onCancel:s,showInsertReplace:a=!0,showSubmitCancel:l=!1,className:c}){return _s.createElement("div",{className:J("tw-flex tw-items-center tw-gap-2",c)},t==="loading"&&_s.createElement(oe,{variant:"secondary",size:"sm",onClick:e},"Stop"),t==="result"&&a&&_s.createElement(_s.Fragment,null,n&&_s.createElement(oe,{size:"sm",variant:"secondary",onClick:n,title:"Copy to clipboard"},"Copy"),_s.createElement(oe,{size:"sm",variant:"secondary",onClick:r,title:`Insert below selection (${doe.Platform.isMacOS?"\u2318":"Ctrl"}+Shift+Enter)`},"Insert",_s.createElement(_Br,null)),_s.createElement(oe,{size:"sm",onClick:o,title:`Replace selection (${doe.Platform.isMacOS?"\u2318":"Ctrl"}+Enter)`},"Replace",_s.createElement(bBr,null))),l&&t!=="loading"&&_s.createElement(_s.Fragment,null,_s.createElement(oe,{variant:"secondary",size:"sm",onClick:s},"Cancel"),_s.createElement(oe,{size:"sm",onClick:i},"Submit")))}yt();Se();function Wat({open:t,onClose:e,commandIcon:n,commandLabel:r,contentState:o,editableContent:i,onEditableContentChange:s,followUpValue:a,onFollowUpChange:l,onFollowUpSubmit:c,selectedModel:u,onSelectModel:d,models:f,onStop:p,onCopy:m,onInsert:h,onReplace:g,initialPosition:v,anchorBottom:y,resizable:w=!1,hideContentAreaOnIdle:_=!1,includeNoteContext:S,onIncludeNoteContextChange:I,renderMarkdown:C}){let k=xt(),T=o.type==="loading"||o.type==="result"&&o.isStreaming?"loading":o.type==="result"?"result":"idle",P=o.type==="loading"||o.type==="result"&&!!o.isStreaming,E=o.type==="result"&&!o.isStreaming&&!!s,O=V=>{if(T!=="result"||V.nativeEvent.isComposing)return;let K=kCn.Platform.isMacOS?V.metaKey:V.ctrlKey;V.key!=="Enter"||!K||(V.preventDefault(),V.stopPropagation(),V.shiftKey?h?.():g?.())},$=_?o.type!=="idle":!0;return zd.createElement(wCn,{open:t,onClose:e,initialPosition:v,anchorBottom:y,resizable:w,minHeight:w?$?400:180:void 0,width:"min(620px, 92vw)",closeOnEscapeFromOutside:!0},zd.createElement("div",{onKeyDown:O,className:"tw-flex tw-min-h-0 tw-flex-1 tw-flex-col"},zd.createElement(bCn,{icon:n,label:r,className:"tw-border-b tw-border-border"}),$&&zd.createElement(xCn,{state:o,editable:E,value:i,onChange:s,disableAutoGrow:w,minHeight:w?"0px":void 0,renderMarkdown:C}),zd.createElement(SCn,{value:a,onChange:l,onSubmit:()=>{P||c()},onClear:()=>l(""),placeholder:"Enter follow-up instructions...",className:$?void 0:"tw-mt-auto",hint:P?"Generating...":void 0,autoFocus:!0}),zd.createElement("div",{className:"tw-flex tw-flex-none tw-items-center tw-justify-between tw-border-t tw-border-border tw-px-4 tw-py-3"},zd.createElement("div",{className:"tw-flex tw-items-center tw-gap-3"},zd.createElement(U6,{size:"sm",variant:"ghost",value:u,onChange:d,models:f??k.activeModels,apiKeySettings:f?void 0:k,disabled:P}),I&&zd.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},zd.createElement(Wl,{id:"menuCommandIncludeContext",checked:S,onCheckedChange:V=>I(!!V),className:"tw-size-3.5",disabled:P}),zd.createElement("label",{htmlFor:"menuCommandIncludeContext",className:"tw-cursor-pointer tw-text-xs tw-text-muted"},"Note"),zd.createElement(rs,{content:"Include the active note's content as context",side:"top"}))),zd.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},_&&T==="idle"&&zd.createElement(oe,{variant:"default",size:"sm",onClick:c,disabled:!a.trim()||P,title:"Send message"},zd.createElement(zC,{className:"tw-mr-1 tw-size-4"}),"Send"),zd.createElement(CCn,{state:T,onStop:p,onCopy:m,onInsert:h,onReplace:g})))))}ko();pe();var foe=require("@codemirror/state"),yF=require("@codemirror/view");function mTe(t){let e=foe.StateEffect.define(),n=yF.Decoration.mark({class:t});function r(f,p,m){let h=Math.max(0,Math.min(p,f)),g=Math.max(0,Math.min(m,f));return h===g?null:{from:Math.min(h,g),to:Math.max(h,g)}}let o=foe.StateField.define({create:()=>null,update(f,p){let m=f;if(m&&!p.changes.empty){let h=p.changes.mapPos(m.from,1),g=p.changes.mapPos(m.to,-1);m=r(p.state.doc.length,h,g)}for(let h of p.effects)h.is(e)&&(m=h.value?r(p.state.doc.length,h.value.from,h.value.to):null);return m},provide:f=>yF.EditorView.decorations.from(f,p=>p?yF.Decoration.set([n.range(p.from,p.to)]):yF.Decoration.none)}),i=yF.EditorView.baseTheme({[`.${t}`]:{backgroundColor:"var(--text-selection)",borderRadius:"2px"}}),s=[o,i];function a(f){return f.state.field(o,!1)!==void 0}function l(f,p){let m=[];if(!p)return a(f)&&m.push(e.of(null)),m;let h=r(f.state.doc.length,p.from,p.to);return h?(a(f)||m.push(foe.StateEffect.appendConfig.of(s)),m.push(e.of(h)),m):(a(f)&&m.push(e.of(null)),m)}function c(f,p,m){let h=l(f,{from:p,to:m});h.length>0&&f.dispatch({effects:h})}function u(f){let p=l(f,null);p.length>0&&f.dispatch({effects:p})}function d(f){return f.state.field(o,!1)??null}return{field:o,effect:e,extension:s,show:c,hide:u,buildEffects:l,getRange:d}}var hTe=mTe("copilot-selection-highlight");function ICn(t,e){try{t.dispatch(e)}catch(n){H("SelectionHighlight dispatch failed:",n)}}function xBr(t,e){return hTe.buildEffects(t,e)}function TCn(t,e,n){let r=hTe.buildEffects(t,{from:e,to:n});r.length>0&&ICn(t,{effects:r})}function SBr(t,e,n){TCn(t,e,n)}function CBr(t){let e=hTe.buildEffects(t,null);e.length>0&&ICn(t,{effects:e})}function kBr(t){return hTe.getRange(t)}var ph={show:TCn,update:SBr,hide:CBr,getRange:kBr,buildEffects:xBr};pe();function p5(t){switch(t){case"no_range":return"No selection range available.";case"range_out_of_bounds":return"Selection range is out of bounds.";case"content_changed":return"Selection content has changed. Please reselect and try again.";case"file_changed":return"File has changed. Please reselect in the original file.";case"editor_changed":return"Editor has changed. Please reselect and try again.";case"leaf_changed":return"Editor pane has changed. Please reselect and try again.";case"target_unavailable":return"Editor is no longer available.";default:return"Cannot replace. Please reselect and try again."}}function PCn(t,e,n){let r=t.state.toText(n);t.dispatch({changes:{from:e.from,to:e.to,insert:r},selection:{anchor:e.from,head:e.from+r.length}}),t.focus()}function ACn(t){let{editorView:e,leafSnapshot:n,filePathSnapshot:r,selectedTextSnapshot:o,initialRange:i,getLeafState:s}=t,a={...i},l=!0,c=null,u=null,d=h=>{let g=h.mapPos(a.from,1),v=h.mapPos(a.to,-1);a={from:Math.min(g,v),to:Math.max(g,v)},l=!0},f=()=>({...a}),p=()=>{let h=s(),g=!c||h.leaf!==c.leaf||h.editorView!==c.editorView||h.filePath!==c.filePath||!e.dom.isConnected;if(!l&&!g&&u)return u;l=!1,c=h;let v=(_,S)=>({ok:!1,reason:_,range:S,message:p5(_)});if(!h.leaf||h.leaf!==n)return u=v("leaf_changed",null),u;if(!h.editorView||h.editorView!==e)return u=v("editor_changed",null),u;if(h.filePath!==r)return u=v("file_changed",null),u;if(!e.dom.isConnected)return u=v("target_unavailable",null),u;let y=e.state.doc;return a.from<0||a.to>y.length||a.from>=a.to?(u=v("range_out_of_bounds",null),u):y.sliceString(a.from,a.to)!==o?(u=v("content_changed",{...a}),u):(u={ok:!0,reason:null,range:{...a}},u)};return{getRange:f,validate:p,onDocChanged:d,replace:h=>{let g=p();if(!g.ok||!g.range)return g;try{return PCn(e,g.range,h),{ok:!0,reason:null,range:g.range}}catch(v){return H("MapPosReplaceGuard replace failed:",v),{ok:!1,reason:"target_unavailable",range:null,message:p5("target_unavailable")}}}}}function ECn(t){let{editorView:e,filePathSnapshot:n,selectedTextSnapshot:r,getCurrentContext:o}=t,i=()=>{let l=ph.getRange(e);return l?{from:l.from,to:l.to}:null},s=()=>{let l=o(),c=(p,m)=>({ok:!1,reason:p,range:m,message:p5(p)});if(!l.editorView)return c("target_unavailable",null);if(l.editorView!==e)return c("editor_changed",null);if(l.filePath!==n)return c("file_changed",null);let u=i();if(!u)return c("no_range",null);let d=e.state.doc;return u.from<0||u.to>d.length||u.from>=u.to?c("range_out_of_bounds",null):d.sliceString(u.from,u.to)!==r?c("content_changed",u):{ok:!0,reason:null,range:u}};return{getRange:i,validate:s,replace:l=>{let c=s();if(!c.ok||!c.range)return c;try{return PCn(e,c.range,l),{ok:!0,reason:null,range:c.range}}catch(u){return H("HighlightReplaceGuard replace failed:",u),{ok:!1,reason:"target_unavailable",range:null,message:p5("target_unavailable")}}}}}pe();ut();mp();Se();hke();Us();var m5=L(B()),IBr=()=>{},TBr=Object.freeze([]),MCn={name:"__chat_no_models__",provider:"",displayName:"No models \u2014 enable in Basic \u2192 Agents \u2192 Quick Chat",enabled:!0,_disabledReason:"Add a model"},PBr=Jn(MCn);function h5(t){let{value:e,onChange:n}=t,r=Ar(ZN("chat"),{store:on}),o=xt(),i=m5.default.useMemo(()=>f3(o.providers)?mke():TBr,[o.providers]),{models:s,byModelKey:a,idToModelKey:l}=m5.default.useMemo(()=>{let f=[],p=new Map,m=new Map;for(let h of r){if(h.state!=="ok")continue;let{configuredModel:g,provider:v,configuredModelId:y}=h,w=Uw(g.info),_=Fw(v)&&!v.apiKeyKeychainId,S={name:y,provider:NU(v),displayName:g.info.displayName||g.info.id,enabled:!0,capabilities:w,_disabledReason:_?"Add API key":void 0,_needsSelfHostWarning:h.needsSelfHostWarning},I=Jn(S);f.push(S),p.set(I,y),m.set(y,I)}return{models:f,byModelKey:p,idToModelKey:m}},[r]),c=m5.default.useMemo(()=>{let f=Q9(r,e),p=f?l.get(f):void 0;if(p)return p;let m=s[0];return m?Jn(m):""},[r,e,l,s]),u=m5.default.useMemo(()=>{if(!s.some(m=>m._needsSelfHostWarning))return s;let f=[],p=[];for(let m of s)(m._needsSelfHostWarning?p:f).push(m);return[...f,...p]},[s]),d=m5.default.useCallback(f=>{let p=a.get(f);p&&n(p)},[a,n]);return u.length===0?{models:[...i,MCn],value:PBr,onChange:IBr}:{models:i.length>0?[...i,...u]:u,value:c,onChange:d}}var OCn=L(B());Us();mp();cP();Se();function gTe(t,e){let n=Ar(ZN("chat"),{store:on});return(0,OCn.useMemo)(()=>{let r=RU(n,e);if(!r)return null;let o=r.provider.apiKeyKeychainId?Ha.getInstance(t).getSecretById(r.provider.apiKeyKeychainId):null;return X9({provider:r.provider,configuredModel:r.configuredModel,apiKey:o})},[n,e,t])}Wtt();function yTe(t,e){let n=t.from,r=t.to,o=t.head;return!t.empty&&r>0&&e.lineAt(r).from===r&&(r=r-1),!t.empty&&o>0&&o===t.to&&e.lineAt(o).from===o&&(o=o-1),{bottomPos:r,topPos:n,focusPos:o}}Re();var rd=require("obsidian"),li=L(B());$Se();Pa();Se();var Ni=L(B());LA();a5();jq();function Vat(){return new Dat({returnMessages:!0,memoryKey:"history"})}async function NCn(t,e,n){let r=await nw.getInstance().createModelInstanceFromBridged(t),i=A_.fromMessages([pF.fromTemplate(e||"You are a helpful assistant. You'll help the user with their content editing needs."),new Z0("history"),Y0.fromTemplate("{input}")]);return r1.from([{input:s=>s.input,memory:()=>n.loadMemoryVariables({})},{input:s=>s.input,history:s=>s.memory.history},i,r])}gt();pe();var X0=L(B());function RCn(t){let e=(0,X0.useRef)(t),n=(0,X0.useRef)(null),r=(0,X0.useRef)(null);return(0,X0.useEffect)(()=>{e.current=t},[t]),(0,X0.useEffect)(()=>()=>{n.current!==null&&(cancelAnimationFrame(n.current),n.current=null)},[]),(0,X0.useCallback)((...o)=>{r.current=o,n.current===null&&(n.current=window.requestAnimationFrame(()=>{n.current=null;let i=r.current;i&&e.current(...i)}))},[])}function ABr(t){if(!t.aborted)return!1;let e=t.reason;if(typeof e!="string")return!0;let n=e;return n==="new-chat"||n==="component-unmount"}function vTe(t){let{model:e,systemPrompt:n,excludeThinking:r=!0,onNoModel:o,onNonAbortError:i}=t,[s,a]=(0,Ni.useState)(!1),[l,c]=(0,Ni.useState)(""),u=(0,Ni.useRef)(!0),d=(0,Ni.useRef)(!1),f=(0,Ni.useRef)(null),p=(0,Ni.useRef)(""),m=(0,Ni.useRef)(!1),h=(0,Ni.useRef)(0),g=(0,Ni.useRef)(o),v=(0,Ni.useRef)(i);(0,Ni.useEffect)(()=>{g.current=o,v.current=i},[o,i]);let y=(0,Ni.useRef)(null),w=(0,Ni.useRef)(null),_=(0,Ni.useRef)(null),S=(0,Ni.useRef)(null),I=(0,Ni.useMemo)(()=>e?.configuredModelId??null,[e]),C=RCn(K=>{u.current&&c(K)}),k=(0,Ni.useCallback)(K=>{u.current&&(p.current=K,C(K))},[C]),T=(0,Ni.useCallback)(async K=>{if(!e||!I)return g.current?.(),null;if(!w.current||_.current!==I||S.current!==n){y.current||(y.current=Vat());let le=await NCn(e,n,y.current);if(K.aborted)return null;w.current=le,_.current=I,S.current=n}return!w.current||!y.current?null:{chain:w.current,memory:y.current}},[e,I,n]);(0,Ni.useEffect)(()=>(u.current=!0,()=>{u.current=!1,f.current?.abort("component-unmount"),f.current=null}),[]),(0,Ni.useEffect)(()=>{d.current&&f.current?.abort("new-chat"),w.current=null,_.current=null,S.current=null},[I,n]);let P=(0,Ni.useCallback)(()=>!m.current,[]),E=(0,Ni.useCallback)(()=>y.current,[]),O=(0,Ni.useCallback)(()=>p.current,[]),$=(0,Ni.useCallback)((K="user-stopped")=>{f.current?.abort(K)},[]),U=(0,Ni.useCallback)(()=>{f.current?.abort("new-chat"),f.current=null,w.current=null,_.current=null,S.current=null,y.current=Vat(),m.current=!1,h.current+=1,p.current="",d.current=!1,u.current&&(c(""),C(""),a(!1))},[C]),V=(0,Ni.useCallback)(async K=>{if(d.current)return null;d.current=!0,u.current&&a(!0);let se=++h.current,le=new AbortController;f.current=le,p.current="",u.current&&(c(""),C(""));let Q=z=>{h.current===se&&k(z)},ne=new Ug(Q,r),ee=!1,ae=null,q="",F=null;try{let z=!m.current;if(!e)return g.current?.(),null;if(q=await K({signal:le.signal,isFirstTurn:z}),le.signal.aborted||!q.trim())return null;let N=await T(le.signal);if(!N)return null;ae=N.memory;let X=await N.chain.withConfig({signal:le.signal}).stream({input:q});for await(let D of X)if(ne.processChunk(D),le.signal.aborted)break}catch(z){z instanceof Error&&z.name==="AbortError"||le.signal.aborted||(ee=!0,v.current?.(z))}finally{let z=ne.close().content.trim(),N=ABr(le.signal),R=h.current!==se;if(!ee&&z&&!N&&!R&&(F=z,ae))try{let X=d5(z);await ae.saveContext({input:q},{output:typeof X=="string"?X:z}),m.current=!0}catch(X){H("Error saving chat context:",X)}R||(p.current="",d.current=!1),f.current===le&&(f.current=null),u.current&&!R&&(c(""),C(""),a(!1))}return F},[r,T,k,e,C]);return{isStreaming:s,streamingText:l,getIsFirstTurn:P,runTurn:V,stop:$,reset:U,getMemory:E,getLatestStreamingText:O}}gt();Hl();function EBr(t,e){return{...{autoExecuteOnOpen:!0,hideContentAreaOnIdle:!1,commandLabel:t.title,commandIcon:li.default.createElement(Qf,{className:"tw-size-4 tw-text-muted"})},...e}}function MBr({originalText:t,command:e,onInsert:n,onReplace:r,onClose:o,systemPrompt:i,initialPosition:s,anchorBottom:a,behaviorConfig:l}){let c=vn(),u=(0,li.useMemo)(()=>EBr(e,l),[e,l]),d=(0,li.useRef)(!1),f=(0,li.useRef)(!0);(0,li.useEffect)(()=>(f.current=!0,()=>{f.current=!1}),[]);let p=(0,li.useRef)(null);if(!p.current){let de=new rd.Component;de.load(),p.current=de}(0,li.useEffect)(()=>()=>{p.current?.unload(),p.current=null},[]);let m=(0,li.useRef)(c.workspace.getActiveFile()?.path??""),h=(0,li.useCallback)(async(de,ye)=>{let Te=p.current;if(!Te)return;let Be=UV(de);await rd.MarkdownRenderer.renderMarkdown(Be,ye,m.current,Te)},[]),[g,v]=(0,li.useState)(""),[y,w]=(0,li.useState)(""),[_,S]=(0,li.useState)(u.autoExecuteOnOpen),[I,C]=(0,li.useState)(""),[k]=CT(),T=xt(),P=u.modelSelectionScope??"custom-command",E=(0,li.useMemo)(()=>P==="quick-command"?T.quickCommandModelKey??k:e.modelKey||k,[P,T.quickCommandModelKey,e.modelKey,k]),[O,$]=(0,li.useState)(E),U=(0,li.useCallback)(de=>{$(de),P==="quick-command"&&At("quickCommandModelKey",de)},[P]),[V,K]=(0,li.useState)(()=>T.quickCommandIncludeNoteContext),se=(0,li.useCallback)(de=>{K(de),At("quickCommandIncludeNoteContext",de)},[]),le=gTe(c,O),Q=h5({value:O,onChange:U}),{isStreaming:ne,streamingText:ee,runTurn:ae,stop:q,getLatestStreamingText:F}=vTe({model:le,systemPrompt:i||"",excludeThinking:!0,onNoModel:()=>{new rd.Notice("No active model is configured. Please configure a model in Copilot settings."),S(!1)},onNonAbortError:de=>{H("Error generating response:",de),new rd.Notice("Error generating response. Please try again."),S(!1)}}),z=(0,li.useRef)(""),[N,R]=(0,li.useState)(g);N!==g&&(R(g),g&&w(g));let X=(0,li.useMemo)(()=>_&&!ne&&!ee&&!g?{type:"loading"}:ne||ee?{type:"result",text:ee||g,isStreaming:ne}:g?{type:"result",text:g,isStreaming:!1}:{type:"idle"},[_,ne,ee,g]),D=(0,li.useRef)(!1);(0,li.useEffect)(()=>{if(!u.autoExecuteOnOpen||D.current)return;D.current=!0;let de=!1;async function ye(){try{let Te=await ae(async Be=>{if(Be.signal.aborted)return"";let qe=await ate(c,e.content,t);return z.current=qe,qe});!de&&Te&&(v(Te),z.current="")}catch(Te){H("Error in initial response:",Te)}finally{de||S(!1)}}return ye(),()=>{de=!0,q("component-unmount")}},[c,u.autoExecuteOnOpen,e.content,t,ae,q]);let G=async()=>{if(!I.trim()||d.current||_||ne)return;d.current=!0;let de=I;C(""),v(""),w("");try{S(!0);let ye=await ae(async Te=>{if(Te.signal.aborted)return"";let Be=Te.isFirstTurn,qe=de;Be&&u.firstSubmitTransform&&(qe=u.firstSubmitTransform(qe,V));let Ae=await ate(c,qe,t,!Be);return z.current=Ae,Ae});if(!f.current)return;ye&&(v(ye),z.current="")}catch(ye){ye instanceof Error&&ye.name==="AbortError"||(H("Error in follow-up submit:",ye),f.current&&new rd.Notice("Failed to send message. Please try again."))}finally{f.current&&S(!1),d.current=!1}},ce=(0,li.useCallback)(()=>{let de=F().trim();q("user-stopped"),de&&v(de),z.current=""},[q,F]),Z=(0,li.useCallback)(async()=>{let de=y||g||ee;if(!de)return;let ye=_h(de);try{await navigator.clipboard.writeText(ye),new rd.Notice("Copied to clipboard")}catch{new rd.Notice("Failed to copy to clipboard")}},[y,g,ee]),te=()=>{let de=y||g||ee;de&&n(de)},fe=()=>{let de=y||g||ee;de&&r(de)};return li.default.createElement(Wat,{open:!0,onClose:o,commandIcon:u.commandIcon,commandLabel:u.commandLabel,contentState:X,editableContent:y,onEditableContentChange:w,followUpValue:I,onFollowUpChange:C,onFollowUpSubmit:xn(G),selectedModel:Q.value,onSelectModel:Q.onChange,models:Q.models,onStop:ce,onCopy:xn(Z),onInsert:te,onReplace:fe,initialPosition:s,anchorBottom:a,resizable:!0,hideContentAreaOnIdle:u.hideContentAreaOnIdle,includeNoteContext:u.showIncludeNoteContext?V:void 0,onIncludeNoteContextChange:u.showIncludeNoteContext?se:void 0,renderMarkdown:h})}var TO=class{constructor(e,n){this.app=e;this.configs=n;this.root=null;this.container=null;this.highlightView=null;this.replaceGuard=null;this.scope=null}resolveWindow(e){return e?.containerEl?.win??window}resolveDocument(e){return e?.containerEl?.doc??activeDocument}getInitialPosition(e){let n=this.resolveWindow(e),r=Math.min(500,n.innerWidth*.9),i=this.configs.behaviorConfig?.hideContentAreaOnIdle??!1?180:400,s=12,a=6,l={x:Math.max(s,(n.innerWidth-r)/2),y:Math.max(s,(n.innerHeight-i)/2)};if(!e?.editor?.cm)return l;let c=e.editor.cm,u=c.state.selection.main,d=u.empty,f=yTe(u,c.state.doc),p=c.coordsAtPos(f.focusPos),m=c.coordsAtPos(f.bottomPos),h=c.coordsAtPos(f.topPos);if(!p&&!m&&!h)return l;let g=c.scrollDOM.getBoundingClientRect(),v=E=>E.bottom>=g.top&&E.top<=g.bottom&&E.right>=g.left&&E.left<=g.right,y=p&&v(p)?p:null,w=m&&v(m)?m:null,_=h&&v(h)?h:null;if(!y&&!w&&!_)return l;let S=Math.min((h?.bottom??0)-(h?.top??0),(m?.bottom??0)-(m?.top??0)),I=!d&&h&&m&&Math.abs(h.top-m.top)>Math.max(S/2,2),{top:C,anchorBottomY:k}=xCe({scrollRect:g,visibleBottom:w,visibleTop:_,panelHeight:i,margin:s,gap:a,viewportHeight:n.innerHeight}),T=C,P;if(d)P=(y??w??_).left;else if(I)P=(g.left+g.right)/2-r/2;else{let E=c.coordsAtPos(f.topPos),O=c.coordsAtPos(f.bottomPos);E&&O?P=(E.left+O.right)/2-r/2:P=(g.left+g.right)/2-r/2}return P=Math.max(g.left,Math.min(P,g.right-r)),P=Math.max(s,Math.min(P,n.innerWidth-s-r)),{x:P,y:T,anchorBottom:k}}open(){this.scope=new rd.Scope,this.scope.register(["Mod"],"Enter",()=>!0),this.scope.register(["Mod","Shift"],"Enter",()=>!0),this.app.keymap.pushScope(this.scope);let e=this.app.workspace.getActiveViewOfType(rd.MarkdownView),n=this.resolveDocument(e);this.container=n.body.createDiv("copilot-menu-command-modal-container"),this.root=Er(this.container,this.app);let{selectedText:r,command:o,systemPrompt:i,behaviorConfig:s}=this.configs,a=r;if(e?.editor?.cm){let p=e.editor.cm,m=p.state.selection.main,h=e.file?.path??null;a=p.state.doc.sliceString(m.from,m.to),ph.show(p,m.from,m.to),this.highlightView=p,this.replaceGuard=ECn({editorView:p,filePathSnapshot:h,selectedTextSnapshot:a,getCurrentContext:()=>{let g=this.app.workspace.getActiveViewOfType(rd.MarkdownView);return{editorView:g?.editor?.cm??null,filePath:g?.file?.path??null}}})}let{anchorBottom:l,...c}=this.getInitialPosition(e),u=p=>{zK(this.app,p),this.close()},d=p=>{if(!this.replaceGuard){new rd.Notice("No selection to replace.");return}let m=_h(p),h=this.replaceGuard.replace(m);if(!h.ok){new rd.Notice(h.message??"Cannot replace.");return}new rd.Notice("Message replaced in the active note."),this.close()},f=()=>{this.close()};this.root.render(li.default.createElement(MBr,{originalText:a,command:o,onInsert:u,onReplace:d,onClose:f,systemPrompt:i,initialPosition:c,anchorBottom:l,behaviorConfig:s}))}close(){this.scope&&(this.app.keymap.popScope(this.scope),this.scope=null),this.highlightView&&(ph.hide(this.highlightView),this.highlightView=null),this.replaceGuard=null,this.root?.unmount(),this.root=null,this.container?.remove(),this.container=null}};fm();var bTe=require("obsidian");c_();Og();x0();var wTe=class extends bTe.FuzzySuggestModal{constructor(e){super(e),this.setPlaceholder("Select a custom command to apply...");let n=Bf();this.commands=uSe(n)}onOpen(){super.onOpen(),this.commands.length===0&&this.setInstructions([{command:"",purpose:"No custom commands found. Create some custom commands first in the settings."}])}getItems(){return this.commands}getItemText(e){return e.title}onChooseItem(e,n){let r=this.app.workspace.getActiveViewOfType(bTe.MarkdownView);if(!r||!r.editor){this.openCommandModal(e,"");return}let o=r.editor.getSelection();this.openCommandModal(e,o)}openCommandModal(e,n){Fa.getInstance().recordUsage(e),new TO(this.app,{selectedText:n,command:e}).open()}};_v();yt();hl();ko();pe();ut();Pa();var g5=require("obsidian"),xs=L(B());function OBr({onClose:t}){let e=vn(),[n,r]=xs.useState("input"),[o,i]=xs.useState(""),[s,a]=xs.useState(!1),[l,c]=xs.useState(""),[u,d]=xs.useState(!1),[f,p]=xs.useState(null),m=(S,I=!0)=>{if(!S.trim())return I&&(c(""),d(!1)),{isValid:!1};let C=NEe(S);return C.isValid?(I&&(c(""),d(!0)),{isValid:!0,videoId:C.videoId}):(I&&(c(C.error||"Invalid URL"),d(!1)),{isValid:!1})},h=S=>{i(S),m(S,!0)},g=async()=>{if(s)return;let S=m(o);if(S.isValid){a(!0),c("");try{let I=await Gi.getInstance().youtube4llm(o);if(!I.response.transcript)throw new Error("Transcript not available. Only English videos with auto transcript enabled are supported.");let C={videoId:S.videoId,transcript:I.response.transcript,url:qdt(S.videoId)};p(C),r("display")}catch(I){H("Error downloading YouTube transcript:",I);let C=I instanceof Error?I.message:"An error occurred while downloading the transcript";c(C)}finally{a(!1)}}},v=async()=>{if(f)try{let S=`# YouTube Video Transcript
Source: ${f.url}
${f.transcript}`;await navigator.clipboard.writeText(S),new g5.Notice("Transcript copied to clipboard!")}catch(S){H("Failed to copy to clipboard:",S),new g5.Notice("Failed to copy to clipboard")}},y=async()=>{if(f)try{let S=`# YouTube Video Transcript
Source: ${f.url}
${f.transcript}`;await zK(e,S,!1),t()}catch(S){H("Failed to insert to note:",S),new g5.Notice("Failed to insert to note")}},w=()=>{r("input"),i(""),c(""),p(null)},_=S=>{S.key==="Enter"&&!s&&u&&g()};return n==="display"&&f?xs.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},xs.createElement("div",{className:"tw-rounded tw-bg-secondary tw-p-3"},xs.createElement("a",{href:f.url,className:"tw-text-sm tw-text-muted hover:tw-text-normal",target:"_blank",rel:"noopener noreferrer"},f.url)),xs.createElement("div",{className:"tw-max-h-96 tw-overflow-y-auto tw-rounded tw-border tw-border-border tw-bg-primary tw-p-4"},xs.createElement("div",{className:"tw-whitespace-pre-wrap tw-text-sm tw-leading-relaxed"},f.transcript)),xs.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},xs.createElement(oe,{variant:"ghost",onClick:w},"Download Another"),xs.createElement(oe,{variant:"default",onClick:()=>void v()},"Copy to Clipboard"),xs.createElement(oe,{variant:"default",onClick:()=>void y()},"Insert at Cursor"),xs.createElement(oe,{variant:"secondary",onClick:t},"Close"))):xs.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},xs.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},xs.createElement("div",{className:"tw-text-sm tw-text-muted"},"Enter a valid YouTube video URL"),xs.createElement(Ir,{placeholder:"https://www.youtube.com/watch?v=...",value:o,onChange:S=>h(S.target.value),onKeyDown:_,disabled:s}),l&&xs.createElement("div",{className:"tw-text-sm tw-text-error"},l)),xs.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},xs.createElement(oe,{variant:"secondary",onClick:t,disabled:s},"Cancel"),xs.createElement(oe,{variant:"default",onClick:()=>void g(),disabled:s||!u},s?"Downloading...":"Download Transcript")))}var _Te=class extends g5.Modal{constructor(e){super(e),this.setTitle("Download YouTube Script (plus)")}onOpen(){let{contentEl:e}=this;this.root=Er(e,this.app);let n=()=>{this.close()};this.root.render(xs.createElement(OBr,{onClose:n}))}onClose(){this.root.unmount()}};vc();zu();ha();ut();Is();$n();var Gn=require("obsidian");Gf();gt();es();function dl(t,e,n){t.addCommand({id:e,name:jO[e],icon:BO[e],callback:()=>{let r=n();r instanceof Promise&&r.catch(o=>H(`Command ${e} failed`,o))}})}function LCn(t,e,n){t.addCommand({id:e,name:jO[e],icon:BO[e],editorCallback:r=>{let o=n(r);o instanceof Promise&&o.catch(i=>H(`Editor command ${e} failed`,i))}})}function qat(t,e,n){t.addCommand({id:e,name:jO[e],icon:BO[e],checkCallback:n})}function $Cn(t,e){qat(t,ht.PUBLISH_FILE_TO_SYMPOSIUM,n=>{let r=t.app.workspace.getActiveFile();return!(r instanceof Gn.TFile)||r.extension!=="md"?!1:(n||e(r),!0)}),LCn(t,ht.COUNT_WORD_AND_TOKENS_SELECTION,async n=>{let r=n.getSelection(),o=r.split(" ").length,i=await t.chainOwner.getCurrentChainManager().chatModelManager.countTokens(r);new Gn.Notice(`Selected text contains ${o} words and ${i} tokens.`)}),dl(t,ht.COUNT_TOTAL_VAULT_TOKENS,async()=>{try{let n=await T9e(t.app),r=await t.chainOwner.getCurrentChainManager().chatModelManager.countTokens(n);new Gn.Notice(`Total tokens in your vault: ${r}`)}catch(n){H("Error counting tokens: ",n),new Gn.Notice("An error occurred while counting tokens.")}}),dl(t,ht.TOGGLE_COPILOT_CHAT_WINDOW,()=>{t.toggleView()}),dl(t,ht.OPEN_COPILOT_CHAT_WINDOW,async()=>{await t.activateView()}),dl(t,ht.OPEN_RELEVANT_NOTES_VIEW,async()=>{await t.activateRelevantNotesView()}),dl(t,ht.NEW_CHAT,async()=>{w3(),await t.newChat()}),Ln()&&(dl(t,ht.OPEN_AGENT_CHAT_WINDOW,()=>{t.activateAgentView()}),dl(t,ht.TOGGLE_AGENT_CHAT_WINDOW,()=>{t.toggleAgentView()}),dl(t,ht.NEW_AGENT_CHAT,()=>{t.newAgentChat()})),qat(t,ht.TRIGGER_QUICK_COMMAND,n=>{let r=t.app.workspace.getActiveViewOfType(Gn.MarkdownView);if(n)return!!(!qK(t.app)&&r&&r.editor);if(qK(t.app))return new Gn.Notice("Quick command is not available in source mode."),!1;if(!r||!r.editor)return new Gn.Notice("No active editor found."),!1;let i=r.editor.getSelection();if(!i.trim())return new Gn.Notice("Please select some text first. Selected text is required for quick commands."),!1;let s={title:"Quick Command",content:"",showInContextMenu:!1,showInSlashMenu:!1,order:0,modelKey:"",lastUsedMs:Date.now()};return new TO(t.app,{selectedText:i,command:s,systemPrompt:cTe,behaviorConfig:{autoExecuteOnOpen:!1,hideContentAreaOnIdle:!0,commandLabel:"Quick Command",commandIcon:null,showIncludeNoteContext:!0,modelSelectionScope:"quick-command",firstSubmitTransform:(l,c)=>uTe(l,c)}}).open(),!0}),dl(t,ht.CLEAR_LOCAL_COPILOT_INDEX,async()=>{let{getSettings:n}=await Promise.resolve().then(()=>(Se(),SC)),r=n();if(Bu(r)==="miyo"){new Gn.Notice("Miyo folders are managed in Miyo. Remove the folder there if you want to clear it.");return}let i=`This will permanently delete all document indexes in Copilot. This action cannot be undone.
Are you sure you want to proceed?`;if(await new Promise(a=>{new _i(t.app,()=>a(!0),i,"Clear Semantic Index","Clear Index","Cancel",()=>a(!1)).open()}))try{await(await Promise.resolve().then(()=>(El(),nd))).default.getInstance().clearIndex(),new Gn.Notice("Cleared local Copilot semantic index.")}catch(a){H("Error clearing semantic index:",a),new Gn.Notice("Failed to clear semantic index.")}}),dl(t,ht.GARBAGE_COLLECT_COPILOT_INDEX,async()=>{try{let{getSettings:n}=await Promise.resolve().then(()=>(Se(),SC));if(Bu(n())==="miyo"){new Gn.Notice("Miyo manages file cleanup automatically. Run Index (refresh) vault to trigger a scan if needed.");return}let o=await(await Promise.resolve().then(()=>(El(),nd))).default.getInstance().garbageCollectVectorStore();new Gn.Notice(`Garbage collection completed. Removed ${o} stale documents.`)}catch(n){H("Error during garbage collection:",n),new Gn.Notice("Failed to garbage collect semantic index.")}}),dl(t,ht.INDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let{getSettings:n}=await Promise.resolve().then(()=>(Se(),SC)),r=n();if(r.enableSemanticSearchV3){let i=await(await Promise.resolve().then(()=>(El(),nd))).default.getInstance().indexVaultToVectorStore(!1,{userInitiated:!0});Bu(r)==="miyo"?new Gn.Notice("Miyo folder index refresh started. Open the Miyo app to check details."):new Gn.Notice(`Semantic search index refreshed with ${i} documents.`)}else new Gn.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(n){H("Error building index:",n),new Gn.Notice("An error occurred while building the index.")}}),dl(t,ht.FORCE_REINDEX_VAULT_TO_COPILOT_INDEX,async()=>{if(await new Promise(r=>{new _i(t.app,()=>r(!0),"This will delete and rebuild your entire vault index from scratch. This operation cannot be undone. Are you sure you want to proceed?","Force Reindex Vault","Continue","Cancel",()=>r(!1)).open()}))try{let{getSettings:r}=await Promise.resolve().then(()=>(Se(),SC)),o=r();if(o.enableSemanticSearchV3){let s=await(await Promise.resolve().then(()=>(El(),nd))).default.getInstance().indexVaultToVectorStore(!0,{userInitiated:!0});Bu(o)==="miyo"?new Gn.Notice("Miyo folder index refresh started. Open the Miyo app to check details."):new Gn.Notice(`Semantic search index rebuilt with ${s} documents.`)}else new Gn.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(r){H("Error rebuilding index:",r),new Gn.Notice("An error occurred while rebuilding the index.")}}),dl(t,ht.LOAD_COPILOT_CHAT_CONVERSATION,async()=>{await t.loadCopilotChatHistory()}),dl(t,ht.LIST_INDEXED_FILES,async()=>{try{let r=await(await Promise.resolve().then(()=>(El(),nd))).default.getInstance().getIndexedFiles(),{getMatchingPatterns:o,shouldIndexFile:i}=await Promise.resolve().then(()=>(ha(),bKt)),{inclusions:s,exclusions:a}=o(),l=t.app.vault.getMarkdownFiles(),c=new Set,u=new Set,d=new Set,f=new Set(r);for(let w of l){if(!i(t.app,w,s,a)){d.add(w.path);continue}let _=await t.app.vault.cachedRead(w);!_||_.trim().length===0?c.add(w.path):f.has(w.path)||u.add(w.path)}let p=["# Copilot Files Status",`- Indexed files: ${f.size}`,`- Unindexed files: ${u.size}`,`- Empty files: ${c.size}`,`- Excluded files: ${d.size}`,"","## Indexed Files",...f.size>0?Array.from(f).sort().map(w=>`- [[${w}]]`):["No indexed files found."],"","## Unindexed Files",...u.size>0?Array.from(u).sort().map(w=>`- [[${w}]]`):["No unindexed files found."],"","## Empty Files",...c.size>0?Array.from(c).sort().map(w=>`- [[${w}]]`):["No empty files found."],"","## Excluded Files (based on settings)",...d.size>0?Array.from(d).sort().map(w=>`- [[${w}]]`):["No excluded files."]].join(`
`),m=`Copilot-Indexed-Files-${new Date().toLocaleDateString().replace(/\//g,"-")}.md`,h=GK(),g=`${h}/${m}`;await ao(t.app.vault,h);let v=t.app.vault.getAbstractFileByPath(g);v instanceof Gn.TFile?await t.app.vault.modify(v,p):await t.app.vault.create(g,p);let y=t.app.vault.getAbstractFileByPath(g);y instanceof Gn.TFile&&(await t.app.workspace.getLeaf().openFile(y),new Gn.Notice(`Listed ${f.size} indexed files`))}catch(n){H("Error listing indexed files:",n),new Gn.Notice("Failed to list indexed files.")}}),dl(t,ht.INSPECT_COPILOT_INDEX_BY_NOTE_PATHS,async()=>{try{let n=t.app.workspace.getActiveFile();if(!n){new Gn.Notice("No active file. Please open a note first.");return}let r=(await Promise.resolve().then(()=>(El(),nd))).default,{DBOperations:o}=await Promise.resolve().then(()=>(nke(),Lmn)),i=await r.getInstance().getDb(),s=await o.getDocsByPath(i,n.path);if(!s||s.length===0){new Gn.Notice(`No embedding data found for: ${n.path}`);return}let a=s.map(m=>m.document),l=[`# Embedding Debug: ${n.basename}`,"",`**Path:** ${n.path}`,`**Chunks:** ${a.length}`,`**Embedding Model:** ${a[0]?.embeddingModel||"unknown"}`,"",...a.flatMap((m,h)=>{let g=m.embedding||[],v=g.slice(0,10).map(y=>y.toFixed(6)).join(", ");return[`## Chunk ${h+1}`,`- **ID:** ${m.id}`,`- **Content Preview:** "${(m.content||"").substring(0,200)}..."`,`- **Vector Length:** ${g.length}`,`- **Vector Preview:** [${v}${g.length>10?", ...":""}]`,`- **Tags:** ${(m.tags||[]).join(", ")||"none"}`,`- **Characters:** ${m.nchars||0}`,""]})].join(`
`),c=`Copilot-Embedding-Debug-${n.basename.replace(/[\\/:*?"<>|]/g,"_")}.md`,u=GK(),d=`${u}/${c}`;await ao(t.app.vault,u);let f=t.app.vault.getAbstractFileByPath(d);f instanceof Gn.TFile?await t.app.vault.modify(f,l):await t.app.vault.create(d,l);let p=t.app.vault.getAbstractFileByPath(d);p instanceof Gn.TFile&&(await t.app.workspace.getLeaf().openFile(p),new Gn.Notice(`Embedding debug info for ${a.length} chunk(s)`))}catch(n){H("Error inspecting embeddings:",n),new Gn.Notice("Failed to inspect embeddings. Is the index loaded?")}}),dl(t,ht.CLEAR_COPILOT_CACHE,async()=>{try{if(await t.fileParserManager.clearPDFCache(t.app.vault),await sTe.getInstance().clear(t.app.vault),Ln()){let{cacheRoot:r}=await Promise.resolve().then(()=>(_$(),Bwe)),{createNodeContextCacheFs:o}=await Promise.resolve().then(()=>(n6(),Qwe));await o(r(t.app)).clear()}new Gn.Notice("All Copilot caches cleared successfully")}catch(n){H("Error clearing Copilot caches:",n),new Gn.Notice("Failed to clear Copilot caches")}}),dl(t,ht.OPEN_LOG_FILE,async()=>{try{await $ke(),await $l.openLogFile()}catch(n){H("Error creating Copilot log file:",n),new Gn.Notice("Failed to create Copilot log file.")}}),dl(t,ht.CLEAR_LOG_FILE,async()=>{try{await $l.clear(),new Gn.Notice("Copilot log cleared.")}catch(n){H("Error clearing Copilot log file:",n),new Gn.Notice("Failed to clear Copilot log file.")}}),LCn(t,ht.ADD_SELECTION_TO_CHAT_CONTEXT,async n=>{let r=n.getSelection();if(!r){new Gn.Notice("No text selected");return}let o=t.app.workspace.getActiveFile();if(!o){new Gn.Notice("No active file");return}let i=n.listSelections()[0];if(!i){new Gn.Notice("Could not determine selection range");return}let s=i.anchor.line+1,a=i.head.line+1,l={id:Co(),content:r,sourceType:"note",noteTitle:o.basename,notePath:o.path,startLine:Math.min(s,a),endLine:Math.max(s,a)};z_([l]),await t.activateChatViewForContext()}),dl(t,ht.ADD_WEB_SELECTION_TO_CHAT_CONTEXT,async()=>{if(!Ln()){new Gn.Notice("Web selection is only available on desktop");return}let{getWebViewerService:n}=await Promise.resolve().then(()=>(T$(),FXt));try{let r=n(t.app),o=r.getActiveLeaf()??r.getLastActiveLeaf();if(!o){new Gn.Notice("No active Web Tab found");return}let i=await r.getSelectedMarkdown(o);if(!i.trim()){new Gn.Notice("No text selected in Web Tab");return}let s=r.getPageInfo(o),a={id:Co(),content:i,sourceType:"web",title:s.title||"Untitled",url:s.url,faviconUrl:s.faviconUrl||void 0};z_([a]),await t.activateChatViewForContext()}catch(r){H("Error adding web selection to context:",r),new Gn.Notice("Failed to get web selection")}}),dl(t,ht.ADD_CUSTOM_COMMAND,async()=>{let n=Bf(),r={...US};new kO(t.app,n,r,async i=>{await Fa.getInstance().createCommand(i)}).open()}),dl(t,ht.APPLY_CUSTOM_COMMAND,()=>{new wTe(t.app).open()}),dl(t,ht.DOWNLOAD_YOUTUBE_SCRIPT,async()=>{if(!await ch(t.app,{trigger:"tool_call"})){new Gn.Notice("Download YouTube Script (plus) is a Copilot Plus feature");return}new _Te(t.app).open()}),qat(t,ht.TRIGGER_QUICK_ASK,n=>{let r=t.app.workspace.getActiveViewOfType(Gn.MarkdownView);if(n)return!!(!qK(t.app)&&r&&r.editor);if(qK(t.app))return new Gn.Notice("Quick Ask is not available in source mode."),!1;if(!r||!r.editor)return new Gn.Notice("No active editor found."),!1;let o=r.editor.cm;return o?(t.quickAskController.show(r,o),!0):(new Gn.Notice("Could not access CodeMirror editor."),!1)})}es();var poe={title:"",content:"",createdMs:0,modifiedMs:0,lastUsedMs:0},y5="copilot-system-prompt-created",v5="copilot-system-prompt-modified",w5="copilot-system-prompt-last-used",Kat="copilot-system-prompt-default";var vF=require("obsidian");Is();ut();rk();pe();function xTe(t,e,n){let r=t.trim();return r?t!==r?"Prompt name cannot have leading or trailing spaces":n&&t===n?null:/[#<>:"/\\|?*[\]^\x00-\x1F]/g.test(r)?'Prompt name contains invalid characters. Avoid using: < > : " / \\ | ? * [ ] ^':e.some(i=>i.title.toLowerCase()===r.toLowerCase())?"A prompt with this name already exists":null:"Prompt name cannot be empty"}function aw(){return Wie()}function PO(t){return(0,vF.normalizePath)(`${aw()}/${t}.md`)}function moe(t,e){let n=e?(0,vF.normalizePath)(e):aw();return(0,vF.normalizePath)(`${n}/${t}.md`)}function b5(t){if(!(t instanceof vF.TFile)||t.extension!=="md")return!1;let e=aw();if(!t.path.startsWith(e+"/"))return!1;let n=t.path.slice(e.length+1);return!(n.startsWith("unsupported/")||n.includes("/"))}function Gat(t,e){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let n=Number(t);if(Number.isFinite(n))return n}return e}async function wF(t,e){let n=await t.vault.read(e),r=fy(n),i=t.metadataCache.getFileCache(e)?.frontmatter,s=Gat(i?.[y5],poe.createdMs),a=Gat(i?.[v5],poe.modifiedMs),l=Gat(i?.[w5],poe.lastUsedMs);return{title:e.basename,content:r,createdMs:s,modifiedMs:a,lastUsedMs:l}}async function Zat(t){let e=t.vault.getFiles().filter(n=>b5(n));return await Promise.all(e.map(n=>wF(t,n)))}async function _5(t){let e=await Zat(t);return Pae(e),e}async function bF(t,e,n){let r=nk(e.path),o=Date.now(),i=Number.isFinite(n.createdMs)&&n.createdMs>0?n.createdMs:o,s=Number.isFinite(n.modifiedMs)&&n.modifiedMs>0?n.modifiedMs:o,a=Number.isFinite(n.lastUsedMs)&&n.lastUsedMs>0?n.lastUsedMs:0;try{r||oP(e.path),await t.fileManager.processFrontMatter(e,l=>{l[y5]==null&&(l[y5]=i),l[v5]==null&&(l[v5]=s),l[w5]==null&&(l[w5]=a)})}finally{r||iP(e.path)}}function DCn(t,e){let r=`${t} (copy)`,o=1;for(;e.some(i=>i.title.toLowerCase()===r.toLowerCase());)o++,r=`${t} (copy ${o})`;return r}async function Yat(t,e,n,r){let o=moe(e,r),i=t.vault.getAbstractFileByPath(o);if(!(i instanceof vF.TFile)){W(`System prompt file not found for default flag update: ${o}`);return}let s=nk(i.path);try{s||oP(i.path),await t.fileManager.processFrontMatter(i,a=>{n?a[Kat]=!0:delete a[Kat]})}finally{s||iP(i.path)}}rk();var hoe=require("obsidian");rk();pe();ut();Jh();Se();var x5=class t{constructor(e){this.app=e,this.vault=e.vault}static getInstance(e){if(!t.instance){if(!e)throw new Error("App is required for first initialization");t.instance=new t(e)}return t.instance}async initialize(){j("Initializing SystemPromptManager"),await _5(this.app)}async createPrompt(e,n=!1){let r=kU(),o=xTe(e.title,r);if(o)throw new Error(o);let i=aw(),s=moe(e.title,i);try{oP(s),await ao(this.vault,i),await this.vault.create(s,e.content);let a=this.vault.getAbstractFileByPath(s);a instanceof hoe.TFile&&await bF(this.app,a,e),n||AN(e),j(`Created system prompt: ${e.title}`)}finally{iP(s)}}async updatePrompt(e,n,r=!1){let o=PO(e),i=PO(n.title),s=e!==n.title;if(s){let a=kU(),l=xTe(n.title,a,e);if(l)throw new Error(l)}try{if(oP(i),s&&oP(o),s){let l=this.vault.getAbstractFileByPath(o);l instanceof hoe.TFile&&await this.app.fileManager.renameFile(l,i)}let a=this.vault.getAbstractFileByPath(i);a instanceof hoe.TFile&&(await this.vault.modify(a,n.content),await this.app.fileManager.processFrontMatter(a,l=>{l[y5]=n.createdMs,l[v5]=n.modifiedMs,l[w5]=n.lastUsedMs})),r||(s&&(IU(e),Y().defaultSystemPromptTitle===e&&(At("defaultSystemPromptTitle",n.title),j(`Updated defaultSystemPromptTitle: ${e} -> ${n.title}`))),AN(n)),j(`Updated system prompt: ${e} -> ${n.title}`)}finally{iP(i),s&&iP(o)}}async deletePrompt(e){let n=PO(e);try{oP(n);let r=this.vault.getAbstractFileByPath(n);r instanceof hoe.TFile&&await Bc(this.app,r),Y().defaultSystemPromptTitle===e&&(At("defaultSystemPromptTitle",""),j(`Cleared defaultSystemPromptTitle (deleted: ${e})`)),PN()===e&&(rP(""),j(`Cleared session selectedPromptTitle (deleted: ${e})`)),IU(e),j(`Deleted system prompt: ${e}`)}finally{iP(n)}}async duplicatePrompt(e){let n=kU(),r=DCn(e.title,n),o=Date.now(),i={title:r,content:e.content,createdMs:o,modifiedMs:o,lastUsedMs:0};return await this.createPrompt(i),j(`Duplicated system prompt: ${e.title} -> ${r}`),i}getPrompts(){return kU()}async reloadPrompts(){return await _5(this.app)}async fetchPrompts(){return await Zat(this.app)}};var S5=require("obsidian");rk();Se();Is();AC();pe();var goe=class{constructor(e,n){this.folderChangeRequestId=0;this.handleSettingsChange=(e,n)=>{let r=xT(e),o=xT(n),i=r!==o;if(e.defaultSystemPromptTitle!==n.defaultSystemPromptTitle){let a=i?r:void 0;this.handleDefaultPromptChange(e.defaultSystemPromptTitle,n.defaultSystemPromptTitle,a)}i&&this.debouncedFolderChange(o)};this.debouncedFolderChange=Ba(e=>{this.handleSystemPromptsFolderChange(e)},300,{leading:!1,trailing:!0});this.handleFileModify=Ba(async e=>{if(!(!b5(e)||nk(e.path)))try{let n=await wF(this.app,e);AN(n)}catch(n){H(`Error processing system prompt modification: ${e.path}`,n)}},1e3,{leading:!1,trailing:!0});this.handleFileCreation=async e=>{if(!(!b5(e)||nk(e.path)))try{let n=await wF(this.app,e);await bF(this.app,e,n);let r=await wF(this.app,e);AN(r)}catch(n){H(`Error processing system prompt creation: ${e.path}`,n)}};this.handleFileDeletion=async e=>{if(!(!b5(e)||nk(e.path)))try{IU(e.basename),Y().defaultSystemPromptTitle===e.basename&&At("defaultSystemPromptTitle",""),PN()===e.basename&&(rP(""),new S5.Notice(`System prompt "${e.basename}" was deleted. Cleared current chat selection.`))}catch(n){H(`Error processing system prompt deletion: ${e.path}`,n)}};this.handleFileRename=async(e,n)=>{if(nk(e.path)||nk(n))return;let r=aw(),o=n.startsWith(r+"/")?n.slice(r.length+1):"",i=o!==""&&!o.includes("/")&&n.endsWith(".md"),s=b5(e)?e:null;if(!(!i&&!s))try{if(i){let a=n.split("/").pop()?.replace(/\.md$/i,"");if(a&&(IU(a),Y().defaultSystemPromptTitle===a&&(s?At("defaultSystemPromptTitle",s.basename):At("defaultSystemPromptTitle","")),PN()===a)){let c=s?s.basename:"";rP(c),s?new S5.Notice(`System prompt "${a}" was renamed to "${s.basename}". Updated current chat selection.`):new S5.Notice(`System prompt "${a}" was moved out of the prompts folder. Cleared current chat selection.`)}}if(s){let a=await wF(this.app,s);await bF(this.app,s,a);let l=await wF(this.app,s);AN(l)}}catch(a){H(`Error processing system prompt rename: ${e.path}`,a)}};this.plugin=e,this.app=n,this.vault=n.vault,this.manager=x5.getInstance(n),this.initializeEventListeners()}async initialize(){await this.manager.initialize(),kvt()}cleanup(){this.handleFileModify.cancel(),this.debouncedFolderChange.cancel(),this.settingsUnsubscriber?.(),this.vault.off("create",this.handleFileCreation),this.vault.off("delete",this.handleFileDeletion),this.vault.off("rename",this.handleFileRename),this.vault.off("modify",this.handleFileModify)}initializeEventListeners(){this.vault.on("create",this.handleFileCreation),this.vault.on("delete",this.handleFileDeletion),this.vault.on("rename",this.handleFileRename),this.vault.on("modify",this.handleFileModify),this.settingsUnsubscriber=zr(this.handleSettingsChange)}async handleDefaultPromptChange(e,n,r){try{e&&await Yat(this.app,e,!1,r),n&&await Yat(this.app,n,!0),j(`Default system prompt changed: "${e}" -> "${n}"`)}catch(o){H("Error updating default system prompt frontmatter",o)}}async handleSystemPromptsFolderChange(e){let n=++this.folderChangeRequestId;try{j(`System prompts folder changed to: ${e}`);let r=await this.manager.fetchPrompts();if(n!==this.folderChangeRequestId){j(`Folder change request ${n} superseded by ${this.folderChangeRequestId}, discarding results`);return}Pae(r);let o=new Set(r.map(i=>i.title));this.validatePromptReferences(o)}catch(r){n===this.folderChangeRequestId&&H(`Error reloading system prompts after folder change to: ${e}`,r)}}validatePromptReferences(e){let n=Y(),r=PN();n.defaultSystemPromptTitle&&!e.has(n.defaultSystemPromptTitle)&&(At("defaultSystemPromptTitle",""),j(`Cleared defaultSystemPromptTitle (not found in new folder): ${n.defaultSystemPromptTitle}`),new S5.Notice(`Default system prompt "${n.defaultSystemPromptTitle}" not found in new folder. Cleared default selection.`)),r&&!e.has(r)&&(rP(""),j(`Cleared selectedPromptTitle (not found in new folder): ${r}`),new S5.Notice(`Current system prompt "${r}" not found in new folder. Cleared chat selection.`))}};var FCn=L(B());yt();xI();hl();IZ();var Jat=require("obsidian");Pa();Se();Is();var NBr=L(B());pe();Hl();var BCn=require("obsidian");pe();Se();ut();var UCn="Migrated Custom System Prompt";function RBr(t,e){let n=t,r=1;for(;e.getAbstractFileByPath(PO(n));)r++,n=`${t} ${r}`;return n}function Xat(t){return t.replace(/\r\n/g,`
`).replace(/\r/g,`
`)}async function jCn(t,e,n){let r=aw(),o=`${r}/unsupported`;await ao(t,o);let i="Migrated System Prompt (Failed Verification)",s=i,a=1;for(;t.getAbstractFileByPath(`${o}/${s}.md`);)a++,s=`${i} ${a}`;let l=`${o}/${s}.md`,c=`> Migration failed: ${n}
>
> To fix: Review the content below, then move this file to ${r}
${e}`;return await t.create(l,c),l}async function LBr(t,e,n){try{let r=await t.read(e),o=fy(r,{trimStart:!1}),i=Xat(o).replace(/^\n+/,""),s=Xat(n).replace(/^\n+/,"");return i!==s?(W(`Migration verification failed: content mismatch. Expected ${s.length} chars, got ${i.length} chars`),!1):!0}catch(r){return H("Migration verification failed: unable to read back file",r),!1}}async function Qat(t){let e=t.vault,r=Y().userSystemPrompt;if(!r||r.trim().length===0)return j("No legacy userSystemPrompt to migrate"),null;try{j("Migrating legacy userSystemPrompt from settings to file system");let o=aw();await ao(e,o);let i=RBr(UCn,e),s=moe(i,o);i!==UCn&&j(`Default name already exists, using unique name: "${i}"`);let a=Date.now(),l=Xat(r),c={title:i,content:l,createdMs:a,modifiedMs:a,lastUsedMs:0};await e.create(s,l);let u=e.getAbstractFileByPath(s);if(!(u instanceof BCn.TFile))throw new Error("File not found after creation");if(await bF(t,u,c),await LBr(e,u,r)){At("defaultSystemPromptTitle",i);try{await _5(t)}catch(f){W("Failed to reload prompts after migration:",f)}return At("userSystemPrompt",""),j("Cleared legacy userSystemPrompt field"),{id:"system-prompt",title:"System prompt",status:"success",summary:`Migrated "${i}" and set it as the default system prompt.`,details:[`Stored in ${s}.`]}}else{let f=await jCn(e,r,"content verification mismatch");try{await _5(t)}catch(p){W("Failed to reload prompts after failed migration:",p)}return At("userSystemPrompt",""),j("Cleared legacy userSystemPrompt field (saved to unsupported)"),{id:"system-prompt",title:"System prompt",status:"action-required",summary:"The prompt was preserved, but its migrated content could not be verified.",details:[`Review ${f}, then move it to ${o} to make the prompt available.`]}}}catch(o){let i=o instanceof Error?o.message:String(o);H("Failed to migrate legacy userSystemPrompt:",o);try{let s=await jCn(e,r,i);return At("userSystemPrompt",""),j("Cleared legacy userSystemPrompt field (saved to unsupported after error)"),{id:"system-prompt",title:"System prompt",status:"action-required",summary:"The prompt migration failed, but the original content was preserved.",details:[`Review ${s}, then move it to ${aw()} to make the prompt available.`]}}catch(s){return H("Failed to save to unsupported folder:",s),W("Preserving userSystemPrompt in settings for manual recovery"),{id:"system-prompt",title:"System prompt",status:"error",summary:"The prompt could not be migrated. It remains in settings and will be retried.",details:[i,`Check folder permissions and available disk space for ${aw()}.`]}}}}pe();es();mw();fm();yt();xk();OP();Oc();gt();pe();zu();vc();Se();ko();cUe();Re();var Q0=require("obsidian"),dr=L(B());Zbe();rtt();var kn=L(B());ko();yt();Gb();IZ();var _F=L(B());De();Re();function zCn({options:t,placeholder:e,containerClassName:n,className:r,...o}){return _F.default.createElement("div",{className:J("tw-group tw-relative tw-w-full",n)},_F.default.createElement("select",{className:J("tw-w-full tw-appearance-none","tw-flex tw-h-9 tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-dropdown tw-px-3 tw-py-1 tw-pr-8","tw-text-left tw-text-sm tw-shadow tw-transition-colors","focus:tw-outline-none focus:tw-ring-1 focus:tw-ring-ring","disabled:tw-cursor-not-allowed disabled:tw-opacity-50","hover:tw-bg-interactive-hover hover:tw-text-normal",r),...o},e&&_F.default.createElement("option",{value:"",disabled:!0},e),t.map(i=>_F.default.createElement("option",{key:i.value,value:i.value},i.label))),_F.default.createElement("div",{className:J("tw-pointer-events-none tw-absolute tw-inset-y-0 tw-right-0 tw-flex tw-items-center tw-pr-2","tw-transition-colors group-hover:[&>svg]:tw-text-normal",o.disabled&&"tw-opacity-50")},_F.default.createElement(Bs,{className:"tw-size-4"})))}xxe();M$();Oc();Re();OP();function HCn(){let t=vn(),e=Tae(),[n,r]=xvt(),o=Aae(),i=y=>y?e.some(w=>w.title===y):!1,s=i(n)?n:i(o)?o:"",[a,l]=(0,kn.useState)(()=>EN()),[c,u]=(0,kn.useState)(!1),d=(0,kn.useRef)(null);(0,kn.useEffect)(()=>{c&&d.current&&d.current.scrollIntoView({behavior:"smooth",block:"end"})},[c]);let f=(0,kn.useCallback)(y=>{if(y){let w=EN();l(w),w||u(!1)}},[]),p=(0,kn.useCallback)(()=>{r(""),l(!1),u(!1),M9(!1)},[r]),m=y=>{y?u(!0):(l(!1),u(!1),M9(!1))},h=()=>{l(!0),u(!1),M9(!0)},g=()=>{u(!1)},v=()=>{if(!s)return;let y=PO(s);t.workspace.openLinkText(y,"",!0)};return kn.default.createElement(nc,{onOpenChange:f},kn.default.createElement(hr,null,kn.default.createElement(gr,{asChild:!0},kn.default.createElement(Ku,{asChild:!0},kn.default.createElement(oe,{variant:"ghost2",size:"icon"},kn.default.createElement(Ih,{className:"tw-size-4"})))),kn.default.createElement(fr,null,"Chat Settings")),kn.default.createElement(Cl,{className:"tw-w-80 tw-rounded-md tw-p-0",align:"end"},kn.default.createElement("div",{className:"tw-flex tw-max-h-[500px] tw-flex-col"},kn.default.createElement("div",{className:"tw-shrink-0 tw-border-b tw-px-4"},kn.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between"},kn.default.createElement("h3",{className:"tw-font-semibold"},"Chat Settings"),kn.default.createElement(oe,{variant:"ghost",size:"sm",onClick:p,className:"tw-h-8 tw-text-xs"},kn.default.createElement(uN,{className:"tw-mr-1 tw-size-3"}),"Reset"))),kn.default.createElement(Lv,null),kn.default.createElement(Ym,{className:"tw-flex-1 tw-overflow-y-auto"},kn.default.createElement("div",{className:"tw-space-y-4 tw-p-4"},kn.default.createElement("div",{className:"tw-space-y-2"},kn.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2 sm:tw-flex-row sm:tw-items-center sm:tw-justify-between"},kn.default.createElement($h,{htmlFor:"system-prompt",className:"tw-text-sm sm:tw-min-w-fit"},"System Prompt"),kn.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-2 sm:tw-flex-1"},kn.default.createElement(zCn,{value:s,onChange:y=>{let w=y.target.value;w===""?r(""):i(w)&&r(w)},options:[{label:"None (use built-in prompt)",value:""},...e.map(y=>({label:y.title===o?`${y.title} (Default)`:y.title,value:y.title}))],placeholder:"Select system prompt",containerClassName:"tw-flex-1"}),kn.default.createElement(oe,{variant:"ghost",size:"icon",onClick:v,className:"tw-size-5 tw-shrink-0 tw-p-0",title:"Open the source file",disabled:!s},kn.default.createElement(us,{className:"tw-size-5"}))))),kn.default.createElement("div",{className:"tw-space-y-3"},kn.default.createElement("div",{className:"tw-space-y-1.5"},kn.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between"},kn.default.createElement($h,{htmlFor:"disable-builtin",className:"tw-text-sm tw-font-medium"},"Disable Builtin System Prompt"),kn.default.createElement(fp,{checked:a,onCheckedChange:m,disabled:c})),kn.default.createElement("div",{className:"tw-pr-12 tw-text-xs tw-leading-relaxed tw-text-muted"},"Disables the builtin system prompt and only uses your custom system prompt."," ",kn.default.createElement("span",{className:"tw-text-xs tw-text-error"},"WARNING: This may break expected functionality."))),(a||c)&&kn.default.createElement("div",{ref:d,className:"tw-rounded-md tw-border tw-bg-error/10 tw-p-3 tw-border-error/50"},kn.default.createElement("div",{className:"tw-flex tw-gap-2"},kn.default.createElement(Wr,{className:"tw-mt-0.5 tw-size-4 tw-shrink-0 tw-text-error"}),kn.default.createElement("div",{className:"tw-flex-1 tw-space-y-2"},kn.default.createElement("div",{className:"tw-space-y-1"},kn.default.createElement("div",{className:"tw-text-xs tw-font-semibold tw-text-error"},"Copilot Plus Features Will Become Unavailable"),kn.default.createElement("div",{className:"tw-flex tw-flex-col tw-items-center tw-gap-2 tw-text-xs tw-leading-relaxed tw-text-muted"},kn.default.createElement("div",null,"When enabled, advanced features such as vault search, web search, and agent mode will become unavailable."," "),kn.default.createElement("div",{className:"tw-italic"},"Only your custom system prompt (configured in Settings) will be used."))),c&&kn.default.createElement("div",{className:"tw-flex tw-gap-2 tw-pt-1"},kn.default.createElement(oe,{size:"sm",variant:"destructive",onClick:h,className:"tw-h-7 tw-text-xs"},"Disable Builtin"),kn.default.createElement(oe,{size:"sm",variant:"ghost",onClick:g,className:"tw-h-7 tw-bg-transparent tw-text-xs"},"Cancel")))))))),kn.default.createElement(Lv,null),kn.default.createElement("div",{className:"tw-shrink-0 tw-rounded-md tw-bg-primary tw-px-4 tw-py-1"},kn.default.createElement("div",{className:"tw-flex tw-flex-row tw-flex-wrap"},kn.default.createElement("span",{className:"tw-text-xs tw-text-normal"},kn.default.createElement("span",{className:" tw-italic"},"System Prompt and Disable Builtin System Prompt")," ",kn.default.createElement("strong",null,"apply to this chat session only"),"."))))))}async function $Br(){try{let{getSettings:t}=await Promise.resolve().then(()=>(Se(),SC)),e=t();if(e.enableSemanticSearchV3){let r=await(await Promise.resolve().then(()=>(El(),nd))).default.getInstance().indexVaultToVectorStore(!1,{userInitiated:!0});Bu(e)==="miyo"?new Q0.Notice("Miyo folder index refresh started. Open the Miyo app to check details."):new Q0.Notice(`Semantic search index refreshed with ${r} documents.`)}else new Q0.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(t){H("Error refreshing vault index:",t),new Q0.Notice("Failed to refresh vault index. Check console for details.")}}async function DBr(){try{let{getSettings:t}=await Promise.resolve().then(()=>(Se(),SC)),e=t();if(e.enableSemanticSearchV3){let r=await(await Promise.resolve().then(()=>(El(),nd))).default.getInstance().indexVaultToVectorStore(!0,{userInitiated:!0});Bu(e)==="miyo"?new Q0.Notice("Miyo folder index refresh started. Open the Miyo app to check details."):new Q0.Notice(`Semantic search index rebuilt with ${r} documents.`)}else new Q0.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(t){H("Error force reindexing vault:",t),new Q0.Notice("Failed to force reindex vault. Check console for details.")}}function WCn({onNewChat:t,onSaveAsNote:e,onLoadHistory:n,chatHistory:r,onUpdateChatTitle:o,onDeleteChat:i,onLoadChat:s,onOpenSourceFile:a,latestTokenCount:l}){let c=vn(),u=xt(),[d,f]=Cw(),p=Lke(),m=h=>f(h);return dr.default.createElement("div",{className:"tw-flex tw-w-full tw-items-center tw-justify-between tw-p-1"},dr.default.createElement("div",{className:"tw-flex-1"},dr.default.createElement(bZ,null,dr.default.createElement(_Z,{asChild:!0},dr.default.createElement(oe,{variant:"ghost2",size:"fit",className:"tw-ml-1 tw-text-sm tw-text-muted"},d==="llm_chain"&&"chat (free)",d==="vault_qa"&&"vault QA (free)",d==="copilot_plus"&&dr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},dr.default.createElement(hc,{className:"tw-size-4"}),"copilot plus"),dr.default.createElement(Bs,{className:"tw-mt-0.5 tw-size-5"}))),dr.default.createElement(Ac,{align:"start"},dr.default.createElement(co,{onSelect:()=>m("llm_chain")},"chat (free)"),dr.default.createElement(co,{onSelect:()=>m("vault_qa")},"vault QA (free)"),p?dr.default.createElement(co,{onSelect:()=>m("copilot_plus")},dr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},dr.default.createElement(hc,{className:"tw-size-4"}),"copilot plus")):dr.default.createElement(co,{onSelect:()=>ek(hw.CHAT_MODE_SELECT)},"copilot plus",dr.default.createElement(NT,{className:"tw-size-3"}))))),dr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},dr.default.createElement("div",{className:"tw-mr-2"},dr.default.createElement(WSe,{tokenCount:l??null})),dr.default.createElement(hr,null,dr.default.createElement(gr,{asChild:!0},dr.default.createElement(oe,{variant:"ghost2",size:"icon",title:"New Chat",onClick:t},dr.default.createElement(lN,{className:"tw-size-4"}))),dr.default.createElement(fr,null,"New Chat")),dr.default.createElement(HCn,null),!u.autosaveChat&&dr.default.createElement(hr,null,dr.default.createElement(gr,{asChild:!0},dr.default.createElement(oe,{variant:"ghost2",size:"icon",title:"Save Chat as Note",onClick:()=>void e()},dr.default.createElement(LC,{className:"tw-size-4"}))),dr.default.createElement(fr,null,"Save Chat as Note")),dr.default.createElement(hr,null,dr.default.createElement(C6,{chatHistory:r,onUpdateTitle:o,onDeleteChat:i,onLoadChat:s,onOpenSourceFile:a},dr.default.createElement(gr,{asChild:!0},dr.default.createElement(oe,{variant:"ghost2",size:"icon",title:"Chat History",onClick:n},dr.default.createElement(aN,{className:"tw-size-4"})))),dr.default.createElement(fr,null,"Chat History")),dr.default.createElement(bZ,null,dr.default.createElement(_Z,{asChild:!0},dr.default.createElement(oe,{variant:"ghost2",size:"icon",title:"Advanced Settings"},dr.default.createElement(V_,{className:"tw-size-4"}))),dr.default.createElement(Ac,{align:"end",className:"tw-w-64"},dr.default.createElement(co,{className:"tw-flex tw-justify-between",onSelect:h=>{h.preventDefault(),At("autoAcceptEdits",!u.autoAcceptEdits)}},dr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},dr.default.createElement(yy,{className:"tw-size-4"}),"Auto-accept Edits"),dr.default.createElement(fp,{checked:u.autoAcceptEdits})),dr.default.createElement(co,{className:"tw-flex tw-items-center tw-gap-2",onSelect:()=>void $Br()},dr.default.createElement(kh,{className:"tw-size-4"}),"Refresh Vault Index"),dr.default.createElement(co,{className:"tw-flex tw-items-center tw-gap-2",onSelect:()=>{new _i(c,()=>DBr(),"This will delete and rebuild your entire vault index from scratch. This operation cannot be undone. Are you sure you want to proceed?","Force Reindex Vault").open()}},dr.default.createElement(Wr,{className:"tw-size-4"}),"Force Reindex Vault")))))}zet();n_e();var xF=L(B()),elt=({label:t="Thinking"})=>xF.default.createElement("div",{className:"tw-mb-2 tw-mt-1 tw-w-full tw-text-ui-medium max-md:tw-mb-1.5 max-md:tw-mt-0.5",role:"status","aria-live":"polite"},xF.default.createElement("div",{className:"tw-flex tw-w-full tw-items-center tw-gap-1.5 tw-text-left tw-text-ui-small tw-text-muted"},xF.default.createElement("span",{className:"tw-flex tw-size-icon-xs tw-shrink-0 tw-items-center tw-justify-center"},xF.default.createElement(A6,null)),xF.default.createElement("span",{className:"copilot-shimmer-text tw-font-medium"},t),xF.default.createElement("span",{className:"tw-ml-auto tw-size-3","aria-hidden":"true"})));Qet();gt();ett();var Xg=L(B());function tlt(t,e){return!t.some(n=>n.isVisible)&&!e}var VCn=(0,Xg.memo)(({chatHistory:t,currentAiMessage:e,streamingMessageId:n,loading:r,loadingMessage:o,app:i,onRegenerate:s,onEdit:a,onDelete:l})=>{let{containerMinHeight:c,scrollContainerCallbackRef:u,getMessageKey:d}=USe({chatHistory:t});return tlt(t,e)?Xg.default.createElement("div",{className:"tw-flex tw-w-full tw-flex-col tw-gap-2"},r&&Xg.default.createElement(elt,{label:o})):Xg.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-1 tw-flex-col tw-overflow-hidden"},Xg.default.createElement("div",{ref:u,"data-testid":"chat-messages",className:"tw-relative tw-flex tw-w-full tw-flex-1 tw-select-text tw-flex-col tw-items-start tw-justify-start tw-overflow-y-auto tw-scroll-smooth tw-break-words tw-text-[calc(var(--font-text-size)_-_2px)]"},t.map((f,p)=>{let m=t.filter(v=>v.isVisible),g=p===m.length-1&&f.sender!==ar;return f.isVisible&&Xg.default.createElement("div",{key:d(f,p),"data-message-key":d(f,p),className:"tw-w-full",style:{minHeight:g?`${c}px`:"auto"}},Xg.default.createElement(wte,{message:f,app:i,isStreaming:!1,onRegenerate:()=>s(p),onEdit:v=>a(p,v),onDelete:()=>l(p)}))}),e?Xg.default.createElement("div",{className:"tw-w-full",style:{minHeight:`${c}px`}},Xg.default.createElement(wte,{key:n??"ai_message_streaming",message:{id:n??void 0,sender:"AI",message:e,isVisible:!0,timestamp:null},app:i,isStreaming:!0,onDelete:()=>{}})):r?Xg.default.createElement("div",{className:"tw-w-full",style:{minHeight:`${c}px`}},Xg.default.createElement(elt,{label:o})):null))});VCn.displayName="ChatMessages";var qCn=VCn;ont();yt();De();$n();var C5=L(B());function KCn({onOpenAgent:t}){return Ln()?C5.default.createElement(oe,{variant:"ghost2",size:"fit",className:J("tw-h-auto tw-min-h-[30%] tw-w-full tw-shrink-0 tw-cursor-pointer","tw-flex-col tw-justify-center tw-gap-4 tw-rounded-md tw-border tw-border-solid","tw-border-border tw-bg-secondary tw-p-6 tw-text-center tw-text-normal","hover:tw-bg-interactive-hover hover:tw-text-normal","tw-whitespace-normal"),title:"Open Copilot Agent Chat",onClick:t},C5.default.createElement(OCe,{className:"tw-size-12 tw-text-accent"}),C5.default.createElement("span",{className:"tw-flex tw-flex-col tw-gap-2 tw-text-ui-larger tw-leading-tight"},C5.default.createElement("span",{className:"tw-font-semibold"},"Switch to Copilot Agent Chat"),C5.default.createElement("span",{className:"tw-text-muted"},"for a more capable agent experience"))):null}yt();pe();ut();var STe=L(B());function CTe(t){let[e,n]=(0,STe.useState)(null);(0,STe.useEffect)(()=>{(async()=>{let i=await Jdt();i.version&&n(i.version)})().catch(i=>H("checkVersion failed",i))},[]);let r=e!==null&&Uie(e,t);return{latestVersion:e,hasUpdate:r}}De();Se();ut();Re();var lw=L(B());function GCn({currentVersion:t}){let{latestVersion:e,hasUpdate:n}=CTe(t),r=xt().lastDismissedVersion,[o,i]=(0,lw.useState)(!0),s=n&&e&&Uie(e,t)&&r!==e,a=()=>{e&&(i(!1),window.setTimeout(()=>{At("lastDismissedVersion",e)},300))};return s?lw.default.createElement("div",{className:J("tw-min-h-14 tw-overflow-hidden",o?"tw-duration-300 tw-animate-in tw-slide-in-from-top":"tw-duration-300 tw-animate-out tw-slide-out-to-top")},lw.default.createElement("div",{className:"tw-mb-1 tw-flex tw-items-center tw-justify-between tw-gap-2 tw-rounded-md tw-border tw-border-solid tw-border-border tw-p-2 tw-pl-3 tw-text-xs"},lw.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},lw.default.createElement("span",{className:"tw-font-medium"},"Update available:"),lw.default.createElement("a",{href:"https://github.com/logancyang/obsidian-copilot/releases/latest",target:"_blank",rel:"noopener noreferrer",className:"tw-text-normal"},"v",e)),lw.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},lw.default.createElement(oe,{size:"fit",variant:"ghost2",className:"tw-text-accent hover:tw-text-accent-hover",onClick:()=>{window.open("obsidian://show-plugin?id=copilot","_blank"),a()}},"Update"),lw.default.createElement(oe,{variant:"ghost2",size:"icon",onClick:a},lw.default.createElement(pn,{className:"tw-size-4"}))))):null}var Wo=L(B()),kTe=L(B());SCe();d$();pm();yt();Re();es();function nlt({onClose:t,onPause:e,onResume:n,onStop:r}){let[o]=kT(),i=(0,kTe.useRef)(null),{isActive:s,isPaused:a,indexedCount:l,totalFiles:c,errors:u,completionStatus:d}=o,f=c>0?Math.round(l/c*100):0;(0,kTe.useEffect)(()=>(i.current&&(window.clearTimeout(i.current),i.current=null),!s&&d!=="none"&&!(d==="error"&&c===0)&&(i.current=window.setTimeout(()=>{t()},3e3)),()=>{i.current&&(window.clearTimeout(i.current),i.current=null)}),[s,d,c,t]);let p=()=>d==="success"?c===0?"Index Up to Date":"Indexing Complete":d==="cancelled"?"Indexing Cancelled":d==="error"?c===0?"Indexing Failed":"Indexing Complete (with errors)":a?"Indexing Paused":"Indexing Vault";return Wo.createElement(hD,{className:"tw-w-full tw-border tw-border-solid tw-border-border tw-bg-transparent tw-shadow-none"},Wo.createElement(Rte,null,Wo.createElement(Ktt,{className:"tw-flex tw-items-center tw-justify-between tw-gap-2"},Wo.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},!s&&d!=="none"?d==="error"?Wo.createElement(mc,{className:"tw-size-4 tw-text-error"}):d==="success"?Wo.createElement(yy,{className:"tw-size-4 tw-text-success"}):Wo.createElement(RC,{className:"tw-size-4"}):a?Wo.createElement(G2,{className:"tw-size-4 tw-text-warning"}):Wo.createElement(Dr,{className:"tw-size-4 tw-animate-spin tw-text-accent"}),Wo.createElement("span",{className:"tw-text-sm"},p())),Wo.createElement(oe,{size:"sm",variant:"ghost2",className:"tw-size-6 tw-p-0 tw-text-muted",title:"Close",onClick:t},Wo.createElement(pn,{className:"tw-size-4"})))),Wo.createElement(Lte,{className:"tw-space-y-3"},c>0&&Wo.createElement("div",{className:"tw-space-y-2"},Wo.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-text-sm"},Wo.createElement("span",{className:"tw-text-muted"},l,"/",c," files"),Wo.createElement("span",{className:"tw-font-medium"},f,"%")),Wo.createElement(Op,{value:f,className:"tw-h-2"})),u.length>0&&Wo.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1"},Wo.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Wo.createElement(mc,{className:"tw-size-3 tw-text-error"}),Wo.createElement(ei,{variant:"destructive",className:"tw-text-xs"},u.length," ",u.length===1?"error":"errors")),c===0&&u[0]&&Wo.createElement("span",{className:"tw-text-xs tw-text-error"},u[0])),s&&Wo.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Wo.createElement(oe,{size:"sm",variant:"ghost",className:"tw-h-6 tw-px-2 tw-text-xs",onClick:a?n:e},a?Wo.createElement(Wo.Fragment,null,Wo.createElement(MG,{className:"tw-mr-1 tw-size-3"}),"Resume"):Wo.createElement(Wo.Fragment,null,Wo.createElement(G2,{className:"tw-mr-1 tw-size-3"}),"Pause")),Wo.createElement(oe,{size:"sm",variant:"ghost",className:"tw-h-6 tw-px-2 tw-text-xs",onClick:r},Wo.createElement(HC,{className:"tw-mr-1 tw-size-3"}),"Stop"))))}gt();ko();hte();var Kf=L(B());pe();function ZCn(t){let[e,n]=(0,Kf.useState)([]);(0,Kf.useEffect)(()=>(n([...t.getMessages()]),t.subscribe(()=>{n([...t.getMessages()])})),[t]);let r=(0,Kf.useCallback)(async(m,h,g,v=!1,y=!1)=>await t.sendMessage(m,h,g,v,y),[t]),o=(0,Kf.useCallback)(async(m,h,g,v=!1)=>await t.editMessage(m,h,g,v),[t]),i=(0,Kf.useCallback)(async(m,h,g)=>await t.regenerateMessage(m,h,g),[t]),s=(0,Kf.useCallback)(async m=>await t.deleteMessage(m),[t]),a=(0,Kf.useCallback)(()=>{t.clearMessages()},[t]),l=(0,Kf.useCallback)(async m=>{await t.truncateAfterMessageId(m)},[t]),c=(0,Kf.useCallback)(m=>{t.addMessage(m)},[t]),u=(0,Kf.useCallback)(m=>{t.loadMessages(m).catch(h=>H("loadMessages failed",h))},[t]),d=(0,Kf.useCallback)(m=>t.getMessage(m),[t]),f=(0,Kf.useCallback)(()=>t.getLLMMessages(),[t]),p=(0,Kf.useCallback)(()=>t.getDebugInfo(),[t]);return{messages:e,sendMessage:r,editMessage:o,regenerateMessage:i,deleteMessage:s,addMessage:c,clearMessages:a,truncateAfterMessageId:l,loadMessages:u,getMessage:d,getLLMMessages:f,getDebugInfo:p}}vrt();gt();ut();pe();Gf();var rlt=async(t,e,n,r,o,i={})=>{let s=new AbortController;o(s);try{await e.runChain(t,s,r,n,i)}catch(a){H("Model request failed:",a);let l=Dke("Model request failed: "+kt(a));n({id:Co(),sender:pl,isErrorMessage:!0,message:l,isVisible:!0,timestamp:Cs(new Date)})}};nN();Se();ut();jV();x_e();var uc=require("obsidian"),jt=L(B());Gf();vV();Hl();var FBr=({chainManager:t,onSaveChat:e,updateUserMessageHistory:n,fileParserManager:r,plugin:o,chatUIState:i,chatInput:s})=>{let a=xt(),l=(0,jt.useContext)(Gd),{messages:c,addMessage:u}=ZCn(i),[d,f]=CT(),[p]=Cw(),m=h5({value:d,onChange:f}),[h,g]=(0,jt.useState)(""),[v,y]=(0,jt.useState)(""),w=(0,jt.useRef)(null),_=(0,jt.useRef)(null),S=(0,jt.useCallback)(ct=>{let Qt=_.current,Ct=Qt&&ct.sender===pl&&!ct.isErrorMessage&&!ct.id?{...ct,id:Qt}:ct;u(Ct)},[u]),I=(0,jt.useCallback)(ct=>{w.current=ct},[]),[C,k]=(0,jt.useState)(!1),[T,P]=(0,jt.useState)(gh.DEFAULT),[E,O]=(0,jt.useState)([]),[$,U]=(0,jt.useState)(a.autoAddActiveContentToContext===!0),[V,K]=(0,jt.useState)(a.autoAddActiveContentToContext===!0),[se,le]=(0,jt.useState)([]),[Q,ne]=(0,jt.useState)([]),[ee,ae]=(0,jt.useState)(null),[q]=kT(),F=(0,jt.useRef)(!1),z=(0,jt.useRef)(null),N=(0,jt.useCallback)(()=>{o.chatSelectionHighlightController.persistFromPointerDown()},[o]),R=(0,jt.useMemo)(()=>({setCurrentAiMessage:ct=>F.current&&g(ct),setLoadingMessage:ct=>F.current&&P(ct),setLoading:ct=>F.current&&k(ct)}),[]),[X]=Yie(),D=X.length>0,G=$&&!D,ce=V&&!D,{activeWebTabForMentions:Z}=RS(),te=()=>ee===!1?!1:q.isActive||q.completionStatus!=="none",[fe,de]=(0,jt.useState)({isActive:q.isActive,completionStatus:q.completionStatus});(fe.isActive!==q.isActive||fe.completionStatus!==q.completionStatus)&&(de({isActive:q.isActive,completionStatus:q.completionStatus}),(q.isActive||q.completionStatus!=="none")&&ae(null));let ye=(0,jt.useCallback)(()=>{ae(!1),q.isActive||ad({completionStatus:"none"})},[q.isActive]),Te=(0,jt.useCallback)(async()=>{(await Promise.resolve().then(()=>(El(),nd))).default.getInstance().pauseIndexing()},[]),Be=(0,jt.useCallback)(async()=>{(await Promise.resolve().then(()=>(El(),nd))).default.getInstance().resumeIndexing()},[]),qe=(0,jt.useCallback)(async()=>{await(await Promise.resolve().then(()=>(El(),nd))).default.getInstance().cancelIndexing()},[]),Ae=(0,jt.useMemo)(()=>{for(let ct=c.length-1;ct>=0;ct--){let Qt=c[ct];if(Qt.sender===pl)return Qt.responseMetadata?.tokenUsage?.totalTokens??null}return null},[c]),[Xt]=Cw(),Ve=(0,jt.useContext)(fN),Ee=o.app||Ve,st=(0,jt.useCallback)(ct=>{le(Qt=>__e(Qt,ct))},[]),{isDragActive:Ne}=Ske({app:Ee,contextNotes:E,setContextNotes:O,selectedImages:se,onAddImage:st,containerRef:z}),He=async({toolCalls:ct,urls:Qt,contextNotes:ir,contextTags:Ct,contextFolders:wt,webTabs:_t}={})=>{if(!v&&se.length===0)return;if(Qt&&Qt.length>0&&!sd(p)&&new uc.Notice(Zoe.URL_PROCESSING_RESTRICTED),se.length>0){let Qr=m.models.find(Vo=>Jn(Vo)===m.value);if(Array.isArray(Qr?.capabilities)&&!Fie(Qr)){let Vo=Qr.displayName||Qr.name;new uc.Notice(`${Vo} doesn't support images. Switch to a vision-capable model to send images.`);return}}try{let Qr=[];v&&Qr.push({type:"text",text:v});for(let pc of se){let pw=await pc.arrayBuffer(),DO=Fv(pw);Qr.push({type:"image_url",image_url:{url:`data:${pc.type};base64,${DO}`}})}let ny=[...ir||[],...E].filter((pc,pw,DO)=>DO.findIndex(ETn=>ETn.path===pc.path)===pw),Vt=v.trim();ct&&(Vt+=" "+ct.join(`
`));let vi={notes:ny,urls:sd(p)?Qt||[]:[],tags:Ct||[],folders:wt||[],selectedTextContexts:X,webTabs:_t||[]};y(""),le([]),_.current=`msg-${Co()}`,R.setLoading(!0),R.setLoadingMessage(gh.DEFAULT);let fc=await i.sendMessage(Vt,vi,p,G,ce,Qr.length>0?Qr:void 0,R.setLoadingMessage);v&&n(v),a.autosaveChat&&await et();let ry=i.getLLMMessage(fc);ry&&await rlt(ry,t,S,R.setCurrentAiMessage,I,{debug:a.debug,updateLoadingMessage:R.setLoadingMessage}),a.autosaveChat&&await et()}catch(Qr){H("Error sending message:",Qr),new uc.Notice("Failed to send message. Please try again.")}finally{R.setLoading(!1),R.setLoadingMessage(gh.DEFAULT),_.current=null}},et=(0,jt.useCallback)(async()=>{if(!Ee){H("App instance is not available.");return}try{await i.saveChat(d)}catch(ct){H("Error saving chat as note:",kt(ct)),new uc.Notice("Failed to save chat as note. Check console for details.")}},[Ee,i,d]),it=(0,jt.useCallback)(ct=>{w.current&&(j(`stopping generation..., reason: ${ct}`),w.current.abort(ct),R.setLoading(!1),R.setLoadingMessage(gh.DEFAULT))},[R]);(0,jt.useEffect)(()=>(F.current=!0,()=>{F.current=!1,w.current&&w.current.abort("component-unmount")}),[]);let Br=(0,jt.useCallback)(async ct=>{if(ct<=0){new uc.Notice("Cannot regenerate the first message.");return}let Qt=c[ct];if(!Qt){new uc.Notice("Message not found.");return}R.setCurrentAiMessage(""),_.current=`msg-${Co()}`,R.setLoading(!0);try{await i.regenerateMessage(Qt.id,R.setCurrentAiMessage,S)?a.debug&&j("Message regenerated successfully"):new uc.Notice("Failed to regenerate message. Please try again."),a.autosaveChat&&await et()}catch(ir){H("Error regenerating message:",ir),new uc.Notice("Failed to regenerate message. Please try again.")}finally{R.setLoading(!1),_.current=null}},[c,i,a.debug,a.autosaveChat,et,S,R]),Xr=(0,jt.useCallback)(async(ct,Qt)=>{let ir=c[ct];if(!(!ir||ir.message===Qt))try{if(!await i.editMessage(ir.id,Qt,p,G)){new uc.Notice("Failed to edit message. Please try again.");return}if(ir.sender===ar){let wt=ct<c.length-1;if(await i.truncateAfterMessageId(ir.id),wt){_.current=`msg-${Co()}`,R.setLoading(!0);try{let _t=i.getLLMMessage(ir.id);_t&&await rlt(_t,t,S,R.setCurrentAiMessage,I,{debug:a.debug,updateLoadingMessage:R.setLoadingMessage})}catch(_t){H("Error regenerating AI response:",_t),new uc.Notice("Failed to regenerate AI response. Please try again.")}finally{R.setLoading(!1),_.current=null}}}a.autosaveChat&&await et()}catch(Ct){H("Error editing message:",Ct),new uc.Notice("Failed to edit message. Please try again.")}},[c,i,p,G,S,t,a.debug,a.autosaveChat,et,R,I]);(0,jt.useEffect)(()=>{e&&e(et)},[e,et]);let An=(0,jt.useCallback)(ct=>{let ir=hy().find(Ct=>Ct.id===ct);Zie(ct),ir?.sourceType==="web"&&o.suppressCurrentWebSelection(ir.url)},[o]);(0,jt.useEffect)(()=>{o.chatSelectionHighlightController.clearIfNoNoteContexts(X)},[X,o]),(0,jt.useEffect)(()=>{let ct=()=>{s.focusInput()};return l?.addEventListener(cs.CHAT_IS_VISIBLE,ct),()=>{l?.removeEventListener(cs.CHAT_IS_VISIBLE,ct)}},[l,s]),(0,jt.useEffect)(()=>{let ct=l instanceof by?l:null,Qt=Ct=>{ct?.consumePendingInsertText();let wt=Ct.detail?.text;typeof wt=="string"&&s.insertTextWithPills(wt,!0)};l?.addEventListener(cs.INSERT_TEXT_TO_CHAT,Qt);let ir=ct?.consumePendingInsertText();return typeof ir=="string"&&s.insertTextWithPills(ir,!0),()=>{l?.removeEventListener(cs.INSERT_TEXT_TO_CHAT,Qt)}},[l,s]);let zn=(0,jt.useCallback)(async ct=>{let Qt=c[ct];if(!Qt){new uc.Notice("Message not found.");return}try{await i.deleteMessage(Qt.id)||new uc.Notice("Failed to delete message. Please try again.")}catch(ir){H("Error deleting message:",ir),new uc.Notice("Failed to delete message. Please try again.")}},[c,i]),Yp=(0,jt.useCallback)(async()=>{if(w3(),await $l.clear(),it("new-chat"),a.enableRecentConversations)try{let Qt=t.chatModelManager.getChatModel();o.userMemoryManager.addRecentConversation(i.getMessages(),Qt)}catch(Qt){j("Failed to analyze chat messages for memory:",Qt)}a.autosaveChat&&await et(),i.clearMessages(),pNe(),R.setCurrentAiMessage(""),O([]);let ct=X.find(Qt=>Qt.sourceType==="web")?.url;YK(),o.chatSelectionHighlightController.clearForNewChat(),o.suppressCurrentWebSelection(ct),U(a.autoAddActiveContentToContext),K(a.autoAddActiveContentToContext)},[it,t.chatModelManager,i,a.autosaveChat,a.enableRecentConversations,a.autoAddActiveContentToContext,et,R,o,X]),la=(0,jt.useCallback)(async()=>{try{let ct=await o.getChatHistoryItems();ne(ct)}catch(ct){H("Error loading chat history:",ct),new uc.Notice("Failed to load chat history.")}},[o]),vu=(0,jt.useCallback)(async(ct,Qt)=>{try{await o.updateChatTitle(ct,Qt),await la()}catch(ir){throw H("Error updating chat title:",ir),new uc.Notice("Failed to update chat title."),ir}},[o,la]),Ds=(0,jt.useCallback)(async ct=>{try{await o.deleteChatHistory(ct),await la()}catch(Qt){throw H("Error deleting chat:",Qt),new uc.Notice("Failed to delete chat."),Qt}},[o,la]),hh=(0,jt.useCallback)(async ct=>{try{await o.loadChatById(ct),pNe()}catch(Qt){H("Error loading chat:",Qt),new uc.Notice("Failed to load chat.")}},[o]),N_=(0,jt.useCallback)(async ct=>{try{await o.openChatSourceFile(ct)}catch(Qt){H("Error opening source file:",Qt),new uc.Notice("Failed to open source file.")}},[o]);(0,jt.useEffect)(()=>{let ct=Qt=>{let ir=Qt.detail?.reason||"new-chat";it(ir)};return l?.addEventListener(cs.ABORT_STREAM,ct),()=>{l?.removeEventListener(cs.ABORT_STREAM,ct)}},[l,it]);let[ty,fl]=(0,jt.useState)({autoAdd:a.autoAddActiveContentToContext,chain:Xt});return(ty.autoAdd!==a.autoAddActiveContentToContext||ty.chain!==Xt)&&(fl({autoAdd:a.autoAddActiveContentToContext,chain:Xt}),a.autoAddActiveContentToContext!==void 0&&(U(a.autoAddActiveContentToContext),K(a.autoAddActiveContentToContext))),jt.default.createElement("div",{ref:z,onPointerDownCapture:N,className:"tw-flex tw-size-full tw-flex-col tw-overflow-hidden"},jt.default.createElement("div",{className:"tw-h-full"},jt.default.createElement("div",{className:"tw-relative tw-flex tw-h-full tw-flex-col"},Ne&&jt.default.createElement("div",{className:"tw-absolute tw-inset-0 tw-z-modal tw-flex tw-items-center tw-justify-center tw-rounded-md tw-border tw-border-dashed tw-bg-primary tw-opacity-80"},jt.default.createElement("span",null,"Drop files here...")),jt.default.createElement(jt.default.Fragment,null,jt.default.createElement("div",{className:"tw-flex tw-size-full tw-flex-col tw-overflow-hidden"},jt.default.createElement(GCn,{currentVersion:o.manifest.version}),tlt(c,h)&&jt.default.createElement("div",{className:"tw-mx-auto tw-flex tw-w-full tw-max-w-lg tw-flex-1 tw-items-center tw-px-4"},jt.default.createElement(KCn,{onOpenAgent:xn(()=>o.activateAgentView())})),jt.default.createElement(qCn,{chatHistory:c,currentAiMessage:h,streamingMessageId:_.current,loading:C,loadingMessage:T,app:Ee,onRegenerate:xn(Br),onEdit:xn(Xr),onDelete:xn(zn)}),te()?jt.default.createElement("div",{className:"tw-inset-0 tw-z-modal tw-flex tw-items-center tw-justify-center tw-rounded-xl"},jt.default.createElement(nlt,{onClose:ye,onPause:()=>void Te(),onResume:()=>void Be(),onStop:()=>void qe()})):jt.default.createElement(jt.default.Fragment,null,jt.default.createElement(WCn,{onNewChat:()=>void Yp(),onSaveAsNote:()=>et(),onLoadHistory:()=>void la(),chatHistory:Q,onUpdateChatTitle:vu,onDeleteChat:Ds,onLoadChat:hh,onOpenSourceFile:N_,latestTokenCount:Ae}),jt.default.createElement(ESe,{inputMessage:v,setInputMessage:y,handleSendMessage:xn(He),isGenerating:C,onStopGenerating:()=>it("user-stopped"),app:Ee,contextNotes:E,setContextNotes:O,includeActiveNote:$,setIncludeActiveNote:U,includeActiveWebTab:V,setIncludeActiveWebTab:K,activeWebTab:Z,selectedImages:se,onAddImage:st,setSelectedImages:le,modelPickerOverride:m,selectedTextContexts:X,onRemoveSelectedText:An,showIndexingCard:()=>{ae(!0)}})))))))},UBr=t=>jt.default.createElement(PSe,null,jt.default.createElement(jBr,{...t})),jBr=t=>{let e=IM();return jt.default.createElement(FBr,{...t,chatInput:e})},YCn=UBr;gt();ko();Ike();brt();ode();var TTe=require("obsidian"),ITe=L(B()),AO=class extends TTe.ItemView{constructor(n,r){super(n);this.plugin=r;this.viewRoot=null;this.handleSaveAsNote=null;this.drawerHideObserver=null;this.setSaveHandler=n=>{this.handleSaveAsNote=n};this.handleUpdateUserMessageHistory=n=>{this.plugin.updateUserMessageHistory(n)};this.app=r.app,this.fileParserManager=r.fileParserManager,this.eventTarget=new by,this.plugin=r}get chainManager(){return this.plugin.chainOwner.getCurrentChainManager()}getViewType(){return Fs}getIcon(){return"message-square"}getTitle(){return"Copilot Chat"}getDisplayText(){return"Copilot (Quick Chat)"}async onOpen(){this.viewRoot=Tke(this.containerEl,this.app,()=>this.renderTree()),this.setupDrawerHideObserver(),h3(this,this.eventTarget),this.registerEvent(this.app.workspace.on("layout-change",()=>{window.requestAnimationFrame(()=>this.setupDrawerHideObserver())}))}setupDrawerHideObserver(){if(!TTe.Platform.isMobile)return;this.drawerHideObserver?.disconnect();let n=this.containerEl.closest(".workspace-drawer");if(!n)return;let r=n.classList.contains("is-hidden");this.drawerHideObserver=new MutationObserver(()=>{let o=n.classList.contains("is-hidden");o&&!r&&this.containerEl.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0,cancelable:!0})),r=o}),this.drawerHideObserver.observe(n,{attributes:!0,attributeFilter:["class"]})}renderTree(){return ITe.createElement(Gd.Provider,{value:this.eventTarget},ITe.createElement(Vj,{delayDuration:0},ITe.createElement(YCn,{chainManager:this.chainManager,updateUserMessageHistory:this.handleUpdateUserMessageHistory,fileParserManager:this.fileParserManager,plugin:this.plugin,onSaveChat:this.setSaveHandler,chatUIState:this.plugin.chatUIState})))}async saveChat(){this.handleSaveAsNote&&await this.handleSaveAsNote()}updateView(){this.viewRoot?.rerender()}async onClose(){this.drawerHideObserver?.disconnect(),this.drawerHideObserver=null,this.viewRoot?.unmount(),this.viewRoot=null}};urt();gt();ko();Pa();Ike();var JCn=require("obsidian"),PTe=L(B()),yoe=class extends JCn.ItemView{constructor(n,r){super(n);this.plugin=r;this.root=null;this.app=r.app,this.eventTarget=new EventTarget}getViewType(){return iT}getIcon(){return"files"}getTitle(){return"Copilot Relevant Notes"}getDisplayText(){return"Copilot Relevant Notes"}async onOpen(){this.root=Er(this.containerEl.children[1],this.app),this.renderView(),h3(this,this.eventTarget)}renderView(){this.root&&this.root.render(PTe.createElement(Gd.Provider,{value:this.eventTarget},PTe.createElement("div",{className:"tw-flex tw-size-full tw-flex-col tw-overflow-hidden"},PTe.createElement(Xte,{onAddToChat:n=>void this.plugin.insertTextIntoActiveChat(n)}))))}async onClose(){this.root&&(this.root.unmount(),this.root=null)}};fm();zQ();Se();wC();var XCn=require("obsidian"),ATe=class extends XCn.FuzzySuggestModal{constructor(n,r,o,i){super(n);this.chatFiles=r;this.chatHistoryLastAccessedAtManager=o;this.onChooseFile=i}getItems(){let n=Y().chatHistorySortStrategy;return ay(this.chatFiles,n,{getName:r=>obe(this.app,r),getCreatedAtMs:r=>ibe(this.app,r).getTime(),getLastUsedAtMs:r=>{let o=BQ(this.app,r);return this.chatHistoryLastAccessedAtManager.getEffectiveLastUsedAt(r.path,o)}})}getItemText(n){return XJt(this.app,n)}onChooseItem(n,r){this.onChooseFile(n)}};Og();c_();gt();var QCn=require("obsidian");function BBr(t){return typeof t.commands?.executeCommandById=="function"}function ekn(t){return t instanceof QCn.TFile&&t.extension==="md"}function tkn(t,e,n,r){if(!BBr(e))return;let o=i=>{e.commands.executeCommandById(i)};t.addItem(i=>{i.setTitle("Copilot"),i.setSubmenu();let s=i.submenu;if(!s)return;s.addItem(c=>{c.setTitle("Add selection to chat context").onClick(()=>{o(`copilot:${ht.ADD_SELECTION_TO_CHAT_CONTEXT}`)})}),s.addItem(c=>{c.setTitle("Quick Ask").onClick(()=>{o(`copilot:${ht.TRIGGER_QUICK_ASK}`)})}),s.addItem(c=>{c.setTitle("Trigger quick command").onClick(()=>{o(`copilot:${ht.TRIGGER_QUICK_COMMAND}`)})}),ekn(n)&&s.addItem(c=>{c.setTitle(jO[ht.PUBLISH_FILE_TO_SYMPOSIUM]).setIcon(BO[ht.PUBLISH_FILE_TO_SYMPOSIUM]).onClick(()=>r(n))});let l=Bf().filter(c=>c.showInContextMenu);l.length>0&&s.addSeparator(),ste(l).forEach(c=>{s.addItem(u=>{u.setTitle(c.title).onClick(()=>{o(`copilot:${oD(c.title)}`)})})})})}function nkn(t,e){t.registerEvent(t.app.workspace.on("file-menu",(n,r)=>{ekn(r)&&n.addItem(o=>{o.setTitle(jO[ht.PUBLISH_FILE_TO_SYMPOSIUM]).setIcon(BO[ht.PUBLISH_FILE_TO_SYMPOSIUM]).onClick(()=>e(r))})}))}Og();AC();c_();x0();Se();Is();pe();var ETe=class{constructor(e,n){this.folderChangeRequestId=0;this.disposed=!1;this.handleSettingsChange=(e,n)=>{EC(e)!==EC(n)&&this.handleFolderChange()};this.handleFileModify=Ba(async e=>{if(!EV(e)||rte(e.path))return;let n=await ite(this.app,e);this.registerCommand(n),nD(n,n.title)},1e3,{leading:!1,trailing:!0});this.handleFileCreation=async e=>{if(!(!EV(e)||rte(e.path)))try{let n=await ite(this.app,e);if(!hln(this.app,e)){let r=dSe();n={...n,order:r}}await ket(this.app,e,n),nD(n,n.title),this.registerCommand(n)}catch(n){H(`Error processing custom command creation: ${e.path}`,n)}};this.handleFileDeletion=async e=>{if(!EV(e)||rte(e.path))return;let n=oD(e.basename);this.plugin.removeCommand(n),ote(e.basename)};this.handleFileRename=async(e,n)=>{if(rte(e.path))return;let r=n.split("/").pop()?.replace(/\.md$/,"");if(r){let o=oD(r);this.plugin.removeCommand(o),ote(r)}if(EV(e)){let o=await ite(this.app,e);this.registerCommand(o),nD(o,o.title),await ket(this.app,e,o)}};this.plugin=e,this.app=n,this.vault=n.vault,this.initializeEventListeners()}async initialize(){await gln(this.app),this.registerCommands()}registerCommands(){Bf().forEach(n=>{this.registerCommand(n)})}cleanup(){this.disposed=!0,++this.folderChangeRequestId,this.settingsUnsubscriber?.(),this.vault.off("create",this.handleFileCreation),this.vault.off("delete",this.handleFileDeletion),this.vault.off("rename",this.handleFileRename),this.vault.off("modify",this.handleFileModify)}initializeEventListeners(){this.vault.on("create",this.handleFileCreation),this.vault.on("delete",this.handleFileDeletion),this.vault.on("rename",this.handleFileRename),this.vault.on("modify",this.handleFileModify),this.settingsUnsubscriber=zr(this.handleSettingsChange)}async handleFolderChange(){let e=++this.folderChangeRequestId;try{let n=await Cet(this.app);if(this.disposed||e!==this.folderChangeRequestId)return;let r=new Set(n.map(o=>o.title));for(let o of Bf())r.has(o.title)||this.removeRegisteredCommand(o.title);n.forEach(o=>this.registerCommand(o)),PV(n)}catch(n){if(e!==this.folderChangeRequestId)return;H("Error reloading custom commands after folder change",n)}}removeRegisteredCommand(e){let n=oD(e);this.plugin.removeCommand(n)}registerCommand(e){let n=oD(e.title);this.plugin.removeCommand(n),this.plugin.addCommand({id:n,name:e.title,editorCallback:r=>{new TO(this.plugin.app,{selectedText:r.getSelection(),command:e}).open(),Fa.getInstance().recordUsage(e).catch(o=>H("recordUsage failed",o))}})}};x0();Og();Se();ut();rD();rD();c_();async function zBr(t,e){let r=`${bM()}/unsupported`;return await ao(t.vault,r),Promise.all(e.map(async o=>{let i=`${r}/${o.title}.md`,s=await t.vault.create(i,o.content);await t.fileManager.processFrontMatter(s,a=>{a[v0]=o.showInContextMenu,a[w0]=o.showInSlashMenu,a[jS]=o.order,a[b0]=o.modelKey,a[_0]=0})}))}async function rkn(t){let e=Y().inlineEditCommands;if(!e||e.length===0)return null;let n=[],r=[],o=Bf(),i=e.map((a,l)=>({title:a.name,content:a.prompt,showInContextMenu:a.showInContextMenu,showInSlashMenu:!1,order:l*10,modelKey:a.modelKey??"",lastUsedMs:0}));for(let a of i){let l=cSe(a.title,o);l?r.push({...a,title:encodeURIComponent(a.title),content:`> ${l}
Original name: ${a.title}
${a.content}`}):n.push(a)}await Fa.getInstance().updateCommands([...o.map(a=>({...a,showInSlashMenu:!0})),...n]);let s=[`Stored in ${bM()}.`];return r.length>0&&(await zBr(t,r),s.push(`${r.length} unsupported command${r.length===1?" was":"s were"} saved in ${bM()}/unsupported. Resolve the errors, then move each note out of that folder.`)),At("inlineEditCommands",[]),{id:"custom-commands",title:"Custom commands",status:r.length>0?"action-required":"success",summary:`${n.length} command${n.length===1?" was":"s were"} migrated to note files.`,details:s}}async function okn(){let t=Bf(),e=mln.filter(r=>!t.some(o=>o.title===r.title)),n=[...t,...e];await Fa.getInstance().updateCommands(n)}pe();zI();YQ();Md();YQ();sA();Se();Is();AC();var olt=require("obsidian"),MTe=class{constructor(e){this.folderChangeRequestId=0;this.fileModifyDebouncers=new Map;this.handleSettingsChange=(e,n)=>{let r=KK(n);KK(e)!==r&&this.debouncedFolderChange(r)};this.debouncedFolderChange=Ba(e=>{this.handleProjectsFolderChange(e)},1e3,{leading:!1,trailing:!0});this.handleFileCreation=async e=>{if(!(!C$(e)||qb(e.path)))try{let n=await P$(this.app,e);if(!n)return;let r=mo(n.project.id);if(r&&r.filePath!==n.filePath){W(`[Projects] Duplicate id="${n.project.id}": existing=${r.filePath}, incoming=${n.filePath}; ignored`);return}await ZQ(this.app,e,n);let o=await P$(this.app,e);o&&S$(o)}catch(n){H(`[Projects] Error on file creation: ${e.path}`,n)}};this.handleFileDeletion=async e=>{if(!(!C$(e)||qb(e.path))){this.evictFileModifyDebouncer(e.path);try{let n=RQ(e.path);UE(e.path),n&&BI(this.app).catch(r=>H("[Projects] Rescan after delete failed",r))}catch(n){H(`[Projects] Error on file deletion: ${e.path}`,n)}}};this.handleFileRename=async(e,n)=>{if(qb(e.path)||qb(n))return;let r=this.isProjectConfigPathString(n),o=C$(e);if(!(!r&&!o)){r&&this.evictFileModifyDebouncer(n);try{let i=r?RQ(n):void 0;if(o){let s=await P$(this.app,e);if(!s){r&&UE(n);return}let a=mo(s.project.id);if(a&&a.filePath!==s.filePath&&a.filePath!==n){r&&UE(n),W(`[Projects] Duplicate id="${s.project.id}" after rename: existing=${a.filePath}, incoming=${s.filePath}; ignored`);return}await ZQ(this.app,e,s);let c=await P$(this.app,e);c?r?X7e(n,c):S$(c):r&&UE(n)}else r&&UE(n);r&&!o&&i&&BI(this.app).catch(s=>H("[Projects] Rescan after rename-out failed",s))}catch(i){H(`[Projects] Error on file rename: ${n} -> ${e.path}`,i)}}};this.handleFileModify=e=>{!C$(e)||qb(e.path)||this.getFileModifyDebouncer(e.path)(e)};this.app=e,this.vault=e.vault,this.manager=nl.getInstance(e)}async initialize(){return this.initializeEventListeners(),this.manager.initialize()}cleanup(){for(let e of this.fileModifyDebouncers.values())e.cancel();this.fileModifyDebouncers.clear(),this.debouncedFolderChange.cancel(),this.folderChangeRequestId++,this.settingsUnsubscriber?.(),this.vault.off("create",this.handleFileCreation),this.vault.off("delete",this.handleFileDeletion),this.vault.off("rename",this.handleFileRename),this.vault.off("modify",this.handleFileModify)}initializeEventListeners(){this.vault.on("create",this.handleFileCreation),this.vault.on("delete",this.handleFileDeletion),this.vault.on("rename",this.handleFileRename),this.vault.on("modify",this.handleFileModify),this.settingsUnsubscriber=zr(this.handleSettingsChange)}async handleProjectsFolderChange(e){let n=++this.folderChangeRequestId;try{let r=await this.manager.fetchProjects();if(n!==this.folderChangeRequestId)return;for(let o of this.fileModifyDebouncers.values())o.cancel();this.fileModifyDebouncers.clear(),LQ(r),j(`[Projects] Folder changed -> reloaded: ${e}`),new olt.Notice(`Projects folder updated: ${e}`)}catch(r){if(n!==this.folderChangeRequestId)return;for(let o of this.fileModifyDebouncers.values())o.cancel();this.fileModifyDebouncers.clear(),LQ([]),H(`[Projects] Failed to reload after folder change: ${e}`,r),new olt.Notice(`Failed to reload projects from "${e}". Projects cleared \u2014 reopen settings to retry.`)}}isProjectConfigPathString(e){let n=Od();if(!e.startsWith(n+"/"))return!1;let r=e.slice(n.length+1);if(r.startsWith(`${ff}/`))return!1;let o=r.split("/");return o.length===2&&o[1]===Xh}evictFileModifyDebouncer(e){let n=this.fileModifyDebouncers.get(e);n&&(n.cancel(),this.fileModifyDebouncers.delete(e))}async processFileModify(e){if(!(!C$(e)||qb(e.path)))try{let n=await P$(this.app,e);if(!n){let o=RQ(e.path);UE(e.path),o&&BI(this.app).catch(i=>H("[Projects] Rescan after invalid edit failed",i));return}let r=mo(n.project.id);if(r&&r.filePath!==n.filePath){let o=RQ(e.path);UE(e.path),o&&BI(this.app).catch(i=>H("[Projects] Rescan after duplicate edit failed",i)),W(`[Projects] Duplicate id="${n.project.id}" on modify: existing=${r.filePath}, incoming=${n.filePath}; ignored`);return}X7e(e.path,n)}catch(n){H(`[Projects] Error on file modify: ${e.path}`,n)}}getFileModifyDebouncer(e){let n=this.fileModifyDebouncers.get(e);return n||(n=Ba(r=>{this.processFileModify(r)},1e3,{leading:!1,trailing:!0}),this.fileModifyDebouncers.set(e,n)),n}};gt();Se();es();pe();Og();gt();async function ikn(t,e){await e.clearChatMemory();for(let n=0;n<t.length-1;n++){let r=t[n];if(r.sender===ar){let o=t[n+1];o?.sender===pl&&await e.saveContext({input:r.message},{output:o.message})}}}es();mw();Og();gt();Py();pe();var skn=["L1_SYSTEM","L2_PREVIOUS","L3_TURN","L4_STRIP","L5_USER"],akn={L1_SYSTEM:"System Instructions",L2_PREVIOUS:"Previous Turn Context",L3_TURN:"Current Turn Context",L4_STRIP:"Conversation Strip",L5_USER:"User Message"};var EO=class EO{constructor(){}static getInstance(){return EO.instance||(EO.instance=new EO),EO.instance}buildEnvelope(e){let n=skn.map(a=>this.buildLayer(a,e.layerSegments[a]??[])),r=this.serializeLayers(n),o=this.collectLayerHashes(n),i=this.hash(r),s=typeof e.metadata?.debugLabel=="string"?e.metadata.debugLabel:void 0;return s&&j(`[PromptContextEngine] Built envelope for ${s}`,o),{version:EO.ENVELOPE_VERSION,conversationId:e.conversationId,messageId:e.messageId,layers:n,serializedText:r,layerHashes:o,combinedHash:i,debug:{warnings:this.collectWarnings(n)}}}buildLayer(e,n){let r=n.map((i,s)=>({...i,id:i.id||`${e}-segment-${s}`,content:this.normalizeWhitespace(i.content),stable:i.stable??!0})),o=this.normalizeWhitespace(r.map(i=>i.content).filter(Boolean).join(`
`));return{id:e,label:akn[e],text:o,segments:r,stable:r.every(i=>i.stable),metadata:r.length===1?r[0].metadata:void 0,hash:this.hash(o)}}serializeLayers(e){return e.map(n=>n.text).filter(n=>n.length>0).join(`
`)}collectLayerHashes(e){return e.reduce((n,r)=>(n[r.id]=r.hash,n),{})}hash(e){return MN(e||"")}normalizeWhitespace(e){return e.replace(/\s+$/g,"").trim()}collectWarnings(e){let n=[];return e.forEach(r=>{if(!r.text)return;r.text.includes("\0")&&n.push(`Layer ${r.id} contains control characters and was normalized`)}),n}};EO.ENVELOPE_VERSION=1;var OTe=EO;function HBr(t){let e=/<path>([^<]+)<\/path>/.exec(t);if(e)return e[1];let n=/<url>([^<]+)<\/url>/.exec(t);if(n)return n[1];let r=/<name>([^<]+)<\/name>/.exec(t);return r?r[1]:""}function WBr(t,e,n,r={}){let o=r.verbatimThreshold??Jg.verbatimThreshold;if(t.length<=o)return t;let i=r.previewCharsPerSection??Jg.previewCharsPerSection,s=r.maxSections??Jg.maxSections,a=hF(t,i,s);return`<prior_context source="${rTe(e)}" type="${n}">
${a}
</prior_context>`}function lkn(t,e,n={}){if(!nTe(e))return t;let r=n.verbatimThreshold??Jg.verbatimThreshold;if(t.length<=r)return t;let o=c5(t,e)||HBr(t),i=aoe(t),s=mF(e);return WBr(i,o,s,n)}function ckn(){return`<prior_context_note>
The above prior_context blocks contain previews of content from earlier turns.
To access full content: use [[note title]] for notes, or ask to read a specific URL/video.
</prior_context_note>`}function ukn(t,e){if(!t.trim())return[];let n=[],o=[...l5.map(l=>l.tag),"prior_context"],i=new RegExp(`<(${o.join("|")})(\\s[^>]*)?>[\\s\\S]*?</\\1>`,"g"),s=new Map,a;for(;(a=i.exec(t))!==null;){let l=a[0],c=a[1];if(c==="prior_context"){let d=/source="([^"]+)"/.exec(l)?.[1]??"prior_context";n.push({id:d,content:l,stable:e,metadata:{source:"previous_turns_compacted",notePath:d}})}else{let u=c5(l,c),d;if(u)d=u;else{let p=(s.get(c)||0)+1;s.set(c,p),d=p===1?c:`${c}:${p}`}let f=mF(c)==="note";n.push({id:d,content:l,stable:e,metadata:{source:e?"previous_turns":"current_turn",...f?{notePath:d}:{}}})}}return n}bbe();pe();_v();ut();pe();vc();Se();HS();var NTe=class t{constructor(){this.mentions=new Map,this.brevilabsClient=Gi.getInstance()}static getInstance(){return t.instance||(t.instance=new t),t.instance}extractAllUrls(e){return YSe(e)}extractUrls(e){return YSe(e)}async processUrl(e){try{return await this.brevilabsClient.url4llm(e)}catch(n){let r=kt(n);return H(`Error processing URL ${e}: ${r}`),{response:e,elapsed_time_ms:0,error:r}}}async processYoutubeUrl(e){try{return{transcript:(UM()&&Y().supadataApiKey?await $0e(e):await this.brevilabsClient.youtube4llm(e)).response.transcript}}catch(n){let r=kt(n);return H(`Error processing YouTube URL ${e}: ${r}`),{transcript:"",error:r}}}async processTwitterUrl(e){try{return await this.brevilabsClient.twitter4llm(e)}catch(n){let r=kt(n);return H(`Error processing Twitter URL ${e}: ${r}`),{response:e,elapsed_time_ms:0,error:r}}}async processUrlList(e,n){let r="",o=[],i={};if(n.length===0)return{urlContext:r,imageUrls:o,processedErrorUrls:i};let s=n.map(async l=>{if(await uC.isImageUrl(l,e))return o.push(l),{type:"image",url:l};if(Kdt(l)){let u=this.mentions.get(l);if(!u||u.error){let d=await this.processYoutubeUrl(l);this.mentions.set(l,{type:"youtube",original:l,processed:d.transcript,error:d.error})}return{type:"youtube",data:this.mentions.get(l)}}if(Gdt(l)){let u=this.mentions.get(l);if(!u||u.error){let d=await this.processTwitterUrl(l);this.mentions.set(l,{type:"twitter",original:l,processed:d.response,error:d.error})}return{type:"twitter",data:this.mentions.get(l)}}let c=this.mentions.get(l);if(!c||c.error){let u=await this.processUrl(l);this.mentions.set(l,{type:"url",original:l,processed:u.response,error:u.error})}return{type:"url",data:this.mentions.get(l)}});return(await Promise.all(s)).forEach(l=>{if(l.type==="image")return;let c=l.data;c&&(c.processed&&(l.type==="youtube"?r+=`
<youtube_video_context>
<url>${c.original}</url>
<content>
${c.processed}
</content>
</youtube_video_context>`:l.type==="twitter"?r+=`
<twitter_content>
<url>${c.original}</url>
<content>
${c.processed}
</content>
</twitter_content>`:r+=`
<url_content>
<url>${c.original}</url>
<content>
${c.processed}
</content>
</url_content>`),c.error&&(i[c.original]=c.error))}),{urlContext:r,imageUrls:o,processedErrorUrls:i}}async processUrls(e,n){let r=this.extractUrls(n);return this.processUrlList(e,r)}getMentions(){return this.mentions}clearMentions(){this.mentions.clear()}};Se();ut();var slt=null;async function VBr(){return slt||(slt=(await Promise.resolve().then(()=>(fkn(),dkn))).ContextCompactor),slt.getInstance()}var RTe=class t{constructor(){this.contextProcessor=WE.getInstance(),this.mention=NTe.getInstance(),this.promptContextEngine=OTe.getInstance()}static getInstance(){return t.instance||(t.instance=new t),t.instance}async processMessageContext(e,n,r,o,i,s,a,l,c,u=[],d){try{j(`[ContextManager] Processing context for message ${n.id}`);let f=n.originalMessage||n.message,{processedPrompt:p,includedFiles:m}=await lte(e,f,"",o,a),{l2Context:h,l2Paths:g}=this.buildL2ContextFromPreviousTurns(n.id,l),v=n.context?.urls||[],y=i==="copilot_plus"?await this.mention.processUrlList(o,v):{urlContext:"",imageUrls:[]},w=new Set([...m.map(q=>q.path),...u.map(q=>q.path),...g]),_=new Set,I=(n.context?.notes||[]).filter(q=>!g.has(q.path));s&&a&&!w.has(a.path)&&!I.some(q=>q.path===a.path)&&I.push(a);let C=await this.contextProcessor.processContextNotes(w,r,o,I,s,a,i);I.forEach(q=>{w.add(q.path),_.add(q.path)});let k=n.context?.tags||[],T="",P=[];if(k.length>0){let F=Nie(e,k).filter(z=>!w.has(z.path));F.length>0&&(T=await this.contextProcessor.processContextNotes(new Set,r,o,F,!1,null,i),F.forEach(z=>{w.add(z.path),_.add(z.path),P.push(z.path)}))}let E=n.context?.folders||[],O="",$=[];if(E.length>0){let F=E.flatMap(z=>BK(o,z)).filter(z=>!w.has(z.path));F.length>0&&(O=await this.contextProcessor.processContextNotes(new Set,r,o,F,!1,null,i),F.forEach(z=>{w.add(z.path),_.add(z.path),$.push(z.path)}))}let U=this.contextProcessor.processSelectedTextContexts(),V=n.context?.webTabs||[],K=await this.contextProcessor.processContextWebTabs(V),se=h+C+T+O+y.urlContext+U+K,le=p+se,Q=Y().autoCompactThreshold*4,ne=!1,ee=se;if(le.length>Q){d?.(gh.COMPACTING);let F=await(await VBr()).compact(se);F.wasCompacted&&(ee=F.content,le=p+ee,ne=!0,j(`[ContextManager] Compacted context: ${F.originalCharCount} -> ${F.compactedCharCount} chars`)),d?.(gh.DEFAULT)}j(`[ContextManager] Successfully processed context for message ${n.id}`);let ae=ne?this.buildCompactedEnvelope({chainType:i,message:n,systemPrompt:c||"",processedUserMessage:p,compactedContext:ee,compactedPaths:Array.from(_)}):this.buildPromptContextEnvelope({chainType:i,message:n,systemPrompt:c||"",processedUserMessage:p,l2PreviousContext:h,noteContextAddition:C,tagContextAddition:T,tagNotePaths:P,folderContextAddition:O,folderNotePaths:$,urlContext:y.urlContext,selectedText:U,webTabContext:K});return{processedContent:le,contextEnvelope:ae}}catch(f){return j(`[ContextManager] Error processing context for message ${n.id}:`,f),{processedContent:n.originalMessage||n.message,contextEnvelope:void 0}}}async reprocessMessageContext(e,n,r,o,i,s,a,l,c,u=[]){let d=r.getMessage(n);if(!d||d.sender!=="user"||!d.id)return;j(`[ContextManager] Reprocessing context for message ${n}`);let{processedContent:f,contextEnvelope:p}=await this.processMessageContext(e,d,o,i,s,a,l,r,c,u);r.updateProcessedText(d.id,f,p),j(`[ContextManager] Completed context reprocessing for message ${n}`)}buildL2ContextFromPreviousTurns(e,n){let r=n.getDisplayMessages(),o=r.findIndex(p=>p.id===e);if(o===-1||o===0)return{l2Context:"",l2Paths:new Set};let i=r.slice(0,o).filter(p=>p.sender==="user"),s=new Map,a=[],l=new Set,c=-1;for(let p=i.length-1;p>=0;p--)if(i[p].contextEnvelope?.layers?.find(v=>v.id==="L3_TURN")?.segments?.some(v=>v.metadata?.wasCompacted)){c=p;break}for(let p=0;p<i.length;p++){let h=i[p].contextEnvelope?.layers?.find(g=>g.id==="L3_TURN");if(h){if(p>=c){for(let g of h.segments||[])if(g.content){let v=this.compactSegmentForL2(g.content);if(!v.trim())continue;s.has(g.id)||a.push(g.id),s.set(g.id,v)}}for(let g of h.segments||[]){if(g.metadata?.notePath&&l.add(g.metadata.notePath),g.metadata?.compactedPaths)for(let v of g.metadata.compactedPaths)l.add(v);if(g.metadata?.notePaths)for(let v of g.metadata.notePaths)l.add(v)}}}let u=a.map(p=>s.get(p)).join(`
`);return{l2Context:/<prior_context\s+source=/.test(u)?u+`
`+ckn():u,l2Paths:l}}buildPromptContextEnvelope(e){let n=e.message.id;if(!n)return;let r={};if(e.systemPrompt&&(r.L1_SYSTEM=[{id:"system",content:e.systemPrompt,stable:!0,metadata:{source:"system_prompt"}}]),e.l2PreviousContext){let i=this.parseContextIntoSegments(e.l2PreviousContext,!0);i.length>0&&(r.L2_PREVIOUS=i)}let o=[];if(e.noteContextAddition){let i=this.parseContextIntoSegments(e.noteContextAddition,!1);o.push(...i)}return this.appendParsedSegments(o,e.tagContextAddition,{source:"tags",notePaths:e.tagNotePaths}),this.appendParsedSegments(o,e.folderContextAddition,{source:"folders",notePaths:e.folderNotePaths}),this.appendParsedSegments(o,e.urlContext),this.appendParsedSegments(o,e.selectedText),this.appendParsedSegments(o,e.webTabContext),o.length>0&&(r.L3_TURN=o),r.L5_USER=[{id:`${n}-user`,content:e.processedUserMessage,stable:!1,metadata:{source:"user_input"}}],this.promptContextEngine.buildEnvelope({conversationId:null,messageId:n,layerSegments:r,metadata:{debugLabel:`message:${n}`,chainType:e.chainType}})}buildCompactedEnvelope(e){let n=e.message.id;if(!n)return;let r={};return e.systemPrompt&&(r.L1_SYSTEM=[{id:"system",content:e.systemPrompt,stable:!0,metadata:{source:"system_prompt"}}]),e.compactedContext.trim()&&(r.L3_TURN=[{id:"compacted_context",content:e.compactedContext,stable:!1,metadata:{source:"compacted",wasCompacted:!0,compactedPaths:e.compactedPaths}}]),r.L5_USER=[{id:`${n}-user`,content:e.processedUserMessage,stable:!1,metadata:{source:"user_input"}}],this.promptContextEngine.buildEnvelope({conversationId:null,messageId:n,layerSegments:r,metadata:{debugLabel:`message:${n}:compacted`,chainType:e.chainType}})}parseContextIntoSegments(e,n){return ukn(e,n)}appendParsedSegments(e,n,r){let o=(n||"").trim();if(!o)return;let i=this.parseContextIntoSegments(o,!1);if(i.length>0)for(let s of i)r&&(s.metadata={...s.metadata,...r}),e.push(s);else e.push({id:`unparsed-${Date.now()}`,content:o,stable:!1,metadata:{source:"unparsed",...r}})}createMessageContext(e,n,r=hy()){return{notes:e,urls:n,selectedTextContexts:r}}async extractContextNotes(e,n,r=[]){return[...j_(e,n),...r].filter((a,l,c)=>c.findIndex(u=>u.path===a.path)===l)}needsContextReprocessing(e){return e.needsContextReprocessing===!0}getSelectedTextContexts(){return hy()}compactSegmentForL2(e){let n=[...l5.map(i=>i.tag),"prior_context","prior_context_note"].join("|"),r=new RegExp(`<(${n})(\\s[^>]*)?>[\\s\\S]*?</\\1>`,"g");return e.replace(r,(i,s)=>{let a=l5.find(l=>l.tag===s);return a&&!a.recoverable||s==="prior_context_note"?"":s==="prior_context"?i:a?lkn(i,s):i}).trim()}};gt();NSe();pe();zQ();Se();Is();ut();Jh();rp();var Kp=require("obsidian"),alt=100;function pkn(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var LTe=class{constructor(e,n,r){this.app=e;this.messageRepo=n;this.chainManager=r}async saveChat(e){try{let n=this.messageRepo.getDisplayMessages();if(n.length===0){new Kp.Notice("No messages to save.");return}let r=this.formatChatContent(n),o=n[0].timestamp?.epoch||Date.now(),i=ST();await ao(this.app.vault,i);let s=await this.findFileByEpoch(o,i),a=s?this.app.metadataCache.getFileCache(s)?.frontmatter:void 0,l=a?.topic,c=a?.lastAccessedAt;if(s&&!a)try{let m=await uf(this.app,s.path);m&&(m.topic&&(l=m.topic),m.lastAccessedAt&&(c=Number(m.lastAccessedAt)))}catch{}let u=s?s.path:this.generateFileName(n,o,i,l),d=this.generateNoteContent(r,o,e,l,c),f=s,p=s!=null&&xp(this.app,s.path);if(s&&p)await this.app.vault.modify(s,d),j(`[ChatPersistenceManager] Updated existing chat file: ${s.path}`);else if(!xp(this.app,u)&&await this.app.vault.adapter.exists(u))await this.app.vault.adapter.write(u,d),new Kp.Notice("Existing chat note found - updating it now."),j(`[ChatPersistenceManager] Updated existing chat file via adapter: ${u}`);else try{f=await this.app.vault.create(u,d),new Kp.Notice(`Chat saved as note: ${u}`),j(`[ChatPersistenceManager] Created new chat file: ${u}`)}catch(m){if(KR(m)){let h=this.app.vault.getAbstractFileByPath(u);if(h&&h instanceof Kp.TFile){let g=this.app.metadataCache.getFileCache(h)?.frontmatter;l=g?.topic??l;let v=g?.lastAccessedAt,y=this.generateNoteContent(r,o,e,l,v);await this.app.vault.modify(h,y),f=h,new Kp.Notice("Existing chat note found - updating it now."),j(`[ChatPersistenceManager] Resolved save conflict by updating existing chat file: ${h.path}`)}else await this.app.vault.adapter.write(u,d),new Kp.Notice("Existing chat note found - updating it now."),j(`[ChatPersistenceManager] Resolved save conflict via adapter: ${u}`)}else if(cY(m)){let h=`${i}/chat-${o}.md`;try{f=await this.app.vault.create(h,d),new Kp.Notice(`Chat saved as note: ${h}`),W(`[ChatPersistenceManager] Used minimal filename due to length constraints: ${h}`)}catch(g){if(KR(g)){let v=this.app.vault.getAbstractFileByPath(h);if(v&&v instanceof Kp.TFile){let y=this.app.metadataCache.getFileCache(v)?.frontmatter,w=y?.lastAccessedAt,_=y?.topic,S=this.generateNoteContent(r,o,e,_,w);await this.app.vault.modify(v,S),f=v,new Kp.Notice("Existing chat note found - updating it now."),j(`[ChatPersistenceManager] Resolved fallback save conflict by updating existing chat file: ${v.path}`)}else await this.app.vault.adapter.write(h,d),new Kp.Notice("Existing chat note found - updating it now."),j(`[ChatPersistenceManager] Resolved fallback save conflict via adapter: ${h}`)}else throw g}}else throw m}this.generateTopicAsyncIfNeeded(f,n,l)}catch(n){H("[ChatPersistenceManager] Error saving chat:",n),new Kp.Notice("Failed to save chat as note. Check console for details.")}}async loadChat(e){try{let n;try{n=await this.app.vault.read(e)}catch{n=await this.app.vault.adapter.read(e.path)}let r=this.parseChatContent(n);return j(`[ChatPersistenceManager] Loaded ${r.length} messages from ${e.path}`),r}catch(n){return H("[ChatPersistenceManager] Error loading chat:",n),new Kp.Notice("Failed to load chat history. Check console for details."),[]}}async getChatHistoryFiles(e=ST()){let n=await qR(this.app,e);return n.length===0?[]:rbe(this.app,n)}formatChatContent(e){return e.map(n=>{let r=n.timestamp?n.timestamp.display:"Unknown time",o=n.message;if(n.sender===pl){let s=yte(o);s&&(o=s.contentAfter)}let i=`**${n.sender}**: ${o}`;if(n.context){let s=[];n.context.notes?.length&&s.push(`Notes: ${n.context.notes.map(a=>a.path).join(", ")}`),n.context.urls?.length&&s.push(`URLs: ${n.context.urls.join(", ")}`),n.context.webTabs?.length&&s.push(`Web Tabs: ${n.context.webTabs.map(a=>a.url).join(", ")}`),n.context.tags?.length&&s.push(`Tags: ${n.context.tags.join(", ")}`),n.context.folders?.length&&s.push(`Folders: ${n.context.folders.join(", ")}`),s.length>0&&(i+=`
[Context: ${s.join(" | ")}]`)}return i+=`
[Timestamp: ${r}]`,i}).join(`
`)}parseChatContent(e){let n=[],r=e.match(/^---\n([\s\S]*?)\n---/),o=e;r&&(o=e.slice(r[0].length).trim());let i=/\*\*(user|ai)\*\*: ([\s\S]*?)(?=(?:\n\*\*(?:user|ai)\*\*: )|$)/g,s;for(;(s=i.exec(o))!==null;){let a=s[1]==="user"?ar:pl,l=s[2].trim(),c=l.split(`
`),u=l,d="Unknown time",f,p=c.length;if(c[p-1]?.startsWith("[Timestamp: ")){let h=c[p-1].match(/\[Timestamp: (.*?)\]/);h&&(d=h[1],p--)}if(p>0&&c[p-1]?.startsWith("[Context: ")){let h=c[p-1].match(/\[Context: (.*?)\]/);if(h){let g=h[1];f=this.parseContextString(g),p--}}if(u=c.slice(0,p).join(`
`).trim(),a===pl){u=u.replace(/<!--TOOL_CALL_START:[^:]+:[^:]+:[^:]+:[^:]+:[^:]*:[^:]+-->[\s\S]*?<!--TOOL_CALL_END:[^:]+:[\s\S]*?-->/g,"");let h=yte(u);h&&(u=h.contentAfter),u=u.replace(/\n{3,}/g,`
`).trim()}let m;if(d!=="Unknown time"){let h=new Date(d);isNaN(h.getTime())||(m=h.getTime())}n.push({message:u,sender:a,isVisible:!0,timestamp:m?{epoch:m,display:d,fileName:""}:null,context:f})}return n}parseContextString(e){let n={notes:[],urls:[],tags:[],folders:[],webTabs:[]},r=e.split(" | ");for(let o of r){let i=o.trim();if(i.startsWith("Notes: ")){let s=i.substring(7);s&&(n.notes=s.split(", ").map(a=>{let l=a.trim(),c=this.app.vault.getAbstractFileByPath(l);if(c instanceof Kp.TFile)return c;let u=l.includes("/")?l.split("/").pop():l,d=this.app.vault.getMarkdownFiles().filter(f=>f.basename===u);return d.length===1?(j(`[ChatPersistenceManager] Resolved legacy basename "${u}" to ${d[0].path}`),d[0]):(d.length>1?W(`[ChatPersistenceManager] Ambiguous basename "${u}", skipping. Matches: ${d.map(f=>f.path).join(", ")}`):W(`[ChatPersistenceManager] Note not found: ${l}`),null)}).filter(a=>a!==null))}else if(i.startsWith("URLs: ")){let s=i.substring(6);s&&(n.urls=s.split(", ").map(a=>a.trim()))}else if(i.startsWith("Web Tabs: ")||i.startsWith("WebTabs: ")){let s=i.startsWith("Web Tabs: ")?i.substring(10):i.substring(9);s&&(n.webTabs=s.split(", ").map(a=>a.trim()).filter(a=>a.length>0).map(a=>({url:a})))}else if(i.startsWith("Tags: ")){let s=i.substring(6);s&&(n.tags=s.split(", ").map(a=>a.trim()))}else if(i.startsWith("Folders: ")){let s=i.substring(9);s&&(n.folders=s.split(", ").map(a=>a.trim()))}}if(n.notes.length>0||n.urls.length>0||(n.tags?.length??0)>0||(n.folders?.length??0)>0||(n.webTabs?.length??0)>0)return n}async findFileByEpoch(e,n){let r=await this.getChatHistoryFiles(n);for(let o of r){let i=this.app.metadataCache.getFileCache(o)?.frontmatter?.epoch;if(i===void 0)try{let a=await uf(this.app,o.path);a?.epoch&&(i=Number(a.epoch))}catch{continue}let s=typeof i=="number"?i:typeof i=="string"?Number(i):void 0;if(typeof s=="number"&&!Number.isNaN(s)&&s===e)return o}return null}async generateAITopic(e){if(this.chainManager)try{let n=this.chainManager.chatModelManager.getChatModel();if(!n)return;let r=6,o=200,s=`Generate a concise title (max 5 words) for this conversation based on its content. Return only the title without any explanation or quotes.
Conversation:
${e.reduce((u,d,f)=>f>=r?u:u+(u?`
`:"")+`${d.sender}: ${d.message.slice(0,o)}`,"")}`,a=await n.invoke(s),l=typeof a=="string"?a:a.content??a.text??a;return T2(l).trim().replace(/^["']|["']$/g,"").replace(/[\\/:*?"<>|]/g,"").slice(0,50)||void 0}catch(n){H("[ChatPersistenceManager] Error generating AI topic:",n);return}}generateFileName(e,n,r,o){let i=Y(),a=Cs(new Date(n)).fileName,l;if(o)l=o;else{let y=e.find(w=>w.sender===ar);l=y&&y.message.replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/[{}[\]]/g,"").split(/\s+/).slice(0,10).join(" ").replace(/[\\/:*?"<>|\x00-\x1F]/g,"").trim()||"Untitled Chat"}let c=i.defaultConversationNoteName||"{$date}_{$time}__{$topic}",u=xw(".md"),d=c.replace("{$topic}","").replace("{$date}",a.split("_")[0]).replace("{$time}",a.split("_")[1]),f=xw(d),p=Math.max(20,alt-u-f),m=l.replace(/\s+/g,"_"),h=_T(m,p);c=c.replace("{$topic}",h).replace("{$date}",a.split("_")[0]).replace("{$time}",a.split("_")[1]);let g=c.replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/[{}[\]]/g,"_").replace(/[\\/:*?"<>|\x00-\x1F]/g,"_"),v=`${g}.md`;if(xw(v)>alt){let y=alt-u,w=_T(g,y);return Fr(r,`${w}.md`)}return Fr(r,v)}generateNoteContent(e,n,r,o,i){return`---
epoch: ${n}
modelKey: "${pkn(r)}"
${o?`topic: "${pkn(o)}"`:""}
${i?`lastAccessedAt: ${i}`:""}
tags:
- ${Woe}
---
${e}`}generateTopicAsyncIfNeeded(e,n,r){!e||r||(async()=>{try{let o=await this.generateAITopic(n);if(!o)return;await this.applyTopicToFrontmatter(e,o),await this.renameFileToMatchTopic(e,o)}catch(o){H("[ChatPersistenceManager] Error during async topic generation:",o)}})()}async applyTopicToFrontmatter(e,n){try{await kx(this.app,e.path,{topic:n.trim()}),j(`[ChatPersistenceManager] Applied AI topic to chat file: ${e.path}`)}catch(r){H("[ChatPersistenceManager] Error applying AI topic to file:",r)}}errorToMessage(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}isNameTooLongError(e){if(!e)return!1;let n=this.errorToMessage(e).toLowerCase();return n.includes("enametoolong")||n.includes("name too long")}isFileAlreadyExistsError(e){return e?this.errorToMessage(e).toLowerCase().includes("already exists"):!1}async renameFileToMatchTopic(e,n){if(!e||!n)return;let r,o=this.app.metadataCache.getFileCache(e);if(o?.frontmatter?.epoch)r=o.frontmatter.epoch;else try{let c=await uf(this.app,e.path);c?.epoch&&(r=Number(c.epoch))}catch{}if(!r)return;let i=this.messageRepo.getDisplayMessages(),s=e.path.lastIndexOf("/"),a=s===-1?"":e.path.slice(0,s),l=this.generateFileName(i,r,a,n);e.path!==l&&await this.app.fileManager.renameFile(e,l)}};gt();ntt();var $Te=class{constructor(e,n,r,o){this.messageRepo=e;this.chainManager=n;this.fileParserManager=r;this.plugin=o;this.contextManager=RTe.getInstance(),this.persistenceManager=new LTe(o.app,e,n)}setOnMessageCreatedCallback(e){this.onMessageCreatedCallback=e}async processSystemPromptTemplates(e,n,r){if(!e.includes("{")||!e.includes("}"))return{processedPrompt:e,includedFiles:[]};if(!Y().enableCustomPromptTemplating)return{processedPrompt:e,includedFiles:[]};try{let i=await lte(this.plugin.app,e,"",n,r,!0);return{processedPrompt:i.processedPrompt.trimEnd(),includedFiles:i.includedFiles}}catch(i){return W("[ChatManager] Error processing system prompt templates:",i),{processedPrompt:e,includedFiles:[]}}}injectProcessedUserCustomPromptIntoSystemPrompt(e){let{systemPromptWithoutMemory:n,userCustomPrompt:r,processedUserCustomPrompt:o}=e,i=/<user_custom_instructions>\n[\s\S]*?\n<\/user_custom_instructions>/;return i.test(n)?n.replace(i,()=>`<user_custom_instructions>
${o}
</user_custom_instructions>`):n===r?o:(j("[ChatManager] Could not locate <user_custom_instructions> block for injection; returning original system prompt."),n)}replaceSystemPromptWithoutMemoryInBasePrompt(e){let{basePromptWithMemory:n,systemPromptWithoutMemory:r,processedSystemPromptWithoutMemory:o}=e;return n.endsWith(r)?`${n.slice(0,n.length-r.length)}${o}`:(j("[ChatManager] basePromptWithMemory does not end with systemPromptWithoutMemory; returning original base prompt."),n)}async getSystemPromptForMessage(e,n,r){let o=P0e(),i=[],s=await H0(this.chainManager.userMemoryManager),a=pO(),l=s;if(o){let c=await this.processSystemPromptTemplates(o,n,r),u=this.injectProcessedUserCustomPromptIntoSystemPrompt({systemPromptWithoutMemory:a,userCustomPrompt:o,processedUserCustomPrompt:c.processedPrompt}),d=this.replaceSystemPromptWithoutMemoryInBasePrompt({basePromptWithMemory:s,systemPromptWithoutMemory:a,processedSystemPromptWithoutMemory:u});d!==s&&i.push(...c.includedFiles),l=d}return{processedPrompt:l,includedFiles:i}}async sendMessage(e,n,r,o=!1,i=!1,s,a){try{j(`[ChatManager] Sending message: "${e}"`);let l=this.plugin.app.workspace.getActiveFile(),c={...n};if(o&&l){let y=n.notes||[],w=y.some(_=>_.path===l.path);c.notes=w?y:[...y,l]}let d=!((c.selectedTextContexts||[]).length>0)&&(i||e.includes(vC));c.webTabs=BSe(this.plugin.app,c.webTabs||[],d);let f=this.messageRepo.addMessage(e,e,ar,c,s);this.onMessageCreatedCallback&&this.onMessageCreatedCallback(f);let p=this.messageRepo.getMessage(f);if(!p)throw new Error(`Failed to retrieve message ${f}`);let{processedPrompt:m,includedFiles:h}=await this.getSystemPromptForMessage(r,this.plugin.app.vault,l),{processedContent:g,contextEnvelope:v}=await this.contextManager.processMessageContext(this.plugin.app,p,this.fileParserManager,this.plugin.app.vault,r,o,l,this.messageRepo,m,h,a);return this.messageRepo.updateProcessedText(f,g,v),j(`[ChatManager] Successfully sent message ${f}`),f}catch(l){throw j("[ChatManager] Error sending message:",l),l}}async editMessage(e,n,r,o=!1){try{if(j(`[ChatManager] Editing message ${e}: "${n}"`),!this.messageRepo.editMessage(e,n))return!1;let s=this.plugin.app.workspace.getActiveFile(),{processedPrompt:a,includedFiles:l}=await this.getSystemPromptForMessage(r,this.plugin.app.vault,s);return await this.contextManager.reprocessMessageContext(this.plugin.app,e,this.messageRepo,this.fileParserManager,this.plugin.app.vault,r,o,s,a,l),await this.updateChainMemory(),j(`[ChatManager] Successfully edited message ${e}`),!0}catch(i){return j(`[ChatManager] Error editing message ${e}:`,i),!1}}async regenerateMessage(e,n,r,o){try{if(j(`[ChatManager] Regenerating message ${e}`),!this.messageRepo.getMessage(e))return j(`[ChatManager] Message not found: ${e}`),!1;let s=this.messageRepo.getDisplayMessages(),a=s.findIndex(d=>d.id===e);if(a<=0)return j("[ChatManager] Cannot regenerate first message or no user message found"),!1;let l=s[a-1];if(l.sender!==ar)return j("[ChatManager] Previous message is not from user"),!1;if(this.messageRepo.truncateAfter(a-1),o&&o(),await this.updateChainMemory(),!l.id)return j("[ChatManager] User message has no ID for regeneration"),!1;let c=this.messageRepo.getLLMMessage(l.id);if(!c)return j("[ChatManager] LLM message not found for regeneration"),!1;if(!c.contextEnvelope){j("[ChatManager] Context envelope missing, reprocessing context for regeneration");let d=B_(),f=this.plugin.app.workspace.getActiveFile(),{processedPrompt:p,includedFiles:m}=await this.getSystemPromptForMessage(d,this.plugin.app.vault,f);await this.contextManager.reprocessMessageContext(this.plugin.app,l.id,this.messageRepo,this.fileParserManager,this.plugin.app.vault,d,!1,f,p,m),c=this.messageRepo.getLLMMessage(l.id)}let u=new AbortController;return await this.chainManager.runChain(c,u,n,r,{debug:Y().debug}),j(`[ChatManager] Successfully regenerated message ${e}`),!0}catch(i){return j(`[ChatManager] Error regenerating message ${e}:`,i),!1}}async deleteMessage(e){try{return j(`[ChatManager] Deleting message ${e}`),this.messageRepo.deleteMessage(e)?(await this.updateChainMemory(),j(`[ChatManager] Successfully deleted message ${e}`),!0):!1}catch(n){return j(`[ChatManager] Error deleting message ${e}:`,n),!1}}addMessage(e){return this.messageRepo.addMessage(e)}clearMessages(){this.messageRepo.clear(),this.chainManager.memoryManager.clearChatMemory().catch(e=>H("clearChatMemory failed",e)),j("[ChatManager] Cleared all messages")}async truncateAfterMessageId(e){this.messageRepo.truncateAfterMessageId(e),await this.updateChainMemory(),j(`[ChatManager] Truncated messages after ${e}`)}getDisplayMessages(){return this.messageRepo.getDisplayMessages()}getLLMMessages(){return this.messageRepo.getLLMMessages()}getMessage(e){return this.messageRepo.getMessage(e)}getLLMMessage(e){return this.messageRepo.getLLMMessage(e)}async updateChainMemory(){try{let e=this.messageRepo.getLLMMessages();await ikn(e,this.chainManager.memoryManager),j(`[ChatManager] Updated chain memory with ${e.length} messages`)}catch(e){j("[ChatManager] Error updating chain memory:",e)}}async loadMessages(e){this.messageRepo.clear(),e.forEach(n=>{this.messageRepo.addMessage(n)}),await this.updateChainMemory(),j(`[ChatManager] Loaded ${e.length} messages`)}async saveChat(e){await this.persistenceManager.saveChat(e)}getDebugInfo(){return this.messageRepo.getDebugInfo()}async loadChatHistory(e){this.clearMessages();let n=await this.persistenceManager.loadChat(e);for(let r of n)this.messageRepo.addMessage(r);await this.updateChainMemory(),j(`[ChatManager] Loaded ${n.length} messages from chat history`)}};ut();pe();var DTe=class{constructor(){this.messages=[]}generateId(){return`msg-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}addMessage(e,n,r,o,i){if(typeof e=="object"){let u=e,d=u.id||this.generateId(),f=u.timestamp||Cs(new Date),p={id:d,displayText:u.message,processedText:u.originalMessage||u.message,sender:u.sender,timestamp:f,context:u.context,contextEnvelope:u.contextEnvelope,isVisible:u.isVisible!==!1,isErrorMessage:u.isErrorMessage,sources:u.sources,content:u.content,responseMetadata:u.responseMetadata};return this.messages.push(p),j(`[MessageRepository] Added message with ID: ${d}`),d}if(n===void 0||r===void 0)throw new Error("processedText and sender are required when using string-based addMessage");let s=e,a=this.generateId(),l=Cs(new Date),c={id:a,displayText:s,processedText:n,sender:r,timestamp:l,context:o,contextEnvelope:void 0,isVisible:!0,isErrorMessage:!1,content:i};return this.messages.push(c),j(`[MessageRepository] Added message with ID: ${a}`),a}editMessage(e,n){let r=this.messages.find(o=>o.id===e);return r?r.displayText===n?(j(`[MessageRepository] No changes needed for message: ${e}`),!0):(r.displayText=n,r.sender==="user"||r.sender==="USER"?j(`[MessageRepository] Edited user message ${e}, needs context reprocessing`):(r.processedText=n,j(`[MessageRepository] Edited AI message ${e}`)),!0):(j(`[MessageRepository] Message not found for edit: ${e}`),!1)}updateProcessedText(e,n,r){let o=this.messages.find(i=>i.id===e);return o?(o.processedText=n,o.contextEnvelope=r,j(`[MessageRepository] Updated processed text for message ${e}`),!0):(j(`[MessageRepository] Message not found for processed text update: ${e}`),!1)}deleteMessage(e){let n=this.messages.findIndex(r=>r.id===e);return n===-1?(j(`[MessageRepository] Message not found for deletion: ${e}`),!1):(this.messages.splice(n,1),j(`[MessageRepository] Deleted message ${e}`),!0)}clear(){this.messages=[],j("[MessageRepository] Cleared all messages")}truncateAfter(e){this.messages=this.messages.slice(0,e+1),j(`[MessageRepository] Truncated messages after index ${e}`)}truncateAfterMessageId(e){let n=this.messages.findIndex(r=>r.id===e);n!==-1&&(this.messages=this.messages.slice(0,n+1),j(`[MessageRepository] Truncated messages after message ${e}`))}getDisplayMessages(){return this.messages.filter(e=>e.isVisible).map(e=>({id:e.id,message:e.displayText,originalMessage:e.displayText,sender:e.sender,timestamp:e.timestamp,isVisible:!0,context:e.context,contextEnvelope:e.contextEnvelope,isErrorMessage:e.isErrorMessage,sources:e.sources,content:e.content,responseMetadata:e.responseMetadata}))}getLLMMessage(e){let n=this.messages.find(r=>r.id===e);if(n)return{id:n.id,message:n.processedText,originalMessage:n.displayText,sender:n.sender,timestamp:n.timestamp,isVisible:!1,context:n.context,contextEnvelope:n.contextEnvelope,isErrorMessage:n.isErrorMessage,sources:n.sources,content:n.content,responseMetadata:n.responseMetadata}}getLLMMessages(){return this.messages.map(e=>({id:e.id,message:e.displayText,originalMessage:e.displayText,sender:e.sender,timestamp:e.timestamp,isVisible:!1,context:e.context,contextEnvelope:e.contextEnvelope,isErrorMessage:e.isErrorMessage,sources:e.sources,content:e.content}))}getMessage(e){let n=this.messages.find(r=>r.id===e);if(n)return{id:n.id,message:n.displayText,originalMessage:n.displayText,sender:n.sender,timestamp:n.timestamp,isVisible:n.isVisible,context:n.context,contextEnvelope:n.contextEnvelope,isErrorMessage:n.isErrorMessage,sources:n.sources,content:n.content}}loadMessages(e){this.clear(),e.forEach(n=>{this.messages.push({id:n.id||this.generateId(),displayText:n.message,processedText:n.originalMessage||n.message,sender:n.sender,timestamp:n.timestamp||Cs(new Date),context:n.context,contextEnvelope:n.contextEnvelope,isVisible:n.isVisible!==!1,isErrorMessage:n.isErrorMessage,sources:n.sources,content:n.content})}),j(`[MessageRepository] Loaded ${e.length} messages`)}getDebugInfo(){return{totalMessages:this.messages.length,visibleMessages:this.messages.filter(e=>e.isVisible).length,userMessages:this.messages.filter(e=>e.sender==="user"||e.sender==="USER").length,aiMessages:this.messages.filter(e=>e.sender==="AI"||e.sender==="assistant").length}}};pe();nN();mp();cP();WO();Py();var qBr="data-v3-credentials-backup";function KBr(t){return`${qBr}-${MN(t).slice(0,8)}.json`}function GBr(t){return/"enc_[a-z]+_/.test(t)}async function mkn(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))return{status:"not-needed"};if(!rie(t))return{status:"not-needed"};let r=JSON.stringify(t,null,2),o=`${e}/${KBr(r)}`;try{if(!await n.exists(o)){let i=`${o}.writing`;await n.write(i,r),await n.rename(i,o)}return{status:"backed-up",path:o,encrypted:GBr(r)}}catch(i){return{status:"failed",error:i}}}gt();pe();cP();WO();Se();gX();var gkn=require("obsidian"),k5=Promise.resolve(),SF,FTe=!1,UTe=0,jTe=!1,voe=new Set,ZBr=/^[a-f0-9]{8}$/;function YBr(t){return typeof t=="string"&&ZBr.test(t)}function ykn(t){return!t||typeof t!="object"||Array.isArray(t)?{}:structuredClone(t)}function JBr(t,e,n){let r=QF(e2(ykn(t)));return r._keychainVaultId=e,n&&(r.settingsVersion=11),r}function vkn(){k5=Promise.resolve(),SF=void 0,FTe=!1,UTe=0,jTe=!1,voe.clear()}function wkn(){jTe=!1}function bkn(t){SF=structuredClone(t)}function BTe(){FTe=!0}async function zTe(t){let e=k5.then(async()=>{try{await t()}finally{UTe++}});return k5=e.catch(()=>{}),e}async function _kn(){await k5}function hkn(t,e){return!e||e.deviceId!==wg(t)||typeof e.path!="string"||typeof e.encrypted!="boolean"?null:{id:"credentials",title:"API keys",status:"action-required",summary:"Credential storage moved to the Obsidian Keychain.",details:e.encrypted?[`Previous keys were copied to ${e.path}.`,"Some keys are encrypted and cannot be read back. Get fresh keys from those providers and enter them in Settings."]:[`Previous keys were copied to ${e.path}.`,"Re-enter the keys in Settings, then delete the backup file."]}}async function xkn(t,e,n,r,o){let i=e==null,s=ykn(e),a=Ha.getInstance(),l=s._keychainVaultId,c=YBr(l)?l:a.getVaultId();a.setVaultId(c);let u=JBr(e,c,i),d=hkn(t,u._pendingCredentialRecovery),f=()=>{d&&o&&o(d)},p=(_,S)=>{(!o||!d)&&new gkn.Notice(_,S)},m=(_,S)=>{d&&(d={...d,status:"error",summary:S??d.summary,details:[...d.details??[],_]})};if(JSON.stringify(s)!==JSON.stringify(u)){let _=await r(e);if(_.status==="failed")jTe=!0,d={id:"credentials",title:"API keys",status:"error",summary:"API keys could not be backed up, so data.json was left untouched.",details:["Check that the vault is writable, then restart Obsidian to retry."]},p("Copilot could not back up the API keys stored in data.json, so it left the file untouched. Check that the vault is writable, then restart Obsidian.");else{_.status==="backed-up"&&(u._pendingCredentialRecovery={deviceId:wg(t),path:_.path,encrypted:_.encrypted},d=hkn(t,u._pendingCredentialRecovery),p(_.encrypted?`Copilot moved credential storage to the Obsidian Keychain. Your previous keys were copied to ${_.path}, but some are encrypted and cannot be read back. Get fresh keys from those providers and enter them in Settings.`:`Copilot moved credential storage to the Obsidian Keychain. Your previous keys were copied to ${_.path}. Re-enter them in Settings, then delete that file.`,15e3));try{await n(u)}catch{m("Check that the vault is writable, then restart Obsidian to retry.","API keys were backed up, but could not be removed from data.json."),p("Copilot could not remove API keys from data.json. Check that the vault is writable, then restart Obsidian.")}}}let h=i?structuredClone(Yn):s,g=e2(_Ae(h)),v=QF({...g,_keychainVaultId:c,_pendingCredentialRecovery:u._pendingCredentialRecovery});if(!a.isAvailable())return m("Obsidian Keychain is unavailable in this Obsidian build, so keys cannot be loaded or saved."),p("Obsidian Keychain is unavailable. Copilot cannot load or save API keys in this Obsidian build."),f(),SF=structuredClone(v),v;let{settings:y,hadFailures:w}=await a.hydrateFromKeychain(v);return w&&(m("Some API keys could not be loaded from the Obsidian Keychain. Restart Obsidian if the issue persists."),p("Some API keys could not be loaded from the Obsidian Keychain. Restart Obsidian if the issue persists.")),f(),SF=structuredClone(y),y}async function Skn(t,e,n){if(jTe)throw new Error("Copilot cannot save settings until it can back up the API keys still in data.json. Check that the vault is writable, then restart Obsidian.");let r=Ha.getInstance(),o=e2(t),i=SF??n,s=SF??n,{secretEntries:a,keychainIdsToDelete:l}=r.persistSecrets(o,i),c=[];try{for(let u of voe)r.setSecretById(u,""),c.push(u);for(let[u,d]of a)r.setSecretById(u,d);for(let u of l)try{r.setSecretById(u,"")}catch(d){throw voe.add(u),d}await e(QF(o)),SF=structuredClone(o);for(let u of c)voe.delete(u)}catch(u){try{await XBr(r,s,o)}catch(d){W("Failed to roll back Keychain after settings persistence failed.",d)}throw u}}async function llt(t,e,n){await Skn(t,e,n)}async function Ckn(t,e,n){if(FTe){FTe=!1;return}let r=UTe,o=k5.then(()=>{if(r===UTe)return Skn(t,e,n)});return k5=o.catch(()=>{}),o}async function XBr(t,e,n){if(!e)return;let{secretEntries:r,keychainIdsToDelete:o}=t.persistSecrets(e,n);for(let[i,s]of r)try{t.setSecretById(i,s)}catch(a){W(`Failed to restore Keychain entry "${i}" during rollback.`,a)}for(let i of o)try{t.setSecretById(i,""),voe.delete(i)}catch(s){W(`Failed to write Keychain tombstone "${i}" during rollback.`,s)}}vc();T$();IYe();Gf();var HTe=class{constructor(e){this.timeoutId=null;this.isRunning=!1;this.leafState=new WeakMap;this.suppressedSelectionsByUrl=new Map;this.intervalMs=e.intervalMs??500;let n=e.emptySelectionDebounceCount??2;this.emptySelectionDebounceCount=Number.isFinite(n)&&n>0?Math.floor(n):2,this.isEnabled=e.isEnabled,this.getLeaf=e.getLeaf,this.getActiveLeaf=e.getActiveLeaf,this.onSelectionChange=e.onSelectionChange,this.onSelectionClear=e.onSelectionClear}start(){this.isRunning||(this.isRunning=!0,this.scheduleNext())}stop(){this.isRunning=!1,this.timeoutId!==null&&(window.clearTimeout(this.timeoutId),this.timeoutId=null),this.leafState=new WeakMap,this.suppressedSelectionsByUrl=new Map}scheduleNext(){this.isRunning&&(this.timeoutId=window.setTimeout(()=>{(async()=>(await this.checkSelection(),this.scheduleNext()))()},this.intervalMs))}async checkSelection(){if(this.isEnabled())try{let e=this.getLeaf();if(!e)return;let n=this.getOrCreateLeafState(e),r=d6(e),o=r.url;if(this.isValidUrl(o))n.consecutiveInvalidUrlChecks=0;else{n.consecutiveEmptyChecks=0,this.maybeClearSelectionForInvalidUrl(e,n);return}let i=await gbe(e);if(!i.trim()){this.handleEmptySelection(e,n);return}if(n.consecutiveEmptyChecks=0,this.shouldSuppressSelectionForUrl(o,i)||n.lastSelection&&n.lastSelection.url===o&&n.lastSelection.text===i)return;let s=await ybe(e);if(!s.trim()||this.shouldSuppressSelectionForUrl(o,i))return;n.lastSelection={url:o,text:i};let a={id:Co(),content:s,sourceType:"web",title:r.title||"Untitled",url:o,faviconUrl:r.faviconUrl||void 0};this.onSelectionChange(a)}catch{}}getOrCreateLeafState(e){let n=this.leafState.get(e);if(n)return n;let r={lastSelection:null,consecutiveEmptyChecks:0,consecutiveInvalidUrlChecks:0};return this.leafState.set(e,r),r}isValidUrl(e){let n=e.trim();if(!n)return!1;try{return new URL(n),!0}catch{return!1}}isActiveWebViewerLeaf(e){let n=this.getActiveLeaf();return!!(n&&n===e)}handleEmptySelection(e,n){if(!n.lastSelection||!this.isActiveWebViewerLeaf(e)||(n.consecutiveEmptyChecks+=1,n.consecutiveEmptyChecks<this.emptySelectionDebounceCount))return;let r=n.lastSelection.url;n.lastSelection=null,n.consecutiveEmptyChecks=0,this.clearSuppressionForUrl(r),this.onSelectionClear({url:r,reason:"selection-cleared"})}maybeClearSelectionForInvalidUrl(e,n){if(!n.lastSelection||!this.isActiveWebViewerLeaf(e)||(n.consecutiveInvalidUrlChecks+=1,n.consecutiveInvalidUrlChecks<this.emptySelectionDebounceCount))return;let r=n.lastSelection.url;n.lastSelection=null,n.consecutiveEmptyChecks=0,n.consecutiveInvalidUrlChecks=0,this.clearSuppressionForUrl(r),this.onSelectionClear({url:r,reason:"invalid-url"})}clearSuppressionForUrl(e){this.suppressedSelectionsByUrl.delete(e.trim())}shouldSuppressSelectionForUrl(e,n){let r=e.trim(),o=this.suppressedSelectionsByUrl.get(r);return o===void 0?!1:o===null?(this.suppressedSelectionsByUrl.set(r,n),!0):o===n?!0:(this.suppressedSelectionsByUrl.delete(r),!1)}suppressSelectionForUrl(e){let n=e.trim();this.isValidUrl(n)&&this.suppressedSelectionsByUrl.set(n,null)}suppressCurrentSelection(){let e=this.getLeaf();if(!e)return;let n=d6(e);this.suppressSelectionForUrl(n.url)}};El();gt();pe();zu();Se();pe();cP();Se();var QBr="bedrock",kkn="amazon-bedrock",ezr="amazonBedrockApiKey";function tzr(t){return t.endsWith(`|${kkn}`)}function nzr(t){let e=Object.values(t.providers??{}).filter(u=>String(u.providerType)===QBr).map(u=>u.providerId),n=new Set(e),r=new Set((t.configuredModels??[]).filter(u=>n.has(u.providerId)).map(u=>u.configuredModelId)),o=u=>!!u&&(r.has(u)||tzr(u)),i={},s=t.activeModels??[],a=s.filter(u=>u.provider!==kkn);a.length!==s.length&&(i.activeModels=a),o(t.defaultModelKey)&&(i.defaultModelKey=""),o(t.quickCommandModelKey)&&(i.quickCommandModelKey=void 0);let l=t.projectList??[];return l.some(u=>o(u.projectModelKey))&&(i.projectList=l.map(u=>o(u.projectModelKey)?{...u,projectModelKey:""}:u)),e.length>0||Object.keys(i).length>0?{providerIds:e,patch:i}:null}function rzr(){try{let t=Ha.getInstance();if(!t.isAvailable())return;t.deleteSecret(ezr)}catch(t){W("[bedrock-removal] could not delete the legacy stored API key",t)}}async function Ikn(t,e){rzr();let n=nzr(e);if(n){Object.keys(n.patch).length>0&&En(n.patch);for(let r of n.providerIds)await t.coordinator.removeProvider(r)}}gt();pe();var ozr=/(^|[-_/.\s])embed(ding)?($|[-_/.\s])/i,izr={anthropic:{providerType:"anthropic",catalogProviderId:"anthropic",opencodeRoutable:!0},openai:{providerType:"openai-compatible",catalogProviderId:"openai",opencodeRoutable:!0},google:{providerType:"google",catalogProviderId:"google",opencodeRoutable:!0},openrouterai:{providerType:"openai-compatible",catalogProviderId:"openrouter",opencodeRoutable:!0},xai:{providerType:"openai-compatible",catalogProviderId:"xai",opencodeRoutable:!0},groq:{providerType:"openai-compatible",catalogProviderId:"groq",opencodeRoutable:!0},mistralai:{providerType:"openai-compatible",catalogProviderId:"mistral",opencodeRoutable:!0},deepseek:{providerType:"openai-compatible",catalogProviderId:"deepseek",opencodeRoutable:!0},siliconflow:{providerType:"openai-compatible",opencodeRoutable:!0},cohereai:{providerType:"openai-compatible",opencodeRoutable:!0},ollama:{providerType:"openai-compatible",opencodeRoutable:!0,requiresBaseUrl:!0},"lm-studio":{providerType:"openai-compatible",opencodeRoutable:!0,requiresBaseUrl:!0},"3rd party (openai-format)":{providerType:"openai-compatible",opencodeRoutable:!0,requiresBaseUrl:!0},"azure openai":{providerType:"azure",opencodeRoutable:!1}},szr=Object.freeze(["chat","opencode"]),azr=Object.freeze(["chat"]);function clt(t){return(t??"").trim().replace(/\/+$/,"").toLowerCase()}function Tkn(t){return Qp[t]}function lzr(t){let e=Tkn(t)?.curlBaseURL;if(!(!e||e.includes("<")||e.includes("{")))return e}function czr(t){return Tkn(t)?.label??t}function uzr(t,e,n){if(n==="azure"){let r={},o=t.azureOpenAIApiInstanceName||e.azureOpenAIApiInstanceName,i=t.azureOpenAIApiDeploymentName||e.azureOpenAIApiDeploymentName,s=t.azureOpenAIApiVersion||e.azureOpenAIApiVersion;return o&&(r.azureInstanceName=o),i&&(r.azureDeploymentName=i),s&&(r.azureApiVersion=s),Object.keys(r).length>0?r:void 0}if(t.provider==="openai"){let r=t.openAIOrgId||e.openAIOrgId;return r?{openAIOrgId:r}:void 0}}function dzr(t,e){let n=izr[t.provider];if(!n||!t.enabled||(t.isEmbeddingModel??ozr.test(t.name)))return null;let r=Goe[t.provider],o=r?e[r]:void 0,i=typeof o=="string"?o.trim():"",s=t.apiKey?.trim()||i||void 0,a;if(n.requiresBaseUrl){if(a=t.baseUrl?.trim()||void 0,!a)return null}else if(a=t.baseUrl?.trim()||lzr(t.provider),!s)return null;return{mapping:n,apiKey:s,baseUrl:a,enableCors:t.enableCors??!1,extras:uzr(t,e,n.providerType)}}function fzr(t){return{id:t.name,displayName:t.displayName?.trim()||t.name}}function pzr(t){let e=new Map;for(let n of t.activeModels??[]){let r=dzr(n,t);if(!r)continue;let{mapping:o,apiKey:i,baseUrl:s,enableCors:a,extras:l}=r,c=[o.providerType,o.catalogProviderId??"",clt(s),i??"",a?"cors":"stream"].join("\0"),u=e.get(c);if(!u){let f={providerType:o.providerType,displayName:czr(n.provider),models:[],autoEnrollIn:o.opencodeRoutable?szr:azr,requiresApiKey:!o.requiresBaseUrl,enableCors:a};o.catalogProviderId&&(f.catalogProviderId=o.catalogProviderId),s&&(f.baseUrl=s),i&&(f.apiKey=i),l&&(f.extras=l),u={input:f,modelsById:new Map},e.set(c,u)}let d=fzr(n);u.modelsById.set(d.id,d)}return[...e.values()].map(({input:n,modelsById:r})=>({...n,models:[...r.values()]}))}function mzr(t,e){return t.origin.kind!=="byok"?!1:t.providerType===e.providerType&&(t.origin.catalogProviderId??"")===(e.catalogProviderId??"")&&clt(t.baseUrl)===clt(e.baseUrl)}async function Pkn(t,e){let n=pzr(e);if(n.length===0){j("[byok-migration] no legacy BYOK providers to migrate");return}let r=t.providerRegistry.listByOrigin("byok"),o=0,i=0,s=0;for(let a of n){if(r.some(l=>mzr(l,a))){i++,j(`[byok-migration] skipping already-present provider "${a.displayName}"`);continue}try{let l=await t.setup.byok.setupProvider(a);o++,j(`[byok-migration] migrated "${a.displayName}" (${l.configuredModelIds.length} models, enroll=${a.autoEnrollIn?.join("+")})`)}catch(l){s++,H(`[byok-migration] failed to migrate "${a.displayName}"; continuing`,l)}}j(`[byok-migration] done: ${o} migrated, ${i} already present, ${s} failed`)}pe();cP();Se();var Akn="github-copilot",hzr=["githubCopilotAccessToken","githubCopilotToken"];function WTe(t){return t?.endsWith(`|${Akn}`)??!1}function gzr(t){let e={},n=t.activeModels??[],r=n.filter(i=>i.provider!==Akn);r.length!==n.length&&(e.activeModels=r),WTe(t.defaultModelKey)&&(e.defaultModelKey=""),WTe(t.quickCommandModelKey)&&(e.quickCommandModelKey=void 0);let o=t.projectList??[];return o.some(i=>WTe(i.projectModelKey))&&(e.projectList=o.map(i=>WTe(i.projectModelKey)?{...i,projectModelKey:""}:i)),Object.keys(e).length>0?e:null}function Ekn(t){let e=gzr(t);e&&En(e);try{let n=Ha.getInstance();if(!n.isAvailable())return;for(let r of hzr)n.deleteSecret(r)}catch(n){W("[github-copilot-removal] could not delete the stored OAuth tokens",n)}}function Mkn(t){let e=!1,n={};for(let[r,o]of Object.entries(t))o.origin.kind==="byok"&&!o.origin.catalogProviderId&&o.providerType==="openai-compatible"&&o.requiresApiKey!==!1?(n[r]={...o,requiresApiKey:!1},e=!0):n[r]=o;return e?n:null}mp();function yzr(t){switch(t.origin.kind){case"agent":return!1;case"copilot-plus":return!1;case"byok":return t.origin.catalogProviderId?!0:!z9(t);default:return!0}}function Okn(t){let e=!1,n={};for(let[r,o]of Object.entries(t))o.requiresApiKey===void 0?(n[r]={...o,requiresApiKey:yzr(o)},e=!0):n[r]=o;return e?n:null}async function Nkn(t){let e=Y().settingsVersion??0;if(!(e>=11)){if(j(`[settings-migration] migrating from v${e} to v${11}`),e<4&&await Pkn(t,Y()),e<5){let n=Okn(Y().providers);n&&En({providers:n})}if(e<6){let n=Y();En({docProcessorBackend:CKt(n)})}if(e<7&&Y().enableMiyo===!0&&En({enableMiyoSearchSkill:!0}),e<8){En({copilotFolder:VF});let n=Y().copilotFolder;En({copilotRootHistory:_C([VF,n])}),En({upgradedToV8FromLegacy:!0})}if(e<9&&Ekn(Y()),e<10){let n=Mkn(Y().providers);n&&En({providers:n})}e<11&&await Ikn(t,Y()),En({settingsVersion:11})}}gt();Se();pe();var Loe=require("obsidian"),g0n=L(B());fm();var VTe=class extends _i{constructor(e,n){super(e,n,'Resetting settings will restore the default values. API keys are not cleared by this action \u2014 use "Delete All Keys" in Advanced Settings \u2192 API Key Storage if you also want to remove them. Are you sure you want to continue?',"Reset Settings")}};yt();ult();_oe();var pC=L(B()),$kn=(0,pC.createContext)(void 0),Dkn=({children:t})=>{let[e,n]=(0,pC.useState)("basic"),r=(0,pC.useMemo)(()=>({selectedTab:e,setSelectedTab:n}),[e]);return pC.default.createElement($kn.Provider,{value:r},t)},KTe=()=>{let t=(0,pC.useContext)($kn);if(t===void 0)throw new Error("useTab must be used within a TabProvider");return t};mp();Se();var St=L(B());yt();c_();var Wi=L(B());SCe();yt();xk();De();var Rl=L(B());var ze=L(B()),EF=L(Es());var Nl=L(B());function Ukn(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return(0,Nl.useMemo)(()=>r=>{e.forEach(o=>o(r))},e)}var xoe=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function CF(t){let e=Object.prototype.toString.call(t);return e==="[object Window]"||e==="[object global]"}function GTe(t){return"nodeType"in t}function Gp(t){var e,n;return t?CF(t)?t:GTe(t)&&(e=(n=t.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function ZTe(t){let{Document:e}=Gp(t);return t instanceof e}function A5(t){return CF(t)?!1:t instanceof Gp(t).HTMLElement}function flt(t){return t instanceof Gp(t).SVGElement}function kF(t){return t?CF(t)?t.document:GTe(t)?ZTe(t)?t:A5(t)||flt(t)?t.ownerDocument:document:document:document}var cw=xoe?Nl.useLayoutEffect:Nl.useEffect;function YTe(t){let e=(0,Nl.useRef)(t);return cw(()=>{e.current=t}),(0,Nl.useCallback)(function(){for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];return e.current==null?void 0:e.current(...r)},[])}function jkn(){let t=(0,Nl.useRef)(null),e=(0,Nl.useCallback)((r,o)=>{t.current=setInterval(r,o)},[]),n=(0,Nl.useCallback)(()=>{t.current!==null&&(clearInterval(t.current),t.current=null)},[]);return[e,n]}function E5(t,e){e===void 0&&(e=[t]);let n=(0,Nl.useRef)(t);return cw(()=>{n.current!==t&&(n.current=t)},e),n}function M5(t,e){let n=(0,Nl.useRef)();return(0,Nl.useMemo)(()=>{let r=t(n.current);return n.current=r,r},[...e])}function Soe(t){let e=YTe(t),n=(0,Nl.useRef)(null),r=(0,Nl.useCallback)(o=>{o!==n.current&&e?.(o,n.current),n.current=o},[]);return[n,r]}function JTe(t){let e=(0,Nl.useRef)();return(0,Nl.useEffect)(()=>{e.current=t},[t]),e.current}var dlt={};function IF(t,e){return(0,Nl.useMemo)(()=>{if(e)return e;let n=dlt[t]==null?0:dlt[t]+1;return dlt[t]=n,t+"-"+n},[t,e])}function Bkn(t){return function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return r.reduce((i,s)=>{let a=Object.entries(s);for(let[l,c]of a){let u=i[l];u!=null&&(i[l]=u+t*c)}return i},{...e})}}var TF=Bkn(1),PF=Bkn(-1);function vzr(t){return"clientX"in t&&"clientY"in t}function Coe(t){if(!t)return!1;let{KeyboardEvent:e}=Gp(t.target);return e&&t instanceof e}function wzr(t){if(!t)return!1;let{TouchEvent:e}=Gp(t.target);return e&&t instanceof e}function XTe(t){if(wzr(t)){if(t.touches&&t.touches.length){let{clientX:e,clientY:n}=t.touches[0];return{x:e,y:n}}else if(t.changedTouches&&t.changedTouches.length){let{clientX:e,clientY:n}=t.changedTouches[0];return{x:e,y:n}}}return vzr(t)?{x:t.clientX,y:t.clientY}:null}var mC=Object.freeze({Translate:{toString(t){if(!t)return;let{x:e,y:n}=t;return"translate3d("+(e?Math.round(e):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(t){if(!t)return;let{scaleX:e,scaleY:n}=t;return"scaleX("+e+") scaleY("+n+")"}},Transform:{toString(t){if(t)return[mC.Translate.toString(t),mC.Scale.toString(t)].join(" ")}},Transition:{toString(t){let{property:e,duration:n,easing:r}=t;return e+" "+n+"ms "+r}}}),Fkn="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function zkn(t){return t.matches(Fkn)?t:t.querySelector(Fkn)}var AF=L(B()),bzr={display:"none"};function Hkn(t){let{id:e,value:n}=t;return AF.default.createElement("div",{id:e,style:bzr},n)}function Wkn(t){let{id:e,announcement:n,ariaLiveType:r="assertive"}=t,o={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return AF.default.createElement("div",{id:e,style:o,role:"status","aria-live":r,"aria-atomic":!0},n)}function Vkn(){let[t,e]=(0,AF.useState)("");return{announce:(0,AF.useCallback)(r=>{r!=null&&e(r)},[]),announcement:t}}var oIn=(0,ze.createContext)(null);function _zr(t){let e=(0,ze.useContext)(oIn);(0,ze.useEffect)(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of <DndContext>");return e(t)},[t,e])}function xzr(){let[t]=(0,ze.useState)(()=>new Set),e=(0,ze.useCallback)(r=>(t.add(r),()=>t.delete(r)),[t]);return[(0,ze.useCallback)(r=>{let{type:o,event:i}=r;t.forEach(s=>{var a;return(a=s[o])==null?void 0:a.call(s,i)})},[t]),e]}var Szr={draggable:`
To pick up a draggable item, press the space bar.
While dragging, use the arrow keys to move the item.
Press space again to drop the item in its new position, or press escape to cancel.
`},Czr={onDragStart(t){let{active:e}=t;return"Picked up draggable item "+e.id+"."},onDragOver(t){let{active:e,over:n}=t;return n?"Draggable item "+e.id+" was moved over droppable area "+n.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(t){let{active:e,over:n}=t;return n?"Draggable item "+e.id+" was dropped over droppable area "+n.id:"Draggable item "+e.id+" was dropped."},onDragCancel(t){let{active:e}=t;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function kzr(t){let{announcements:e=Czr,container:n,hiddenTextDescribedById:r,screenReaderInstructions:o=Szr}=t,{announce:i,announcement:s}=Vkn(),a=IF("DndLiveRegion"),[l,c]=(0,ze.useState)(!1);if((0,ze.useEffect)(()=>{c(!0)},[]),_zr((0,ze.useMemo)(()=>({onDragStart(d){let{active:f}=d;i(e.onDragStart({active:f}))},onDragMove(d){let{active:f,over:p}=d;e.onDragMove&&i(e.onDragMove({active:f,over:p}))},onDragOver(d){let{active:f,over:p}=d;i(e.onDragOver({active:f,over:p}))},onDragEnd(d){let{active:f,over:p}=d;i(e.onDragEnd({active:f,over:p}))},onDragCancel(d){let{active:f,over:p}=d;i(e.onDragCancel({active:f,over:p}))}}),[i,e])),!l)return null;let u=ze.default.createElement(ze.default.Fragment,null,ze.default.createElement(Hkn,{id:r,value:o.draggable}),ze.default.createElement(Wkn,{id:a,announcement:s}));return n?(0,EF.createPortal)(u,n):u}var hu;(function(t){t.DragStart="dragStart",t.DragMove="dragMove",t.DragEnd="dragEnd",t.DragCancel="dragCancel",t.DragOver="dragOver",t.RegisterDroppable="registerDroppable",t.SetDroppableDisabled="setDroppableDisabled",t.UnregisterDroppable="unregisterDroppable"})(hu||(hu={}));function ePe(){}function _lt(t,e){return(0,ze.useMemo)(()=>({sensor:t,options:e??{}}),[t,e])}function iIn(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return(0,ze.useMemo)(()=>[...e].filter(r=>r!=null),[...e])}var E_=Object.freeze({x:0,y:0});function sIn(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function aIn(t,e){let{data:{value:n}}=t,{data:{value:r}}=e;return n-r}function Izr(t,e){let{data:{value:n}}=t,{data:{value:r}}=e;return r-n}function qkn(t){let{left:e,top:n,height:r,width:o}=t;return[{x:e,y:n},{x:e+o,y:n},{x:e,y:n+r},{x:e+o,y:n+r}]}function xlt(t,e){if(!t||t.length===0)return null;let[n]=t;return e?n[e]:n}function Kkn(t,e,n){return e===void 0&&(e=t.left),n===void 0&&(n=t.top),{x:e+t.width*.5,y:n+t.height*.5}}var Slt=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t,o=Kkn(e,e.left,e.top),i=[];for(let s of r){let{id:a}=s,l=n.get(a);if(l){let c=sIn(Kkn(l),o);i.push({id:a,data:{droppableContainer:s,value:c}})}}return i.sort(aIn)},lIn=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t,o=qkn(e),i=[];for(let s of r){let{id:a}=s,l=n.get(a);if(l){let c=qkn(l),u=o.reduce((f,p,m)=>f+sIn(c[m],p),0),d=Number((u/4).toFixed(4));i.push({id:a,data:{droppableContainer:s,value:d}})}}return i.sort(aIn)};function Tzr(t,e){let n=Math.max(e.top,t.top),r=Math.max(e.left,t.left),o=Math.min(e.left+e.width,t.left+t.width),i=Math.min(e.top+e.height,t.top+t.height),s=o-r,a=i-n;if(r<o&&n<i){let l=e.width*e.height,c=t.width*t.height,u=s*a,d=u/(l+c-u);return Number(d.toFixed(4))}return 0}var Pzr=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t,o=[];for(let i of r){let{id:s}=i,a=n.get(s);if(a){let l=Tzr(a,e);l>0&&o.push({id:s,data:{droppableContainer:i,value:l}})}}return o.sort(Izr)};function Azr(t,e,n){return{...t,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function cIn(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:E_}function Ezr(t){return function(n){for(var r=arguments.length,o=new Array(r>1?r-1:0),i=1;i<r;i++)o[i-1]=arguments[i];return o.reduce((s,a)=>({...s,top:s.top+t*a.y,bottom:s.bottom+t*a.y,left:s.left+t*a.x,right:s.right+t*a.x}),{...n})}}var Mzr=Ezr(1);function Ozr(t){if(t.startsWith("matrix3d(")){let e=t.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(t.startsWith("matrix(")){let e=t.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function Nzr(t,e,n){let r=Ozr(e);if(!r)return t;let{scaleX:o,scaleY:i,x:s,y:a}=r,l=t.left-s-(1-o)*parseFloat(n),c=t.top-a-(1-i)*parseFloat(n.slice(n.indexOf(" ")+1)),u=o?t.width/o:t.width,d=i?t.height/i:t.height;return{width:u,height:d,top:c,right:l+u,bottom:c+d,left:l}}var Rzr={ignoreTransform:!1};function NF(t,e){e===void 0&&(e=Rzr);let n=t.getBoundingClientRect();if(e.ignoreTransform){let{transform:c,transformOrigin:u}=Gp(t).getComputedStyle(t);c&&(n=Nzr(n,c,u))}let{top:r,left:o,width:i,height:s,bottom:a,right:l}=n;return{top:r,left:o,width:i,height:s,bottom:a,right:l}}function Gkn(t){return NF(t,{ignoreTransform:!0})}function Lzr(t){let e=t.innerWidth,n=t.innerHeight;return{top:0,left:0,right:e,bottom:n,width:e,height:n}}function $zr(t,e){return e===void 0&&(e=Gp(t).getComputedStyle(t)),e.position==="fixed"}function Dzr(t,e){e===void 0&&(e=Gp(t).getComputedStyle(t));let n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(o=>{let i=e[o];return typeof i=="string"?n.test(i):!1})}function Aoe(t,e){let n=[];function r(o){if(e!=null&&n.length>=e||!o)return n;if(ZTe(o)&&o.scrollingElement!=null&&!n.includes(o.scrollingElement))return n.push(o.scrollingElement),n;if(!A5(o)||flt(o)||n.includes(o))return n;let i=Gp(t).getComputedStyle(o);return o!==t&&Dzr(o,i)&&n.push(o),$zr(o,i)?n:r(o.parentNode)}return t?r(t):n}function uIn(t){let[e]=Aoe(t,1);return e??null}function plt(t){return!xoe||!t?null:CF(t)?t:GTe(t)?ZTe(t)||t===kF(t).scrollingElement?window:A5(t)?t:null:null}function dIn(t){return CF(t)?t.scrollX:t.scrollLeft}function fIn(t){return CF(t)?t.scrollY:t.scrollTop}function glt(t){return{x:dIn(t),y:fIn(t)}}var od;(function(t){t[t.Forward=1]="Forward",t[t.Backward=-1]="Backward"})(od||(od={}));function pIn(t){return!xoe||!t?!1:t===document.scrollingElement}function mIn(t){let e={x:0,y:0},n=pIn(t)?{height:window.innerHeight,width:window.innerWidth}:{height:t.clientHeight,width:t.clientWidth},r={x:t.scrollWidth-n.width,y:t.scrollHeight-n.height},o=t.scrollTop<=e.y,i=t.scrollLeft<=e.x,s=t.scrollTop>=r.y,a=t.scrollLeft>=r.x;return{isTop:o,isLeft:i,isBottom:s,isRight:a,maxScroll:r,minScroll:e}}var Fzr={x:.2,y:.2};function Uzr(t,e,n,r,o){let{top:i,left:s,right:a,bottom:l}=n;r===void 0&&(r=10),o===void 0&&(o=Fzr);let{isTop:c,isBottom:u,isLeft:d,isRight:f}=mIn(t),p={x:0,y:0},m={x:0,y:0},h={height:e.height*o.y,width:e.width*o.x};return!c&&i<=e.top+h.height?(p.y=od.Backward,m.y=r*Math.abs((e.top+h.height-i)/h.height)):!u&&l>=e.bottom-h.height&&(p.y=od.Forward,m.y=r*Math.abs((e.bottom-h.height-l)/h.height)),!f&&a>=e.right-h.width?(p.x=od.Forward,m.x=r*Math.abs((e.right-h.width-a)/h.width)):!d&&s<=e.left+h.width&&(p.x=od.Backward,m.x=r*Math.abs((e.left+h.width-s)/h.width)),{direction:p,speed:m}}function jzr(t){if(t===document.scrollingElement){let{innerWidth:i,innerHeight:s}=window;return{top:0,left:0,right:i,bottom:s,width:i,height:s}}let{top:e,left:n,right:r,bottom:o}=t.getBoundingClientRect();return{top:e,left:n,right:r,bottom:o,width:t.clientWidth,height:t.clientHeight}}function hIn(t){return t.reduce((e,n)=>TF(e,glt(n)),E_)}function Bzr(t){return t.reduce((e,n)=>e+dIn(n),0)}function zzr(t){return t.reduce((e,n)=>e+fIn(n),0)}function Hzr(t,e){if(e===void 0&&(e=NF),!t)return;let{top:n,left:r,bottom:o,right:i}=e(t);uIn(t)&&(o<=0||i<=0||n>=window.innerHeight||r>=window.innerWidth)&&t.scrollIntoView({block:"center",inline:"center"})}var Wzr=[["x",["left","right"],Bzr],["y",["top","bottom"],zzr]],Ioe=class{constructor(e,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;let r=Aoe(n),o=hIn(r);this.rect={...e},this.width=e.width,this.height=e.height;for(let[i,s,a]of Wzr)for(let l of s)Object.defineProperty(this,l,{get:()=>{let c=a(r),u=o[i]-c;return this.rect[l]+u},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}},MF=class{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=e}add(e,n,r){var o;(o=this.target)==null||o.addEventListener(e,n,r),this.listeners.push([e,n,r])}};function Vzr(t){let{EventTarget:e}=Gp(t);return t instanceof e?t:kF(t)}function mlt(t,e){let n=Math.abs(t.x),r=Math.abs(t.y);return typeof e=="number"?Math.sqrt(n**2+r**2)>e:"x"in e&&"y"in e?n>e.x&&r>e.y:"x"in e?n>e.x:"y"in e?r>e.y:!1}var uw;(function(t){t.Click="click",t.DragStart="dragstart",t.Keydown="keydown",t.ContextMenu="contextmenu",t.Resize="resize",t.SelectionChange="selectionchange",t.VisibilityChange="visibilitychange"})(uw||(uw={}));function Zkn(t){t.preventDefault()}function qzr(t){t.stopPropagation()}var Fo;(function(t){t.Space="Space",t.Down="ArrowDown",t.Right="ArrowRight",t.Left="ArrowLeft",t.Up="ArrowUp",t.Esc="Escape",t.Enter="Enter",t.Tab="Tab"})(Fo||(Fo={}));var gIn={start:[Fo.Space,Fo.Enter],cancel:[Fo.Esc],end:[Fo.Space,Fo.Enter,Fo.Tab]},Kzr=(t,e)=>{let{currentCoordinates:n}=e;switch(t.code){case Fo.Right:return{...n,x:n.x+25};case Fo.Left:return{...n,x:n.x-25};case Fo.Down:return{...n,y:n.y+25};case Fo.Up:return{...n,y:n.y-25}}},O5=class{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;let{event:{target:n}}=e;this.props=e,this.listeners=new MF(kF(n)),this.windowListeners=new MF(Gp(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(uw.Resize,this.handleCancel),this.windowListeners.add(uw.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(uw.Keydown,this.handleKeyDown))}handleStart(){let{activeNode:e,onStart:n}=this.props,r=e.node.current;r&&Hzr(r),n(E_)}handleKeyDown(e){if(Coe(e)){let{active:n,context:r,options:o}=this.props,{keyboardCodes:i=gIn,coordinateGetter:s=Kzr,scrollBehavior:a="smooth"}=o,{code:l}=e;if(i.end.includes(l)){this.handleEnd(e);return}if(i.cancel.includes(l)){this.handleCancel(e);return}let{collisionRect:c}=r.current,u=c?{x:c.left,y:c.top}:E_;this.referenceCoordinates||(this.referenceCoordinates=u);let d=s(e,{active:n,context:r.current,currentCoordinates:u});if(d){let f=PF(d,u),p={x:0,y:0},{scrollableAncestors:m}=r.current;for(let h of m){let g=e.code,{isTop:v,isRight:y,isLeft:w,isBottom:_,maxScroll:S,minScroll:I}=mIn(h),C=jzr(h),k={x:Math.min(g===Fo.Right?C.right-C.width/2:C.right,Math.max(g===Fo.Right?C.left:C.left+C.width/2,d.x)),y:Math.min(g===Fo.Down?C.bottom-C.height/2:C.bottom,Math.max(g===Fo.Down?C.top:C.top+C.height/2,d.y))},T=g===Fo.Right&&!y||g===Fo.Left&&!w,P=g===Fo.Down&&!_||g===Fo.Up&&!v;if(T&&k.x!==d.x){let E=h.scrollLeft+f.x,O=g===Fo.Right&&E<=S.x||g===Fo.Left&&E>=I.x;if(O&&!f.y){h.scrollTo({left:E,behavior:a});return}O?p.x=h.scrollLeft-E:p.x=g===Fo.Right?h.scrollLeft-S.x:h.scrollLeft-I.x,p.x&&h.scrollBy({left:-p.x,behavior:a});break}else if(P&&k.y!==d.y){let E=h.scrollTop+f.y,O=g===Fo.Down&&E<=S.y||g===Fo.Up&&E>=I.y;if(O&&!f.x){h.scrollTo({top:E,behavior:a});return}O?p.y=h.scrollTop-E:p.y=g===Fo.Down?h.scrollTop-S.y:h.scrollTop-I.y,p.y&&h.scrollBy({top:-p.y,behavior:a});break}}this.handleMove(e,TF(PF(d,this.referenceCoordinates),p))}}}handleMove(e,n){let{onMove:r}=this.props;e.preventDefault(),r(n)}handleEnd(e){let{onEnd:n}=this.props;e.preventDefault(),this.detach(),n()}handleCancel(e){let{onCancel:n}=this.props;e.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}};O5.activators=[{eventName:"onKeyDown",handler:(t,e,n)=>{let{keyboardCodes:r=gIn,onActivation:o}=e,{active:i}=n,{code:s}=t.nativeEvent;if(r.start.includes(s)){let a=i.activatorNode.current;return a&&t.target!==a?!1:(t.preventDefault(),o?.({event:t.nativeEvent}),!0)}return!1}}];function Ykn(t){return!!(t&&"distance"in t)}function Jkn(t){return!!(t&&"delay"in t)}var Toe=class{constructor(e,n,r){var o;r===void 0&&(r=Vzr(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=n;let{event:i}=e,{target:s}=i;this.props=e,this.events=n,this.document=kF(s),this.documentListeners=new MF(this.document),this.listeners=new MF(r),this.windowListeners=new MF(Gp(s)),this.initialCoordinates=(o=XTe(i))!=null?o:E_,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){let{events:e,props:{options:{activationConstraint:n,bypassActivationConstraint:r}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(uw.Resize,this.handleCancel),this.windowListeners.add(uw.DragStart,Zkn),this.windowListeners.add(uw.VisibilityChange,this.handleCancel),this.windowListeners.add(uw.ContextMenu,Zkn),this.documentListeners.add(uw.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Jkn(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(Ykn(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,n){let{active:r,onPending:o}=this.props;o(r,e,this.initialCoordinates,n)}handleStart(){let{initialCoordinates:e}=this,{onStart:n}=this.props;e&&(this.activated=!0,this.documentListeners.add(uw.Click,qzr,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(uw.SelectionChange,this.removeTextSelection),n(e))}handleMove(e){var n;let{activated:r,initialCoordinates:o,props:i}=this,{onMove:s,options:{activationConstraint:a}}=i;if(!o)return;let l=(n=XTe(e))!=null?n:E_,c=PF(o,l);if(!r&&a){if(Ykn(a)){if(a.tolerance!=null&&mlt(c,a.tolerance))return this.handleCancel();if(mlt(c,a.distance))return this.handleStart()}if(Jkn(a)&&mlt(c,a.tolerance))return this.handleCancel();this.handlePending(a,c);return}e.cancelable&&e.preventDefault(),s(l)}handleEnd(){let{onAbort:e,onEnd:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleCancel(){let{onAbort:e,onCancel:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleKeydown(e){e.code===Fo.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}},Gzr={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}},N5=class extends Toe{constructor(e){let{event:n}=e,r=kF(n.target);super(e,Gzr,r)}};N5.activators=[{eventName:"onPointerDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;return!n.isPrimary||n.button!==0?!1:(r?.({event:n}),!0)}}];var Zzr={move:{name:"mousemove"},end:{name:"mouseup"}},ylt;(function(t){t[t.RightClick=2]="RightClick"})(ylt||(ylt={}));var vlt=class extends Toe{constructor(e){super(e,Zzr,kF(e.event.target))}};vlt.activators=[{eventName:"onMouseDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;return n.button===ylt.RightClick?!1:(r?.({event:n}),!0)}}];var hlt={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}},wlt=class extends Toe{constructor(e){super(e,hlt)}static setup(){return window.addEventListener(hlt.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(hlt.move.name,e)};function e(){}}};wlt.activators=[{eventName:"onTouchStart",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e,{touches:o}=n;return o.length>1?!1:(r?.({event:n}),!0)}}];var koe;(function(t){t[t.Pointer=0]="Pointer",t[t.DraggableRect=1]="DraggableRect"})(koe||(koe={}));var tPe;(function(t){t[t.TreeOrder=0]="TreeOrder",t[t.ReversedTreeOrder=1]="ReversedTreeOrder"})(tPe||(tPe={}));function Yzr(t){let{acceleration:e,activator:n=koe.Pointer,canScroll:r,draggingRect:o,enabled:i,interval:s=5,order:a=tPe.TreeOrder,pointerCoordinates:l,scrollableAncestors:c,scrollableAncestorRects:u,delta:d,threshold:f}=t,p=Xzr({delta:d,disabled:!i}),[m,h]=jkn(),g=(0,ze.useRef)({x:0,y:0}),v=(0,ze.useRef)({x:0,y:0}),y=(0,ze.useMemo)(()=>{switch(n){case koe.Pointer:return l?{top:l.y,bottom:l.y,left:l.x,right:l.x}:null;case koe.DraggableRect:return o}},[n,o,l]),w=(0,ze.useRef)(null),_=(0,ze.useCallback)(()=>{let I=w.current;if(!I)return;let C=g.current.x*v.current.x,k=g.current.y*v.current.y;I.scrollBy(C,k)},[]),S=(0,ze.useMemo)(()=>a===tPe.TreeOrder?[...c].reverse():c,[a,c]);(0,ze.useEffect)(()=>{if(!i||!c.length||!y){h();return}for(let I of S){if(r?.(I)===!1)continue;let C=c.indexOf(I),k=u[C];if(!k)continue;let{direction:T,speed:P}=Uzr(I,k,y,e,f);for(let E of["x","y"])p[E][T[E]]||(P[E]=0,T[E]=0);if(P.x>0||P.y>0){h(),w.current=I,m(_,s),g.current=P,v.current=T;return}}g.current={x:0,y:0},v.current={x:0,y:0},h()},[e,_,r,h,i,s,JSON.stringify(y),JSON.stringify(p),m,c,S,u,JSON.stringify(f)])}var Jzr={x:{[od.Backward]:!1,[od.Forward]:!1},y:{[od.Backward]:!1,[od.Forward]:!1}};function Xzr(t){let{delta:e,disabled:n}=t,r=JTe(e);return M5(o=>{if(n||!r||!o)return Jzr;let i={x:Math.sign(e.x-r.x),y:Math.sign(e.y-r.y)};return{x:{[od.Backward]:o.x[od.Backward]||i.x===-1,[od.Forward]:o.x[od.Forward]||i.x===1},y:{[od.Backward]:o.y[od.Backward]||i.y===-1,[od.Forward]:o.y[od.Forward]||i.y===1}}},[n,e,r])}function Qzr(t,e){let n=e!=null?t.get(e):void 0,r=n?n.node.current:null;return M5(o=>{var i;return e==null?null:(i=r??o)!=null?i:null},[r,e])}function e4r(t,e){return(0,ze.useMemo)(()=>t.reduce((n,r)=>{let{sensor:o}=r,i=o.activators.map(s=>({eventName:s.eventName,handler:e(s.handler,r)}));return[...n,...i]},[]),[t,e])}var Poe;(function(t){t[t.Always=0]="Always",t[t.BeforeDragging=1]="BeforeDragging",t[t.WhileDragging=2]="WhileDragging"})(Poe||(Poe={}));var blt;(function(t){t.Optimized="optimized"})(blt||(blt={}));var Xkn=new Map;function t4r(t,e){let{dragging:n,dependencies:r,config:o}=e,[i,s]=(0,ze.useState)(null),{frequency:a,measure:l,strategy:c}=o,u=(0,ze.useRef)(t),d=g(),f=E5(d),p=(0,ze.useCallback)(function(v){v===void 0&&(v=[]),!f.current&&s(y=>y===null?v:y.concat(v.filter(w=>!y.includes(w))))},[f]),m=(0,ze.useRef)(null),h=M5(v=>{if(d&&!n)return Xkn;if(!v||v===Xkn||u.current!==t||i!=null){let y=new Map;for(let w of t){if(!w)continue;if(i&&i.length>0&&!i.includes(w.id)&&w.rect.current){y.set(w.id,w.rect.current);continue}let _=w.node.current,S=_?new Ioe(l(_),_):null;w.rect.current=S,S&&y.set(w.id,S)}return y}return v},[t,i,n,d,l]);return(0,ze.useEffect)(()=>{u.current=t},[t]),(0,ze.useEffect)(()=>{d||p()},[n,d]),(0,ze.useEffect)(()=>{i&&i.length>0&&s(null)},[JSON.stringify(i)]),(0,ze.useEffect)(()=>{d||typeof a!="number"||m.current!==null||(m.current=setTimeout(()=>{p(),m.current=null},a))},[a,d,p,...r]),{droppableRects:h,measureDroppableContainers:p,measuringScheduled:i!=null};function g(){switch(c){case Poe.Always:return!1;case Poe.BeforeDragging:return n;default:return!n}}}function yIn(t,e){return M5(n=>t?n||(typeof e=="function"?e(t):t):null,[e,t])}function n4r(t,e){return yIn(t,e)}function r4r(t){let{callback:e,disabled:n}=t,r=YTe(e),o=(0,ze.useMemo)(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;let{MutationObserver:i}=window;return new i(r)},[r,n]);return(0,ze.useEffect)(()=>()=>o?.disconnect(),[o]),o}function nPe(t){let{callback:e,disabled:n}=t,r=YTe(e),o=(0,ze.useMemo)(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;let{ResizeObserver:i}=window;return new i(r)},[n]);return(0,ze.useEffect)(()=>()=>o?.disconnect(),[o]),o}function o4r(t){return new Ioe(NF(t),t)}function Qkn(t,e,n){e===void 0&&(e=o4r);let[r,o]=(0,ze.useState)(null);function i(){o(l=>{if(!t)return null;if(t.isConnected===!1){var c;return(c=l??n)!=null?c:null}let u=e(t);return JSON.stringify(l)===JSON.stringify(u)?l:u})}let s=r4r({callback(l){if(t)for(let c of l){let{type:u,target:d}=c;if(u==="childList"&&d instanceof HTMLElement&&d.contains(t)){i();break}}}}),a=nPe({callback:i});return cw(()=>{i(),t?(a?.observe(t),s?.observe(document.body,{childList:!0,subtree:!0})):(a?.disconnect(),s?.disconnect())},[t]),r}function i4r(t){let e=yIn(t);return cIn(t,e)}var eIn=[];function s4r(t){let e=(0,ze.useRef)(t),n=M5(r=>t?r&&r!==eIn&&t&&e.current&&t.parentNode===e.current.parentNode?r:Aoe(t):eIn,[t]);return(0,ze.useEffect)(()=>{e.current=t},[t]),n}function a4r(t){let[e,n]=(0,ze.useState)(null),r=(0,ze.useRef)(t),o=(0,ze.useCallback)(i=>{let s=plt(i.target);s&&n(a=>a?(a.set(s,glt(s)),new Map(a)):null)},[]);return(0,ze.useEffect)(()=>{let i=r.current;if(t!==i){s(i);let a=t.map(l=>{let c=plt(l);return c?(c.addEventListener("scroll",o,{passive:!0}),[c,glt(c)]):null}).filter(l=>l!=null);n(a.length?new Map(a):null),r.current=t}return()=>{s(t),s(i)};function s(a){a.forEach(l=>{let c=plt(l);c?.removeEventListener("scroll",o)})}},[o,t]),(0,ze.useMemo)(()=>t.length?e?Array.from(e.values()).reduce((i,s)=>TF(i,s),E_):hIn(t):E_,[t,e])}function tIn(t,e){e===void 0&&(e=[]);let n=(0,ze.useRef)(null);return(0,ze.useEffect)(()=>{n.current=null},e),(0,ze.useEffect)(()=>{let r=t!==E_;r&&!n.current&&(n.current=t),!r&&n.current&&(n.current=null)},[t]),n.current?PF(t,n.current):E_}function l4r(t){(0,ze.useEffect)(()=>{if(!xoe)return;let e=t.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(let n of e)n?.()}},t.map(e=>{let{sensor:n}=e;return n}))}function c4r(t,e){return(0,ze.useMemo)(()=>t.reduce((n,r)=>{let{eventName:o,handler:i}=r;return n[o]=s=>{i(s,e)},n},{}),[t,e])}function vIn(t){return(0,ze.useMemo)(()=>t?Lzr(t):null,[t])}var nIn=[];function u4r(t,e){e===void 0&&(e=NF);let[n]=t,r=vIn(n?Gp(n):null),[o,i]=(0,ze.useState)(nIn);function s(){i(()=>t.length?t.map(l=>pIn(l)?r:new Ioe(e(l),l)):nIn)}let a=nPe({callback:s});return cw(()=>{a?.disconnect(),s(),t.forEach(l=>a?.observe(l))},[t]),o}function d4r(t){if(!t)return null;if(t.children.length>1)return t;let e=t.children[0];return A5(e)?e:t}function f4r(t){let{measure:e}=t,[n,r]=(0,ze.useState)(null),o=(0,ze.useCallback)(c=>{for(let{target:u}of c)if(A5(u)){r(d=>{let f=e(u);return d?{...d,width:f.width,height:f.height}:f});break}},[e]),i=nPe({callback:o}),s=(0,ze.useCallback)(c=>{let u=d4r(c);i?.disconnect(),u&&i?.observe(u),r(u?e(u):null)},[e,i]),[a,l]=Soe(s);return(0,ze.useMemo)(()=>({nodeRef:a,rect:n,setRef:l}),[n,a,l])}var p4r=[{sensor:N5,options:{}},{sensor:O5,options:{}}],m4r={current:{}},QTe={draggable:{measure:Gkn},droppable:{measure:Gkn,strategy:Poe.WhileDragging,frequency:blt.Optimized},dragOverlay:{measure:NF}},OF=class extends Map{get(e){var n;return e!=null&&(n=super.get(e))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:n}=e;return!n})}getNodeFor(e){var n,r;return(n=(r=this.get(e))==null?void 0:r.node.current)!=null?n:void 0}},h4r={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new OF,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:ePe},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:QTe,measureDroppableContainers:ePe,windowRect:null,measuringScheduled:!1},g4r={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:ePe,draggableNodes:new Map,over:null,measureDroppableContainers:ePe},rPe=(0,ze.createContext)(g4r),wIn=(0,ze.createContext)(h4r);function y4r(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new OF}}}function v4r(t,e){switch(e.type){case hu.DragStart:return{...t,draggable:{...t.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case hu.DragMove:return t.draggable.active==null?t:{...t,draggable:{...t.draggable,translate:{x:e.coordinates.x-t.draggable.initialCoordinates.x,y:e.coordinates.y-t.draggable.initialCoordinates.y}}};case hu.DragEnd:case hu.DragCancel:return{...t,draggable:{...t.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case hu.RegisterDroppable:{let{element:n}=e,{id:r}=n,o=new OF(t.droppable.containers);return o.set(r,n),{...t,droppable:{...t.droppable,containers:o}}}case hu.SetDroppableDisabled:{let{id:n,key:r,disabled:o}=e,i=t.droppable.containers.get(n);if(!i||r!==i.key)return t;let s=new OF(t.droppable.containers);return s.set(n,{...i,disabled:o}),{...t,droppable:{...t.droppable,containers:s}}}case hu.UnregisterDroppable:{let{id:n,key:r}=e,o=t.droppable.containers.get(n);if(!o||r!==o.key)return t;let i=new OF(t.droppable.containers);return i.delete(n),{...t,droppable:{...t.droppable,containers:i}}}default:return t}}function w4r(t){let{disabled:e}=t,{active:n,activatorEvent:r,draggableNodes:o}=(0,ze.useContext)(rPe),i=JTe(r),s=JTe(n?.id);return(0,ze.useEffect)(()=>{if(!e&&!r&&i&&s!=null){if(!Coe(i)||document.activeElement===i.target)return;let a=o.get(s);if(!a)return;let{activatorNode:l,node:c}=a;if(!l.current&&!c.current)return;requestAnimationFrame(()=>{for(let u of[l.current,c.current]){if(!u)continue;let d=zkn(u);if(d){d.focus();break}}})}},[r,e,o,s,i]),null}function b4r(t,e){let{transform:n,...r}=e;return t!=null&&t.length?t.reduce((o,i)=>i({transform:o,...r}),n):n}function _4r(t){return(0,ze.useMemo)(()=>({draggable:{...QTe.draggable,...t?.draggable},droppable:{...QTe.droppable,...t?.droppable},dragOverlay:{...QTe.dragOverlay,...t?.dragOverlay}}),[t?.draggable,t?.droppable,t?.dragOverlay])}function x4r(t){let{activeNode:e,measure:n,initialRect:r,config:o=!0}=t,i=(0,ze.useRef)(!1),{x:s,y:a}=typeof o=="boolean"?{x:o,y:o}:o;cw(()=>{if(!s&&!a||!e){i.current=!1;return}if(i.current||!r)return;let c=e?.node.current;if(!c||c.isConnected===!1)return;let u=n(c),d=cIn(u,r);if(s||(d.x=0),a||(d.y=0),i.current=!0,Math.abs(d.x)>0||Math.abs(d.y)>0){let f=uIn(c);f&&f.scrollBy({top:d.y,left:d.x})}},[e,s,a,r,n])}var bIn=(0,ze.createContext)({...E_,scaleX:1,scaleY:1}),MO;(function(t){t[t.Uninitialized=0]="Uninitialized",t[t.Initializing=1]="Initializing",t[t.Initialized=2]="Initialized"})(MO||(MO={}));var Clt=(0,ze.memo)(function(e){var n,r,o,i;let{id:s,accessibility:a,autoScroll:l=!0,children:c,sensors:u=p4r,collisionDetection:d=Pzr,measuring:f,modifiers:p,...m}=e,h=(0,ze.useReducer)(v4r,void 0,y4r),[g,v]=h,[y,w]=xzr(),[_,S]=(0,ze.useState)(MO.Uninitialized),I=_===MO.Initialized,{draggable:{active:C,nodes:k,translate:T},droppable:{containers:P}}=g,E=C!=null?k.get(C):null,O=(0,ze.useRef)({initial:null,translated:null}),$=(0,ze.useMemo)(()=>{var ct;return C!=null?{id:C,data:(ct=E?.data)!=null?ct:m4r,rect:O}:null},[C,E]),U=(0,ze.useRef)(null),[V,K]=(0,ze.useState)(null),[se,le]=(0,ze.useState)(null),Q=E5(m,Object.values(m)),ne=IF("DndDescribedBy",s),ee=(0,ze.useMemo)(()=>P.getEnabled(),[P]),ae=_4r(f),{droppableRects:q,measureDroppableContainers:F,measuringScheduled:z}=t4r(ee,{dragging:I,dependencies:[T.x,T.y],config:ae.droppable}),N=Qzr(k,C),R=(0,ze.useMemo)(()=>se?XTe(se):null,[se]),X=wu(),D=n4r(N,ae.draggable.measure);x4r({activeNode:C!=null?k.get(C):null,config:X.layoutShiftCompensation,initialRect:D,measure:ae.draggable.measure});let G=Qkn(N,ae.draggable.measure,D),ce=Qkn(N?N.parentElement:null),Z=(0,ze.useRef)({activatorEvent:null,active:null,activeNode:N,collisionRect:null,collisions:null,droppableRects:q,draggableNodes:k,draggingNode:null,draggingNodeRect:null,droppableContainers:P,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),te=P.getNodeFor((n=Z.current.over)==null?void 0:n.id),fe=f4r({measure:ae.dragOverlay.measure}),de=(r=fe.nodeRef.current)!=null?r:N,ye=I?(o=fe.rect)!=null?o:G:null,Te=!!(fe.nodeRef.current&&fe.rect),Be=i4r(Te?null:G),qe=vIn(de?Gp(de):null),Ae=s4r(I?te??N:null),Xt=u4r(Ae),Ve=b4r(p,{transform:{x:T.x-Be.x,y:T.y-Be.y,scaleX:1,scaleY:1},activatorEvent:se,active:$,activeNodeRect:G,containerNodeRect:ce,draggingNodeRect:ye,over:Z.current.over,overlayNodeRect:fe.rect,scrollableAncestors:Ae,scrollableAncestorRects:Xt,windowRect:qe}),Ee=R?TF(R,T):null,st=a4r(Ae),Ne=tIn(st),He=tIn(st,[G]),et=TF(Ve,Ne),it=ye?Mzr(ye,Ve):null,Br=$&&it?d({active:$,collisionRect:it,droppableRects:q,droppableContainers:ee,pointerCoordinates:Ee}):null,Xr=xlt(Br,"id"),[An,zn]=(0,ze.useState)(null),Yp=Te?Ve:TF(Ve,He),la=Azr(Yp,(i=An?.rect)!=null?i:null,G),vu=(0,ze.useRef)(null),Ds=(0,ze.useCallback)((ct,Qt)=>{let{sensor:ir,options:Ct}=Qt;if(U.current==null)return;let wt=k.get(U.current);if(!wt)return;let _t=ct.nativeEvent,an=new ir({active:U.current,activeNode:wt,event:_t,options:Ct,context:Z,onAbort(Vo){if(!k.get(Vo))return;let{onDragAbort:Vt}=Q.current,vi={id:Vo};Vt?.(vi),y({type:"onDragAbort",event:vi})},onPending(Vo,ny,Vt,vi){if(!k.get(Vo))return;let{onDragPending:ry}=Q.current,pc={id:Vo,constraint:ny,initialCoordinates:Vt,offset:vi};ry?.(pc),y({type:"onDragPending",event:pc})},onStart(Vo){let ny=U.current;if(ny==null)return;let Vt=k.get(ny);if(!Vt)return;let{onDragStart:vi}=Q.current,fc={activatorEvent:_t,active:{id:ny,data:Vt.data,rect:O}};(0,EF.unstable_batchedUpdates)(()=>{vi?.(fc),S(MO.Initializing),v({type:hu.DragStart,initialCoordinates:Vo,active:ny}),y({type:"onDragStart",event:fc}),K(vu.current),le(_t)})},onMove(Vo){v({type:hu.DragMove,coordinates:Vo})},onEnd:Qr(hu.DragEnd),onCancel:Qr(hu.DragCancel)});vu.current=an;function Qr(Vo){return async function(){let{active:Vt,collisions:vi,over:fc,scrollAdjustedTranslate:ry}=Z.current,pc=null;if(Vt&&ry){let{cancelDrop:pw}=Q.current;pc={activatorEvent:_t,active:Vt,collisions:vi,delta:ry,over:fc},Vo===hu.DragEnd&&typeof pw=="function"&&await Promise.resolve(pw(pc))&&(Vo=hu.DragCancel)}U.current=null,(0,EF.unstable_batchedUpdates)(()=>{v({type:Vo}),S(MO.Uninitialized),zn(null),K(null),le(null),vu.current=null;let pw=Vo===hu.DragEnd?"onDragEnd":"onDragCancel";if(pc){let DO=Q.current[pw];DO?.(pc),y({type:pw,event:pc})}})}}},[k]),hh=(0,ze.useCallback)((ct,Qt)=>(ir,Ct)=>{let wt=ir.nativeEvent,_t=k.get(Ct);if(U.current!==null||!_t||wt.dndKit||wt.defaultPrevented)return;let an={active:_t};ct(ir,Qt.options,an)===!0&&(wt.dndKit={capturedBy:Qt.sensor},U.current=Ct,Ds(ir,Qt))},[k,Ds]),N_=e4r(u,hh);l4r(u),cw(()=>{G&&_===MO.Initializing&&S(MO.Initialized)},[G,_]),(0,ze.useEffect)(()=>{let{onDragMove:ct}=Q.current,{active:Qt,activatorEvent:ir,collisions:Ct,over:wt}=Z.current;if(!Qt||!ir)return;let _t={active:Qt,activatorEvent:ir,collisions:Ct,delta:{x:et.x,y:et.y},over:wt};(0,EF.unstable_batchedUpdates)(()=>{ct?.(_t),y({type:"onDragMove",event:_t})})},[et.x,et.y]),(0,ze.useEffect)(()=>{let{active:ct,activatorEvent:Qt,collisions:ir,droppableContainers:Ct,scrollAdjustedTranslate:wt}=Z.current;if(!ct||U.current==null||!Qt||!wt)return;let{onDragOver:_t}=Q.current,an=Ct.get(Xr),Qr=an&&an.rect.current?{id:an.id,rect:an.rect.current,data:an.data,disabled:an.disabled}:null,Vo={active:ct,activatorEvent:Qt,collisions:ir,delta:{x:wt.x,y:wt.y},over:Qr};(0,EF.unstable_batchedUpdates)(()=>{zn(Qr),_t?.(Vo),y({type:"onDragOver",event:Vo})})},[Xr]),cw(()=>{Z.current={activatorEvent:se,active:$,activeNode:N,collisionRect:it,collisions:Br,droppableRects:q,draggableNodes:k,draggingNode:de,draggingNodeRect:ye,droppableContainers:P,over:An,scrollableAncestors:Ae,scrollAdjustedTranslate:et},O.current={initial:ye,translated:it}},[$,N,Br,it,k,de,ye,q,P,An,Ae,et]),Yzr({...X,delta:T,draggingRect:it,pointerCoordinates:Ee,scrollableAncestors:Ae,scrollableAncestorRects:Xt});let ty=(0,ze.useMemo)(()=>({active:$,activeNode:N,activeNodeRect:G,activatorEvent:se,collisions:Br,containerNodeRect:ce,dragOverlay:fe,draggableNodes:k,droppableContainers:P,droppableRects:q,over:An,measureDroppableContainers:F,scrollableAncestors:Ae,scrollableAncestorRects:Xt,measuringConfiguration:ae,measuringScheduled:z,windowRect:qe}),[$,N,G,se,Br,ce,fe,k,P,q,An,F,Ae,Xt,ae,z,qe]),fl=(0,ze.useMemo)(()=>({activatorEvent:se,activators:N_,active:$,activeNodeRect:G,ariaDescribedById:{draggable:ne},dispatch:v,draggableNodes:k,over:An,measureDroppableContainers:F}),[se,N_,$,G,v,ne,k,An,F]);return ze.default.createElement(oIn.Provider,{value:w},ze.default.createElement(rPe.Provider,{value:fl},ze.default.createElement(wIn.Provider,{value:ty},ze.default.createElement(bIn.Provider,{value:la},c)),ze.default.createElement(w4r,{disabled:a?.restoreFocus===!1})),ze.default.createElement(kzr,{...a,hiddenTextDescribedById:ne}));function wu(){let ct=V?.autoScrollEnabled===!1,Qt=typeof l=="object"?l.enabled===!1:l===!1,ir=I&&!ct&&!Qt;return typeof l=="object"?{...l,enabled:ir}:{enabled:ir}}}),S4r=(0,ze.createContext)(null),rIn="button",C4r="Draggable";function _In(t){let{id:e,data:n,disabled:r=!1,attributes:o}=t,i=IF(C4r),{activators:s,activatorEvent:a,active:l,activeNodeRect:c,ariaDescribedById:u,draggableNodes:d,over:f}=(0,ze.useContext)(rPe),{role:p=rIn,roleDescription:m="draggable",tabIndex:h=0}=o??{},g=l?.id===e,v=(0,ze.useContext)(g?bIn:S4r),[y,w]=Soe(),[_,S]=Soe(),I=c4r(s,e),C=E5(n);cw(()=>(d.set(e,{id:e,key:i,node:y,activatorNode:_,data:C}),()=>{let T=d.get(e);T&&T.key===i&&d.delete(e)}),[d,e]);let k=(0,ze.useMemo)(()=>({role:p,tabIndex:h,"aria-disabled":r,"aria-pressed":g&&p===rIn?!0:void 0,"aria-roledescription":m,"aria-describedby":u.draggable}),[r,p,h,g,m,u.draggable]);return{active:l,activatorEvent:a,activeNodeRect:c,attributes:k,isDragging:g,listeners:r?void 0:I,node:y,over:f,setNodeRef:w,setActivatorNodeRef:S,transform:v}}function xIn(){return(0,ze.useContext)(wIn)}var k4r="Droppable",I4r={timeout:25};function SIn(t){let{data:e,disabled:n=!1,id:r,resizeObserverConfig:o}=t,i=IF(k4r),{active:s,dispatch:a,over:l,measureDroppableContainers:c}=(0,ze.useContext)(rPe),u=(0,ze.useRef)({disabled:n}),d=(0,ze.useRef)(!1),f=(0,ze.useRef)(null),p=(0,ze.useRef)(null),{disabled:m,updateMeasurementsFor:h,timeout:g}={...I4r,...o},v=E5(h??r),y=(0,ze.useCallback)(()=>{if(!d.current){d.current=!0;return}p.current!=null&&clearTimeout(p.current),p.current=setTimeout(()=>{c(Array.isArray(v.current)?v.current:[v.current]),p.current=null},g)},[g]),w=nPe({callback:y,disabled:m||!s}),_=(0,ze.useCallback)((k,T)=>{w&&(T&&(w.unobserve(T),d.current=!1),k&&w.observe(k))},[w]),[S,I]=Soe(_),C=E5(e);return(0,ze.useEffect)(()=>{!w||!S.current||(w.disconnect(),d.current=!1,w.observe(S.current))},[S,w]),(0,ze.useEffect)(()=>(a({type:hu.RegisterDroppable,element:{id:r,key:i,disabled:n,node:S,rect:f,data:C}}),()=>a({type:hu.UnregisterDroppable,key:i,id:r})),[r]),(0,ze.useEffect)(()=>{n!==u.current.disabled&&(a({type:hu.SetDroppableDisabled,id:r,key:i,disabled:n}),u.current.disabled=n)},[r,i,n,a]),{active:s,rect:f,isOver:l?.id===r,node:S,over:l,setNodeRef:I}}function CIn(t,e,n){let r=t.slice();return r.splice(n<0?r.length+n:n,0,r.splice(e,1)[0]),r}function T4r(t,e){return t.reduce((n,r,o)=>{let i=e.get(r);return i&&(n[o]=i),n},Array(t.length))}function oPe(t){return t!==null&&t>=0}function P4r(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function A4r(t){return typeof t=="boolean"?{draggable:t,droppable:t}:t}var kIn=t=>{let{rects:e,activeIndex:n,overIndex:r,index:o}=t,i=CIn(e,r,n),s=e[o],a=i[o];return!a||!s?null:{x:a.left-s.left,y:a.top-s.top,scaleX:a.width/s.width,scaleY:a.height/s.height}};var iPe={scaleX:1,scaleY:1},klt=t=>{var e;let{activeIndex:n,activeNodeRect:r,index:o,rects:i,overIndex:s}=t,a=(e=i[n])!=null?e:r;if(!a)return null;if(o===n){let c=i[s];return c?{x:0,y:n<s?c.top+c.height-(a.top+a.height):c.top-a.top,...iPe}:null}let l=E4r(i,o,n);return o>n&&o<=s?{x:0,y:-a.height-l,...iPe}:o<n&&o>=s?{x:0,y:a.height+l,...iPe}:{x:0,y:0,...iPe}};function E4r(t,e,n){let r=t[e],o=t[e-1],i=t[e+1];return r?n<e?o?r.top-(o.top+o.height):i?i.top-(r.top+r.height):0:i?i.top-(r.top+r.height):o?r.top-(o.top+o.height):0:0}var IIn="Sortable",TIn=Rl.default.createContext({activeIndex:-1,containerId:IIn,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:kIn,disabled:{draggable:!1,droppable:!1}});function Ilt(t){let{children:e,id:n,items:r,strategy:o=kIn,disabled:i=!1}=t,{active:s,dragOverlay:a,droppableRects:l,over:c,measureDroppableContainers:u}=xIn(),d=IF(IIn,n),f=a.rect!==null,p=(0,Rl.useMemo)(()=>r.map(I=>typeof I=="object"&&"id"in I?I.id:I),[r]),m=s!=null,h=s?p.indexOf(s.id):-1,g=c?p.indexOf(c.id):-1,v=(0,Rl.useRef)(p),y=!P4r(p,v.current),w=g!==-1&&h===-1||y,_=A4r(i);cw(()=>{y&&m&&u(p)},[y,p,m,u]),(0,Rl.useEffect)(()=>{v.current=p},[p]);let S=(0,Rl.useMemo)(()=>({activeIndex:h,containerId:d,disabled:_,disableTransforms:w,items:p,overIndex:g,useDragOverlay:f,sortedRects:T4r(p,l),strategy:o}),[h,d,_.draggable,_.droppable,w,p,g,l,f,o]);return Rl.default.createElement(TIn.Provider,{value:S},e)}var M4r=t=>{let{id:e,items:n,activeIndex:r,overIndex:o}=t;return CIn(n,r,o).indexOf(e)},O4r=t=>{let{containerId:e,isSorting:n,wasDragging:r,index:o,items:i,newIndex:s,previousItems:a,previousContainerId:l,transition:c}=t;return!c||!r||a!==i&&o===s?!1:n?!0:s!==o&&e===l},N4r={duration:200,easing:"ease"},PIn="transform",R4r=mC.Transition.toString({property:PIn,duration:0,easing:"linear"}),L4r={roleDescription:"sortable"};function $4r(t){let{disabled:e,index:n,node:r,rect:o}=t,[i,s]=(0,Rl.useState)(null),a=(0,Rl.useRef)(n);return cw(()=>{if(!e&&n!==a.current&&r.current){let l=o.current;if(l){let c=NF(r.current,{ignoreTransform:!0}),u={x:l.left-c.left,y:l.top-c.top,scaleX:l.width/c.width,scaleY:l.height/c.height};(u.x||u.y)&&s(u)}}n!==a.current&&(a.current=n)},[e,n,r,o]),(0,Rl.useEffect)(()=>{i&&s(null)},[i]),i}function aPe(t){let{animateLayoutChanges:e=O4r,attributes:n,disabled:r,data:o,getNewIndex:i=M4r,id:s,strategy:a,resizeObserverConfig:l,transition:c=N4r}=t,{items:u,containerId:d,activeIndex:f,disabled:p,disableTransforms:m,sortedRects:h,overIndex:g,useDragOverlay:v,strategy:y}=(0,Rl.useContext)(TIn),w=D4r(r,p),_=u.indexOf(s),S=(0,Rl.useMemo)(()=>({sortable:{containerId:d,index:_,items:u},...o}),[d,o,_,u]),I=(0,Rl.useMemo)(()=>u.slice(u.indexOf(s)),[u,s]),{rect:C,node:k,isOver:T,setNodeRef:P}=SIn({id:s,data:S,disabled:w.droppable,resizeObserverConfig:{updateMeasurementsFor:I,...l}}),{active:E,activatorEvent:O,activeNodeRect:$,attributes:U,setNodeRef:V,listeners:K,isDragging:se,over:le,setActivatorNodeRef:Q,transform:ne}=_In({id:s,data:S,attributes:{...L4r,...n},disabled:w.draggable}),ee=Ukn(P,V),ae=!!E,q=ae&&!m&&oPe(f)&&oPe(g),F=!v&&se,z=F&&q?ne:null,R=q?z??(a??y)({rects:h,activeNodeRect:$,activeIndex:f,overIndex:g,index:_}):null,X=oPe(f)&&oPe(g)?i({id:s,items:u,activeIndex:f,overIndex:g}):_,D=E?.id,G=(0,Rl.useRef)({activeId:D,items:u,newIndex:X,containerId:d}),ce=u!==G.current.items,Z=e({active:E,containerId:d,isDragging:se,isSorting:ae,id:s,index:_,items:u,newIndex:G.current.newIndex,previousItems:G.current.items,previousContainerId:G.current.containerId,transition:c,wasDragging:G.current.activeId!=null}),te=$4r({disabled:!Z,index:_,node:k,rect:C});return(0,Rl.useEffect)(()=>{ae&&G.current.newIndex!==X&&(G.current.newIndex=X),d!==G.current.containerId&&(G.current.containerId=d),u!==G.current.items&&(G.current.items=u)},[ae,X,d,u]),(0,Rl.useEffect)(()=>{if(D===G.current.activeId)return;if(D!=null&&G.current.activeId==null){G.current.activeId=D;return}let de=setTimeout(()=>{G.current.activeId=D},50);return()=>clearTimeout(de)},[D]),{active:E,activeIndex:f,attributes:U,data:S,rect:C,index:_,newIndex:X,items:u,isOver:T,isSorting:ae,isDragging:se,listeners:K,node:k,overIndex:g,over:le,setNodeRef:ee,setActivatorNodeRef:Q,setDroppableNodeRef:P,setDraggableNodeRef:V,transform:te??R,transition:fe()};function fe(){if(te||ce&&G.current.newIndex===_)return R4r;if(!(F&&!Coe(O)||!c)&&(ae||Z))return mC.Transition.toString({...c,property:PIn})}}function D4r(t,e){var n,r;return typeof t=="boolean"?{draggable:t,droppable:!1}:{draggable:(n=t?.draggable)!=null?n:e.draggable,droppable:(r=t?.droppable)!=null?r:e.droppable}}function sPe(t){if(!t)return!1;let e=t.data.current;return!!(e&&"sortable"in e&&typeof e.sortable=="object"&&"containerId"in e.sortable&&"items"in e.sortable&&"index"in e.sortable)}var F4r=[Fo.Down,Fo.Right,Fo.Up,Fo.Left],AIn=(t,e)=>{let{context:{active:n,collisionRect:r,droppableRects:o,droppableContainers:i,over:s,scrollableAncestors:a}}=e;if(F4r.includes(t.code)){if(t.preventDefault(),!n||!r)return;let l=[];i.getEnabled().forEach(d=>{if(!d||d!=null&&d.disabled)return;let f=o.get(d.id);if(f)switch(t.code){case Fo.Down:r.top<f.top&&l.push(d);break;case Fo.Up:r.top>f.top&&l.push(d);break;case Fo.Left:r.left>f.left&&l.push(d);break;case Fo.Right:r.left<f.left&&l.push(d);break}});let c=lIn({active:n,collisionRect:r,droppableRects:o,droppableContainers:l,pointerCoordinates:null}),u=xlt(c,"id");if(u===s?.id&&c.length>1&&(u=c[1].id),u!=null){let d=i.get(n.id),f=i.get(u),p=f?o.get(f.id):null,m=f?.node.current;if(m&&p&&d&&f){let g=Aoe(m).some((I,C)=>a[C]!==I),v=EIn(d,f),y=U4r(d,f),w=g||!v?{x:0,y:0}:{x:y?r.width-p.width:0,y:y?r.height-p.height:0},_={x:p.left,y:p.top};return w.x&&w.y?_:PF(_,w)}}}};function EIn(t,e){return!sPe(t)||!sPe(e)?!1:t.data.current.sortable.containerId===e.data.current.sortable.containerId}function U4r(t,e){return!sPe(t)||!sPe(e)||!EIn(t,e)?!1:t.data.current.sortable.index<e.data.current.sortable.index}Re();var j4r=[];function MIn({id:t,item:e,title:n,subtitle:r,badge:o,icon:i,isDraggable:s=!1,isExpandable:a=!1,defaultExpanded:l=!1,expandedContent:c,primaryAction:u,dropdownActions:d=j4r,containerRef:f,className:p,onExpandToggle:m}){let[h,g]=(0,Wi.useState)(l),{attributes:v,listeners:y,setNodeRef:w,transform:_,transition:S,isDragging:I}=aPe({id:t,disabled:!s}),C={transform:mC.Transform.toString(_),transition:S},k=()=>{if(a){let P=!h;g(P),m?.(P)}},T=d.length>0;return Wi.default.createElement(hD,{ref:w,style:C,className:J("tw-mb-2",I&&["tw-opacity-90","tw-shadow-lg","tw-border-accent/50","tw-relative","tw-z-[9999]","tw-bg-primary","tw-rounded-lg","tw-transform-gpu"],s&&"tw-touch-manipulation",p)},Wi.default.createElement(Rte,{className:"tw-p-3"},Wi.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between"},s&&Wi.default.createElement("div",{className:"tw-mr-2 tw-cursor-grab tw-touch-none active:tw-cursor-grabbing",...v,...y},Wi.default.createElement(FC,{className:"tw-size-4"})),Wi.default.createElement("div",{className:"tw-flex-1 tw-touch-auto",onClick:a?k:void 0,style:{cursor:a?"pointer":"default"}},Wi.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},a&&Wi.default.createElement("div",{className:"tw-flex tw-size-3 tw-items-center tw-justify-center"},h?Wi.default.createElement(Bs,{className:"tw-size-3 tw-stroke-[7]"}):Wi.default.createElement(Vi,{className:"tw-size-3 tw-stroke-[7]"})),i&&Wi.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-center"},i),Wi.default.createElement("div",{className:"tw-min-w-0 tw-flex-1"},Wi.default.createElement("div",{className:"tw-break-words tw-font-medium tw-leading-relaxed"},n,o&&Wi.default.createElement("span",{className:"tw-ml-1 tw-inline-flex tw-items-center"},o)),r&&Wi.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Wi.default.createElement("span",{className:"tw-bg-secondary tw-text-sm tw-text-muted"},r))))),Wi.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},u&&Wi.default.createElement(oe,{variant:"ghost",size:"icon",onClick:P=>{P.stopPropagation(),u.onClick(e)},title:u.tooltip},u.icon),T&&Wi.default.createElement(up,null,Wi.default.createElement(dp,{asChild:!0},Wi.default.createElement(oe,{variant:"ghost",size:"icon"},Wi.default.createElement(vy,{className:"tw-size-4"}))),Wi.default.createElement(Ac,{align:"end",container:f?.current},d.map(P=>Wi.default.createElement(co,{key:P.label,onClick:E=>{E.stopPropagation(),P.onClick(e)},className:J(P.variant==="destructive"&&"tw-text-error")},Wi.default.createElement("span",{className:"tw-mr-2 tw-flex tw-size-4 tw-items-center tw-justify-center"},P.icon),P.label))))))),a&&Wi.default.createElement("div",{className:J("tw-transition-all tw-duration-300 tw-ease-in-out",h?"tw-max-h-96 tw-opacity-100":"tw-max-h-0 tw-overflow-hidden tw-opacity-0")},Wi.default.createElement(Lte,{className:"tw-p-3 tw-pt-0"},c)))}Re();RP();var gu=L(B());De();var Tlt=gu.forwardRef(({className:t,...e},n)=>gu.createElement("div",{className:"tw-relative tw-w-full tw-overflow-auto"},gu.createElement("table",{ref:n,className:J("tw-w-full tw-caption-bottom tw-border-collapse tw-text-sm",t),...e})));Tlt.displayName="Table";var Plt=gu.forwardRef(({className:t,...e},n)=>gu.createElement("thead",{ref:n,className:J("[&_tr]:tw-border-b",t),...e}));Plt.displayName="TableHeader";var Alt=gu.forwardRef(({className:t,...e},n)=>gu.createElement("tbody",{ref:n,className:t,...e}));Alt.displayName="TableBody";var B4r=gu.forwardRef(({className:t,...e},n)=>gu.createElement("tfoot",{ref:n,className:J("tw-border-t tw-font-medium tw-bg-primary-alt/50",t),...e}));B4r.displayName="TableFooter";var Eoe=gu.forwardRef(({className:t,...e},n)=>gu.createElement("tr",{ref:n,className:J("tw-border-b tw-transition-colors hover:tw-bg-primary-alt/50 data-[state=selected]:tw-bg-primary-alt",t),...e}));Eoe.displayName="TableRow";var RF=gu.forwardRef(({className:t,...e},n)=>gu.createElement("th",{ref:n,className:J("tw-h-10 tw-px-2 tw-text-left tw-align-middle tw-font-medium tw-text-muted [&>[role=checkbox]]:tw-translate-y-[2px]",t),...e}));RF.displayName="TableHead";var OO=gu.forwardRef(({className:t,...e},n)=>gu.createElement("td",{ref:n,className:J("tw-p-2 tw-align-middle [&>[role=checkbox]]:tw-translate-y-[2px]",t),...e}));OO.displayName="TableCell";var z4r=gu.forwardRef(({className:t,...e},n)=>gu.createElement("caption",{ref:n,className:J("tw-mt-4 tw-text-sm tw-text-muted",t),...e}));z4r.displayName="TableCaption";De();pe();Se();W5();Lh();rD();x0();Og();fm();Is();ko();Iv();LF();var lPe=require("obsidian");Hl();var H4r=({command:t,commands:e,onUpdate:n,onRemove:r,onCopy:o,containerRef:i})=>{let s=vn(),a=u=>{new kO(s,e,u,async f=>{await n(f,u.title)}).open()},l=[{icon:St.default.createElement(Qf,{className:"tw-size-4"}),label:"Edit",onClick:a},{icon:St.default.createElement(B2,{className:"tw-size-4"}),label:"Duplicate",onClick:o},{icon:St.default.createElement(Ts,{className:"tw-size-4"}),label:"Delete",onClick:u=>{new _i(s,()=>r(u),`Are you sure you want to delete the command "${u.title}"? This will permanently remove the command file and cannot be undone.`,"Delete Command","Delete","Cancel").open()},variant:"destructive"}],c=St.default.createElement("div",{className:"tw-flex tw-flex-wrap tw-justify-around"},St.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-gap-2"},St.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},St.default.createElement("span",{className:"tw-text-sm tw-font-medium"},"In Menu"),St.default.createElement(rs,{content:St.default.createElement("div",{className:"tw-max-w-xs tw-text-xs"},"If enabled, the command will be available in the context menu when you right-click in the editor.")})),St.default.createElement(Wl,{checked:t.showInContextMenu,onCheckedChange:u=>{n({...t,showInContextMenu:u===!0},t.title)}})),St.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-gap-2"},St.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},St.default.createElement("span",{className:"tw-text-sm tw-font-medium"},"In Slash"),St.default.createElement(rs,{content:St.default.createElement("div",{className:"tw-max-w-xs tw-text-xs"},"If enabled, the command will be available as a slash command in the chat.")})),St.default.createElement(Wl,{checked:t.showInSlashMenu,onCheckedChange:xn(async u=>n({...t,showInSlashMenu:u===!0},t.title))})));return St.default.createElement(MIn,{id:t.title,item:t,title:t.title,isDraggable:!0,isExpandable:!0,expandedContent:c,primaryAction:{icon:St.default.createElement(Qf,{className:"tw-size-4"}),onClick:a,tooltip:"Edit Command"},dropdownActions:l,containerRef:i})},W4r=({command:t,commands:e,onUpdate:n,onRemove:r,onCopy:o})=>{let i=vn(),{attributes:s,listeners:a,setNodeRef:l,transform:c,transition:u,isDragging:d}=aPe({id:t.title}),f={transform:mC.Transform.toString(c),transition:u},p=()=>{r(t)};return St.default.createElement(Eoe,{ref:l,style:f,className:J("tw-transition-colors",d&&"tw-relative tw-z-[100] tw-cursor-grabbing tw-shadow-lg tw-backdrop-blur-sm tw-border-accent/50")},St.default.createElement(OO,{className:"tw-w-10"},St.default.createElement("div",{...s,...a,className:"tw-flex tw-cursor-grab tw-items-center tw-justify-center"},St.default.createElement(FC,{className:"tw-size-4"}))),St.default.createElement(OO,null,t.title),St.default.createElement(OO,{className:"tw-text-center"},St.default.createElement(Wl,{checked:t.showInContextMenu,onCheckedChange:m=>{n({...t,showInContextMenu:m===!0},t.title)},className:"tw-mx-auto"})),St.default.createElement(OO,{className:"tw-text-center"},St.default.createElement(Wl,{checked:t.showInSlashMenu,onCheckedChange:xn(async m=>n({...t,showInSlashMenu:m===!0},t.title)),className:"tw-mx-auto"})),St.default.createElement(OO,{className:"tw-text-center"},St.default.createElement("div",{className:"tw-flex tw-justify-center tw-space-x-1"},St.default.createElement(oe,{variant:"ghost",size:"icon",onClick:()=>{new kO(i,e,t,async h=>{await n(h,t.title)}).open()}},St.default.createElement(Qf,{className:"tw-size-4"})),St.default.createElement(oe,{variant:"ghost",size:"icon",onClick:xn(async()=>o(t)),title:"Duplicate command"},St.default.createElement(B2,{className:"tw-size-4"})),St.default.createElement(oe,{variant:"ghost",size:"icon",onClick:()=>{new _i(i,p,`Are you sure you want to delete the command "${t.title}"? This will permanently remove the command file and cannot be undone.`,"Delete Command","Delete","Cancel").open()}},St.default.createElement(Ts,{className:"tw-size-4"})))))},OIn=()=>{let t=vn(),e=aSe(),n=(0,St.useMemo)(()=>ste([...e]),[e]),r=xt(),o=EC(r),i=(0,St.useRef)(null),s=iIn(_lt(N5,{activationConstraint:{distance:8}}),_lt(O5,{coordinateGetter:AIn})),a=async(p,m)=>{await Fa.getInstance().updateCommand(p,m)},l=async p=>{await Fa.getInstance().createCommand(p)},c=async p=>{try{await Fa.getInstance().deleteCommand(p),new lPe.Notice(`Command "${p.title}" deleted successfully!`)}catch(m){throw H("Failed to delete command:",m),new lPe.Notice("Failed to delete command. Please try again."),m}},u=async p=>{try{let m=yln(p.title,n),h={...p,title:m};await Fa.getInstance().createCommand(h,{autoOrder:!1})}catch(m){H("Failed to duplicate command:",m),new lPe.Notice("Failed to duplicate command. Please try again.")}},d=async p=>{let{active:m,over:h}=p;if(!h||m.id===h.id)return;let g=n.findIndex(_=>_.title===m.id),v=n.findIndex(_=>_.title===h.id);if(g===-1||v===-1)return;let y=[...n],[w]=y.splice(g,1);y.splice(v,0,w),await Fa.getInstance().reorderCommands(y)},f=()=>St.default.createElement("div",{className:"tw-relative md:tw-hidden"},St.default.createElement(Clt,{sensors:s,collisionDetection:Slt,onDragEnd:p=>void d(p)},St.default.createElement(Ilt,{items:n.map(p=>p.title),strategy:klt},St.default.createElement("div",{className:"tw-space-y-2"},n.length===0?St.default.createElement("div",{className:"tw-rounded-lg tw-border tw-border-border tw-bg-primary tw-p-8 tw-text-center tw-text-muted"},"No custom prompt files found."):n.map(p=>St.default.createElement(H4r,{key:p.title,command:p,commands:n,onUpdate:a,onRemove:c,onCopy:u,containerRef:i}))))));return St.default.createElement("div",{className:"tw-space-y-4",ref:i},St.default.createElement("section",{className:J("tw-flex tw-flex-col tw-gap-4")},St.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},St.default.createElement("div",{className:"tw-text-xl tw-font-bold"},"Custom Commands"),St.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Preset prompts you trigger from the editor right-click menu or with a ",St.default.createElement("code",null,"/")," ","command in chat.")),St.default.createElement("div",{className:"tw-flex tw-items-start tw-gap-2 tw-rounded-md tw-border tw-border-solid tw-border-border tw-p-4 tw-text-muted tw-bg-interactive-accent/10"},St.default.createElement(jC,{className:"tw-size-5 tw-shrink-0 tw-text-accent"})," ",St.default.createElement("div",null,"Commands are automatically loaded from .md files in your custom prompts folder"," ",St.default.createElement("strong",null,o),". Modifying the files will also update the command settings.")),St.default.createElement(yu,null,St.default.createElement(_o,{type:"switch",title:"Custom Prompt Templating",description:"Process variables like {activenote}, {foldername}, or {#tag} in prompts. Disable for raw prompts.",checked:r.enableCustomPromptTemplating,onCheckedChange:p=>{At("enableCustomPromptTemplating",p)}}),St.default.createElement(_o,{type:"select",title:"Custom Prompts Sort Strategy",description:"Sort order for slash command menu prompts",value:r.promptSortStrategy,onChange:p=>At("promptSortStrategy",p),options:[{label:"Recency",value:"timestamp"},{label:"Alphabetical",value:"alphabetical"},{label:"Manual",value:"manual"}]})),St.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},St.default.createElement("div",{className:"tw-flex tw-w-full tw-justify-between tw-gap-2 md:tw-justify-end"},St.default.createElement("div",null,St.default.createElement(oe,{variant:"secondary",onClick:()=>new _i(t,okn,"This will add default commands to your custom prompts folder. Do you want to continue?","Generate Default Commands").open()},"Generate Default")),St.default.createElement(oe,{variant:"default",className:"tw-gap-2",onClick:()=>{let p={...US};new kO(t,n,p,async h=>{await l(h)}).open()}},St.default.createElement(zs,{className:"tw-size-2 md:tw-size-4"}),"Add Cmd")),St.default.createElement("div",{className:"tw-hidden md:tw-block"},St.default.createElement(Clt,{sensors:s,collisionDetection:Slt,onDragEnd:p=>void d(p)},St.default.createElement(Tlt,null,St.default.createElement(Plt,null,St.default.createElement(Eoe,null,St.default.createElement(RF,{className:"tw-w-10"}),St.default.createElement(RF,null,"Name"),St.default.createElement(RF,{className:"tw-w-24 tw-text-center"},St.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-center tw-gap-1"},"In Menu",St.default.createElement(rs,{content:St.default.createElement("div",{className:"tw-max-w-xs tw-text-xs"},"If enabled, the command will be available in the context menu when you right-click in the editor.")}))),St.default.createElement(RF,{className:"tw-w-28 tw-text-center"},St.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-center tw-gap-1"},"Slash Cmd",St.default.createElement(rs,{content:St.default.createElement("div",{className:"tw-max-w-xs tw-text-xs"},"If enabled, the command will be available as a slash command in the chat.")}))),St.default.createElement(RF,{className:"tw-w-32 tw-text-center"},"Actions"))),St.default.createElement(Ilt,{items:n.map(p=>p.title),strategy:klt},St.default.createElement(Alt,null,n.length===0?St.default.createElement(Eoe,null,St.default.createElement(OO,{colSpan:5,className:"tw-py-8 tw-text-center tw-text-muted"},"No custom prompt files found.")):n.map(p=>St.default.createElement(W4r,{key:p.title,command:p,commands:n,onUpdate:a,onRemove:c,onCopy:u}))))))),f())))};Re();var $r=L(B());$n();gt();yt();Iv();LF();Is();rk();var Moe=L(B()),V4r=({promptCount:t,folderPath:e})=>t===0?null:Moe.default.createElement("div",{className:"tw-mb-3 tw-rounded-md tw-border tw-border-border tw-bg-secondary tw-px-3 tw-py-2 tw-text-ui-smaller tw-text-muted"},"Agent Mode now reads your instructions from ",Moe.default.createElement("code",null,"AGENTS.md"),". Your"," ",t===1?"saved system prompt is":`${t} saved system prompts are`," ","still in ",Moe.default.createElement("code",null,e)," \u2014 open one there and paste anything you want the agent to keep following."),cPe=()=>{let t=Tae();return Moe.default.createElement(V4r,{promptCount:t.length,folderPath:Wie()})};pnt();Iv();Se();var NIn=L(B()),q4r="The built-in embedding index that powers semantic search when you are not using Miyo. Turning it off stops all indexing and falls back to keyword search; the index already on disk is kept, but no longer read or updated.",K4r="Miyo is handling semantic search, so the built-in index is not in use and has nothing to index. Disconnect from the Miyo tab to return to keyword search.",RIn=({enabled:t,miyoManaged:e,onToggle:n})=>NIn.default.createElement(_o,{type:"switch",title:"Legacy vault index",description:e?K4r:q4r,checked:t,disabled:e,onCheckedChange:n});function LIn(t,e){new YV(t,()=>At("enableSemanticSearchV3",e),e).open()}ko();nN();function uPe(t){return async e=>{let{plugins:n}=t,r=n.getPlugin("copilot");if(!r)throw new Error("Copilot plugin not found");await r.saveData(e)}}cP();WO();pe();Se();Re();fm();var NO=require("obsidian"),ro=L(B());$n();Hl();var G4r="(Agent Mode frame logs are desktop-only)",$In=()=>{let t=vn(),e=xt(),[n,r]=(0,ro.useState)(!1),[o,i]=(0,ro.useState)(G4r);(0,ro.useEffect)(()=>{if(!Ln())return;let u=!1;return Promise.resolve().then(()=>(Hf(),d_)).then(({acpFrameSink:d})=>{u||i(d.getPath())}),()=>{u=!0}},[]);let s=Ha.getInstance().isAvailable(),a=s&&!rie(e),l=(0,ro.useCallback)(()=>{if(!Ln()){new NO.Notice("Reporting an issue is available on desktop only.");return}(async()=>{let{ReportIssueModal:u}=await Promise.resolve().then(()=>(Hf(),d_)),d=t.plugins.getPlugin("copilot"),f=d?.agentSessionManager?.getActiveSession?.()?.backendId??e.agentMode.activeBackend;new u({app:t,activeBackend:f,pluginVersion:d?.manifest?.version??"unknown",resolveCaptureTarget:()=>{t.setting.close();let p=t.workspace.getLeavesOfType(Vd)[0];if(!p)return null;t.workspace.revealLeaf(p);let m=p.view;return m.contentEl??m.containerEl??null}}).open()})()},[t,e.agentMode.activeBackend]),c=(0,ro.useCallback)(async()=>{if(!(n||!await new Promise(d=>{new _i(t,()=>d(!0),"This will remove all API keys for this vault from the Obsidian Keychain, data.json, and memory. You will need to re-enter them. Any credential backup files written during the v4 upgrade are left in place \u2014 delete those yourself once you no longer need them.","\u26A0\uFE0F Forget All Secrets","Remove","Cancel",()=>d(!1)).open()}))){r(!0);try{let d=Ha.getInstance(),f=uPe(t);await zTe(()=>d.forgetAllSecrets(async p=>{await f(p),wkn()},p=>{bkn(p),BTe(),En(p)}))}catch(d){H("Failed to forget secrets.",d),new NO.Notice("Failed to remove API keys. Please try again.")}finally{r(!1)}}},[t,n]);return ro.default.createElement("div",{className:"tw-space-y-4"},ro.default.createElement(cPe,null),ro.default.createElement(yu,{label:"Others"},ro.default.createElement(_o,{type:"custom",title:"API Key Storage",description:s?a?ro.default.createElement("span",{className:"tw-text-warning"},"No API keys found in this device's"," ",ro.default.createElement("strong",{className:"tw-font-semibold tw-text-normal"},"Obsidian Keychain"),". Re-enter your API keys in the relevant settings sections \u2014 each device has a separate Keychain."):ro.default.createElement(ro.default.Fragment,null,"API keys are stored in this device's"," ",ro.default.createElement("strong",{className:"tw-font-semibold tw-text-normal"},"Obsidian Keychain"),"."):ro.default.createElement(ro.default.Fragment,null,"Update Obsidian to ",ro.default.createElement("code",null,"1.11.4+")," to use the"," ",ro.default.createElement("strong",{className:"tw-font-semibold tw-text-normal"},"Obsidian Keychain"),". Keys cannot be loaded or saved in this build.")},ro.default.createElement("div",{className:"tw-flex tw-flex-col tw-items-start tw-gap-2 sm:tw-items-end"},s?ro.default.createElement("div",{className:"tw-inline-flex tw-items-center tw-gap-1.5 tw-rounded-md tw-bg-success tw-px-3 tw-py-1 tw-text-smallest tw-font-semibold tw-text-success"},ro.default.createElement(Tw,{className:"tw-size-4"}),"Obsidian Keychain"):ro.default.createElement("div",{className:"tw-inline-flex tw-items-center tw-gap-1.5 tw-rounded-md tw-border tw-border-border tw-bg-secondary tw-px-3 tw-py-1 tw-text-smallest tw-font-semibold tw-text-muted"},ro.default.createElement(jC,{className:"tw-size-4"}),"Unavailable"),ro.default.createElement(oe,{variant:"destructive",size:"sm",onClick:xn(c),disabled:n||!s,title:s?void 0:"Update Obsidian to 1.11.4+ to delete Keychain entries.",className:"tw-gap-1.5"},ro.default.createElement(Ts,{className:"tw-size-4"}),n?"Removing...":"Delete All Keys"))),ro.default.createElement(RIn,{enabled:e.enableSemanticSearchV3,miyoManaged:e.enableMiyo,onToggle:u=>LIn(t,u)}),ro.default.createElement(_o,{type:"switch",title:"Debug Mode",description:"Logs Copilot chat activity to the developer console (View \u2192 Toggle Developer Tools). For troubleshooting the regular chat \u2014 Agent Mode has its own log below.",checked:e.debug,onCheckedChange:u=>At("debug",u)}),ro.default.createElement(_o,{type:"custom",title:"Create Log File",description:`Save and open the regular Copilot chat log (${$l.getLogPath()}) to share when reporting a chat issue. Agent Mode issues are handled by the "Report an Issue" button in the agent pane instead.`},ro.default.createElement(oe,{variant:"secondary",size:"sm",onClick:()=>{(async()=>(await $ke(),await $l.flush(),await $l.openLogFile()))()}},"Create Log File"))),ro.default.createElement(yu,{label:"Agent Mode debugging",description:"Tools for diagnosing Agent Mode problems, separate from the regular Copilot chat logs above."},ro.default.createElement(_o,{type:"custom",title:"Report an Issue",description:"Bundles a screenshot of the Agent Mode chat pane and a recent activity log into a folder, then opens a prefilled GitHub issue for you to attach them to."},ro.default.createElement(oe,{variant:"secondary",size:"sm",onClick:l},"Report an Issue")),ro.default.createElement(_o,{type:"switch",title:"Keep an Agent Mode activity log",description:"Records the behind-the-scenes messages between Copilot and the agent so the Report an Issue button always has recent activity to attach. Stored on this device only, outside your vault, and can include your prompts and note contents in plain text. On by default; turn off to stop logging.",checked:e.agentMode.debugFullFrames,onCheckedChange:u=>{En(d=>({agentMode:{...d.agentMode,debugFullFrames:u}}))}}),ro.default.createElement(_o,{type:"custom",title:"Agent Mode activity log file",description:`Open or clear the log file on disk (${o}).`},ro.default.createElement("div",{className:"tw-flex tw-gap-2"},ro.default.createElement(oe,{variant:"secondary",size:"sm",onClick:xn(async()=>{if(!Ln()){new NO.Notice("Agent Mode frame logs are available on desktop only.");return}try{let{acpFrameSink:u}=await Promise.resolve().then(()=>(Hf(),d_));await u.open(),i(u.getPath())}catch{new NO.Notice("Failed to open Agent Mode frame log.")}})},"Open"),ro.default.createElement(oe,{variant:"secondary",size:"sm",onClick:xn(async()=>{if(!Ln()){new NO.Notice("Agent Mode frame logs are available on desktop only.");return}try{let{acpFrameSink:u}=await Promise.resolve().then(()=>(Hf(),d_));await u.clear(),i(u.getPath()),new NO.Notice("Agent Mode frame log cleared.")}catch{new NO.Notice("Failed to clear Agent Mode frame log.")}})},"Clear")))))};fm();yt();Sj();Lh();hl();Iv();De();Re();var dPe=L(B()),Ooe=dPe.default.forwardRef(({open:t,label:e="Advanced",className:n,...r},o)=>dPe.default.createElement("button",{ref:o,type:"button","aria-expanded":t,className:J("tw-flex tw-w-full tw-cursor-pointer tw-items-center !tw-justify-start tw-gap-1.5","!tw-border-none !tw-bg-transparent !tw-px-0 !tw-py-3 !tw-shadow-none","tw-text-left tw-text-sm tw-font-medium tw-text-muted hover:tw-text-normal",n),...r},dPe.default.createElement(Vi,{className:J("tw-size-3.5 tw-transition-transform",t&&"tw-rotate-90")}),e));Ooe.displayName="SettingDisclosure";LF();gt();ko();_oe();De();pe();nA();zu();ha();Se();ut();gX();_I();var Elt=Promise.resolve(),fPe=0;function Mlt(){return fPe+=1,Elt=Promise.resolve(),Object.freeze({lifecycle:fPe})}function $5(t){if(t!==fPe)throw new Error("Miyo mutation belongs to an expired plugin lifecycle")}function $F(t,e){if(t!==fPe){W("Miyo: discarded a receipt write from an expired plugin lifecycle.");return}At("miyoSyncedExclusions",e)}function pPe(t,e){let{lifecycle:n}=e,r=Elt.then(async()=>{$5(n);let o=await t(n);return $5(n),o});return Elt=r.catch(()=>{}),r}var DIn=1e4;function L5(t,e){return new Promise((n,r)=>{let o=window.setTimeout(()=>r(new Error(`Miyo ${e} timed out after ${DIn}ms`)),DIn);t.then(i=>{window.clearTimeout(o),n(i)},i=>{window.clearTimeout(o),r(i instanceof Error?i:new Error(String(i)))})})}function Z4r(t,e,n,r){return e.device===wg(t)&&e.url===(n.miyoServerUrl||"").trim()&&e.folder===r}function R5(t,e){let n=t[e];return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}function Y4r(t,e){let n=new Set(t);return e.every(r=>n.has(r))}function J4r(t,e){let n=(a,l)=>{let c=[...new Set([...a??[],...l])];return c.length>0?c:void 0};t.exclude_folders=n(t.exclude_folders,R5(e,"exclude_folders")),t.exclude_patterns=n(t.exclude_patterns,R5(e,"exclude_patterns"));let r=R5(e,"include_folders"),o=R5(e,"include_patterns"),i=R5(e,"include_extensions");r.length+o.length+i.length>0&&(t.include_folders=r.length>0?r:void 0,t.include_patterns=o.length>0?o:void 0,t.include_extensions=i.length>0?i:void 0)}function FIn(t,e){let n=vX("",vg(e));return Y4r(R5(t,"exclude_folders"),n.exclude_folders??[])}function X4r(t,e=Y()){return{path:Hu(t)??"",...$ye(e.qaInclusions),...vX(e.qaExclusions,[...vg(e),...e$(t)])}}function UIn(t,e){return pPe(n=>tHr(t,n),e).catch(n=>(W(`Miyo resync abandoned: ${kt(n)}`),"failed"))}function mPe(t,e){return pPe(n=>Q4r(t,n),e).catch(n=>(W(`Miyo scope verification abandoned: ${kt(n)}`),"unknown"))}async function Q4r(t,e){try{let n=Y(),r=Mp(t),o=Ci(n)||void 0,i=new jc({plusLicenseKey:n.plusLicenseKey}),s=await i.resolveBaseUrl(o),a;try{a=await L5(i.getFolder(s,r),"folder lookup")}catch{if(await L5(i.checkFolderRegistration(r,o),"registration check")!=="unregistered")return"unknown";let u=Fye(n.miyoSyncedExclusions);if(!u)return"unregistered";if(Z4r(t,u,n,r))return $F(e,""),"unregistered";if(u.device===wg(t)&&u.url===Ci(n)){let d=await L5(i.checkFolderRegistration(u.folder,o),"previous-name check");return d==="unregistered"?($F(e,""),"unregistered"):d!=="registered"?"unknown":"stale"}return"unregistered"}if(!FIn(a,n))return"stale";let l=JH(t,n);return n.miyoSyncedExclusions!==l&&$F(e,l),"covered"}catch(n){return W(`Miyo scope verification failed: ${kt(n)}`),"unknown"}}async function eHr(t,e,n){try{return await t.addFolder(e,n)}catch(r){return W(`Miyo resync: re-add failed, retrying once: ${kt(r)}`),await t.addFolder(e,n)}}async function tHr(t,e){try{let n=Y();if(!Hu(t))return W("Miyo resync: no vault base path (mobile/remote?); cannot resync."),"failed";let o=Mp(t),i=Ci(n);if(!r$(i))return W("Miyo resync: endpoint switched to a remote target while queued; not resyncing."),"failed";let s=i||void 0,a=new jc({plusLicenseKey:n.plusLicenseKey}),l=await a.resolveBaseUrl(s),c=JH(t,n),u=X4r(t,n),d;try{d=await L5(a.getFolder(l,o),"folder lookup")}catch(p){if(await L5(a.checkFolderRegistration(o,s),"registration check")!=="unregistered")return W(`Miyo resync: could not read folder record: ${kt(p)}`),"failed";let h=Fye(n.miyoSyncedExclusions);if(h&&h.device===wg(t)&&h.url===Ci(n)){if(h.folder!==o){let v=await L5(a.checkFolderRegistration(h.folder,s),"previous-name check");return v==="unregistered"?($F(e,""),"unregistered"):v!=="registered"?(W("Miyo resync: could not determine the previous-name registration's state."),"failed"):(W("Miyo resync: a registration under this vault's previous name still exists; remove it in the Miyo app."),"conflict")}if(u.allow_remote_read=!1,u.allow_writes=!1,await a.addFolder(u,s,()=>$5(e))===null)return W("Miyo resync: re-add of a vanished registration returned 409."),"conflict";$F(e,c);try{await a.scanFolder(l,o,!1)}catch(v){W(`Miyo resync: re-scan trigger failed: ${kt(v)}`)}return"resynced-grants-reset"}return"unregistered"}if(FIn(d,n))return $F(e,c),j("Miyo resync: server record already covers the scope."),"verified";if(u.allow_remote_read=d.allow_remote_read===!0,u.allow_writes=d.allow_writes===!0,J4r(u,d),await a.deleteFolder(o,s,()=>$5(e)),await eHr(a,u,s)===null)return W("Miyo resync: re-add returned 409; server registration contested."),"conflict";$F(e,c);try{return await a.scanFolder(l,o,!1),"resynced"}catch(p){return W(`Miyo resync: re-scan trigger failed: ${kt(p)}`),"resynced-scan-failed"}}catch(n){return W(`Miyo resync failed: ${kt(n)}`),"failed"}}zu();db();db();pe();var hPe=L(B());function jIn(t,e){let[n,r]=(0,hPe.useState)(null);return(0,hPe.useEffect)(()=>{if(e===null)return;let o=!1;return mme(t,e).then(i=>{o||r(i)}).catch(i=>{H(`Failed to read AGENTS.md for "${e||"<vault root>"}".`,i)}),()=>{o=!0}},[t,e]),[n,r]}pe();AC();Is();pe();ha();Se();var Noe=require("obsidian");function Olt(t,e){return{copilotRootHistory:_C([...t.copilotRootHistory,t.copilotFolder,e]),copilotFolder:e}}function BIn(t,e){let n=(0,Noe.normalizePath)(e).replace(/\/+$/,"");return n.length===0?!1:t.vault.getMarkdownFiles().some(r=>fX(r.path,[n]))}function zIn(t,e){let n=(0,Noe.normalizePath)(e).replace(/\/+$/,"");if(n.length===0)return null;let r="";for(let o of n.split("/"))if(r=r?`${r}/${o}`:o,t.vault.getAbstractFileByPath(r)instanceof Noe.TFile)return r;return null}async function HIn(t,e){let n=n2(e,t.vault.configDir);if(!n.ok){W("Copilot root change rejected an invalid folder value.",n.reason);return}let r=n.folder,o=uPe(t);await zTe(async()=>{let i=Y(),s={...i,...Olt(i,r)};await llt(s,o,i);let a=Y(),l={...a,...Olt(a,r)};if(JSON.stringify(l)!==JSON.stringify(s))try{await llt(l,o,s)}catch(c){W("Copilot root change: reconcile save for a concurrent edit failed; it stays in memory and lands with the next save.",c)}BTe(),En(c=>Olt(c,r))});try{let{default:i}=await Promise.resolve().then(()=>(El(),nd)),s=await i.getInstance().garbageCollectVectorStore();j(`Copilot root change: garbage collection removed ${s} stale index docs.`)}catch(i){W("Copilot root change: garbage collection failed (will retry on next index).",i)}}Se();var WIn=L(B()),gPe=({message:t})=>WIn.default.createElement("section",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-p-4 tw-text-sm tw-text-muted"},t);De();Re();var Qg=L(B()),VIn=({oldRoot:t,newRoot:e,containsMarkdown:n})=>Qg.default.createElement("div",{className:J("tw-flex tw-flex-col tw-gap-4")},Qg.default.createElement("div",{className:J("tw-flex tw-items-center tw-gap-3 tw-text-normal")},Qg.default.createElement(vG,{className:J("tw-size-6 tw-shrink-0 tw-text-accent"),"aria-hidden":"true"}),Qg.default.createElement("h2",{className:J("tw-m-0 tw-text-xl tw-font-bold")},"Change Copilot folder")),Qg.default.createElement("p",{className:J("tw-m-0 tw-text-muted")},"Copilot will keep new chats and data under ",Qg.default.createElement("code",null,e,"/"),". Your files aren't moved \u2014 your old data stays in ",Qg.default.createElement("strong",{className:J("tw-text-normal")},t,"/"),", which stays permanently excluded from Copilot search. Move it over if you want; Obsidian updates the links."),n&&Qg.default.createElement("div",{className:J("tw-flex tw-items-start tw-gap-2 tw-rounded-lg tw-border tw-border-solid tw-border-warning/40","tw-bg-secondary tw-px-3 tw-py-2.5 tw-text-xs tw-text-normal"),role:"alert"},Qg.default.createElement(Wr,{className:J("tw-mt-0.5 tw-size-4 tw-shrink-0 tw-text-warning"),"aria-hidden":"true"}),Qg.default.createElement("span",null,Qg.default.createElement("strong",null,"This folder already contains Markdown files.")," If you continue, every Markdown file under ",Qg.default.createElement("code",null,e,"/")," \u2014 including regular notes \u2014 will be excluded from Copilot search. The folder stays excluded even if you change the Copilot folder later.")));var M_=L(B()),qIn=require("obsidian");yt();Pa();pe();vc();function nHr({onConfirm:t,onCancel:e}){return M_.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},M_.default.createElement("div",null,M_.default.createElement("p",null,"Thanks for purchasing! Your license includes Copilot exclusive models, cross-agent skills, access to the ",M_.default.createElement("a",{href:"https://symposium.md"},"symposium.md")," doc sharing service, and much more!"),M_.default.createElement("p",null,"Would you like to make ",M_.default.createElement("b",{className:"tw-text-accent"},y3)," ","the default model for chat and your agents now? You can always change this later in Settings.")),M_.default.createElement("div",{className:"tw-flex tw-w-full tw-justify-end tw-gap-2"},M_.default.createElement(oe,{variant:"ghost",onClick:e},"Apply Later"),M_.default.createElement(oe,{variant:"default",onClick:t},"Apply Now")))}var yPe=class extends qIn.Modal{constructor(e){super(e),this.setTitle("Welcome to Copilot \u{1F680}")}onOpen(){let{contentEl:e}=this;this.root=Er(e,this.app);let n=()=>{Pgn().catch(o=>H("Failed to apply the licensed default model",o)),this.close()},r=()=>{this.close()};this.root.render(M_.default.createElement(nHr,{onConfirm:n,onCancel:r}))}onClose(){this.root.unmount()}};ko();pm();yt();cde();gt();vc();Se();Re();var jr=L(B());Hl();function rHr(){return null}var oHr="believer";function KIn(){let t=vn(),e=xt(),[n,r]=(0,jr.useState)(null),[o,i]=(0,jr.useState)(!1),s=Lke(),a=Ign(),l=o?"none":a.status,[c,u]=(0,jr.useState)(e.plusLicenseKey),d=rHr();return jr.default.createElement("section",{className:"tw-flex tw-flex-col tw-gap-4 tw-rounded-xl tw-border tw-border-solid tw-border-border tw-p-4 tw-shadow-sm tw-bg-interactive-accent/10"},jr.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-gap-2 tw-text-lg tw-font-semibold"},jr.default.createElement("span",null,"Copilot License"),l==="active"&&jr.default.createElement(ei,{className:"tw-rounded-full tw-bg-success tw-capitalize tw-text-success"},a.plan===oHr?"Lifetime":a.plan??"Active"),l==="inactive"&&jr.default.createElement(ei,{className:"tw-rounded-full tw-bg-error tw-text-error"},"Inactive")),jr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2 tw-text-sm tw-text-muted"},jr.default.createElement("div",null,jr.default.createElement("a",{href:Irt(hw.SETTINGS),target:"_blank",rel:"noopener noreferrer",className:"tw-font-semibold tw-text-accent"},"Copilot paid plans")," ","add ",jr.default.createElement("strong",{className:"tw-font-semibold tw-text-normal"},"premium chat models"),","," ",jr.default.createElement("strong",{className:"tw-font-semibold tw-text-normal"},"document understanding"),","," ",jr.default.createElement("strong",{className:"tw-font-semibold tw-text-normal"},"advanced web search"),", and"," ",jr.default.createElement("strong",{className:"tw-font-semibold tw-text-normal"},"multi-agent capabilities")," to your Copilot agentic experience. Pair it with"," ",jr.default.createElement("a",{href:q5,target:"_blank",rel:"noopener noreferrer",className:"tw-font-semibold tw-text-accent"},"Miyo")," ","and turn your vault into a centralized workspace for all your AI tools across devices.")),(s===!1||l==="inactive")&&!o&&jr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2 tw-rounded-lg tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-3"},jr.default.createElement("div",{className:"tw-text-sm tw-text-normal"},"All of it for a few dollars a month."),jr.default.createElement("div",{className:"tw-flex tw-flex-wrap tw-items-center tw-gap-2"},jr.default.createElement(oe,{className:"tw-text-xs md:tw-text-sm",onClick:()=>ek(hw.SETTINGS)},"See plans ",jr.default.createElement(Ch,{className:"tw-size-2 md:tw-size-4"})),jr.default.createElement("a",{href:q5,target:"_blank",rel:"noopener noreferrer",className:"tw-inline-flex tw-items-center tw-gap-0.5 tw-text-sm tw-text-accent"},"New: pair Copilot with Miyo ",jr.default.createElement(Ch,{className:"tw-size-3.5"})))),jr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},jr.default.createElement(Yj,{className:"tw-w-full",placeholder:"Enter your license key",value:c,onChange:f=>{u(f)}}),jr.default.createElement(oe,{disabled:o,onClick:xn(async()=>{At("plusLicenseKey",c),i(!0);let f=await ch(t,{trigger:"manual"});i(!1),f?(r(null),new yPe(t).open()):r("Invalid license key")}),className:"tw-min-w-10 tw-text-xs md:tw-text-sm"},o?jr.default.createElement(Dr,{className:"tw-size-2 tw-animate-spin md:tw-size-4"}):"Apply")),n&&jr.default.createElement("div",{className:"tw-text-error"},n),s&&d&&jr.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-gap-4 tw-border-t tw-border-border tw-pt-4 tw-text-sm"},jr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-3 tw-text-muted"},jr.default.createElement("span",{className:"tw-flex tw-items-center tw-gap-1.5"},jr.default.createElement("span",{className:"tw-text-accent"},"\u25CF"),jr.default.createElement("span",null,"Current 5h ",jr.default.createElement("strong",{className:"tw-font-semibold"},d.currentPct,"%")," ","used")),jr.default.createElement("span",{className:"tw-text-faint"},"\xB7"),jr.default.createElement("span",{className:"tw-flex tw-items-center tw-gap-1.5"},jr.default.createElement("span",{className:"tw-text-accent"},"\u25CF"),jr.default.createElement("span",null,"Weekly ",jr.default.createElement("strong",{className:"tw-font-semibold"},d.weeklyPct,"%")," used"))),jr.default.createElement(oe,{variant:"ghost",size:"sm",className:"tw-gap-1 tw-text-sm tw-text-accent hover:tw-text-accent-hover",onClick:()=>{window.open("https://obsidiancopilot.com/dashboard","_blank")}},"Dashboard ",jr.default.createElement(Ch,{className:"tw-size-3.5"}))))}yt();Jtt();Re();var eT=L(B()),GIn=({value:t,onChange:e,onOpen:n})=>eT.default.createElement("div",{className:"tw-flex tw-w-full tw-flex-col tw-gap-4 tw-py-4"},eT.default.createElement("div",{className:"tw-grid tw-w-full tw-grid-cols-[minmax(0,1fr)_auto] tw-items-center tw-gap-4"},eT.default.createElement("div",{className:"tw-space-y-1.5"},eT.default.createElement("div",{className:"tw-text-sm tw-font-medium tw-leading-none"},"Custom vault instructions"),eT.default.createElement("div",{className:"tw-text-xs tw-text-muted"},"Your custom instructions for the agent to follow for every vault interaction. Saved to AGENTS.md in your vault root, which you can also edit as a note.")),eT.default.createElement(oe,{variant:"secondary",onClick:n},eT.default.createElement(us,{className:"tw-size-4"}),"Open AGENTS.md")),eT.default.createElement(PCe,{label:"Custom vault instructions",value:t,onChange:e}));ut();$n();pe();var Roe=require("obsidian");function ZIn(t,e){let n=t.vault.getAbstractFileByPath(e);if(!(n instanceof Roe.TFolder)){new Roe.Notice(`Folder "${e}" doesn't exist yet \u2014 it's created on first use.`,5e3);return}let r=t.internalPlugins?.getPluginById?.("file-explorer");if(r?.enabled&&r.instance?.revealInFolder){r.instance.revealInFolder(n);return}W("[settings] File Explorer plugin unavailable; cannot reveal folder."),new Roe.Notice("File Explorer isn't enabled; can't reveal the folder.",5e3)}Re();var ey=require("obsidian"),rn=L(B()),hHr=rn.default.lazy(()=>Promise.resolve().then(()=>(o0n(),r0n)).then(t=>({default:t.AgentSettings}))),gHr=()=>Ln()?rn.default.createElement(rn.default.Suspense,{fallback:null},rn.default.createElement(hHr,null)):rn.default.createElement(gPe,{message:"Agent settings are available on desktop."}),i0n=()=>{let t=vn(),e=xt(),{miyoMutationSession:n}=P5(),[r,o]=(0,rn.useState)(!1),[i,s]=(0,rn.useState)(!1),[a,l]=(0,rn.useState)(e.defaultConversationNoteName||"{$date}_{$time}__{$topic}"),c=e.copilotFolder,[u,d]=(0,rn.useState)(c);(0,rn.useEffect)(()=>{d(c)},[c]);let[f,p]=jIn(t,""),m=(0,rn.useMemo)(()=>{let y=Promise.resolve();return Ba(_=>(y=y.then(()=>hme(t,"",_).catch(S=>{H("Failed to save vault instructions.",S),new ey.Notice("Failed to save AGENTS.md.")})),y),1e3)},[t]);(0,rn.useEffect)(()=>()=>void m.flush(),[m]);let h=async()=>{await m.flush(),t.setting.close();try{await yme(t,"","",!0)}catch(y){H("Failed to open vault AGENTS.md.",y),new ey.Notice(y instanceof Error?y.message:"Failed to open AGENTS.md.")}},g=()=>{let y=n2(u,t.vault.configDir);if(!y.ok){new ey.Notice(`Invalid Copilot folder: ${y.reason}`,5e3);return}let w=y.folder;if(w===c){new ey.Notice("That's already the Copilot folder.",3e3);return}let _=zIn(t,w);if(_){new ey.Notice(`"${_}" is an existing file, so "${w}" can't be used as a folder. Choose another location.`,8e3);return}let S=BIn(t,w);new _i(t,()=>{HIn(t,w).then(()=>{let I=Y(),C=()=>new ey.Notice("Miyo search needs a resync \u2014 open the Miyo settings tab.",6e3);XH(t,I)?C():I.miyoSyncedExclusions===""&&mPe(t,n).then(k=>{k==="stale"&&C()})}).then(()=>qie(t.vault,{copilotFolder:w})).then(()=>new ey.Notice(`Copilot folder changed to "${w}".`,4e3)).catch(()=>new ey.Notice("Failed to change the Copilot folder. Check the logs.",5e3))},rn.default.createElement(VIn,{oldRoot:c,newRoot:w,containsMarkdown:S}),"",S?"Use folder":"Change folder","Cancel",()=>d(c)).open()},v=()=>{o(!0);try{let y=a||"{$date}_{$time}__{$topic}",_=["{$date}","{$time}","{$topic}"].filter(P=>!y.includes(P));if(_.length>0){new ey.Notice(`Error: Missing required variables: ${_.join(", ")}`,4e3);return}let S=/[\\/:*?"<>|]/,I=y.replace(/\{\$date}/g,"").replace(/\{\$time}/g,"").replace(/\{\$topic}/g,"");if(S.test(I)){new ey.Notice('Error: Format contains illegal characters (\\/:*?"<>|)',4e3);return}let{fileName:C}=Cs(new Date),T=y.replace("{$topic}","test topic name".slice(0,100).replace(/\s+/g,"_")).replace("{$date}",C.split("_")[0]).replace("{$time}",C.split("_")[1]);At("defaultConversationNoteName",y),l(y),new ey.Notice(`Format applied successfully! Example: ${T}`,4e3)}catch(y){new ey.Notice(`Error applying format: ${y instanceof Error?y.message:String(y)}`,4e3)}finally{o(!1)}};return rn.default.createElement("div",{className:"tw-space-y-4"},rn.default.createElement(KIn,null),rn.default.createElement(gHr,null),rn.default.createElement(yu,{label:"General"},rn.default.createElement(_o,{type:"select",title:"Open Plugin In",description:"Choose where to open the plugin.",value:e.defaultOpenArea,onChange:y=>At("defaultOpenArea",y),options:[{label:"Sidebar View",value:"view"},{label:"Editor",value:"editor"}]}),rn.default.createElement(_o,{type:"select",title:"Send Shortcut",description:rn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},rn.default.createElement("span",{className:"tw-leading-none"},"Keyboard shortcut to send messages."),rn.default.createElement(rs,{content:rn.default.createElement("div",{className:"tw-flex tw-max-w-96 tw-flex-col tw-gap-2 tw-py-4"},rn.default.createElement("div",{className:"tw-text-xs tw-text-muted"},"If your selected shortcut doesn't work, check"," ",rn.default.createElement("strong",null,"Obsidian \u2192 Hotkeys")," to see if another command is using the same key combination."))})),value:e.defaultSendShortcut,onChange:y=>At("defaultSendShortcut",y),options:[{label:"Enter",value:"enter"},{label:"Shift + Enter",value:"shift+enter"}]}),rn.default.createElement(_o,{type:"custom",title:"Copilot folder location",description:"Where Copilot keeps conversations, prompts, memory and more. All sub-folders derive from this."},rn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},rn.default.createElement(Ir,{type:"text",value:u,onChange:y=>d(y.target.value),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),g())},placeholder:"copilot",className:"tw-w-full sm:tw-w-[160px]","aria-label":"Copilot folder"}),rn.default.createElement(oe,{variant:"secondary",onClick:g,"aria-label":"Apply Copilot folder"},"Apply"),rn.default.createElement(oe,{variant:"secondary",size:"icon",onClick:()=>ZIn(t,e.copilotFolder),"aria-label":"Open Copilot folder",title:"Open Copilot folder"},rn.default.createElement(Fl,{className:"tw-size-4"}))))),rn.default.createElement(yu,{label:"Custom instructions"},rn.default.createElement(cPe,null),f!==null&&rn.default.createElement(GIn,{value:f,onChange:y=>{p(y),m(y)},onOpen:()=>void h()})),rn.default.createElement(yu,{label:"Saving conversations"},rn.default.createElement(_o,{type:"switch",title:"Autosave Chat as Markdown",description:"Writes each chat to a Markdown note in your vault after every user message and AI response. With this off, agent chats still appear in Recent Chats from session history; only the Markdown note is skipped.",checked:e.autosaveChat,onCheckedChange:y=>At("autosaveChat",y)}),rn.default.createElement(dx,{open:i,onOpenChange:s},rn.default.createElement(fx,{asChild:!0},rn.default.createElement(Ooe,{open:i})),rn.default.createElement(px,null,rn.default.createElement(_o,{type:"custom",title:"Conversation Filename Template",description:rn.default.createElement("div",{className:"tw-flex tw-items-start tw-gap-1.5 "},rn.default.createElement("span",{className:"tw-leading-none"},"Customize the format of saved conversation note names."),rn.default.createElement(rs,{content:rn.default.createElement("div",{className:"tw-flex tw-max-w-96 tw-flex-col tw-gap-2 tw-py-4"},rn.default.createElement("div",{className:"tw-text-sm tw-font-medium tw-text-accent"},"Note: All the following variables must be included in the template."),rn.default.createElement("div",null,rn.default.createElement("div",{className:"tw-text-sm tw-font-medium tw-text-muted"},"Available variables:"),rn.default.createElement("ul",{className:"tw-pl-4 tw-text-sm tw-text-muted"},rn.default.createElement("li",null,rn.default.createElement("strong",null,"{$date}"),": Date in YYYYMMDD format"),rn.default.createElement("li",null,rn.default.createElement("strong",null,"{$time}"),": Time in HHMMSS format"),rn.default.createElement("li",null,rn.default.createElement("strong",null,"{$topic}"),": Chat conversation topic")),rn.default.createElement("i",{className:"tw-mt-2 tw-text-sm tw-text-muted"},"Example: ","{$date}_{$time}__{$topic}"," \u2192 20250114_153232__polish_this_article_[[Readme]]")))}))},rn.default.createElement("div",{className:"tw-flex tw-w-[320px] tw-items-center tw-gap-1.5"},rn.default.createElement(Ir,{type:"text",className:J("tw-min-w-[80px] tw-grow tw-transition-all tw-duration-200",r?"tw-w-[80px]":"tw-w-[120px]"),placeholder:"{$date}_{$time}__{$topic}",value:a,onChange:y=>l(y.target.value),disabled:r}),rn.default.createElement(oe,{onClick:()=>v(),disabled:r,variant:"secondary"},r?rn.default.createElement(rn.default.Fragment,null,rn.default.createElement(Dr,{className:"tw-mr-2 tw-size-4 tw-animate-spin"}),"Apply"):"Apply")))))))};yt();hl();B8e();Iv();LF();OP();gt();ko();_oe();De();pe();nA();dme();zu();dme();var s0n=L(B());function a0n(){return(0,s0n.useSyncExternalStore)(MUt,lY)}Is();Se();yt();De();zu();Pa();Re();var c0n=require("obsidian"),Zn=L(B()),l0n=({tone:t,children:e})=>Zn.default.createElement("div",{className:J("tw-mb-3 tw-inline-flex tw-size-10 tw-items-center tw-justify-center tw-rounded-lg",t==="warning"&&"tw-bg-project-yellow tw-text-warning",t==="info"&&"tw-text-accent tw-bg-interactive-accent/20",t==="success"&&"tw-bg-project-green tw-text-project-green")},e),yHr=({step:t,downloadUrl:e,canAutoAdd:n,onClose:r,onRetry:o,onAddVault:i})=>{let[s,a]=Zn.default.useState(!1),[l,c]=Zn.default.useState(!1),u=Zn.default.useCallback(async()=>{c(!1),a(!0);let d=await i();a(!1),d==="error"&&c(!0)},[i]);return Zn.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},t==="guide"&&Zn.default.createElement(Zn.default.Fragment,null,Zn.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Zn.default.createElement(l0n,{tone:"warning"},Zn.default.createElement(mc,{className:"tw-size-5"})),Zn.default.createElement("div",{className:"tw-text-lg tw-font-semibold tw-text-normal"},"Miyo isn't running"),Zn.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Copilot couldn't reach a local Miyo instance. If you haven't installed Miyo yet, download it; if it's installed, open the app, then retry.")),Zn.default.createElement("div",{className:"tw-flex tw-gap-2"},Zn.default.createElement(oe,{variant:"default",className:"tw-flex-1 tw-justify-center",onClick:()=>window.open(e,"_blank")},"Download Miyo ",Zn.default.createElement(us,{className:"tw-size-3.5"})),Zn.default.createElement(oe,{variant:"secondary",className:"tw-flex-1 tw-justify-center tw-border-none tw-shadow-none",onClick:()=>window.open(yX,"_blank")},Zn.default.createElement(K2,{className:"tw-size-3.5"})," Open Miyo")),Zn.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between"},Zn.default.createElement(oe,{variant:"ghost2",size:"sm",onClick:r},"Cancel"),Zn.default.createElement(oe,{variant:"link",size:"sm",className:"tw-border-none tw-bg-transparent tw-shadow-none",onClick:o},Zn.default.createElement(kh,{className:"tw-size-3.5"})," Retry connection"))),t==="addVault"&&Zn.default.createElement(Zn.default.Fragment,null,Zn.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Zn.default.createElement(l0n,{tone:"success"},Zn.default.createElement(RT,{className:"tw-size-5"})),Zn.default.createElement("div",{className:"tw-text-lg tw-font-semibold tw-text-normal"},"Register this vault with Miyo"),Zn.default.createElement("div",{className:"tw-text-sm tw-text-muted"},n?Zn.default.createElement(Zn.default.Fragment,null,"Miyo is running. Copilot will register"," ",Zn.default.createElement("span",{className:"tw-font-semibold tw-text-normal"},"this vault")," so Miyo can index it locally for search and chat \u2014 unlimited, no credits. The folders you register are the boundary Miyo works within; if you turn on Miyo's Relay connector, ChatGPT and Claude can reach this vault too."):Zn.default.createElement(Zn.default.Fragment,null,"Miyo is running, but"," ",Zn.default.createElement("span",{className:"tw-font-semibold tw-text-normal"},"this vault")," isn't added to it yet. Open Miyo, add this vault as a folder, then retry \u2014 Miyo indexes it locally for search and chat, unlimited and no credits. If you turn on Miyo's Relay connector, ChatGPT and Claude can reach it too.")),l&&Zn.default.createElement("div",{className:"tw-text-sm tw-text-error"},"Couldn't register this vault with Miyo. Please try again.")),n?Zn.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-end tw-gap-2"},Zn.default.createElement(oe,{variant:"secondary",size:"sm",onClick:r},"Cancel"),Zn.default.createElement(oe,{variant:"default",size:"sm",disabled:s,onClick:()=>void u()},s?Zn.default.createElement(Zn.default.Fragment,null,Zn.default.createElement(kh,{className:"tw-size-3.5 tw-animate-spin"})," Registering\u2026"):"Register & connect")):Zn.default.createElement(Zn.default.Fragment,null,Zn.default.createElement("div",{className:"tw-flex tw-gap-2"},Zn.default.createElement(oe,{variant:"default",className:"tw-flex-1 tw-justify-center",onClick:()=>window.open(_Kt,"_blank")},Zn.default.createElement(K2,{className:"tw-size-3.5"})," Open Miyo")),Zn.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between"},Zn.default.createElement(oe,{variant:"ghost2",size:"sm",onClick:r},"Cancel"),Zn.default.createElement(oe,{variant:"link",size:"sm",className:"tw-border-none tw-bg-transparent tw-shadow-none",onClick:o},Zn.default.createElement(kh,{className:"tw-size-3.5"})," Retry")))))},wPe=class extends c0n.Modal{constructor(n,r){super(n);this.options=r;this.root=null;this.step=r.initialStep}onOpen(){this.root=Er(this.contentEl,this.app),this.renderContent()}onClose(){this.root?.unmount(),this.root=null,this.options.onClose?.()}advanceTo(n){this.step=n,this.renderContent()}renderContent(){this.root?.render(Zn.default.createElement(yHr,{step:this.step,downloadUrl:this.options.downloadUrl,canAutoAdd:this.options.canAutoAdd,onClose:()=>this.close(),onRetry:()=>{Promise.resolve(this.options.onRetry()).then(n=>{this.root&&(n==="connected"?this.close():n==="needs-add"?this.advanceTo("addVault"):n==="unreachable"&&this.advanceTo("guide"))})},onAddVault:async()=>{let n=await this.options.onAddVault();return this.root&&n==="added"?this.close():this.root&&n==="unreachable"&&this.advanceTo("guide"),n}}))}};yt();De();Re();var gC=L(B()),vHr={available:"tw-text-success",unavailable:"tw-text-warning",unknown:"tw-text-faint",stale:"tw-text-faint",syncing:"tw-text-muted"},wHr={available:"tw-bg-success",unavailable:"tw-bg-warning/80",unknown:"tw-bg-faint/40",stale:"tw-bg-faint/40",syncing:"tw-bg-interactive-accent tw-animate-pulse"},$lt=({title:t,description:e,status:n,statusText:r,actionLabel:o,onAction:i,disabled:s=!1})=>gC.default.createElement("div",{className:"tw-flex tw-flex-col tw-items-start tw-justify-between tw-gap-4 tw-py-4 sm:tw-flex-row sm:tw-items-start"},gC.default.createElement("div",{className:"tw-w-full tw-space-y-1.5 sm:tw-w-[320px]"},gC.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2 tw-text-sm tw-font-medium tw-leading-none"},t),gC.default.createElement("div",{className:"tw-text-xs tw-text-muted"},e),gC.default.createElement("div",{className:J("tw-flex tw-items-center tw-gap-1.5 tw-text-xs tw-font-medium",vHr[n])},gC.default.createElement("span",{className:J("tw-size-1.5 tw-shrink-0 tw-rounded-full",wHr[n])}),r)),gC.default.createElement("div",{className:"tw-flex tw-w-full tw-flex-1 tw-items-center tw-gap-2 sm:tw-justify-end"},gC.default.createElement(oe,{variant:"secondary",size:"sm",onClick:i,disabled:s},o," ",gC.default.createElement(us,{className:"tw-size-3.5"}))));ut();_I();ha();Re();var Hd=require("obsidian"),mt=L(B()),u0n=q5,bHr=()=>mt.default.createElement("span",{className:"tw-rounded tw-px-1.5 tw-py-0.5 tw-text-smallest tw-font-semibold tw-uppercase tw-tracking-wide tw-text-accent tw-bg-interactive-accent/20"},"Relay");function _Hr(t){switch(t){case"available":return"Connected \u2014 tunnel & sign-in active";case"unavailable":return"Not set up \u2014 finish tunnel & sign-in in Miyo";default:return"Checking\u2026"}}function xHr(t){switch(t){case"available":return"Ready \xB7 chats indexed";case"syncing":return"Syncing chats\u2026";case"unavailable":return"Not set up \u2014 add chat sources in Miyo";default:return"Checking\u2026"}}var bPe=({title:t,description:e,control:n,indented:r=!1})=>mt.default.createElement("div",{className:J("tw-flex tw-flex-col tw-items-start tw-justify-between tw-gap-4 tw-py-4 sm:tw-flex-row sm:tw-items-center",r&&"!tw-pl-9")},mt.default.createElement("div",{className:"tw-w-full tw-space-y-1.5 sm:tw-w-[300px]"},mt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2 tw-text-sm tw-font-medium tw-leading-none"},t),mt.default.createElement("div",{className:"tw-text-xs tw-text-muted"},e)),mt.default.createElement("div",{className:"tw-flex tw-w-full tw-flex-1 tw-items-center tw-gap-2 sm:tw-justify-end"},n)),d0n=()=>{let t=vn(),e=xt(),n=a0n(),{miyoMutationSession:r}=P5(),[o,i]=(0,mt.useState)(e.miyoServerUrl||""),[s,a]=(0,mt.useState)(!1),[l,c]=(0,mt.useState)(!1),u=(0,mt.useRef)(!0),d=(0,mt.useRef)(null),f=(0,mt.useRef)(0),p=(0,mt.useRef)(0),m=(0,mt.useRef)(0),[h,g]=(0,mt.useState)(null),v=(0,mt.useRef)(0),y=(0,mt.useCallback)(()=>{v.current+=1,c(!0)},[]),w=(0,mt.useCallback)(()=>{v.current=Math.max(0,v.current-1),v.current===0&&u.current&&c(!1)},[]);(0,mt.useEffect)(()=>(u.current=!0,()=>{u.current=!1,f.current+=1,d.current?.close()}),[]);let _=(0,mt.useCallback)(async D=>{y();try{return(await ume({force:D})).backend==="available"}finally{w()}},[y,w]);(0,mt.useEffect)(()=>{_(!1)},[_]);let[S,I]=(0,mt.useState)(null),[C,k]=(0,mt.useState)(!1),[T,P]=(0,mt.useState)(0),E=(0,mt.useCallback)(()=>P(D=>D+1),[]),O=Ci(e),$=[...vg(e)].sort().join(`
`);(0,mt.useEffect)(()=>{I(null);let D=!1;return mPe(t,r).then(G=>{D||!u.current||(G==="stale"?I(!0):(G==="covered"||G==="unregistered")&&I(!1))}),()=>{D=!0}},[t,O,r,$,T]);let U=(0,mt.useCallback)(async()=>{k(!0);try{let D=await UIn(t,r);if(!u.current)return;switch(D){case"verified":new Hd.Notice("Miyo is already in sync with your Copilot folders."),I(!1);break;case"resynced":new Hd.Notice("Miyo resynced \u2014 excluded folders updated, re-index started."),I(!1);break;case"resynced-scan-failed":new Hd.Notice("Miyo resynced; indexing will catch up on Miyo's next scan."),I(!1);break;case"resynced-grants-reset":new Hd.Notice("Miyo resynced. This folder's registration had to be rebuilt, so its remote read and write access were turned off \u2014 re-enable them in the Miyo app if you want them.",1e4),I(!1);break;case"conflict":new Hd.Notice("Miyo reports a conflicting registration (possibly under this vault's previous name). Remove it in the Miyo app, then retry.");break;case"unregistered":new Hd.Notice("This vault isn't registered with Miyo. Reconnect to register it."),I(!1);break;case"failed":new Hd.Notice("Couldn't resync Miyo. Make sure Miyo is running, then retry.");break}}finally{u.current&&k(!1)}},[t,r]),V=(0,mt.useCallback)(async()=>{y();try{return await new jc().isBackendAvailable(Ci(e)||void 0)}finally{w()}},[e,y,w]),K=(0,mt.useCallback)(async D=>{let G=p.current+=1,ce=e.enableMiyo,Z=!e.enableSemanticSearchV3;At("enableMiyo",!0),Z&&At("enableSemanticSearchV3",!0);let te=await _(!0);return p.current===G&&(!te||D())&&(At("enableMiyo",ce),Z&&At("enableSemanticSearchV3",!1)),te},[e.enableMiyo,e.enableSemanticSearchV3,_]),se=(0,mt.useCallback)(()=>!!Hu(t)&&r$(Ci(e)),[t,e]),le=(0,mt.useCallback)(async()=>{let D=Ci(e),G=Hu(t);if(!G||!r$(D))return"manual";let ce=f.current+=1,Z=()=>f.current!==ce||!u.current;try{let fe=await pPe(async de=>{let ye=Y(),Te=Ci(ye);if(!r$(Te))throw new Error("Miyo endpoint switched to a remote target while registration was queued");return{created:await new jc({plusLicenseKey:ye.plusLicenseKey}).addFolder({path:G,allow_remote_read:!0,...$ye(ye.qaInclusions),...vX(ye.qaExclusions,[...vg(ye),...e$(t)])},Te||void 0,()=>$5(de)),receipt:JH(t,ye)}},r);fe.created!==null&&At("miyoSyncedExclusions",fe.receipt)}catch(fe){return W(`Miyo add-folder failed: ${kt(fe)}`),"error"}if(Z())return"unreachable";E();let te=await K(Z);return Z()?"unreachable":te?"added":"unreachable"},[t,e,K,E,r]),Q=(0,mt.useCallback)(async()=>{let D=f.current+=1,G=()=>f.current!==D||!u.current,ce=await V();if(G())return"superseded";if(!ce)return"unreachable";let Z=await new jc().checkFolderRegistration(Mp(t),Ci(e)||void 0);if(G())return"superseded";if(Z==="error")return"error";if(Z==="unregistered")return"needs-add";if(G())return"superseded";E();let te=await K(G);return G()?"superseded":te?"connected":"unreachable"},[t,e,V,K,E]),ne=(0,mt.useCallback)(async()=>{let D=await Q();return D==="superseded"?"error":(D==="error"&&u.current&&new Hd.Notice("Couldn't confirm this vault with Miyo. Please try again."),D)},[Q]),ee=(0,mt.useCallback)(D=>{d.current?.close();let G=new wPe(t,{initialStep:D,downloadUrl:u0n,canAutoAdd:se(),onClose:()=>{f.current+=1,d.current===G&&(d.current=null)},onRetry:()=>ne(),onAddVault:()=>le()});d.current=G,G.open()},[t,se,ne,le]),ae=(0,mt.useCallback)(async()=>{let D=await ne();u.current&&(D==="needs-add"?ee("addVault"):D==="unreachable"&&ee("guide"))},[ne,ee]),q=(0,mt.useCallback)(async()=>{f.current+=1,At("enableMiyo",!1),e.enableSemanticSearchV3&&At("enableSemanticSearchV3",!1),await _(!0)},[e.enableSemanticSearchV3,_]),F=Sw(e),z=(0,mt.useCallback)(async D=>{let G=m.current+=1,ce=()=>m.current!==G,Z=()=>!u.current;g(D);try{let{installMiyoSearchSkill:te,removeMiyoSearchSkill:fe}=await Promise.resolve().then(()=>(Hf(),d_));if(ce()||Z())return;if(D){let de=await te(t,F);if(ce())return;de==="installed"?(At("enableMiyoSearchSkill",!0),Z()||new Hd.Notice("Miyo search skill installed")):de==="collision"?Z()||new Hd.Notice("A skill named \u201Cmiyo-search\u201D already exists in your skills folder. Rename or remove it, then try again."):Z()||new Hd.Notice("Couldn't install the Miyo search skill. Please try again.")}else{let de=await fe(t,F);if(ce())return;if(de==="failed"){Z()||new Hd.Notice("Couldn't remove the Miyo search skill. Please try again.");return}At("enableMiyoSearchSkill",!1),de==="collision"&&!Z()&&new Hd.Notice("Disabled. A user-created \u201Cmiyo-search\u201D skill was left in place \u2014 remove it manually if you don't want it.")}}catch{!ce()&&!Z()&&new Hd.Notice("Couldn't update the Miyo search skill. Please try again.")}finally{!ce()&&!Z()&&g(null)}},[t,F]),N=(0,mt.useCallback)(()=>{let D=o.trim();D!==(e.miyoServerUrl||"")&&(f.current+=1,At("miyoServerUrl",D),_(!0))},[o,e.miyoServerUrl,_]),R=n.backend==="available"||n.backend==="stale",X=!r$(Ci(e));return mt.default.createElement("div",{className:"tw-space-y-4"},mt.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Local, private context that stays on your machine \u2014 unlimited, no credits."),(S===!0||S===null&&XH(t,e))&&mt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2 tw-rounded-lg tw-border tw-border-solid tw-px-3 tw-py-2.5 tw-text-xs tw-text-warning tw-bg-warning/10 tw-border-warning/30"},mt.default.createElement(Wr,{className:"tw-size-4 tw-shrink-0"}),mt.default.createElement("span",{className:"tw-flex-1"},"Miyo's excluded folders don't match your Copilot folder \u2014 chats could be indexed and exposed. Resync to update them."),se()?mt.default.createElement(oe,{size:"sm",variant:"secondary",disabled:C,onClick:()=>void U()},C?"Resyncing\u2026":"Resync Miyo"):mt.default.createElement("span",{className:"tw-shrink-0"},"Remove and re-add this folder in the Miyo app.")),mt.default.createElement(yu,{label:"Connection"},mt.default.createElement(bPe,{title:"Miyo",description:mt.default.createElement("span",null,"Runs locally and connects automatically. Don't have Miyo yet?"," ",mt.default.createElement("a",{href:u0n,target:"_blank",rel:"noopener noreferrer",className:"tw-inline-flex tw-items-center tw-gap-0.5 tw-text-accent"},"Download ",mt.default.createElement(us,{className:"tw-size-3.5"}))),control:e.enableMiyo?mt.default.createElement("button",{type:"button",onClick:()=>void q(),disabled:l,title:"Disconnect Miyo",className:J("tw-group tw-inline-flex tw-shrink-0 tw-cursor-pointer tw-items-center tw-gap-1.5 tw-rounded-full !tw-border-none !tw-px-3 !tw-py-1 tw-text-smallest tw-font-semibold !tw-shadow-none tw-transition-colors",R?"!tw-bg-success tw-text-success hover:!tw-bg-error hover:tw-text-error":"tw-text-warning !tw-bg-warning/20 hover:!tw-bg-error hover:tw-text-error")},mt.default.createElement("span",{className:"tw-size-1.5 tw-rounded-full tw-bg-current"}),mt.default.createElement("span",{className:"tw-grid tw-text-center"},mt.default.createElement("span",{className:"tw-col-start-1 tw-row-start-1 group-hover:tw-invisible"},R?`Connected \xB7 ${X?"remote":"local"}`:"Unavailable"),mt.default.createElement("span",{className:"tw-invisible tw-col-start-1 tw-row-start-1 group-hover:tw-visible"},"Disconnect"))):mt.default.createElement(oe,{variant:"default",size:"sm",onClick:()=>void ae(),disabled:l},l?"Connecting\u2026":"Connect")}),mt.default.createElement($lt,{title:mt.default.createElement(mt.default.Fragment,null,"Connector ",mt.default.createElement(bHr,null)),description:"Let ChatGPT / Claude read-write your local files and vault from the cloud.",status:n.connector,statusText:_Hr(n.connector),actionLabel:"Set up in Miyo",onAction:()=>window.open(xKt,"_blank")}),mt.default.createElement("div",null,mt.default.createElement(Ooe,{open:s,onClick:()=>a(D=>!D)}),s&&mt.default.createElement("div",{className:"tw-pb-2"},mt.default.createElement(_o,{type:"custom",title:"Remote Miyo server (advanced)",description:"Leave blank for local discovery, or point at a remote Miyo instance. The Connector above uses this endpoint."},mt.default.createElement(Ir,{value:o,onChange:D=>i(D.target.value),onBlur:N,placeholder:"Leave blank for local discovery",className:"tw-w-full sm:tw-w-[260px]"}))))),mt.default.createElement("div",{className:"tw-space-y-2"},mt.default.createElement("div",{className:"tw-text-xs tw-font-semibold tw-text-muted"},"Powered by Miyo"),mt.default.createElement("div",{className:"tw-text-sm tw-text-muted"},mt.default.createElement("span",{className:"tw-font-semibold tw-text-normal"},"Plus")," = Copilot cloud, uses credits \xB7 ",mt.default.createElement("span",{className:"tw-font-semibold tw-text-accent"},"Miyo")," = local, unlimited, on your machine"),!R&&mt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2 tw-rounded-lg tw-border tw-border-solid tw-px-3 tw-py-2.5 tw-text-xs tw-text-warning tw-bg-warning/10 tw-border-warning/30"},mt.default.createElement(Wr,{className:"tw-size-4 tw-shrink-0"}),"Connect to Miyo to configure these capabilities."),mt.default.createElement("div",{className:"tw-overflow-hidden tw-rounded-xl tw-border tw-border-solid tw-border-border tw-bg-primary tw-shadow-sm"},mt.default.createElement("div",{className:"tw-divide-y tw-divide-border"},(()=>{let D=e.enableMiyoSearchSkill||R;return mt.default.createElement("div",{className:J("tw-px-4",!D&&"tw-pointer-events-none tw-opacity-45"),"aria-disabled":!D},mt.default.createElement(bPe,{title:"Semantic search",description:"Understands meaning, not just keywords \u2014 finds related notes on-device.",control:mt.default.createElement(fp,{checked:h??e.enableMiyoSearchSkill,onCheckedChange:G=>void z(G),disabled:Hd.Platform.isMobile||!D||h!==null,"aria-label":"Enable Miyo semantic search skill"})}))})(),mt.default.createElement("div",{className:J("tw-divide-y tw-divide-border [&>*]:tw-px-4",!R&&"tw-pointer-events-none tw-opacity-45"),"aria-disabled":!R},mt.default.createElement(bPe,{indented:!0,title:mt.default.createElement("span",{className:"tw-flex tw-items-center tw-gap-1.5"},mt.default.createElement(uG,{className:"tw-size-3 tw-text-faint"}),"Search scope"),description:"Only the current vault, or everything Miyo has indexed.",control:mt.default.createElement(NX,{"aria-label":"Search scope",options:[{label:"Current vault",value:"current"},{label:"Unrestricted",value:"unrestricted"}],value:e.miyoSearchAll?"unrestricted":"current",onChange:D=>At("miyoSearchAll",D==="unrestricted"),disabled:!R})}),mt.default.createElement($lt,{title:"Search chat",description:"Search your ChatGPT / Claude chats locally. Set up chat sources and indexing in Miyo.",status:n.chatSync,statusText:xHr(n.chatSync),actionLabel:"Manage in Miyo",onAction:()=>window.open(SKt,"_blank"),disabled:!R})),mt.default.createElement("div",{className:"tw-px-4"},mt.default.createElement(bPe,{title:"Document Processor",description:"Processes PDF & EPUB locally via Miyo; other formats use Plus cloud.",control:mt.default.createElement(NX,{"aria-label":"Document Processor backend",options:[{label:"Plus",value:"plus"},{label:"Miyo",value:"miyo"}],value:e.docProcessorBackend,onChange:D=>At("docProcessorBackend",D)})}))))))};yt();Lh();Iv();LF();De();vc();Se();Re();var Ri=L(B()),SHr="byok",CHr="https://firecrawl.link/logan-yang",kHr="https://supadata.ai/?ref=obcopilot",IHr="https://docs.perplexity.ai",Dlt=({href:t})=>Ri.default.createElement("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"tw-text-accent"},"Sign up ",Ri.default.createElement(us,{className:"tw-inline tw-size-3 tw-align-text-bottom"})),f0n=()=>{let t=xt(),{setSelectedTab:e}=KTe(),n=Tgn(),r=t.enableSelfHostMode;return Ri.default.createElement("div",{className:"tw-space-y-4"},Ri.default.createElement("div",{className:"tw-flex tw-items-start tw-gap-2.5 tw-text-sm tw-text-muted"},Ri.default.createElement("span",{className:"tw-max-w-[620px]"},"Bring your own infrastructure \u2014 self-hosted search, web-search providers, and models."),Ri.default.createElement("span",{className:"tw-shrink-0 tw-rounded tw-bg-callout-warning/20 tw-px-2 tw-py-0.5 tw-text-smallest tw-font-semibold tw-text-warning"},"Lifetime license")),Ri.default.createElement(yu,null,Ri.default.createElement(_o,{type:"switch",title:"Enable Self-Host Mode",description:Ri.default.createElement("span",{className:"tw-inline-flex tw-items-center tw-gap-1.5"},"Route LLMs, embeddings and document understanding through your own endpoints.",Ri.default.createElement(rs,{content:"Believer / Supporter only. Use your own infrastructure for full control and offline use. Stays available offline until your entitlement expires."})),checked:r,onCheckedChange:o=>At("enableSelfHostMode",o),disabled:n!==!0&&!r}),Ri.default.createElement("div",{className:J("tw-flex tw-items-start tw-gap-2 tw-py-3 tw-text-xs tw-text-normal tw-bg-interactive-accent/10")},Ri.default.createElement(Tw,{className:"tw-mt-0.5 tw-size-4 tw-shrink-0 tw-text-accent"}),Ri.default.createElement("div",{className:"tw-leading-relaxed"},Ri.default.createElement("span",{className:"tw-font-semibold"},"Privacy-first.")," While Self-Host is on, cloud options (Claude, Codex, and BYOK cloud providers) are flagged with a warning and sorted below your local / self-hosted models. They stay selectable \u2014 you decide whether to use them."))),Ri.default.createElement("div",{className:J("tw-space-y-4",!r&&"tw-pointer-events-none tw-opacity-40")},Ri.default.createElement(yu,{label:"Web search providers"},Ri.default.createElement(_o,{type:"select",title:"Web Search Provider",description:"Your key turns this into an agent skill parameter.",value:t.selfHostSearchProvider,onChange:o=>At("selfHostSearchProvider",o),options:[{label:"Firecrawl",value:"firecrawl"},{label:"Perplexity Sonar",value:"perplexity"}],disabled:!r}),t.selfHostSearchProvider==="firecrawl"&&Ri.default.createElement(_o,{type:"password",title:"Firecrawl API Key",description:Ri.default.createElement("span",null,"Web search & fetch via Firecrawl. ",Ri.default.createElement(Dlt,{href:CHr})),value:t.firecrawlApiKey,onChange:o=>At("firecrawlApiKey",o),placeholder:"fc-\u2026",disabled:!r}),t.selfHostSearchProvider==="perplexity"&&Ri.default.createElement(_o,{type:"password",title:"Perplexity API Key",description:Ri.default.createElement("span",null,"Web search via Perplexity Sonar. ",Ri.default.createElement(Dlt,{href:IHr})),value:t.perplexityApiKey,onChange:o=>At("perplexityApiKey",o),placeholder:"pplx-\u2026",disabled:!r}),Ri.default.createElement(_o,{type:"password",title:"Supadata API Key",description:Ri.default.createElement("span",null,"YouTube transcripts via Supadata. ",Ri.default.createElement(Dlt,{href:kHr})),value:t.supadataApiKey,onChange:o=>At("supadataApiKey",o),placeholder:"sd-\u2026",disabled:!r})),Ri.default.createElement(yu,{label:"Self-hosted models"},Ri.default.createElement(_o,{type:"custom",title:"LLM & embedding models",description:Ri.default.createElement("span",null,"Add local / self-hosted models as an OpenAI-compatible endpoint in BYOK.")},Ri.default.createElement(oe,{variant:"secondary",size:"sm",onClick:()=>e(SHr),disabled:!r},"Open BYOK")))))};var m0n=["basic","byok","miyo","skills","command","selfhost","advanced"],THr=$r.default.lazy(()=>Promise.resolve().then(()=>(Hf(),d_)).then(t=>({default:t.SkillsSettings}))),PHr=()=>Ln()?$r.default.createElement($r.default.Suspense,{fallback:null},$r.default.createElement(THr,null)):$r.default.createElement(gPe,{message:"Skills are available on desktop."}),AHr={basic:$r.default.createElement(lG,{className:"tw-size-5"}),byok:$r.default.createElement(dG,{className:"tw-size-5"}),miyo:$r.default.createElement($G,{className:"tw-size-5"}),selfhost:$r.default.createElement(Tw,{className:"tw-size-5"}),command:$r.default.createElement(ET,{className:"tw-size-5"}),skills:$r.default.createElement(DG,{className:"tw-size-5"}),advanced:$r.default.createElement(Pw,{className:"tw-size-5"})},EHr={basic:()=>$r.default.createElement(i0n,null),byok:()=>$r.default.createElement(EUe,null),miyo:()=>$r.default.createElement(d0n,null),selfhost:()=>$r.default.createElement(f0n,null),command:()=>$r.default.createElement(OIn,null),skills:PHr,advanced:()=>$r.default.createElement($In,null)},MHr={basic:"Basic",byok:"BYOK",miyo:"Miyo",selfhost:"Self-Host",command:"Command",skills:"Skills",advanced:"Advanced"},p0n=m0n.map(t=>({id:t,icon:AHr[t],label:MHr[t]})),OHr=()=>{let{selectedTab:t,setSelectedTab:e}=KTe();return $r.default.createElement("div",{className:"tw-flex tw-flex-col"},$r.default.createElement("div",{className:"tw-flex tw-flex-wrap tw-rounded-lg"},p0n.map((n,r)=>$r.default.createElement(qTe,{key:n.id,tab:n,isSelected:t===n.id,onClick:()=>e(n.id),isFirst:r===0,isLast:r===p0n.length-1}))),$r.default.createElement("div",{className:"tw-w-full tw-border tw-border-solid"}),$r.default.createElement("div",null,m0n.map(n=>{let r=EHr[n];return $r.default.createElement(boe,{key:n,id:n,isSelected:t===n},$r.default.createElement(r,null))})))},NHr=({plugin:t})=>{let[e,n]=$r.default.useState(0),{latestVersion:r,hasUpdate:o}=CTe(t.manifest.version),i=()=>{new VTe(t.app,()=>{bAe(),n(a=>a+1)}).open()};return $r.default.createElement(Lkn,{plugin:t},$r.default.createElement(J8,{api:t.modelManagement},$r.default.createElement(Dkn,null,$r.default.createElement("div",{className:"tw-mx-auto tw-max-w-[860px]"},$r.default.createElement("div",{className:"tw-mb-4 tw-flex tw-flex-col tw-gap-2"},$r.default.createElement("div",{role:"heading","aria-level":1,className:"tw-flex tw-flex-col tw-gap-2 tw-text-base tw-font-semibold sm:tw-flex-row sm:tw-items-center sm:tw-justify-between"},$r.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},$r.default.createElement("span",null,"Copilot Settings"),$r.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},$r.default.createElement("span",{className:"tw-text-xs tw-font-normal tw-text-muted"},"v",t.manifest.version),r&&$r.default.createElement($r.default.Fragment,null,o?$r.default.createElement("a",{href:"obsidian://show-plugin?id=copilot",target:"_blank",rel:"noopener noreferrer",className:"tw-text-xs tw-font-normal tw-text-accent hover:tw-underline"},"(Update to v",r,")"):$r.default.createElement("span",{className:"tw-text-xs tw-font-normal tw-text-normal"}," ","(up to date)")))),$r.default.createElement("div",{className:"tw-self-end sm:tw-self-auto"},$r.default.createElement(oe,{variant:"secondary",size:"sm",onClick:i},"Reset Settings")))),$r.default.createElement(OHr,{key:e})))))},h0n=NHr;Pa();var _Pe=class extends Loe.PluginSettingTab{constructor(e,n){super(e,n),this.plugin=n}async reloadPlugin(){try{let e=this.app.workspace.getLeavesOfType(Fs)[0]?.view;if(e&&Y().enableRecentConversations)try{let o=this.plugin.chainOwner.getCurrentChainManager().chatModelManager.getChatModel();this.plugin.userMemoryManager.addRecentConversation(this.plugin.chatUIState.getMessages(),o)}catch(r){j("Failed to analyze chat messages for memory:",r)}e&&Y().autosaveChat&&await this.plugin.autosaveCurrentChat();let n=this.plugin.app;await n.plugins.disablePlugin("copilot"),await n.plugins.enablePlugin("copilot"),n.setting.openTabById("copilot").display(),new Loe.Notice("Plugin reloaded successfully.")}catch(e){new Loe.Notice("Failed to reload the plugin. Please reload manually."),H("Error reloading plugin:",e)}}display(){let{containerEl:e}=this;e.empty(),e.addClass("tw-select-text");let n=e.createDiv("div");Er(n,this.app).render(g0n.default.createElement(h0n,{plugin:this.plugin}))}};Se();zu();Is();Is();var RHr=[{label:"Chat conversations",legacyValue:t=>t.defaultSaveFolder,derive:zie},{label:"Custom prompts",legacyValue:t=>t.customPromptsFolder,derive:EC},{label:"System prompts",legacyValue:t=>t.userSystemPromptsFolder,derive:xT},{label:"Agent skills",legacyValue:t=>t.agentMode.skills.folder,derive:Sw},{label:"Memory",legacyValue:t=>t.memoryFolderName,derive:Hie}];function y0n(t){return t.trim().replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+|\/+$/g,"")}function v0n(t){return RHr.flatMap(e=>{let n=e.legacyValue(t),r=e.derive(t);return y0n(n)===y0n(r)?[]:[{label:e.label,oldPath:n,newPath:r}]})}function DF(t){return Object.keys(t).length>0}function Flt(t,e){let n={...t};for(let r of e)delete n[r];return n}var LHr=["binaryPath","envOverrides"],$Hr=["envOverrides"],DHr=["binaryPath","binaryVersion","binarySource","probeSessionId","envOverrides"];function FHr(t){let e={},n=t.claudeCli?.path;n&&(e.claudeCliPath=n);let r=t.backends?.codex;if(r){let s={};r.binaryPath&&(s.binaryPath=r.binaryPath),r.envOverrides&&(s.envOverrides=r.envOverrides),DF(s)&&(e.codex=s)}let o=t.backends?.opencode;if(o){let s={};o.binaryPath&&(s.binaryPath=o.binaryPath),o.binaryVersion&&(s.binaryVersion=o.binaryVersion),o.binaryPath&&o.binarySource&&(s.binarySource=o.binarySource),o.probeSessionId&&(s.probeSessionId=o.probeSessionId),o.envOverrides&&(s.envOverrides=o.envOverrides),DF(s)&&(e.opencode=s)}let i=t.backends?.claude;return i?.envOverrides&&(e.claude={envOverrides:i.envOverrides}),e}function w0n(t){let e={};if(!t)return e;if(t.codex){let n=Flt(t.codex,LHr);DF(n)&&(e.codex=n)}if(t.claude){let n=Flt(t.claude,$Hr);DF(n)&&(e.claude=n)}if(t.opencode){let n=Flt(t.opencode,DHr);DF(n)&&(e.opencode=n)}return e}function b0n(t,e){let n=t?.agentMode;if(!n)return t;let r=FHr(n),o={...n.deviceProfiles??{}};DF(r)?o[e]=r:delete o[e];let i={...n,claudeCli:void 0,backends:w0n(n.backends),deviceProfiles:DF(o)?o:void 0};return{...t,agentMode:i}}function _0n(t,e){let n=t.agentMode;if(!n)return t;let r=n.deviceProfiles?.[e],o=w0n(n.backends);r?.codex&&(o.codex={...o.codex,...r.codex}),r?.opencode&&(o.opencode={...o.opencode,...r.opencode}),r?.claude&&(o.claude={...o.claude,...r.claude});let i={...n,backends:o,claudeCli:r?.claudeCliPath?{path:r.claudeCliPath}:void 0};return{...t,agentMode:i}}gX();$n();$n();var x0n=Symbol.for("obsidian-copilot:setMaxListeners-shim");function UHr(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.aborted=="boolean"&&typeof e.dispatchEvent=="function"}function S0n(){if(!Ln())return;let{EventEmitter:t}=Pe("events"),e=t,n=e.setMaxListeners;if(n[x0n])return;let r=function(...o){try{n.apply(this,o)}catch(i){let s=o.slice(1);if(s.length===0||!s.every(UHr))throw i}};r[x0n]=!0,e.setMaxListeners=r}bbe();x0();pe();var xPe=class{constructor(e){this.chatManager=e;this.listeners=new Set;this.chatManager.setOnMessageCreatedCallback(()=>{this.notifyListeners()})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notifyListeners(){this.listeners.forEach(e=>{try{e()}catch(n){j("[ChatUIState] Error in listener:",n)}})}async sendMessage(e,n,r,o=!1,i=!1,s,a){let l=await this.chatManager.sendMessage(e,n,r,o,i,s,a);return this.notifyListeners(),l}async editMessage(e,n,r,o=!1){let i=await this.chatManager.editMessage(e,n,r,o);return i&&this.notifyListeners(),i}async regenerateMessage(e,n,r){let o=await this.chatManager.regenerateMessage(e,n,i=>{r(i),this.notifyListeners()},()=>{this.notifyListeners()});return o&&this.notifyListeners(),o}async deleteMessage(e){let n=await this.chatManager.deleteMessage(e);return n&&this.notifyListeners(),n}clearMessages(){this.chatManager.clearMessages(),this.notifyListeners()}async truncateAfterMessageId(e){await this.chatManager.truncateAfterMessageId(e),this.notifyListeners()}getMessages(){return this.chatManager.getDisplayMessages()}getMessage(e){return this.chatManager.getMessage(e)}getLLMMessage(e){return this.chatManager.getLLMMessage(e)}getLLMMessages(){return this.chatManager.getLLMMessages()}get chatHistory(){return this.getMessages()}addMessage(e){this.chatManager.addMessage(e),this.notifyListeners()}clearChatHistory(){this.clearMessages()}async replaceMessages(e){await this.chatManager.loadMessages(e),this.notifyListeners()}getDebugInfo(){return this.chatManager.getDebugInfo()}async loadMessages(e){await this.chatManager.loadMessages(e),this.notifyListeners()}async saveChat(e){await this.chatManager.saveChat(e)}async loadChatHistory(e){await this.chatManager.loadChatHistory(e),this.notifyListeners()}};Wee();pe();Py();var SPe=class t{constructor(){this.cacheDir=".copilot/pdf-cache"}static getInstance(){return t.instance||(t.instance=new t),t.instance}async ensureCacheDir(e){await e.adapter.exists(this.cacheDir)||(j("Creating PDF cache directory:",this.cacheDir),await e.adapter.mkdir(this.cacheDir))}getCacheKey(e){let n=`${e.path}:${e.stat.size}:${e.stat.mtime}`,r=jl(n);return j("Generated cache key for PDF:",{path:e.path,key:r}),r}getCachePath(e){return`${this.cacheDir}/${e}.json`}async get(e,n){try{let r=this.getCacheKey(n),o=this.getCachePath(r);if(await e.adapter.exists(o)){j("Cache hit for PDF:",n.path);let i=await e.adapter.read(o);return JSON.parse(i)}return j("Cache miss for PDF:",n.path),null}catch(r){return H("Error reading from PDF cache:",r),null}}async set(e,n,r){try{await this.ensureCacheDir(e);let o=this.getCacheKey(n),i=this.getCachePath(o);j("Caching PDF response for:",n.path),await e.adapter.write(i,JSON.stringify(r))}catch(o){H("Error writing to PDF cache:",o)}}async clear(e){try{if(await e.adapter.exists(this.cacheDir)){let n=await e.adapter.list(this.cacheDir);j("Clearing PDF cache, removing files:",n.files.length);for(let r of n.files)await e.adapter.remove(r)}}catch(n){H("Error clearing PDF cache:",n)}}};pe();nA();zu();Se();pe();ut();async function C0n(t,e,n,r){let o=r?.trim();if(o&&t.extension!=="md"&&!(!e||e.startsWith("[Error:")))try{await ao(n,o);let i=`${o}/${t.basename}.md`;if(await n.adapter.exists(i)){let a=await n.adapter.read(i);if(a&&!a.startsWith(`<!-- source: ${t.path} -->`)){let l=t.path.replace(/\.[^.]+$/,"").replace(/[/\\]/g,"__");if(i=`${o}/${l}.md`,await n.adapter.exists(i)){let c=await n.adapter.read(i);if(c&&!c.startsWith(`<!-- source: ${t.path} -->`)){W(`Skipping converted doc output for ${t.path}: collision at ${i}`);return}}}}let s=`<!-- source: ${t.path} -->
${e}`;if(await n.adapter.exists(i)&&await n.adapter.read(i)===s)return;await n.adapter.write(i,s),j(`Saved converted doc output: ${i}`)}catch(i){H(`Failed to save converted doc output for ${t.path}:`,i)}}function k0n(t){if(!t||typeof t!="object")return!1;let e=t,n=e.message||"";return n.includes("Request rate limit exceeded")||n.includes("RATE_LIMIT_EXCEEDED")||n.includes("429")||e.status===429}function I0n(t){let r=(t?.message||"").match(/Try again in ([\d\w\s]+)/);return r?r[1]:"some time"}var A0n=require("obsidian");var T0n=require("obsidian");var kPe,P0n,CPe=class{constructor(e){this.vault=e;Rt(this,kPe)}async load(e){let n=await this.vault.read(e),{nodes:r=[],edges:o=[]}=JSON.parse(n),i=await Promise.all(r.map(async l=>{if(l.type==="file"&&l.file){let c=this.vault.getAbstractFileByPath(l.file),u=c instanceof T0n.TFile?await this.vault.read(c):"";return{...l,content:u}}return l.type==="text"?{...l,content:l.text??""}:{...l,content:""}})),s=[...o];Je(this,kPe,P0n).call(this,i,s);let a=Object.fromEntries(i.map(l=>[l.id,l]));return{nodes:i,edges:s,byId:a}}buildPrompt(e){let n=new Map,r=e.nodes.filter(a=>a.type==="group");for(let a of r){let l=e.nodes.filter(c=>{if(c.id===a.id)return!1;let u=c.x+c.width/2,d=c.y+c.height/2;return u>=a.x&&d>=a.y&&u<=a.x+a.width&&d<=a.y+a.height});n.set(a.label||a.id,l)}let o=`This canvas contains the following elements:
`,i=a=>{switch(a.type){case"file":return`- File: ${a.file}
Content:
${a.content}
`;case"text":return`- Text: "${a.text}"
`;case"link":return`- Link: ${a.url}
`;default:return""}};r.forEach(a=>{let l=a.label||a.id,c=n.get(l)||[];o+=`Group "${l}" contains:
`,c.forEach(u=>{o+=i(u)}),o+=`
`});let s=e.nodes.filter(a=>a.type==="group"?!1:!Array.from(n.values()).flat().some(l=>l.id===a.id));return s.length>0&&(o+=`Elements outside of groups:
`,s.forEach(a=>{o+=i(a)})),o+=`
When describing this canvas, please:
`,o+=`- Use the actual titles/names of elements instead of their IDs
`,o+=`- Pay attention to the content and relationships between elements
`,o+=`- Describe files by their names, links by their URLs, and text nodes by their content
`,o}};kPe=new WeakSet,P0n=function(e,n){let r=e.filter(o=>o.type==="group");for(let o of r)for(let i of e){if(i.id===o.id)continue;let s=i.x+i.width/2,a=i.y+i.height/2;s>=o.x&&a>=o.y&&s<=o.x+o.width&&a<=o.y+o.height&&n.push({id:crypto.randomUUID(),fromNode:o.id,toNode:i.id,label:"contains"})}};var jHr=new Set(["pdf","epub"]);function zlt(t){return jHr.has(t.extension.toLowerCase())}async function IPe(t,e,n){let r=Y().convertedDocOutputFolder??"";await C0n(t,e,n,r)}var TPe=class{constructor(){this.miyoClient=new jc}async parseDoc(e,n){let r=Y();if(!zlt(e))return null;try{let o=await this.miyoClient.resolveBaseUrl(Ci(r)),i=n.getName(),s=await this.miyoClient.parseDoc(o,i,e.path);return typeof s.text!="string"||s.text.trim().length===0?{error:"Miyo parse-doc returned empty text"}:(j(`[SelfHostDocParser] Parsed document via Miyo: ${e.path}`),{content:s.text})}catch(o){let i=o instanceof Error?o.message:String(o);return W(`[SelfHostDocParser] Failed to parse ${e.path} via Miyo parse-doc: ${i}`),{error:i}}}},Ult=class{constructor(){this.supportedExtensions=["md","base"]}async parseFile(e,n){return await n.read(e)}},PPe=class{constructor(e){this.supportedExtensions=["pdf"];this.brevilabsClient=e,this.pdfCache=SPe.getInstance(),this.selfHostDocParser=new TPe}async parseFile(e,n){try{j("Parsing PDF file:",e.path);let r=await this.pdfCache.get(n,e);if(r)return j("Using cached PDF content for:",e.path),await IPe(e,r.response,n),r.response;let o=Y(),i=zlt(e)?await O9e(o):"plus";if(i==="miyo-unavailable")return W(`[PDFParser] Miyo unavailable for ${e.path}; not falling back to cloud`),`[Error: Could not extract content from PDF ${e.basename}. Miyo (local document processor) is unavailable \u2014 reconnect it or switch the Document Processor to Plus in settings.]`;if(i==="miyo"){let l=await this.selfHostDocParser.parseDoc(e,n);if(l&&"content"in l)return await this.pdfCache.set(n,e,{response:l.content,elapsed_time_ms:0}),await IPe(e,l.content,n),l.content;if(l&&"error"in l)return W(`[PDFParser] Miyo parse failed for ${e.path}: ${l.error}`),`[Error: Could not extract content from PDF ${e.basename}. ${l.error}]`}let s=await n.readBinary(e);j("Calling pdf4llm API for:",e.path);let a=await this.brevilabsClient.pdf4llm(s);return await this.pdfCache.set(n,e,a),await IPe(e,a.response,n),a.response}catch(r){return H(`Error extracting content from PDF ${e.path}:`,r),`[Error: Could not extract content from PDF ${e.basename}]`}}async clearCache(e){j("Clearing PDF cache"),await this.pdfCache.clear(e)}},jlt=class{constructor(){this.supportedExtensions=["canvas"]}async parseFile(e,n){try{j("Parsing Canvas file:",e.path);let r=new CPe(n),o=await r.load(e);return r.buildPrompt(o)}catch(r){return H(`Error parsing Canvas file ${e.path}:`,r),`[Error: Could not parse Canvas file ${e.basename}]`}}},BHr=["pdf","602","abw","cgm","cwk","doc","docx","docm","dot","dotm","hwp","key","lwp","mw","mcw","pages","pbd","ppt","pptm","pptx","pot","potm","potx","rtf","sda","sdd","sdp","sdw","sgl","sti","sxi","sxw","stw","sxg","txt","uof","uop","uot","vor","wpd","wps","xml","zabw","epub","jpg","jpeg","png","gif","bmp","svg","tiff","webp","web","htm","html","xlsx","xls","xlsm","xlsb","xlw","csv","dif","sylk","slk","prn","numbers","et","ods","fods","uos1","uos2","dbf","wk1","wk2","wk3","wk4","wks","123","wq1","wq2","wb1","wb2","wb3","qpw","xlr","eth","tsv","mp3","mp4","mpeg","mpga","m4a","wav","webm"],$oe=class $oe{constructor(){this.supportedExtensions=[...BHr];this.selfHostDocParser=new TPe}async parseFile(e,n){try{j(`[Docs4LLMParser] Parsing ${e.extension} file: ${e.path}`);let r=zlt(e)?await O9e():"plus";if(r==="miyo-unavailable")throw new Error(`Miyo (local document processor) is unavailable for ${e.basename}; not falling back to cloud. Reconnect Miyo or switch the Document Processor to Plus.`);if(r==="miyo"){let o=await this.selfHostDocParser.parseDoc(e,n);if(o&&"content"in o)return await IPe(e,o.content,n),j(`[Docs4LLMParser] Parsed document via Miyo: ${e.path}`),o.content;if(o&&"error"in o)throw new Error(`Miyo failed to parse ${e.basename}: ${o.error}`)}throw new Error(`No document processor available for ${e.basename}. Enable Miyo to convert this file type locally.`)}catch(r){throw H(`[Docs4LLMParser] Error processing file ${e.path}:`,r),k0n(r)&&this.showRateLimitNotice(r),r}}showRateLimitNotice(e){let n=Date.now();if(n-$oe.lastRateLimitNoticeTime<6e4)return;$oe.lastRateLimitNoticeTime=n;let r=I0n(e);new A0n.Notice(`\u26A0\uFE0F Rate limit exceeded for document processing. Please try again in ${r}.`,1e4)}};$oe.lastRateLimitNoticeTime=0;var Blt=$oe,APe=class{constructor(e,n){this.parsers=new Map;this.registerParser(new Ult),this.registerParser(new Blt),this.registerParser(new PPe(e)),this.registerParser(new jlt)}registerParser(e){for(let n of e.supportedExtensions)this.parsers.set(n,e)}async parseFile(e,n){let r=this.parsers.get(e.extension);if(!r)throw new Error(`No parser found for file type: ${e.extension}`);return await r.parseFile(e,n)}supportsExtension(e){return this.parsers.has(e)}async clearPDFCache(e){let n=this.parsers.get("pdf");n instanceof PPe&&await n.clearCache(e)}};var G0n=require("obsidian");var V0n=require("@codemirror/state"),q0n=require("@codemirror/view");var H0n=L(B());var Doe=new WeakMap;function zHr(t){return t.startsWith("--")?t:t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}var E0n=new Set(["z-index","zIndex","opacity","flex","flex-grow","flexGrow","flex-shrink","flexShrink","font-weight","fontWeight","line-height","lineHeight","order","orphans","widows","tab-size","tabSize","column-count","columnCount"]);function HHr(t){let e=new Map;for(let[n,r]of Object.entries(t)){if(r==null)continue;let o=zHr(n),i;typeof r=="number"&&!n.startsWith("--")?i=E0n.has(n)||E0n.has(o)?String(r):`${r}px`:i=String(r),e.set(o,i)}return e}function M0n(t,e){if(!e)return;let n=`${e}-`;Array.from(t.classList).filter(o=>o.startsWith(n)).forEach(o=>{t.classList.remove(o)})}function EPe(t,e,n){if(!t)return;let r=HHr(n),o=Doe.get(t);o&&o.prefix&&o.prefix!==e&&M0n(t,o.prefix);let i=o?.properties??new Set,s=new Set,a={};if(i.forEach(l=>{r.has(l)||(a[l]="")}),r.forEach((l,c)=>{a[c]=l,s.add(c)}),Object.keys(a).length>0&&t.setCssProps(a),s.size===0){Doe.delete(t);return}Doe.set(t,{properties:s,prefix:e})}function O0n(t){let e=Doe.get(t);if(!e)return;let n={};e.properties.forEach(r=>{n[r]=""}),Object.keys(n).length>0&&t.setCssProps(n),e.prefix&&M0n(t,e.prefix),Doe.delete(t)}var Un=L(B()),FF=require("obsidian");Re();es();Se();ut();w_e();RP();Lh();var dw=L(B()),Hlt=require("obsidian");Gf();Og();ko();pe();function N0n(t){let e=vn(),{selectedText:n,selectedModelKey:r,includeNoteContext:o}=t,[i,s]=(0,dw.useState)([]),a=(0,dw.useRef)(!0);(0,dw.useEffect)(()=>(a.current=!0,()=>{a.current=!1}),[]);let l=gTe(e,r),{isStreaming:c,streamingText:u,runTurn:d,stop:f,reset:p}=vTe({model:l,systemPrompt:cTe,excludeThinking:!0,onNoModel:()=>{H("No active model is configured. Please configure a model in Copilot settings."),new Hlt.Notice("No active model configured. Please configure a model in Copilot settings.")},onNonAbortError:y=>{H("Error generating response:",y),new Hlt.Notice("Error generating response. Please try again.")}}),m=(0,dw.useCallback)(async y=>{if(!y.trim())return;let w={id:Co(),role:"user",content:y,timestamp:Date.now()};s(S=>[...S,w]);let _=await d(async S=>{let I=y;return S.isFirstTurn&&(I=uTe(y,o)),S.signal.aborted?"":await ate(e,I,n,!S.isFirstTurn)});if(a.current)if(_){let S={id:Co(),role:"assistant",content:_,timestamp:Date.now()};s(I=>[...I,S])}else s(S=>S[S.length-1]?.id===w.id?S.slice(0,-1):S)},[e,o,d,n]),h=(0,dw.useCallback)(()=>{f()},[f]),g=(0,dw.useCallback)(()=>{s([]),p()},[p]);return{messages:(0,dw.useMemo)(()=>!c||!u?i:[...i,{id:"streaming",role:"assistant",content:u,timestamp:Date.now()}],[i,c,u]),isStreaming:c,sendMessage:m,stop:h,clear:g}}var Ll=L(B()),R0n=require("obsidian");Re();yt();pe();$Se();var L0n=Ll.default.memo(function({message:e,isStreaming:n,isLastAssistantMessage:r,onCopy:o,onInsert:i,onReplace:s,hasSelection:a,isReplaceValid:l,replaceInvalidReason:c,isDisabledDueToStreaming:u,filePathSnapshot:d,plugin:f}){let p=(0,Ll.useRef)(null);if((0,Ll.useEffect)(()=>{if(e.role!=="assistant"||n)return;let h=!1;return(async()=>{let v=p.current;if(!v)return;v.empty();let y=d??"";try{let w=UV(e.content);await R0n.MarkdownRenderer.renderMarkdown(w,v,y,f)}catch(w){if(H("Failed to render markdown:",w),h)return;v.empty(),v.textContent=e.content}h||v.classList.add("markdown-rendered")})(),()=>{h=!0}},[e.content,e.role,n,d,f]),e.role==="user")return Ll.default.createElement("div",{className:"tw-max-w-[85%] tw-self-end tw-rounded-lg tw-rounded-br-sm tw-bg-interactive-accent tw-px-3 tw-py-2 tw-text-on-accent"},Ll.default.createElement("div",{"data-quick-ask-selectable":!0,className:"tw-whitespace-pre-wrap tw-break-words tw-text-sm"},e.content));if(n)return Ll.default.createElement("div",{className:"tw-max-w-[95%] tw-self-start tw-rounded-lg tw-rounded-bl-sm tw-bg-secondary tw-px-3 tw-py-2"},Ll.default.createElement("div",{"data-quick-ask-selectable":!0,className:"tw-whitespace-pre-wrap tw-break-words tw-text-sm tw-text-normal"},e.content,Ll.default.createElement("span",{className:"tw-animate-pulse tw-text-accent"},"\u258A")));let m=r?"tw-opacity-100":"tw-opacity-0 group-hover/message:tw-opacity-100";return Ll.default.createElement("div",{className:"tw-group/message tw-max-w-[95%] tw-self-start"},Ll.default.createElement("div",{className:"tw-rounded-lg tw-rounded-bl-sm tw-bg-secondary tw-px-3 tw-py-2"},Ll.default.createElement("div",{ref:p,"data-quick-ask-selectable":!0,className:"tw-text-sm [&.markdown-rendered]:tw-text-sm [&_code]:tw-text-xs [&_p]:tw-my-1 [&_pre]:tw-my-2"})),e.content&&Ll.default.createElement("div",{className:`tw-mt-1 tw-flex tw-items-center tw-gap-0.5 tw-transition-opacity ${m}`},Ll.default.createElement(oe,{variant:"ghost2",size:"icon",className:"tw-size-5 hover:tw-bg-modifier-hover",onClick:()=>o(e.id),title:"Copy to clipboard"},Ll.default.createElement(rN,{className:"tw-size-3"})),Ll.default.createElement(oe,{variant:"ghost2",size:"icon",className:"tw-size-5 hover:tw-bg-modifier-hover",onClick:()=>i(e.id),title:"Insert at cursor"},Ll.default.createElement(sG,{className:"tw-size-3"})),a&&Ll.default.createElement(oe,{variant:"ghost2",size:"icon",className:"tw-size-5 hover:tw-bg-modifier-hover",onClick:()=>s(e.id),disabled:!l,title:u?"Stop generating to replace":l?"Replace selection":p5(c)},Ll.default.createElement(OG,{className:"tw-size-3"}))))});var Ss=L(B());$o();NQe();iet();aet();met();get();bet();wV();bV();_V();SV();xV();Net();Ret();Let();$et();Det();Fet();Oet();Eet();Dxe();De();pe();gt();var $0n=Ss.default.memo(function({value:e,onChange:n,onSubmit:r,sendShortcut:o="enter",placeholder:i="Ask a question...",disabled:s=!1,className:a="",onNotesChange:l,onNotesRemoved:c,onFoldersChange:u,onFoldersRemoved:d,onActiveNoteAdded:f,onActiveNoteRemoved:p,onEditorReady:m,currentActiveFile:h=null}){let[g,v]=(0,Ss.useState)(null),y=(0,Ss.useCallback)(I=>{v(()=>I)},[]);(0,Ss.useEffect)(()=>{if(g){let I=window.setTimeout(()=>{g()},50);return()=>window.clearTimeout(I)}},[g]);let w=Ss.default.useMemo(()=>({namespace:"QuickAskEditor",theme:{root:"tw-outline-none",paragraph:"tw-m-0"},nodes:[hM,yM,m0,h0,vM],onError:I=>{H("QuickAskInput Lexical error:",I)},editable:!s}),[s]),_=(0,Ss.useCallback)(I=>{I.read(()=>{let k=ho().getTextContent();n(k)})},[n]),S=(0,Ss.useCallback)(I=>{m?.(I)},[m]);return Ss.default.createElement(Wxe,{initialConfig:w},Ss.default.createElement($xe,{currentActiveFile:h},Ss.default.createElement("div",{className:J("tw-relative",a)},Ss.default.createElement(Xxe,{contentEditable:Ss.default.createElement(Qxe,{className:"tw-max-h-48 tw-min-h-12 tw-w-full tw-resize-none tw-overflow-y-auto tw-border-none tw-bg-transparent tw-px-1 tw-py-2 tw-pr-8 tw-text-sm tw-text-normal tw-outline-none","aria-label":"Quick Ask input"}),placeholder:Ss.default.createElement("div",{className:"tw-pointer-events-none tw-absolute tw-left-1 tw-top-2 tw-select-none tw-text-sm tw-text-muted/60"},i),ErrorBoundary:sSe}),Ss.default.createElement(iSe,{onChange:_}),Ss.default.createElement(rSe,null),Ss.default.createElement(ySe,{onSubmit:r,sendShortcut:o}),Ss.default.createElement(vSe,{value:e}),Ss.default.createElement(wSe,{onFocus:y,onEditorReady:S}),Ss.default.createElement(_Se,{onNotesChange:l,onNotesRemoved:c}),Ss.default.createElement(xSe,{onFoldersChange:u,onFoldersRemoved:d}),Ss.default.createElement(SSe,{onActiveNoteAdded:f,onActiveNoteRemoved:p}),Ss.default.createElement(gSe,null),Ss.default.createElement(hSe,{isCopilotPlus:!1,showTools:!1,currentActiveFile:h}))))});yt();Hl();function D0n({plugin:t,view:e,selectedText:n,replaceGuard:r,onClose:o,onDragOffset:i,onResizeStart:s,hasCustomHeight:a}){let[l,c]=(0,Un.useState)(""),u=(0,Un.useRef)(null),d=(0,Un.useRef)(null),f=(0,Un.useRef)(!0),p=t.app.workspace.getActiveFile(),h=(0,Un.useRef)(p?.path??null).current,g=xt(),[v]=CT(),y=g.quickCommandModelKey??v,[w,_]=(0,Un.useState)(()=>g.quickCommandIncludeNoteContext),{messages:S,isStreaming:I,sendMessage:C,stop:k,clear:T}=N0n({selectedText:n,selectedModelKey:y,includeNoteContext:w}),P=S.length>0,E=r.getRange(),O=!!E&&E.from!==E.to,$=S[S.length-1]?.id,U=(0,Un.useMemo)(()=>S.reduce((Z,te,fe)=>te.role==="assistant"?fe:Z,-1),[S]),V=(0,Un.useCallback)(()=>{let Z=d.current?.getBoundingClientRect();return Z?{x:Z.left,y:Z.top}:{x:0,y:0}},[]),K=(0,Un.useCallback)(Z=>{i?.(Z)},[i]),{handleMouseDown:se}=fTe({dragRef:d,bounds:null,writeToDom:!1,getPosition:V,onPositionChange:K}),le=(0,Un.useCallback)(Z=>te=>{te.preventDefault(),te.stopPropagation(),s?.(Z,{x:te.clientX,y:te.clientY})},[s]),Q=(0,Un.useCallback)(async()=>{if(!l.trim()||I)return;let Z=l;c(""),await C(Z)},[l,I,C]),ne=(0,Un.useCallback)(Z=>{Z.stopPropagation(),Z.key==="Escape"&&!Z.defaultPrevented&&(Z.preventDefault(),o())},[o]),ee=(0,Un.useCallback)(Z=>{Z.stopPropagation()},[]);(0,Un.useEffect)(()=>{let Z=u.current;if(!Z)return;let te=24,fe=()=>Z.scrollHeight-Z.scrollTop-Z.clientHeight<=te,de=()=>{f.current=fe()};return f.current=fe(),Z.addEventListener("scroll",de),()=>{Z.removeEventListener("scroll",de)}},[P]),(0,Un.useEffect)(()=>{let Z=u.current;Z&&f.current&&(Z.scrollTop=Z.scrollHeight)},[S]);let ae=(0,Un.useCallback)(async Z=>{let te=S.find(fe=>fe.id===Z);if(te&&te.role==="assistant"){let fe=_h(te.content);try{await navigator.clipboard.writeText(fe),new FF.Notice("Copied to clipboard")}catch{new FF.Notice("Failed to copy to clipboard")}}},[S]),q=(0,Un.useCallback)(Z=>{let te=S.find(fe=>fe.id===Z);if(!(!te||te.role!=="assistant"))try{let fe=_h(te.content),de=e.state.selection.main.to,ye=e.state.toText(fe);e.dispatch({changes:{from:de,to:de,insert:ye},selection:{anchor:de,head:de+ye.length}}),e.focus(),new FF.Notice("Inserted"),o()}catch{new FF.Notice("Failed to insert. Editor may have changed.")}},[S,e,o]),F=(0,Un.useCallback)(Z=>{let te=S.find(ye=>ye.id===Z);if(!te||te.role!=="assistant")return;let fe=_h(te.content),de=r.replace(fe);if(!de.ok){new FF.Notice(de.message??"Cannot replace.");return}new FF.Notice("Replaced"),o()},[S,r,o]),z=(0,Un.useCallback)(Z=>{At("quickCommandModelKey",Z)},[]),N=h5({value:y,onChange:z}),R=(0,Un.useCallback)(Z=>{_(Z),At("quickCommandIncludeNoteContext",Z)},[]),X=O&&!I?r.validate():null,D=!!X?.ok,G=X?.reason??null,ce=O&&I;return Un.default.createElement("div",{ref:d,className:`tw-group tw-relative tw-flex tw-size-full tw-flex-col tw-rounded-lg tw-rounded-b-none tw-border tw-border-solid tw-border-border tw-bg-primary tw-shadow-lg${P&&!a?" tw-max-h-[min(500px,70vh)]":""}`,onKeyDown:ne,onKeyUp:ee,onBeforeInput:ee,onInput:ee,onMouseDown:ee,onMouseUp:ee,onClick:ee},Un.default.createElement("div",{className:"tw-relative tw-flex-none"},Un.default.createElement("div",{className:"tw-flex tw-h-4 tw-cursor-grab tw-items-center tw-justify-center hover:tw-bg-[color-mix(in_srgb,var(--background-modifier-hover)_20%,transparent)] active:tw-cursor-grabbing",onMouseDown:se},Un.default.createElement("div",{className:"tw-h-[5px] tw-w-16 tw-rounded-sm tw-bg-[color-mix(in_srgb,var(--text-muted)_40%,transparent)] hover:tw-bg-[color-mix(in_srgb,var(--text-muted)_65%,transparent)]"})),Un.default.createElement(oe,{className:"tw-absolute tw-right-2 tw-top-1 tw-rounded tw-p-1 tw-text-normal",variant:"ghost2",onClick:o,title:"Close"},Un.default.createElement(pn,{className:"tw-size-4"}))),P&&Un.default.createElement("div",{ref:u,"data-quick-ask-scroll":"true",className:"tw-flex tw-min-h-0 tw-flex-1 tw-flex-col tw-gap-2 tw-overflow-y-auto tw-px-3 tw-py-2"},S.map((Z,te)=>Un.default.createElement(L0n,{key:Z.id,message:Z,isStreaming:I&&Z.id===$&&Z.role==="assistant",isLastAssistantMessage:Z.role==="assistant"&&te===U,onCopy:xn(ae),onInsert:q,onReplace:F,hasSelection:O,isReplaceValid:D,replaceInvalidReason:G,isDisabledDueToStreaming:ce,filePathSnapshot:h,plugin:t}))),!P&&a&&Un.default.createElement("div",{className:"tw-flex-1"}),Un.default.createElement("div",{className:"tw-px-3 tw-pb-1 tw-pt-2"},Un.default.createElement($0n,{value:l,onChange:c,onSubmit:xn(Q),sendShortcut:g.defaultSendShortcut,placeholder:I?"Generating...":"Ask a question... ",currentActiveFile:p})),Un.default.createElement("div",{className:"tw-mt-auto tw-flex tw-items-center tw-justify-between tw-gap-2 tw-border-t tw-border-solid tw-border-border tw-px-3 tw-py-1.5"},Un.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Un.default.createElement(U6,{size:"sm",variant:"ghost",value:N.value,models:N.models,onChange:N.onChange,disabled:I}),Un.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},Un.default.createElement(Wl,{id:"quickAskIncludeContext",checked:w,onCheckedChange:Z=>R(!!Z),className:"tw-size-3.5",disabled:I}),Un.default.createElement("label",{htmlFor:"quickAskIncludeContext",className:"tw-cursor-pointer tw-text-xs tw-text-muted"},"Note"),Un.default.createElement(rs,{content:"Include the active note's content as context",side:"top"}))),Un.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},P&&Un.default.createElement(oe,{variant:"ghost2",size:"icon",className:"hover:tw-bg-modifier-hover",onClick:T,title:"Clear conversation"},Un.default.createElement(PG,{className:"tw-size-4"})),I?Un.default.createElement(oe,{variant:"destructive",size:"icon",onClick:k,title:"Stop generating"},Un.default.createElement(HC,{className:"tw-size-4"})):Un.default.createElement(oe,{variant:"default",size:"icon",onClick:xn(Q),disabled:!l.trim(),title:"Send message"},Un.default.createElement(zC,{className:"tw-size-4"})))),Un.default.createElement("div",{className:"tw-absolute tw-right-0 tw-top-4 tw-h-[calc(100%-16px)] tw-w-1 tw-cursor-ew-resize",onMouseDown:le("right")}),Un.default.createElement("div",{className:"tw-absolute tw-bottom-0 tw-left-0 tw-h-1 tw-w-full tw-cursor-ns-resize",onMouseDown:le("bottom")}),Un.default.createElement("div",{className:"quick-ask-resize-indicator-left tw-absolute tw-bottom-0 tw-left-0 tw-size-3 tw-cursor-nesw-resize",onMouseDown:le("bottom-left")}),Un.default.createElement("div",{className:"quick-ask-resize-indicator-right tw-absolute tw-bottom-0 tw-right-0 tw-z-[10] tw-size-3 tw-cursor-nwse-resize",onMouseDown:le("bottom-right")}))}Pa();var Zp=12,RO=6,F0n=.83,U0n=.9,j0n=420,B0n=560,Wlt=300,z0n=200,dc=class dc{constructor(e){this.options=e;this.root=null;this.overlayContainer=null;this.cleanupCallbacks=[];this.overlayHost=null;this.ownerDocument=null;this.ownerWindow=null;this.rafId=null;this.panelRerenderRafId=null;this.resizeObserver=null;this.isClosing=!1;this.closeAnimationTimeout=null;this.dragPosition=null;this.resizeSize=null;this.hasUserResizedHeight=!1;this.bottomAnchorPos=null;this.topAnchorPos=null;this.focusAnchorPos=null;this.placementSide=null;this.isResizing=!1;this.resizeDirection=null;this.resizeStartRect=null;this.resizeStartMouse=null;this.resizeRafId=null;this.closeWithAnimation=()=>{if(!this.isClosing)if(this.isClosing=!0,this.overlayContainer){this.overlayContainer.classList.add("closing");let e=r=>{r.target!==this.overlayContainer||r.animationName!=="copilot-quick-ask-fade-out"||(this.overlayContainer?.removeEventListener("animationend",e),this.closeAnimationTimeout!==null&&(window.clearTimeout(this.closeAnimationTimeout),this.closeAnimationTimeout=null),this.options.onClose())};this.overlayContainer.addEventListener("animationend",e);let n=this.ownerWindow??window;this.closeAnimationTimeout=n.setTimeout(()=>{this.overlayContainer?.removeEventListener("animationend",e),this.closeAnimationTimeout=null,this.options.onClose()},300)}else this.options.onClose()};this.handleDragOffset=e=>{this.dragPosition=e,this.updateDragPosition()};this.handleResizeStart=(e,n)=>{if(this.isResizing)return;let r=this.overlayContainer?.getBoundingClientRect();if(!r)return;this.isResizing=!0,this.resizeDirection=e,this.resizeStartRect=r,this.resizeStartMouse=n;let o=this.ownerDocument??activeDocument,i=o.body,s={right:"ew-resize",bottom:"ns-resize","bottom-left":"nesw-resize","bottom-right":"nwse-resize"};i.setCssProps({"--copilot-resize-cursor":s[e]??"default"}),i.classList.add("tw-select-none","tw-cursor-[var(--copilot-resize-cursor)]"),o.addEventListener("mousemove",this.handleResizeMove,!0),o.addEventListener("mouseup",this.handleResizeEnd,!0)};this.handleResizeMove=e=>{if(!this.isResizing||!this.resizeStartRect||!this.resizeStartMouse)return;let n=this.ownerWindow??window;this.resizeRafId!==null&&n.cancelAnimationFrame(this.resizeRafId),this.resizeRafId=n.requestAnimationFrame(()=>{this.resizeRafId=null,this.applyResize(e.clientX,e.clientY)})};this.handleResizeEnd=()=>{this.cleanupResize(),this.renderPanel()}}mount(e,n,r){this.bottomAnchorPos=e,this.topAnchorPos=typeof n=="number"?n:null,this.focusAnchorPos=typeof r=="number"?r:null,this.placementSide=null,dc.currentInstance=this,this.mountOverlay(),this.setupGlobalListeners(),this.schedulePositionUpdate()}destroy(){dc.currentInstance===this&&(dc.currentInstance=null);let e=this.ownerWindow??window;this.closeAnimationTimeout!==null&&(e.clearTimeout(this.closeAnimationTimeout),this.closeAnimationTimeout=null),this.cleanupResize();for(let r of this.cleanupCallbacks)try{r()}catch{}this.cleanupCallbacks=[],this.rafId!==null&&(e.cancelAnimationFrame(this.rafId),this.rafId=null),this.panelRerenderRafId!==null&&(e.cancelAnimationFrame(this.panelRerenderRafId),this.panelRerenderRafId=null),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.root?.unmount(),this.root=null,this.overlayContainer?.parentNode&&this.overlayContainer.parentNode.removeChild(this.overlayContainer),this.overlayContainer&&O0n(this.overlayContainer),this.overlayContainer=null;let n=dc.overlayRoot;if(n&&n.childElementCount===0){let r=n.parentElement;n.remove(),dc.overlayRoot=null,r?.classList.remove("copilot-quick-ask-overlay-host")}this.bottomAnchorPos=null,this.topAnchorPos=null,this.focusAnchorPos=null,this.placementSide=null,this.ownerDocument=null,this.ownerWindow=null}updatePosition(e,n,r){typeof e=="number"&&(this.bottomAnchorPos=e),typeof n=="number"?this.topAnchorPos=n:n===null&&(this.topAnchorPos=null),typeof r=="number"?this.focusAnchorPos=r:r===null&&(this.focusAnchorPos=null),this.placementSide=null,this.schedulePositionUpdate()}getReplaceGuard(){return this.options.replaceGuard}schedulePanelRerender(){if(this.panelRerenderRafId!==null)return;let e=this.ownerWindow??window;this.panelRerenderRafId=e.requestAnimationFrame(()=>{this.panelRerenderRafId=null,this.renderPanel()})}renderPanel(){this.root&&this.root.render(H0n.default.createElement(D0n,{plugin:this.options.plugin,editor:this.options.editor,view:this.options.view,selectedText:this.options.selectedText,replaceGuard:this.options.replaceGuard,onClose:this.closeWithAnimation,onDragOffset:this.handleDragOffset,onResizeStart:this.handleResizeStart,hasCustomHeight:this.hasUserResizedHeight}))}static closeCurrentWithAnimation(){return dc.currentInstance?(dc.currentInstance.closeWithAnimation(),!0):!1}static getOverlayRoot(e){if(dc.overlayRoot&&dc.overlayRoot.parentElement!==e&&(dc.overlayRoot.parentElement?.classList.remove("copilot-quick-ask-overlay-host"),dc.overlayRoot.remove(),dc.overlayRoot=null),dc.overlayRoot)return dc.overlayRoot;let n=e.createDiv("copilot-quick-ask-overlay-root");return e.classList.add("copilot-quick-ask-overlay-host"),dc.overlayRoot=n,n}mountOverlay(){let e=this.options.view.dom??activeDocument.body;this.overlayHost=e;let n=e.doc,r=n.defaultView??window;this.ownerDocument=n,this.ownerWindow=r;let i=dc.getOverlayRoot(e).createDiv("copilot-quick-ask-overlay");this.overlayContainer=i,this.root=Er(i,this.options.plugin.app),this.renderPanel();let s=()=>{this.placementSide=null,this.schedulePositionUpdate()};r.addEventListener("scroll",s,!0),this.cleanupCallbacks.push(()=>r.removeEventListener("scroll",s,!0));let a=()=>{this.placementSide=null,this.schedulePositionUpdate()};r.addEventListener("resize",a),this.cleanupCallbacks.push(()=>r.removeEventListener("resize",a));let l=this.options.view?.scrollDOM;l&&(l.addEventListener("scroll",s),this.cleanupCallbacks.push(()=>l.removeEventListener("scroll",s))),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>{this.placementSide=null,this.schedulePositionUpdate()}),l&&this.resizeObserver.observe(l))}setupGlobalListeners(){let e=r=>{if(r.key!=="Escape"||r.defaultPrevented)return;let i=(this.ownerDocument??activeDocument).activeElement;i&&this.overlayContainer?.contains(i)||(r.preventDefault(),r.stopPropagation(),this.closeWithAnimation())},n=this.ownerWindow??window;n.addEventListener("keydown",e),this.cleanupCallbacks.push(()=>n.removeEventListener("keydown",e))}schedulePositionUpdate(){if(this.rafId!==null)return;let e=this.ownerWindow??window;this.rafId=e.requestAnimationFrame(()=>{this.rafId=null,this.updateOverlayPosition()})}isAnchorRectVisible(e,n){return e.bottom>=n.top&&e.top<=n.bottom&&e.right>=n.left&&e.left<=n.right}resolveVisibleAnchors(e,n){let r=n??e,o=i=>{if(typeof i!="number")return null;let s=this.options.view.coordsAtPos(i);return s&&this.isAnchorRectVisible(s,r)?s:null};return{bottomRect:o(this.bottomAnchorPos),topRect:o(this.topAnchorPos),focusRect:o(this.focusAnchorPos)}}computeVerticalPlacement(e,n,r,o,i,s,a,l){let c;if(this.placementSide==="below"&&e)c=e.bottom-r.top+RO;else if(this.placementSide==="above"&&n)c=n.top-r.top-RO-a;else if(e){let f=e.bottom-r.top+RO;if(i-(e.bottom-r.top)-RO>=a+Zp)c=f,this.placementSide="below";else if(n){let m=n.top-r.top-RO-a;n.top-r.top-RO-o>=a+Zp?(c=m,this.placementSide="above"):(c=o+(s-a)/2,this.placementSide=null)}else c=o+(s-a)/2,this.placementSide=null}else if(n){let f=n.top-r.top-RO-a;n.top-r.top-RO-o>=a+Zp?(c=f,this.placementSide="above"):(c=o+(s-a)/2,this.placementSide=null)}else c=o+(s-a)/2,this.placementSide=null;let u=i-Zp-a,d=Math.max(l,u);return Math.max(l,Math.min(c,d))}updateOverlayPosition(){if(!this.overlayContainer||this.bottomAnchorPos===null)return;if(this.dragPosition){this.updateDragPosition();return}let e=this.ownerDocument??activeDocument,n=this.overlayHost?.getBoundingClientRect()??e.body.getBoundingClientRect(),r=n.width,o=this.options.view.scrollDOM,i=o?.getBoundingClientRect(),a=o?.querySelector(".cm-sizer")?.getBoundingClientRect(),{bottomRect:l,topRect:c,focusRect:u}=this.resolveVisibleAnchors(n,i),d=Math.min(j0n,r*F0n),f=Math.min(B0n,r*U0n),p=Math.min(Wlt,r-Zp*2),m=this.resizeSize?.width??Math.max(p,Math.min(d,f)),h=this.resizeSize?.height,g=(a?.left??i?.left??n.left+Zp)-n.left,v=a?.width??i?.width??r-Zp*2,y=g+v,w=this.topAnchorPos!==null&&this.bottomAnchorPos!==null&&this.topAnchorPos===this.bottomAnchorPos,_=typeof this.topAnchorPos=="number"?this.options.view.coordsAtPos(this.topAnchorPos):null,S=typeof this.bottomAnchorPos=="number"?this.options.view.coordsAtPos(this.bottomAnchorPos):null,I=Math.min((_?.bottom??0)-(_?.top??0),(S?.bottom??0)-(S?.top??0)),C=!w&&!!_&&!!S&&Math.abs(_.top-S.top)>Math.max(I/2,2),k=u??l??c,T=C?g+(v-m)/2:k?k.left-n.left:g+(v-m)/2;T=Math.min(T,y-m),T=Math.max(T,g),T=Math.min(T,r-Zp-m),T=Math.max(T,Zp);let P=(i?.top??n.top)-n.top,E=(i?.bottom??n.bottom)-n.top,O=E-P,$=P+Zp;EPe(this.overlayContainer,"copilot-quick-ask-overlay-pos",{width:m,...typeof h=="number"?{height:h}:{},left:Math.round(T),top:Math.round($)});let U=typeof h=="number"?h:this.overlayContainer.getBoundingClientRect().height||z0n,V=this.computeVerticalPlacement(l,c,n,P,E,O,U,$);EPe(this.overlayContainer,"copilot-quick-ask-overlay-pos",{width:m,...typeof h=="number"?{height:h}:{},left:Math.round(T),top:Math.round(V)})}cleanupResize(){let e=this.ownerWindow??window;if(this.resizeRafId!==null&&(e.cancelAnimationFrame(this.resizeRafId),this.resizeRafId=null),this.isResizing){let n=this.ownerDocument??activeDocument,r=n.body;n.removeEventListener("mousemove",this.handleResizeMove,!0),n.removeEventListener("mouseup",this.handleResizeEnd,!0),r.classList.remove("tw-select-none","tw-cursor-[var(--copilot-resize-cursor)]"),r.setCssProps({"--copilot-resize-cursor":""})}this.isResizing=!1,this.resizeDirection=null,this.resizeStartRect=null,this.resizeStartMouse=null}applyResize(e,n){if(!this.resizeStartRect||!this.resizeStartMouse||!this.resizeDirection)return;let r=this.ownerDocument??activeDocument,o=this.overlayHost?.getBoundingClientRect()??r.body.getBoundingClientRect(),i=e-this.resizeStartMouse.x,s=n-this.resizeStartMouse.y,a=this.resizeStartRect,l=this.resizeDirection,c=o.width,u=Math.min(Wlt,c-Zp*2),d=z0n,f=o.left+Zp,p=o.right-Zp,m=o.bottom-Zp,h=a.width,g=a.height,v,y,w=l!=="right";switch(l){case"right":h=a.width+i;break;case"bottom":g=a.height+s;break;case"bottom-right":h=a.width+i,g=a.height+s;break;case"bottom-left":h=a.width-i,g=a.height+s,v=a.left+i,y=a.top;break}let _=p-a.left,S=a.right-f,I=m-a.top;l==="bottom-left"?(h=Math.max(u,Math.min(h,S)),v=a.right-h,v<f&&(v=f,h=a.right-f)):h=Math.max(u,Math.min(h,_)),w&&(g=Math.max(d,Math.min(g,I)));let C=this.resizeSize?.height,k={width:h};w?k.height=g:this.hasUserResizedHeight&&typeof C=="number"&&(k.height=C),this.resizeSize=k;let T=this.hasUserResizedHeight;w&&(this.hasUserResizedHeight=!0),this.hasUserResizedHeight!==T&&this.renderPanel(),l==="bottom-left"&&v!==void 0?(this.dragPosition={x:v,y:y??a.top},this.updateDragPosition()):this.dragPosition?this.updateDragPosition():this.schedulePositionUpdate()}updateDragPosition(){if(!this.overlayContainer||!this.dragPosition)return;let e=this.ownerDocument??activeDocument,n=this.overlayHost?.getBoundingClientRect()??e.body.getBoundingClientRect(),r=n.width,o=Math.min(j0n,r*F0n),i=Math.min(B0n,r*U0n),s=Math.min(Wlt,r-Zp*2),a=this.resizeSize?.width??Math.max(s,Math.min(o,i)),l=this.resizeSize?.height;EPe(this.overlayContainer,"copilot-quick-ask-overlay-pos",{width:a,...l?{height:l}:{},left:Math.round(this.dragPosition.x-n.left),top:Math.round(this.dragPosition.y-n.top)})}};dc.overlayRoot=null,dc.currentInstance=null;var D5=dc;function W0n(t,e){let{bottomAnchorPos:n,topAnchorPos:r,focusAnchorPos:o}=t;if(n!==null&&n===r){let s=e.mapPos(n,1);return{bottomAnchorPos:s,topAnchorPos:s,focusAnchorPos:s}}let i=o===r?1:-1;return{bottomAnchorPos:n!==null?e.mapPos(n,-1):null,topAnchorPos:r!==null?e.mapPos(r,1):null,focusAnchorPos:o!==null?e.mapPos(o,i):null}}var UF=V0n.StateEffect.define(),K0n=q0n.ViewPlugin.fromClass(class{constructor(t){this.view=t;this.overlay=null;this.bottomAnchorPos=null;this.topAnchorPos=null;this.focusAnchorPos=null}update(t){for(let e of t.transactions)for(let n of e.effects){if(!n.is(UF))continue;let r=n.value;if(!r){this.overlay?.destroy(),this.overlay=null,this.bottomAnchorPos=null,this.topAnchorPos=null,this.focusAnchorPos=null;continue}this.overlay?.destroy(),this.bottomAnchorPos=r.bottomAnchorPos,this.topAnchorPos=typeof r.topAnchorPos=="number"?r.topAnchorPos:null,this.focusAnchorPos=typeof r.focusAnchorPos=="number"?r.focusAnchorPos:null,this.overlay=new D5(r.options),this.overlay.mount(r.bottomAnchorPos,this.topAnchorPos,this.focusAnchorPos)}if(this.overlay&&t.docChanged){let e=this.overlay.getReplaceGuard();e?.onDocChanged&&e.onDocChanged(t.changes);let n=W0n({bottomAnchorPos:this.bottomAnchorPos,topAnchorPos:this.topAnchorPos,focusAnchorPos:this.focusAnchorPos},t.changes);this.bottomAnchorPos=n.bottomAnchorPos,this.topAnchorPos=n.topAnchorPos,this.focusAnchorPos=n.focusAnchorPos,this.bottomAnchorPos!==null&&this.overlay.updatePosition(this.bottomAnchorPos,this.topAnchorPos,this.focusAnchorPos),this.overlay.schedulePanelRerender()}}destroy(){this.overlay?.destroy(),this.overlay=null,this.bottomAnchorPos=null,this.topAnchorPos=null,this.focusAnchorPos=null}});pe();var Foe=class{constructor(e){this.quickAskWidgetState=null;this.plugin=e}close(e=!0){let n=this.quickAskWidgetState;if(!n)return;if(!e){this.quickAskWidgetState=null;try{let o=[UF.of(null),...ph.buildEffects(n.view,null)];n.view.dispatch({effects:o})}catch(o){W("Failed to dispatch close effect:",o)}return}if(this.quickAskWidgetState=null,!D5.closeCurrentWithAnimation())try{let o=[UF.of(null),...ph.buildEffects(n.view,null)];n.view.dispatch({effects:o}),n.view.focus()}catch(o){W("Failed to dispatch close effect or focus:",o)}}show(e,n){let r=n.state.selection.main,o=e.editor,i=e.leaf,s=e.file?.path??null,a=n.state.doc.sliceString(r.from,r.to),l=r.from,c=r.to;this.close(!1);let u=ACn({editorView:n,leafSnapshot:i,filePathSnapshot:s,selectedTextSnapshot:a,initialRange:{from:l,to:c},getLeafState:()=>{let f=i.view;return f instanceof G0n.MarkdownView?{leaf:i,editorView:f.editor?.cm??null,filePath:f.file?.path??null}:{leaf:null,editorView:null,filePath:null}}}),d=(f=!0)=>{let p=!this.quickAskWidgetState||this.quickAskWidgetState.view===n;p&&(this.quickAskWidgetState=null);try{let m=[UF.of(null),...ph.buildEffects(n,null)];n.dispatch({effects:m}),p&&f&&n.focus()}catch(m){W("Failed to dispatch close effect or focus:",m)}};try{let f=yTe(r,n.state.doc);n.dispatch({effects:[UF.of(null),...ph.buildEffects(n,null),UF.of({bottomAnchorPos:f.bottomPos,topAnchorPos:f.topPos,focusAnchorPos:f.focusPos,options:{plugin:this.plugin,editor:o,view:n,selectedText:a,selectionFrom:l,selectionTo:c,replaceGuard:u,onClose:()=>d(!0)}}),...ph.buildEffects(n,{from:l,to:c})]}),this.quickAskWidgetState={view:n,close:d}}catch(f){W("Failed to show Quick Ask panel:",f),this.quickAskWidgetState=null}}isOpen(){return this.quickAskWidgetState!==null}createExtension(){return[K0n]}};var F5=require("obsidian");gt();pe();var MPe=mTe("copilot-chat-selection-highlight");function Vlt(t){try{let e=MPe.buildEffects(t,null);e.length>0&&t.dispatch({effects:e})}catch{}}var Uoe=class{constructor(e,n){this.lastActiveMarkdownLeaf=null;this.lastActiveLeafWasMarkdown=!1;this.snapshot=null;this.plugin=e,this.closeQuickAskOnChatFocus=n?.closeQuickAskOnChatFocus??!1}initialize(){let e=this.plugin.app.workspace.getActiveViewOfType(F5.MarkdownView),n=e?.leaf??null;this.lastActiveLeafWasMarkdown=!!e,this.lastActiveLeafWasMarkdown&&n&&(this.lastActiveMarkdownLeaf=n)}cleanup(){this.clear(),this.lastActiveMarkdownLeaf=null,this.lastActiveLeafWasMarkdown=!1}handleActiveLeafChange(e){let n=this.lastActiveLeafWasMarkdown,r=e?.getViewState().type??null,o=e?.view instanceof F5.MarkdownView;this.lastActiveLeafWasMarkdown=o,o&&e&&(this.lastActiveMarkdownLeaf=e),this.snapshot&&r!==Fs&&this.clear(),r===Fs&&n&&(this.closeQuickAskOnChatFocus&&this.plugin.quickAskController?.close(!1),this.persist({useFallback:!0}))}persistFromPointerDown(){this.plugin.app.workspace.getActiveViewOfType(F5.MarkdownView)&&this.persist({useFallback:!1})}clearIfNoNoteContexts(e){e.some(n=>n.sourceType==="note")||this.clear()}clearForNewChat(){this.clear()}persist(e){let n=this.getEditorView(e.useFallback);if(!n)return;let r=n.state.selection.main;if(r.from===r.to)return;let o=r.from,i=r.to,s=this.getHighlightRange(n);if(this.snapshot?.view===n&&this.snapshot.from===o&&this.snapshot.to===i&&s?.from===o&&s?.to===i)return;this.snapshot&&this.snapshot.view!==n&&(this.hideHighlight(this.snapshot.view),this.snapshot=null),this.showHighlight(n,o,i)&&(this.snapshot={view:n,from:o,to:i})}clear(){this.snapshot&&(this.hideHighlight(this.snapshot.view),this.snapshot=null)}getEditorView(e){let n=this.plugin.app.workspace.getActiveViewOfType(F5.MarkdownView);return n?.editor?.cm?n.editor.cm:e&&this.lastActiveMarkdownLeaf?.view instanceof F5.MarkdownView?this.lastActiveMarkdownLeaf.view.editor?.cm??null:null}showHighlight(e,n,r){try{let o=MPe.buildEffects(e,{from:n,to:r});return o.length===0?!1:(e.dispatch({effects:o}),!0)}catch(o){return H("ChatSelectionHighlight show failed:",o),!1}}hideHighlight(e){try{let n=MPe.buildEffects(e,null);n.length>0&&e.dispatch({effects:n})}catch(n){W("ChatSelectionHighlight hide failed (view may be destroyed):",n)}}getHighlightRange(e){return MPe.getRange(e)}};var Qi=require("obsidian");var WHr={success:"Completed","action-required":"Action required",error:"Failed"};function Z0n(t){return["Copilot finished updating this vault.",...t.map(n=>[`${n.title} \u2014 ${WHr[n.status]}`,n.summary,...(n.details??[]).map(r=>`\u2022 ${r}`)].join(`
`))].join(`
`)}function Y0n(t,e,n){return e===n&&t.some(({id:r})=>r==="credentials")}function J0n(t){return t.some(({id:e,status:n})=>e==="folders"&&n!=="error")}async function X0n(t){let e=await Promise.all(t.tasks.map(async r=>{try{return await r.result}catch(o){return r.onFailure(o),r.failure}})),n=[...t.initialItems,...e,...t.afterTasks()].filter(r=>r!==null);n.length!==0&&(t.present(n),t.acknowledge(n))}zQ();wC();Jh();Gf();yt();$we();Pa();var eTn=require("obsidian"),yn=L(B());Hl();function qlt(t){return`${t[0].toUpperCase()}${t.slice(1)}`}var VHr={publish:"Publishing\u2026",update:"Updating\u2026",delete:"Deleting\u2026"};function Q0n({receipt:t,actions:e}){let[n,r]=(0,yn.useState)(""),o=async s=>{try{await s.currentTarget.win.navigator.clipboard.writeText(t.url),r("Copied")}catch{r("Could not copy the link")}},i=s=>{s.currentTarget.win.open(t.url,"_blank","noopener,noreferrer")};return yn.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-3"},yn.default.createElement("code",{className:"tw-break-all tw-rounded-md tw-bg-secondary tw-p-2 tw-text-small"},yn.default.createElement("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",className:"tw-text-accent tw-underline"},t.url)),yn.default.createElement("div",{className:"tw-text-small tw-text-muted"},"Document ",t.docId," \xB7 Version ",t.version),yn.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-end tw-gap-2"},n&&yn.default.createElement("span",{className:"tw-text-small tw-text-muted"},n),e,yn.default.createElement(oe,{variant:"secondary",onClick:xn(o)},"Copy"),yn.default.createElement(oe,{onClick:i},"Open")))}function qHr({fileName:t,docId:e,review:n,initialResult:r,onConfirm:o,onRegenerate:i,onClose:s}){let[a,l]=(0,yn.useState)(n?e?"update":"publish":e?null:"publish"),[c,u]=(0,yn.useState)(r??null),[d,f]=(0,yn.useState)(null),p=d!==null,m=async(w,_)=>{f(w);try{u(await o(w,_))}finally{f(null)}},h=w=>{c?.kind==="failure"&&m(c.action,w.currentTarget.doc)},g=async()=>{if(!(c?.kind!=="persistence"||!c.retrySave)){f(c.action);try{u(await c.retrySave())}finally{f(null)}}};if(c?.kind==="success"){let w=yn.default.createElement(oe,{variant:"secondary",onClick:s},"Close");return yn.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},yn.default.createElement("div",{className:"tw-font-semibold tw-text-normal"},c.action==="delete"?"Removed from Symposium":`${qlt(c.action)} complete`),c.receipt?yn.default.createElement(Q0n,{receipt:c.receipt,actions:w}):yn.default.createElement("div",{className:"tw-flex tw-justify-end"},w))}if(c?.kind==="failure")return yn.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4",role:"alert"},yn.default.createElement("div",{className:"tw-font-semibold tw-text-normal"},c.accessNotice?"Symposium access required":`${qlt(c.action)} failed`),yn.default.createElement("p",{className:"tw-m-0 tw-text-muted"},c.message),yn.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},yn.default.createElement(oe,{variant:"secondary",onClick:s},"Close"),c.retryable&&!n&&yn.default.createElement(oe,{onClick:h,disabled:p},p?"Retrying\u2026":"Retry")));if(c?.kind==="persistence"){let w=yn.default.createElement(yn.default.Fragment,null,yn.default.createElement(oe,{variant:"secondary",onClick:s},"Close"),c.retrySave&&yn.default.createElement(oe,{onClick:()=>void g(),disabled:p},p?"Saving\u2026":"Retry save"));return yn.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4",role:"alert"},yn.default.createElement("div",{className:"tw-font-semibold tw-text-normal"},c.action==="publish"?"Published, but not saved to the note":c.action==="update"?"Page updated; note identity not verified":"Page withdrawn; note unchanged"),yn.default.createElement("p",{className:"tw-m-0 tw-text-muted"},c.message),c.receipt?yn.default.createElement(Q0n,{receipt:c.receipt,actions:w}):yn.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},w))}let v=a?n?`Review \u201C${n.payload.title}\u201D`:`${qlt(a)} \u201C${t}\u201D?`:`Manage \u201C${t}\u201D`;return yn.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},yn.default.createElement("div",null,yn.default.createElement("div",{className:"tw-font-semibold tw-text-normal"},v),yn.default.createElement("p",{className:"tw-mb-0 tw-mt-2 tw-text-muted"},n?`These exact HTML bytes will ${a==="update"?"replace the current public page":"become public"} only after you confirm.`:a==="delete"?"Yes withdraws the link and deletes Symposium\u2019s stored copy. Previously fetched or cached copies cannot be recalled.":a==="update"?"Yes replaces the current public page with this note\u2019s latest content.":a==="publish"?"Yes makes this note available to anyone with the public link.":"Choose whether to replace the current public page or withdraw it.")),n&&yn.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},yn.default.createElement("div",{className:"tw-grid tw-grid-cols-[auto,1fr] tw-gap-x-3 tw-gap-y-1 tw-text-small"},yn.default.createElement("span",{className:"tw-text-muted"},"Source"),yn.default.createElement("code",{className:"tw-break-all"},n.sourcePath),yn.default.createElement("span",{className:"tw-text-muted"},"Title"),yn.default.createElement("span",null,n.payload.title),yn.default.createElement("span",{className:"tw-text-muted"},"HTML"),yn.default.createElement("span",null,n.payload.byteLength," bytes"),yn.default.createElement("span",{className:"tw-text-muted"},"SHA-256"),yn.default.createElement("code",{className:"tw-break-all"},n.digest)),yn.default.createElement("p",{className:"tw-m-0 tw-text-small tw-text-muted"},"Open a sandboxed local preview of these exact HTML bytes in your default browser, review it, then return here to confirm."),yn.default.createElement("a",{href:n.previewUrl,target:"_blank",rel:"noopener noreferrer",title:n.previewPath,className:"tw-text-accent tw-underline",onClick:w=>{w.preventDefault(),w$(n.previewPath)}},"Open local HTML preview")),yn.default.createElement("div",{className:"tw-flex tw-flex-wrap tw-justify-end tw-gap-2","aria-label":"Symposium actions"},a?yn.default.createElement(yn.default.Fragment,null,n&&i&&yn.default.createElement(oe,{variant:"secondary",onClick:()=>{i(),s()},disabled:p},"Ask agent to regenerate"),yn.default.createElement(oe,{variant:"secondary",onClick:s,disabled:p},"No, cancel"),yn.default.createElement(oe,{variant:a==="delete"?"destructive":"default",onClick:w=>void m(a,w.currentTarget.doc),disabled:p},p?VHr[a]:`Yes, ${a}`)):yn.default.createElement(yn.default.Fragment,null,yn.default.createElement(oe,{variant:"secondary",onClick:s},"Cancel"),yn.default.createElement(oe,{onClick:()=>l("update")},"Update"),yn.default.createElement(oe,{variant:"destructive",onClick:()=>l("delete")},"Delete"))))}var OPe=class extends eTn.Modal{constructor(n,r){super(n);this.options=r;this.root=null;this.modalEl.classList.add("copilot-symposium-modal"),this.titleEl.setText("Share with Symposium")}onOpen(){this.contentEl.empty(),this.root=Er(this.contentEl,this.app),this.root.render(yn.default.createElement(qHr,{...this.options,onClose:()=>this.close()}))}onClose(){this.root?.unmount(),this.root=null,this.contentEl.empty(),this.options.onClosed?.()}};pe();Se();i$();var rTn=require("obsidian"),Klt=`${PKt}/api/v1/docs`,KHr="Could not reach Symposium. Please try again.",GHr="Symposium may have published this note, but Copilot did not receive a valid receipt. To avoid creating a duplicate page, this publish cannot be retried until the plugin reloads.",O_=class t extends Error{constructor(n,r,o,i){super(n);this.code=r;this.status=o;this.retryable=i;this.name="SymposiumClientError",Object.setPrototypeOf(this,t.prototype)}},NPe=class{async publish(e,n){return this.push("POST",Klt,e,n)}async update(e,n,r){return this.push("PUT",`${Klt}/${encodeURIComponent(e)}`,n,r,e)}async delete(e,n){let r=await this.request({url:`${Klt}/${encodeURIComponent(e)}`,method:"DELETE",headers:tTn(n),throw:!1});if(r.status===204)return;let o=nTn(r);if(!(r.status===404&&o.code==="not_found"))throw o}async push(e,n,r,o,i){let s;try{s=await this.request({url:n,method:e,headers:tTn(o),contentType:"application/json",body:JSON.stringify({title:r.title,html:r.html}),throw:!1})}catch(l){throw e==="POST"&&l instanceof O_&&l.code==="network"?Glt(null):l}let a=e==="POST"?201:200;if(s.status!==a)throw s.status<200||s.status>=300?nTn(s):e==="POST"?Glt(s.status):RPe(s.status);try{return ZHr(s,i)}catch(l){throw e==="POST"&&l instanceof O_&&l.code==="malformed_response"?Glt(s.status):l}}async request(e){try{return await(0,rTn.requestUrl)(e)}catch{throw new O_(KHr,"network",null,!0)}}};function tTn(t){return{Authorization:`Bearer ${t}`}}function ZHr(t,e){let n=oTn(t);if(!Zlt(n))throw RPe(t.status);let{docId:r,url:o,version:i}=n;if(typeof r!="string"||!Uye.test(r)||e!==void 0&&r!==e||typeof o!="string"||!JHr(o)||new URL(o).pathname.replace(/\/$/,"")!==`/d/${r}`||typeof i!="number"||!Number.isSafeInteger(i)||i<1)throw RPe(t.status);return{docId:r,url:o,version:i}}function nTn(t){let e=oTn(t);if(!YHr(e))return RPe(t.status);let{code:n,message:r}=e.error;return new O_(r,n,t.status,n==="internal"||t.status>=500)}function oTn(t){try{return t.json}catch{return}}function YHr(t){return!Zlt(t)||!Zlt(t.error)?!1:typeof t.error.code=="string"&&t.error.code.length>0&&typeof t.error.message=="string"&&t.error.message.length>0}function Zlt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function JHr(t){try{return new URL(t).protocol==="https:"}catch{return!1}}function RPe(t){return new O_(`Symposium returned an invalid response (HTTP ${t}).`,"malformed_response",t,t>=500)}function Glt(t){return new O_(GHr,"ambiguous_publish",t,!1)}i$();var iTn=require("obsidian"),LO="symposium",U5=class t extends Error{constructor(){super("This note already uses the symposium property for an unrecognized value. Recover its public link from .symposium/publish-history.md, then repair or remove the property before publishing."),this.name="SymposiumPropertyConflictError",Object.setPrototypeOf(this,t.prototype)}},nT=class t extends Error{constructor(){super("This note's frontmatter must be a YAML property map. Fix it before publishing to Symposium."),this.name="SymposiumFrontmatterParseError",Object.setPrototypeOf(this,t.prototype)}};function LPe(t){if(typeof t!="string")return null;try{let e=new URL(t),n=e.pathname.match(/^\/d\/([^/]+)\/?$/)?.[1];return e.protocol==="https:"&&n&&Uye.test(n)?n:null}catch{return null}}function Ylt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}async function rT(t,e){let r=(await t.vault.read(e)).replace(/^\uFEFF/,"").match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];if(r===void 0)return null;let o;try{o=(0,iTn.parseYaml)(r)}catch{throw new nT}if(o==null)return null;if(!Ylt(o))throw new nT;if(!Object.prototype.hasOwnProperty.call(o,LO))return null;let i=LPe(o[LO]);if(!i)throw new U5;return i}async function sTn(t,e,n){if(LPe(n.url)!==n.docId)throw new Error("Cannot save an invalid Symposium document link.");let r=!1;return await t.fileManager.processFrontMatter(e,o=>{if(!Ylt(o))throw new nT;if(Object.prototype.hasOwnProperty.call(o,LO)){r=LPe(o[LO])===n.docId;return}o[LO]=n.url,r=!0}),r}async function aTn(t,e,n){let r=!1;return await t.fileManager.processFrontMatter(e,o=>{if(!Ylt(o))throw new nT;if(!Object.prototype.hasOwnProperty.call(o,LO)){r=!0;return}LPe(o[LO])===n&&(delete o[LO],r=!0)}),r}tct();ut();var rct=".symposium",FPe=`${rct}/publish-history.md`,vWr="| Document ID | Status | Note | URL | Published at (UTC) | Version | Content SHA-256 |",nct=`${vWr}
| --- | --- | --- | --- | --- | ---: | --- |`;function wWr(t){return t===null?"\u2014":String(t).replace(/\\/g,"\\\\").replace(/\r?\n/g," ").replace(/\|/g,"\\|")}async function bTn(t,e){await ao(t,rct).catch(async a=>{if(!await t.adapter.exists(rct))throw a});let n=[e.docId,e.status,e.notePath,e.url?`<${e.url}>`:null,e.publishedAt,e.version,e.contentHash].map(wWr).join(" | "),r=await t.adapter.exists(FPe),o=r?await t.adapter.read(FPe):"",i=o.replace(/\r\n?/g,`
`);if(r&&i!==nct&&!i.startsWith(`${nct}
`))throw new Error(`Refusing to append to non-ledger file: ${FPe}`);let s=r&&!/[\r\n]$/.test(o)?`
`:"";await t.adapter.append(FPe,`${r?s:`${nct}
`}| ${n} |
`)}Py();var zF=require("obsidian"),EWr="Add a Copilot Plus license key in Settings before publishing with Symposium.",MWr="A Symposium action is already in progress for this note.",sct="Symposium review paths must be relative paths inside the current vault.";function act(t){let e=t.replace(/\\/g,"/");if(!e||e.includes("\0")||e.startsWith("/")||/^[A-Za-z]:\//.test(e))return null;let n=[];for(let r of e.split("/"))if(!(!r||r===".")){if(r===".."){if(n.length===0)return null;n.pop();continue}n.push(r)}return n.length>0?n.join("/"):null}function Wd(t){return{status:"failed",message:t}}function UPe(t){return t.kind==="success"&&t.action==="delete"?{status:"deleted"}:(t.kind==="success"||t.kind==="persistence")&&t.action!=="delete"&&t.receipt?{status:t.action==="publish"?"published":"updated",url:t.receipt.url,...t.kind==="persistence"?{message:t.message}:{}}:t.kind==="failure"||t.kind==="persistence"?Wd(t.message):Wd("Copilot could not complete this Symposium action.")}async function OWr(){return Y().plusLicenseKey.trim()}async function NWr(t,e,n){let r=new zF.Component;r.load();try{return await vTn(t,e,r,n)}finally{r.unload()}}function BF(t,e){return e instanceof nT||e instanceof U5?{kind:"failure",action:t,message:e.message,accessNotice:!1,retryable:!1}:e instanceof $O||e instanceof jF?{kind:"failure",action:t,message:e.message,accessNotice:!1,retryable:!1}:e instanceof O_?{kind:"failure",action:t,message:e.message,accessNotice:e.status===401&&e.code==="unauthorized",retryable:e.retryable}:{kind:"failure",action:t,message:"Copilot could not complete this Symposium action.",accessNotice:!1,retryable:!0}}function jPe(t){return{kind:"failure",action:t,message:"This note's Symposium identity changed. Close and reopen this dialog before trying again.",accessNotice:!1,retryable:!1}}function RWr(t){return{kind:"failure",action:t,message:"The local HTML preview changed. Ask the agent to regenerate it before publishing.",accessNotice:!1,retryable:!1}}var BPe=class{constructor(e,n={}){this.app=e;this.inFlightFiles=new Set;this.blockedPublishResults=new Map;this.modals=new Set;this.disposed=!1;this.client=n.client??new NPe,this.loadLicenseKey=n.loadLicenseKey??OWr,this.buildDocument=n.buildDocument??((r,o)=>NWr(this.app,r,o)),this.consumeAgentHandoff=n.consumeAgentHandoff??(r=>this.consumeDesktopAgentHandoff(r)),this.createModal=n.createModal??(r=>new OPe(this.app,r)),this.recordLedger=n.recordLedger??(r=>bTn(this.app.vault,r))}async open(e){if(this.disposed)return;let n=null,r=this.blockedPublishResults.get(e);if(!r)try{n=await rT(this.app,e)}catch(s){if(!(s instanceof nT)&&!(s instanceof U5))throw s;r=BF("publish",s)}if(this.disposed)return;let o=r,i;i=this.createModal({fileName:e.basename,docId:n,initialResult:o,onConfirm:o?()=>Promise.resolve(o):(s,a)=>this.execute(e,n,s,a),onClosed:()=>this.modals.delete(i)}),this.modals.add(i);try{i.open()}catch(s){throw this.modals.delete(i),s}}async reviewAgentManage(e){let n=act(e);if(!n)return Wd(sct);if(this.disposed)return Wd("Symposium publishing is no longer available.");let r=this.app.vault.getAbstractFileByPath(n);if(!(r instanceof zF.TFile)||r.extension!=="md")return Wd("The Symposium source must be an existing Markdown note.");let o=this.blockedPublishResults.get(r);if(o)return Wd(o.message);let i;try{i=await rT(this.app,r)}catch(s){return Wd(BF("update",s).message)}return i?this.openAgentManage(r,i):Wd("This note does not have a valid Symposium link to manage.")}async reviewAgentPublish(e,n){let r=act(n);if(!r)return Wd(sct);let o;try{o=await this.consumeAgentHandoff(r)}catch(i){return Wd(i instanceof Error&&i.name==="SymposiumAgentHandoffError"?i.message:"Copilot could not read the staged Symposium HTML.")}try{let i=act(e);if(!i)return Wd(sct);if(this.disposed)return Wd("Symposium publishing is no longer available.");let s=this.app.vault.getAbstractFileByPath(i);if(!(s instanceof zF.TFile)||s.extension!=="md")return Wd("The Symposium source must be an existing Markdown note.");let a=this.blockedPublishResults.get(s);if(a)return Wd(a.message);let l,c=null;try{l=yTn(s.basename,o.html),c=await rT(this.app,s)}catch(d){return Wd(BF(c?"update":"publish",d).message)}let u=Object.freeze({sourcePath:i,digest:MN(l.html),payload:l,previewPath:o.previewPath,previewUrl:o.previewUrl});return await this.openAgentReview(s,c,u,o.isPreviewCurrent)}finally{try{await o.cleanup()}catch(i){W("Could not remove the temporary Symposium browser preview.",i)}}}dispose(){this.disposed=!0;for(let e of[...this.modals])e.close();this.modals.clear(),this.blockedPublishResults.clear()}getDesktopVaultRoot(){let e=this.app.vault.adapter;if(!(e instanceof zF.FileSystemAdapter))throw new Error("Symposium agent review requires a desktop vault.");return e.getBasePath()}async consumeDesktopAgentHandoff(e){let{consumeSymposiumAgentHandoff:n}=await Promise.resolve().then(()=>(kTn(),CTn));return n(this.getDesktopVaultRoot(),e)}isAgentSourceCurrent(e,n){return e.path===n&&this.app.vault.getAbstractFileByPath(n)===e}openAgentManage(e,n){return new Promise(r=>{let o=!1,i=!1,s=l=>{i||(i=!0,r(l))},a;a=this.createModal({fileName:e.basename,docId:n,onConfirm:async(l,c)=>{o=!0;try{let u=await this.execute(e,n,l,c);return s(UPe(u)),u}catch(u){let d=BF(l,u);return s(UPe(d)),d}finally{o=!1}},onClosed:()=>{this.modals.delete(a),o||s({status:"cancelled"})}}),this.modals.add(a);try{a.open()}catch{this.modals.delete(a),s(Wd("Copilot could not open Symposium management."))}})}openAgentReview(e,n,r,o){return new Promise(i=>{let s=!1,a=!1,l=u=>{a||(a=!0,i(u))},c;c=this.createModal({fileName:e.basename,docId:n,review:r,onConfirm:async(u,d)=>{s=!0;try{let f=await this.execute(e,n,u,d,r,o);return l(UPe(f)),f}catch(f){let p=BF(n?"update":"publish",f);return l(UPe(p)),p}finally{s=!1}},onRegenerate:()=>l({status:"regenerate"}),onClosed:()=>{this.modals.delete(c),s||l({status:"cancelled"})}}),this.modals.add(c);try{c.open()}catch{this.modals.delete(c),l(Wd("Copilot could not open the Symposium review."))}})}async execute(e,n,r,o,i,s){let a=n?"update":"publish",l=!i&&r==="delete",c=l?"delete":a;return this.withFileLock(e,c,async()=>{if(this.disposed)return{kind:"failure",action:c,message:"Symposium publishing is no longer available.",accessNotice:!1,retryable:!1};let u=this.blockedPublishResults.get(e);if(u)return i?{kind:"failure",action:c,message:u.message,accessNotice:!1,retryable:!1}:u;if(i&&!this.isAgentSourceCurrent(e,i.sourcePath))return jPe(c);let d;try{d=await rT(this.app,e)}catch(m){return BF(c,m)}if(d!==n)return jPe(c);let f=l?"delete":d?"update":"publish",p;try{p=await this.loadLicenseKey()}catch{p=""}if(!p)return{kind:"failure",action:f,message:EWr,accessNotice:!0,retryable:!1};if(f==="delete"&&!d)return{kind:"failure",action:f,message:"This note no longer has a valid Symposium link.",accessNotice:!1,retryable:!1};try{if(f==="delete")return await rT(this.app,e)!==d?jPe(f):(await this.client.delete(d,p),await this.recordLedgerSafely({docId:d,status:"unpublished",notePath:e.path,url:null,publishedAt:null,version:null,contentHash:null}),await this.removeLocalIdentity(e,d));let m=i?.payload??await this.buildDocument(e,o);if(await rT(this.app,e)!==d||i&&!this.isAgentSourceCurrent(e,i.sourcePath))return jPe(f);if(i&&!await s?.())return RWr(f);if(!d){let y=await this.client.publish(m,p);return await this.recordPublishedReceipt(e,m,y),await this.savePublishedIdentity(e,y)}let g=await this.client.update(d,m,p);await this.recordPublishedReceipt(e,m,g);let v;try{v=await rT(this.app,e)}catch{}if(v!==d){let y={kind:"persistence",action:"update",message:"The original page was updated, but this note\u2019s Symposium identity changed or could not be verified. Its current identity was left unchanged.",receipt:g};return v||this.blockedPublishResults.set(e,y),y}return{kind:"success",action:"update",receipt:g}}catch(m){let h=BF(f,m);return m instanceof O_&&m.code==="ambiguous_publish"&&this.blockedPublishResults.set(e,h),h}})}async recordPublishedReceipt(e,n,r){await this.recordLedgerSafely({docId:r.docId,status:"published",notePath:e.path,url:r.url,publishedAt:new Date().toISOString(),version:r.version,contentHash:MN(n.html)})}async recordLedgerSafely(e){try{await this.recordLedger(e)}catch(n){W("Could not append a Symposium receipt to the recoverable ledger.",n)}}async savePublishedIdentity(e,n){try{if(!await sTn(this.app,e,n)){let o={kind:"persistence",action:"publish",message:"The page is public, but this note\u2019s Symposium identity changed or could not be verified. Its current frontmatter was left unchanged.",receipt:n},i;try{i=await rT(this.app,e)}catch{}return i?this.blockedPublishResults.delete(e):this.blockedPublishResults.set(e,o),o}return this.blockedPublishResults.delete(e),{kind:"success",action:"publish",receipt:n}}catch{return this.publishPersistenceFailure(e,n)}}publishPersistenceFailure(e,n){let r={kind:"persistence",action:"publish",message:"The page is already public. Retry saving its link to this note; this will not publish again.",receipt:n,retrySave:()=>this.withFileLock(e,"publish",async()=>this.savePublishedIdentity(e,n))};return this.blockedPublishResults.set(e,r),r}async removeLocalIdentity(e,n){try{return await aTn(this.app,e,n)?(this.blockedPublishResults.delete(e),{kind:"success",action:"delete"}):(this.blockedPublishResults.delete(e),{kind:"persistence",action:"delete",message:"The original page was withdrawn, but this note now points to a different Symposium document. Its newer identity was left unchanged."})}catch{return this.deletePersistenceFailure(e,n)}}deletePersistenceFailure(e,n){let r={kind:"persistence",action:"delete",message:"The public page is already deleted. Retry removing its link from this note; this will not contact Symposium again.",retrySave:()=>this.withFileLock(e,"delete",async()=>this.removeLocalIdentity(e,n))};return this.blockedPublishResults.set(e,r),r}async withFileLock(e,n,r){if(this.inFlightFiles.has(e))return{kind:"failure",action:n,message:MWr,accessNotice:!1,retryable:!1};this.inFlightFiles.add(e);try{return await r()}finally{this.inFlightFiles.delete(e)}}};function ITn(t){return Object.freeze({reviewAgentManage:e=>t.reviewAgentManage(e),reviewAgentPublish:(e,n)=>t.reviewAgentPublish(e,n)})}var zPe=class extends Qi.Plugin{constructor(){super(...arguments);this.userMessageHistory=[];this.lastActiveChatViewType=Fs;this.chatHistoryLastAccessedAtManager=new t2;this.startupMigrationItems=[]}async onload(){S0n(),vkn(),this.miyoMutationSession=Mlt(),Ha.resetInstance(),Ha.getInstance(this.app),await this.loadSettings(),this.modelManagement=oFe({app:this.app});let n=Promise.resolve(),r=(p,m)=>{n=n.then(()=>rFe(this.modelManagement,!!p,m))};r(Y().isPaidUser,Y().plusLicenseKey),this.settingsUnsubscriber=zr((p,m)=>{(async()=>{try{await Ckn(m,h=>this.saveData(h),p)}catch(h){H("Failed to persist settings.",h),new Qi.Notice("Copilot failed to save settings. Check logs and try again.")}nFe(p,m)&&r(m.isPaidUser,m.plusLicenseKey)})()}),await Nkn(this.modelManagement);let o=Y().upgradedToV8FromLegacy;if(this.addSettingTab(new _Pe(this.app,this)),e5(this.app),WE.getInstance(this.app),Fa.getInstance(this.app),$l.setApp(this.app),this.brevilabsClient=Gi.getInstance(),this.brevilabsClient.setPluginVersion(this.manifest.version),Egn(),o||ch(this.app,{trigger:"startup"}),this.registerInterval(window.setInterval(()=>void ch(this.app,{trigger:"refresh"}),xgn)),this.chainOwner=N0.getInstance(this.app,this.modelManagement),Ln()){let{CopilotAgentView:p,PlanPreviewView:m,PLAN_PREVIEW_VIEW_TYPE:h,createAgentSessionManager:g,setFrameSinkVaultBasePath:v}=await Promise.resolve().then(()=>(Hf(),d_)),{wireAgentModelDiscovery:y}=await Promise.resolve().then(()=>(ATn(),PTn));this.CopilotAgentView=p,this.PlanPreviewView=m,this.planPreviewViewType=h;let w=this.app.vault.adapter;v(w instanceof Qi.FileSystemAdapter?w.getBasePath():null),this.agentSessionManager=g(this.app,this),this.agentModelDiscoveryUnsubscriber=y(this,this.agentSessionManager)}this.vectorStoreManager=qv.getInstance(this.app),Hee.getInstance().initialize(this.app),this.fileParserManager=new APe(this.brevilabsClient,this.app.vault);let s=new DTe,a=this.chainOwner.getCurrentChainManager(),l=new $Te(s,a,this.fileParserManager,this);if(this.chatUIState=new xPe(l),this.userMemoryManager=new mO(this.app),this.quickAskController=new Foe(this),this.registerEditorExtension(this.quickAskController.createExtension()),this.chatSelectionHighlightController=new Uoe(this,{closeQuickAskOnChatFocus:!1}),this.chatSelectionHighlightController.initialize(),Ln()){let{activeLeafRef:p,layoutRef:m}=PYe(this.app,{preserveOnViewTypes:[Fs]});this.registerEvent(p),this.registerEvent(m)}if((0,Qi.addIcon)(oT,yct),this.safeRegisterView(Fs,p=>new AO(p,this)),this.safeRegisterView(bre,p=>new A0e(p)),this.safeRegisterView(iT,p=>new yoe(p,this)),Ln()&&this.CopilotAgentView&&this.PlanPreviewView&&this.planPreviewViewType){let p=this.CopilotAgentView,m=this.PlanPreviewView;this.safeRegisterView(Vd,h=>new p(h,this)),this.safeRegisterView(this.planPreviewViewType,h=>new m(h))}this.initActiveLeafChangeHandler();let c=this.canUseAgentView();this.ribbonIconEl=this.addRibbonIcon(c?oT:"message-square",c?"Open Copilot Agent Chat":"Open Copilot Chat",()=>this.canUseAgentView()?this.activateAgentView():this.activateView());let u=new BPe(this.app),d=ITn(u);this.symposiumAgentBridge=d;let f=p=>{u.open(p).catch(m=>H("Failed to open Symposium publishing.",m))};this.register(()=>{u.dispose(),this.symposiumAgentBridge===d&&(this.symposiumAgentBridge=void 0)}),$Cn(this,f),nkn(this,f),this.registerEvent(this.app.workspace.on("editor-menu",(p,m,h)=>{tkn(p,this.app,h.file,f)})),this.registerEvent(this.app.workspace.on("active-leaf-change",p=>{this.chatSelectionHighlightController.handleActiveLeafChange(p??null);let m=p?.getViewState().type;(m===Fs||m===Vd)&&(this.lastActiveChatViewType=m)})),this.customCommandRegister=new ETe(this,this.app),this.systemPromptRegister=new goe(this,this.app),this.projectRegister=new MTe(this.app),this.app.workspace.onLayoutReady(()=>{this.runStartupMigrations(o).catch(p=>{H("Failed to finish startup migrations",p),new Qi.Notice("Copilot could not finish startup migration. Reload Obsidian to retry.")})}),this.initSelectionHandler(),this.initWebSelectionWatcher()}async collectLegacyUpgradeRelocation(){if(!Y().upgradedToV8FromLegacy)return null;let n=v0n(Y());return n.length>0&&await qie(this.app.vault,Y()),n.length===0?(At("upgradedToV8FromLegacy",!1),null):{id:"folders",title:"Copilot folders",status:"action-required",summary:"Copilot now keeps its files under one folder. Existing files were not moved.",details:n.map(({label:r,oldPath:o,newPath:i})=>`${r}: move ${o} to ${i}.`)}}async runStartupMigrations(n){let r=Y(),o=n&&r.isPaidUser===!0&&!r.plusLicenseKey,i=(d,f,p)=>({result:d,failure:n?f:null,onFailure:m=>{H(`${f.title} startup migration failed`,m),!n&&p&&new Qi.Notice(p)}}),s=i(this.projectRegister.initialize(),{id:"projects",title:"Projects",status:"error",summary:"Projects could not be loaded or migrated. Reload Obsidian to retry."},"Failed to load projects. Check console for details."),a=i(this.customCommandRegister.initialize().then(()=>rkn(this.app)),{id:"custom-commands",title:"Custom commands",status:"error",summary:"Custom commands could not be loaded or migrated. Reload Obsidian to retry."}),l=i(this.systemPromptRegister.initialize().then(()=>Qat(this.app)),{id:"system-prompt",title:"System prompt",status:"error",summary:"System prompts could not be loaded or migrated. Reload Obsidian to retry."}),c=i(this.collectLegacyUpgradeRelocation(),{id:"folders",title:"Copilot folders",status:"error",summary:"Folder destinations could not be prepared. Reload Obsidian to retry."}),u=o?{id:"copilot-license",title:"Copilot license",status:"action-required",summary:"Copilot could not restore the previous paid status after the upgrade.",details:["Re-enter the license key in Copilot Settings to restore paid features."]}:null;n&&ch(o?void 0:this.app,{trigger:"startup"}),await X0n({initialItems:this.startupMigrationItems,tasks:[s,a,l,c],afterTasks:()=>{let d=Y();return!IKt(d)||!XH(this.app,d)?[u]:n?[u,{id:"miyo",title:"Miyo search",status:"action-required",summary:"Miyo search needs a resync after the Copilot folder update.",details:["Open the Miyo settings tab to resync."]}]:(new Qi.Notice("Miyo search needs a resync \u2014 open the Miyo settings tab.",8e3),[u])},present:d=>{new _i(this.app,()=>{},Z0n(d),"Copilot upgrade summary","Done","").open()},acknowledge:d=>{this.startupMigrationItems=[];let f=Y()._pendingCredentialRecovery;Y0n(d,f?.deviceId,wg(this.app))&&At("_pendingCredentialRecovery",void 0),J0n(d)&&At("upgradedToV8FromLegacy",!1)}})}safeRegisterView(n,r){try{this.registerView(n,r)}catch(o){W(`Copilot: view type "${n}" already registered; skipping re-registration.`,o)}}onunload(){this.teardown().catch(n=>{H("Copilot: plugin teardown failed during unload:",n)})}async teardown(){if(Mlt(),await _kn(),this.clearAllPersistentSelectionHighlights(),this.chatSelectionHighlightController?.cleanup(),this.agentModelDiscoveryUnsubscriber?.(),await this.agentSessionManager?.shutdown(),Hee.getInstance().cleanup(),this.customCommandRegister?.cleanup(),this.systemPromptRegister?.cleanup(),this.projectRegister?.cleanup(),this.settingsUnsubscriber?.(),Ln()){let{SkillManager:r}=await Promise.resolve().then(()=>(Hf(),d_));r.hasInstance()&&r.getInstance().dispose()}this.cleanupSelectionHandler(),this.cleanupWebSelectionWatcher(),this.clearSelectionContext();try{Sl(this.app).stopActiveWebTabTracking()}catch{}this.modelManagement?.dispose(),await $l.flush(),j("Copilot plugin unloaded")}clearAllPersistentSelectionHighlights(){try{let n=this.app.workspace.getLeavesOfType("markdown");for(let r of n){let o=r.view;if(!(o instanceof Qi.MarkdownView))continue;let i=o.editor?.cm;i&&(ph.hide(i),Vlt(i))}}catch(n){W("Failed to clear persistent selection highlights:",n)}}updateUserMessageHistory(n){this.userMessageHistory=[...this.userMessageHistory,n]}async autosaveCurrentChat(){if(Y().autosaveChat){let n=this.app.workspace.getLeavesOfType(Fs)[0]?.view;n&&await n.saveChat()}}async processText(n,r,o,i=!0){let s=n.getSelection();this.app.workspace.getLeavesOfType(Fs).length>0||await this.activateView(),window.setTimeout(()=>{let l=this.app.workspace.getLeavesOfType(Fs).find(c=>c.view instanceof AO)?.view;if(l&&(!i||s)){let c=new CustomEvent(r,{detail:{selectedText:s,eventSubtype:o}});l.eventTarget.dispatchEvent(c)}},0)}processSelection(n,r,o){this.processText(n,r,o)}emitChatIsVisible(n=Fs){let r=this.app.workspace.getLeavesOfType(n).map(o=>o.view).find(o=>o instanceof AO||this.isCopilotAgentView(o));r&&r.eventTarget.dispatchEvent(new CustomEvent(cs.CHAT_IS_VISIBLE))}initActiveLeafChangeHandler(){this.registerEvent(this.app.workspace.on("active-leaf-change",n=>{if(!n)return;let r=n.getViewState().type;(r===Fs||r===Vd)&&this.emitChatIsVisible(r)}))}initSelectionHandler(){this.selectionChangeHandler=()=>{this.selectionDebounceTimer&&window.clearTimeout(this.selectionDebounceTimer),this.selectionDebounceTimer=window.setTimeout(()=>{this.handleSelectionChange()},500)},this.selectionListenerDocument=activeDocument,this.selectionListenerDocument.addEventListener("selectionchange",this.selectionChangeHandler)}cleanupSelectionHandler(){this.selectionDebounceTimer&&window.clearTimeout(this.selectionDebounceTimer),this.selectionChangeHandler&&this.selectionListenerDocument&&this.selectionListenerDocument.removeEventListener("selectionchange",this.selectionChangeHandler),this.selectionListenerDocument=void 0}clearSelectionContext(){z_([])}clearWebSelectionContextForUrl(n){let r=hy(),o=r.filter(i=>i.sourceType!=="web"||i.url!==n);o.length!==r.length&&z_(o)}setSelectionContext(n){z_([n])}handleSelectionChange(){if(!Y().autoAddSelectionToContext)return;let r=this.app.workspace.getActiveViewOfType(Qi.MarkdownView);if(!r||!r.editor)return;let o=r.editor,i=this.app.workspace.getActiveFile(),s=o.listSelections()[0];if(!s)return;let a=i?`${i.path}:${s.anchor.line}:${s.anchor.ch}:${s.head.line}:${s.head.ch}`:"";if(a===this.lastSelectionSignature)return;this.lastSelectionSignature=a;let l=o.getSelection();if(!l||!l.trim()){let m=hy(),h=m.filter(g=>g.sourceType!=="note");m.length!==h.length&&z_(h);return}if(!i)return;let c=s.anchor.line+1,u=s.head.line+1,d=Math.min(c,u),f=Math.max(c,u),p={id:Co(),content:l,sourceType:"note",noteTitle:i.basename,notePath:i.path,startLine:d,endLine:f};this.setSelectionContext(p)}initWebSelectionWatcher(){if(!Ln())return;let n=Sl(this.app);this.webSelectionTracker=new HTe({intervalMs:500,emptySelectionDebounceCount:2,isEnabled:()=>Y().autoAddSelectionToContext,getLeaf:()=>n.getActiveLeaf()??n.getLastActiveLeaf(),getActiveLeaf:()=>n.getActiveLeaf(),onSelectionChange:r=>{this.setSelectionContext(r)},onSelectionClear:({url:r})=>{this.clearWebSelectionContextForUrl(r)}}),this.webSelectionTracker.start()}cleanupWebSelectionWatcher(){this.webSelectionTracker?.stop(),this.webSelectionTracker=void 0}suppressCurrentWebSelection(n){if(n&&n.trim()){this.webSelectionTracker?.suppressSelectionForUrl(n);return}this.webSelectionTracker?.suppressCurrentSelection()}getCurrentEditorOrDummy(){let n=this.app.workspace.getActiveViewOfType(Qi.MarkdownView);return{getSelection:()=>{let r=n?.editor?.getSelection();if(r)return r;let o=this.app.workspace.getActiveFile();return o?this.app.vault.read(o):""},replaceSelection:n?.editor?.replaceSelection.bind(n.editor)||(()=>{})}}processCustomPrompt(n,r){let o=this.getCurrentEditorOrDummy();this.processText(o,n,r,!1)}toggleView(){this.app.workspace.getLeavesOfType(Fs).length>0?this.deactivateView():this.activateView()}async activateView(){await this.openOrRevealView(Fs),window.setTimeout(()=>{this.emitChatIsVisible()},50)}pickContextChatViewType(){let n=this.canUseAgentView(),r=n&&this.app.workspace.getLeavesOfType(Vd).length>0,o=this.app.workspace.getLeavesOfType(Fs).length>0,i;return r&&o?i=this.lastActiveChatViewType===Vd:r||o?i=r:i=n,i?Vd:Fs}async activateChatViewForContext(){this.pickContextChatViewType()===Vd?await this.activateAgentView():await this.activateView()}async deactivateView(){this.app.workspace.detachLeavesOfType(Fs)}toggleAgentView(){if(!this.requireAgentView())return;this.app.workspace.getLeavesOfType(Vd).length>0?this.deactivateAgentView():this.activateAgentView()}async activateAgentView(){if(!this.requireAgentView())return null;let n=await this.openOrRevealView(Vd),r=n?.view;return this.isCopilotAgentView(r)&&r.eventTarget.queueVisible(),n}async deactivateAgentView(){this.app.workspace.detachLeavesOfType(Vd)}async activateRelevantNotesView(){return this.openOrRevealView(iT)}async insertTextIntoActiveChat(n){let r=this.pickContextChatViewType(),o=this.app.workspace.getLeavesOfType(r)[0]??null;if(o||(r===Vd?await this.activateAgentView():await this.activateView(),o=this.app.workspace.getLeavesOfType(r)[0]??null),!o)return;this.app.workspace.revealLeaf(o);let i=o.view;(i instanceof AO||this.isCopilotAgentView(i))&&i.eventTarget.queueInsertText(n)}async newAgentChat(){let n=this.requireAgentView();if(n){await this.activateAgentView();try{await n.createSession()}catch(r){W("[CopilotPlugin] Failed to create agent session",r),new Qi.Notice("Failed to create agent session. Check Copilot logs.")}}}async openOrRevealView(n){let r=this.app.workspace.getLeavesOfType(n);if(r.length>0)return this.app.workspace.revealLeaf(r[0]),r[0];let o=Y().defaultOpenArea==="view"?this.app.workspace.getRightLeaf(!1):this.app.workspace.getLeaf(!0);return o?(await o.setViewState({type:n,active:!0}),o):null}requireAgentView(){return Ln()?this.agentSessionManager?this.agentSessionManager:(new Qi.Notice("Agent Chat is not initialized."),null):(new Qi.Notice("Agent Chat is not available on mobile."),null)}canUseAgentView(){return!!this.agentSessionManager&&Ln()}isCopilotAgentView(n){let r=this.CopilotAgentView;return!!r&&n instanceof r}async loadSettings(){let n=await this.loadData(),r=await xkn(this.app,n,o=>super.saveData(o),o=>mkn(o,this.manifest.dir??"",{exists:i=>this.app.vault.adapter.exists(i),write:(i,s)=>this.app.vault.adapter.write(i,s),rename:(i,s)=>this.app.vault.adapter.rename(i,s)}),o=>this.startupMigrationItems.push(o));En(_0n(r,wg(this.app)))}async saveData(n){return super.saveData(b0n(n,wg(this.app)))}mergeActiveModels(n,r){let o=new Map;return n.forEach(i=>{let s=Jn(i),a=o.get(s);a?o.set(s,{...i,isBuiltIn:a.isBuiltIn||i.isBuiltIn}):o.set(s,i)}),Array.from(o.values())}async loadCopilotChatHistory(){let n=await this.getChatHistoryFiles();if(n.length===0){new Qi.Notice("No chat history found.");return}new ATe(this.app,n,this.chatHistoryLastAccessedAtManager,r=>void this.loadChatHistory(r)).open()}async getChatHistoryFiles(){let n=await qR(this.app,ST());return n.length===0?[]:rbe(this.app,n)}async getChatHistoryItems(){return(await this.getChatHistoryFiles()).map(r=>sbe(this.app,r,this.chatHistoryLastAccessedAtManager))}async touchChatHistoryLastAccessedAt(n){try{this.chatHistoryLastAccessedAtManager.touch(n.path);let r=BQ(this.app,n),o=this.chatHistoryLastAccessedAtManager.shouldPersist(n.path,r);if(o===null)return;let i=o;this.app.fileManager?.processFrontMatter&&this.app.vault.getAbstractFileByPath(n.path)!=null?await this.app.fileManager.processFrontMatter(n,s=>{let a=Number(s.lastAccessedAt),l=Number.isFinite(a)&&a>0?a:0;i=Math.max(l,o),l!==i&&(s.lastAccessedAt=i)}):await kx(this.app,n.path,{lastAccessedAt:i}),this.chatHistoryLastAccessedAtManager.markPersisted(n.path,i)}catch(r){W(`[CopilotPlugin] Failed to update chat lastAccessedAt for ${n.path}`,r)}}getChatHistoryLastAccessedAtManager(){return this.chatHistoryLastAccessedAtManager}async loadChatHistory(n){await this.autosaveCurrentChat();let r=this.app.workspace.getLeavesOfType(Fs)[0];r||await this.activateView(),await this.chatUIState.loadChatHistory(n),this.touchChatHistoryLastAccessedAt(n);let o=(r||this.app.workspace.getLeavesOfType(Fs)[0])?.view;o&&o.updateView()}async loadChatById(n){if(HF(n)){await this.loadNativeAgentChat(n);return}let r=await Dk(this.app,n);if(!r)throw new Error("Chat file not found.");let o=this.app.metadataCache.getFileCache(r)?.frontmatter?.mode,i=typeof o=="string"?o:void 0;if(!i)try{let s=await uf(this.app,r.path);typeof s?.mode=="string"&&(i=s.mode)}catch{}if(i===WF){await this.loadAgentChatHistory(r);return}await this.loadChatHistory(r)}async loadNativeAgentChat(n){let r=z5(n);if(!r)throw new Error("Chat not found.");let o=this.requireAgentView();if(!o)return;let i=await this.activateAgentView();i&&(await o.loadNativeSessionFromHistory(r.backendId,r.sessionId),this.isCopilotAgentView(i.view)&&i.view.updateView())}async loadAgentChatHistory(n){let r=this.requireAgentView();if(!r)return;let o=await this.activateAgentView();o&&(await r.loadSessionFromHistory(n),this.touchChatHistoryLastAccessedAt(n),this.isCopilotAgentView(o.view)&&o.view.updateView())}async openChatSourceFile(n){if(HF(n)){new Qi.Notice("This chat has no saved note. Turn on Autosave Chat as Markdown to save chats as notes in your vault.");return}let r=this.app.vault.getAbstractFileByPath(n);if(r instanceof Qi.TFile)await this.app.workspace.getLeaf(!0).openFile(r);else if(await this.app.vault.adapter.exists(n))new Qi.Notice("Cannot open source files from hidden directories. To open chat notes in the editor, save them to a non-hidden folder in settings.");else throw new Error("Chat file not found.")}async updateChatTitle(n,r){let o=this.app.vault.getAbstractFileByPath(n);if(o instanceof Qi.TFile)await this.app.fileManager.processFrontMatter(o,i=>{i.topic=r}),await new Promise(i=>{let s=l=>{l.path===n&&(this.app.metadataCache.off("changed",s),window.clearTimeout(a),i())};this.app.metadataCache.on("changed",s);let a=window.setTimeout(()=>{this.app.metadataCache.off("changed",s),i()},500)}),new Qi.Notice("Chat title updated.");else if(await Dk(this.app,n))await kx(this.app,n,{topic:r.trim()}),new Qi.Notice("Chat title updated.");else throw new Error("Chat file not found.")}async deleteChatHistory(n){let r=this.app.vault.getAbstractFileByPath(n);if(r instanceof Qi.TFile)await Bc(this.app,r),new Qi.Notice("Chat deleted.");else if(await this.app.vault.adapter.exists(n))await this.app.vault.adapter.remove(n),new Qi.Notice("Chat deleted.");else throw new Error("Chat file not found.")}async handleNewChat(){if(w3(),await $l.clear(),Y().enableRecentConversations)try{let o=this.chainOwner.getCurrentChainManager().chatModelManager.getChatModel();this.userMemoryManager.addRecentConversation(this.chatUIState.getMessages(),o)}catch(r){j("Failed to analyze chat messages for memory:",r)}await this.autosaveCurrentChat();let n=this.app.workspace.getLeavesOfType(Fs)[0];if(n){let r=n.view,o=new CustomEvent(cs.ABORT_STREAM,{detail:{reason:"new-chat"}});r.eventTarget.dispatchEvent(o)}this.chatUIState.clearMessages(),n?n.view.updateView():await this.activateView()}async newChat(){await this.handleNewChat()}async customSearchDB(n,r,o){let i=Y(),{FilterRetriever:s}=await Promise.resolve().then(()=>(I0e(),B_n)),{mergeFilterAndSearchResults:a}=await Promise.resolve().then(()=>(T0e(),z_n)),c=await new s(this.app,{salientTerms:r,maxK:20}).getRelevantDocuments(n),d=await(i.enableSemanticSearchV3?new(await Promise.resolve().then(()=>(Ust(),U_n))).MergedSemanticRetriever(this.app,{minSimilarityScore:.3,maxK:20,salientTerms:r,textWeight:o,returnAll:!1}):new(await Promise.resolve().then(()=>(gre(),F_n))).TieredLexicalRetriever(this.app,{minSimilarityScore:.3,maxK:20,salientTerms:r,textWeight:o,returnAll:!1,useRerankerThreshold:void 0})).getRelevantDocuments(n),{filterResults:f,searchResults:p}=a(c,d);return[...f,...p].map(h=>({content:h.pageContent,metadata:h.metadata}))}};
/*! Bundled license information:
react/cjs/react.production.min.js:
(**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
ieee754/index.js:
(*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
buffer/index.js:
(*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*)
react/cjs/react-jsx-runtime.production.min.js:
(**
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/shared/src/utils.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/defaultAttributes.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/Icon.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/createLucideIcon.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-big-up.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-right-left.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-up-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-up.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/book-open.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/bot.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/brain.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/check.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-down.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-left.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-alert.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-check-big.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-check.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-dashed.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-help.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-plus.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-slash.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-x.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/clipboard-list.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/clipboard-paste.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/clipboard.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/clock.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/cog.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/coins.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/command.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/copy-plus.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/copy.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/corner-down-left.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/corner-down-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/cpu.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/database.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/download.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/ellipsis-vertical.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/ellipsis.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/external-link.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/eye-off.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/eye.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-audio.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-clock.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-image.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-input.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-output.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-search.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-text.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-video.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/files.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/folder-open.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/folder-plus.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/folder-search.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/folder-sync.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/folder-tree.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/folder.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/git-fork.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/globe.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/grip-vertical.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/hammer.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/hash.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/history.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/image.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/inbox.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/info.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/key-round.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/layers.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/layout-grid.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/library-big.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/link.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/list-checks.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/list.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/loader-circle.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/lock.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/message-circle-plus.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/message-circle-question.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/message-circle.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/message-square-x.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/message-square.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/monitor-down.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/move.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pause.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pen-line.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pen.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pencil-line.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pencil.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/play.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/plus.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/refresh-cw.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/replace.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/rotate-ccw.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/rotate-cw.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/search.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/send.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/settings-2.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/settings.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/shield-check.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/shield-question.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/sigma.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/sliders-horizontal.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/sparkle.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/sparkles.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/square-arrow-out-up-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/square-check-big.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/square-pen.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/square-play.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/square.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/tag.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/terminal.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/text-cursor-input.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/trash-2.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/triangle-alert.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/wrench.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/x.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/lucide-react.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
scheduler/cjs/scheduler.production.min.js:
(**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
react-dom/cjs/react-dom.production.min.js:
(**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
@langchain/core/dist/utils/fast-json-patch/src/helpers.js:
(*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2017-2022 Joachim Wester
* MIT licensed
*)
@langchain/core/dist/utils/fast-json-patch/src/core.js:
(*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2013-2021 Joachim Wester
* MIT license
*)
@langchain/core/dist/utils/fast-json-patch/src/duplex.js:
(*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2013-2021 Joachim Wester
* MIT license
*)
@langchain/core/dist/utils/js-sha256/hash.js:
(**
* [js-sha256]{@link https://github.com/emn178/js-sha256}
*
* @version 0.11.1
* @author Chen, Yi-Cyuan [emn178@gmail.com]
* @copyright Chen, Yi-Cyuan 2014-2025
* @license MIT
*)
@langchain/core/dist/utils/sax-js/sax.js:
(*! http://mths.be/fromcodepoint v0.1.0 by @mathias *)
@google/generative-ai/dist/index.mjs:
(**
* @license
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*)
mustache/mustache.mjs:
(*!
* mustache.js - Logic-less {{mustache}} templates with JavaScript
* http://github.com/janl/mustache.js
*)
*/
/* nosourcemap */