@mikedown/web-component 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/mikedown-editor.ai-ui-QFYFN73D-MK2MJ2BC.js +184 -0
- package/dist/{mikedown-editor.chunk-L7U45VO5.js → mikedown-editor.chunk-MZAFS27D.js} +21 -21
- package/dist/mikedown-editor.standalone.js +139 -139
- package/package.json +3 -3
- package/dist/mikedown-editor.ai-ui-C7ENTWWU-WYTCUH47.js +0 -118
|
@@ -1,118 +0,0 @@
|
|
|
1
|
-
/*! @mikedown/web-component 0.3.0 standalone | MIT | bundles third-party code, see THIRD_PARTY_NOTICES.md */
|
|
2
|
-
import{A as vi,Da as yi,Db as sn,Ha as At,Ja as Dt,Ka as wi,Lb as To,Ma as xo,Na as Xt,Oa as Ai,Pa as Zt,Qa as _n,Ra as Eo,Sa as On,Ua as rn,V as ki,h as wo,l as bi,r as Cn,za as Ao}from"./mikedown-editor.chunk-L7U45VO5.js";var Di=["openai-compatible","lmstudio","ollama","anthropic","openai","vscode-lm"],Dr=["vscode-lm"];var en=8192,Pi=["none","default","anyLocal","any"],Pr=["unreachable","auth","modelNotFound","modelLoadFailed","contextOverflow","rateLimited","cloudBlocked","consentDenied","cancelled","badOutput","unknown"],Ur=32768,jt=[{id:"rewrite",label:"Rewrite",description:"Selection rewrite, explain or expand, reading level, translation.",requires:{chat:!0,stream:!0}},{id:"continue",label:"Continue",description:"Inline ghost text. Prefers a small fill-in-the-middle model.",requires:{stream:!0},requiresAny:["fim","chat"]},{id:"chat",label:"Chat",description:"Chat with the document, prompt blocks.",requires:{chat:!0,stream:!0}},{id:"summarize",label:"Summarize",description:'Summaries and "what changed". Works best with a large context window; long documents are cut and labelled.',requires:{chat:!0},prefers:{contextTokens:Ur}},{id:"structure",label:"Structure",description:"Frontmatter and tags, Mermaid, tables, code, titles, paste cleanup. Prefers a model with JSON output.",requires:{chat:!0},prefers:{json:!0}},{id:"notes",label:"Notes",description:"Meeting notes to action items.",requires:{chat:!0,json:!0}},{id:"review",label:"Review",description:"Grammar pass and consistency checks.",requires:{chat:!0,json:!0}},{id:"vision",label:"Vision",description:"Alt text for images.",requires:{vision:!0}},{id:"embed",label:"Embeddings",description:"Workspace search and link suggestions.",requires:{embed:!0},hostMethod:"embed"},{id:"transcribe",label:"Transcribe",description:"Dictation, through the host.",requires:{},hostMethod:"transcribe"}];function ln(e){return jt.find(t=>t.id===e)}function Kr(e,t){let n={...e};for(let[i,o]of Object.entries(t))i==="contextTokens"?typeof o=="number"&&(n.contextTokens=Math.max(n.contextTokens??0,o)):o===!0&&(n[i]=!0);return n}function jn(e,t,n,i=en){let o=[];for(let[a,r]of Object.entries(t))a==="contextTokens"?typeof r=="number"&&(e.contextTokens??i)<r&&o.push("contextTokens"):r===!0&&!e[a]&&o.push(a);return n&&n.length>0&&!n.some(a=>e[a])&&o.push(n[0]),o}var Ui=[{id:"rewrite",label:"Rewrite selection",description:"Shorter, longer, fix flow or a custom prompt, previewed before it replaces the selection.",defaultEnabled:!0,defaultTask:"rewrite",requires:{chat:!0,stream:!0},status:"available",sends:"selection"},{id:"ghostText",label:"Inline suggestions",description:"Dim continuation text while you write. Sends the text around the cursor as you type.",defaultEnabled:!1,defaultTask:"continue",requires:{stream:!0},status:"planned"},{id:"chat",label:"Chat with this document",description:"A sidebar chat with the document as context.",defaultEnabled:!0,defaultTask:"chat",requires:{chat:!0,stream:!0},status:"planned",sends:"document"},{id:"summary",label:"Summary",description:"Insert a summary or outline of the document.",defaultEnabled:!0,defaultTask:"summarize",requires:{chat:!0},status:"available",sends:"document"},{id:"frontmatter",label:"Frontmatter and tags",description:"Suggest a title, tags and other properties.",defaultEnabled:!0,defaultTask:"structure",requires:{chat:!0},status:"available",sends:"documentAndTags"},{id:"title",label:"Suggest titles",description:"Offer a few titles for the document.",defaultEnabled:!0,defaultTask:"structure",requires:{chat:!0},status:"available",sends:"document"},{id:"altText",label:"Image alt text",description:"Describe pasted images for their alt text.",defaultEnabled:!0,defaultTask:"vision",requires:{vision:!0},status:"planned"}];function jo(e){return Ui.find(t=>t.id===e)}function bn(e,t){let n=jo(t),i=e[t]??{};return{id:t,enabled:i.enabled??n?.defaultEnabled??!1,task:i.task??n?.defaultTask??t,requires:n?.requires??{},definition:n}}var xi={chat:!0,stream:!0,vision:!1,json:!1,tools:!1,fim:!1,embed:!1,contextTokens:null},$t={chat:!1,stream:!1,vision:!1,json:!1,tools:!1,fim:!1},Fr=[{family:"qwen",pattern:/qwen/,caps:{json:!0,tools:!0,contextTokens:32768}},{family:"qwen3",pattern:/qwen-?3(?![.\d])/,caps:{contextTokens:40960}},{family:"qwen3.5+",pattern:/qwen-?3\.[5-9]|qwen-?4/,caps:{vision:!0,contextTokens:262144}},{family:"qwen-coder",pattern:/qwen.*coder/,caps:{vision:!1,fim:!0,contextTokens:262144}},{family:"qwen2.5-coder",pattern:/qwen-?2\.5.*coder/,caps:{contextTokens:32768}},{family:"gemma",pattern:/gemma/,caps:{json:!0,contextTokens:8192}},{family:"gemma3",pattern:/gemma-?3/,caps:{vision:!0,contextTokens:131072}},{family:"gemma4",pattern:/gemma-?4/,caps:{vision:!0,tools:!0,contextTokens:131072}},{family:"codegemma",pattern:/codegemma/,caps:{vision:!1,fim:!0}},{family:"llama3.1+",pattern:/llama-?3\.[1-3]/,caps:{json:!0,tools:!0,contextTokens:131072}},{family:"llama4",pattern:/llama-?4/,caps:{json:!0,tools:!0,vision:!0,contextTokens:131072}},{family:"mistral",pattern:/mistral|mixtral|ministral|magistral/,caps:{json:!0,tools:!0,contextTokens:32768}},{family:"mistral-vision",pattern:/mistral-small-3\.[1-9]|mistral-medium|magistral|pixtral/,caps:{vision:!0,contextTokens:131072}},{family:"codestral",pattern:/codestral/,caps:{fim:!0,json:!0,contextTokens:32768}},{family:"deepseek",pattern:/deepseek/,caps:{json:!0,tools:!0,contextTokens:131072}},{family:"deepseek-v4",pattern:/deepseek-?v4/,caps:{contextTokens:1048576}},{family:"deepseek-coder",pattern:/deepseek-coder/,caps:{fim:!0}},{family:"minimax",pattern:/minimax/,caps:{json:!0,tools:!0,contextTokens:196608}},{family:"glm",pattern:/glm/,caps:{json:!0,tools:!0,contextTokens:131072}},{family:"glm5",pattern:/glm-?5/,caps:{contextTokens:1048576}},{family:"gpt-oss",pattern:/gpt-oss/,caps:{json:!0,tools:!0,contextTokens:131072}},{family:"phi4",pattern:/phi-?4/,caps:{json:!0,contextTokens:16384}},{family:"hermes",pattern:/hermes/,caps:{json:!0,tools:!0}},{family:"nemotron",pattern:/nemotron/,caps:{json:!0,tools:!0,contextTokens:131072}},{family:"starcoder",pattern:/starcoder|stable-?code/,caps:{fim:!0}},{family:"vision",pattern:/(^|[^a-z])vl([^a-z]|$)|vision|llava|minicpm-v|moondream|omni|multimodal/,caps:{vision:!0}},{family:"embedding",pattern:/embed|(^|[/_-])(bge|gte|e5)-|minilm|mxbai|arctic-embed|snowflake/,caps:{...$t,embed:!0,contextTokens:8192}},{family:"bge",pattern:/(^|[/_-])bge-(small|base|large)/,caps:{contextTokens:512}},{family:"speech",pattern:/whisper|parakeet|kokoro|(^|[/_-])tts([/_-]|$)|rerank/,caps:{...$t,embed:!1}}],Hr={chat:!0,stream:!0,vision:!0,json:!0,tools:!0,fim:!1,embed:!1},jr=[{prefix:"claude-",caps:{...Hr,contextTokens:2e5}},{prefix:"claude-3",caps:{contextTokens:2e5}},{prefix:"claude-haiku-4-5",caps:{contextTokens:2e5}},{prefix:"claude-opus-4-6",caps:{contextTokens:1e6}},{prefix:"claude-opus-4-7",caps:{contextTokens:1e6}},{prefix:"claude-opus-4-8",caps:{contextTokens:1e6}},{prefix:"claude-sonnet-4-6",caps:{contextTokens:1e6}},{prefix:"claude-opus-5",caps:{contextTokens:1e6}},{prefix:"claude-sonnet-5",caps:{contextTokens:1e6}},{prefix:"claude-haiku-5",caps:{contextTokens:1e6}},{prefix:"claude-fable-5",caps:{contextTokens:1e6}},{prefix:"claude-mythos-5",caps:{contextTokens:1e6}}],Br=[{prefix:"gpt-",caps:{chat:!0,stream:!0,json:!0,tools:!0,vision:!1,fim:!1,embed:!1,contextTokens:128e3}},{prefix:"gpt-3.5",caps:{contextTokens:16385}},{prefix:"gpt-4o",caps:{vision:!0,contextTokens:128e3}},{prefix:"gpt-4.1",caps:{vision:!0,contextTokens:1047576}},{prefix:"gpt-5",caps:{vision:!0,contextTokens:4e5}},{prefix:"gpt-oss",caps:{contextTokens:131072}},{prefix:"o1",caps:{chat:!0,stream:!0,json:!0,tools:!0,vision:!0,contextTokens:2e5}},{prefix:"o3",caps:{chat:!0,stream:!0,json:!0,tools:!0,vision:!0,contextTokens:2e5}},{prefix:"o4",caps:{chat:!0,stream:!0,json:!0,tools:!0,vision:!0,contextTokens:2e5}},{prefix:"text-embedding-",caps:{...$t,embed:!0,contextTokens:8191}},{prefix:"whisper",caps:$t},{prefix:"tts-",caps:$t},{prefix:"gpt-4o-mini-tts",caps:$t},{prefix:"gpt-4o-transcribe",caps:$t},{prefix:"gpt-image",caps:$t},{prefix:"dall-e",caps:$t},{prefix:"omni-moderation",caps:$t}],zr=/^(o\d+|gpt-([5-9]|\d{2,})(\.\d+)?)(-|$)/;function qr(e,t){let n=Gr(e,t);return n!==null&&zr.test(n)}function Gr(e,t){let n=e.trim().toLowerCase();return t==="openai"?n.slice(n.lastIndexOf("/")+1):n.startsWith("openai/")?n.slice(7):null}function Wr(e,t){let n=e.filter(i=>t.startsWith(i.prefix)).sort((i,o)=>i.prefix.length-o.prefix.length);return n.length===0?null:{caps:Object.assign({},...n.map(i=>i.caps)),prefix:n[n.length-1].prefix}}function Bn(e,t){if(t==="vscode-lm")return{capabilities:Ei({...xi}),family:"vscode-lm"};let n=e.trim().toLowerCase(),i=n.slice(n.lastIndexOf("/")+1),o=t==="anthropic"||i.startsWith("claude-")?jr:t==="openai"||/^(gpt-[\d.]|o[134](-|$)|text-embedding-|whisper|tts-|dall-e|gpt-image|omni-moderation)/.test(i)?Br:null;if(o){let u=Wr(o,i);if(u)return{capabilities:Ei({...xi,...u.caps}),family:u.prefix}}let a={...xi},r=null;for(let u of Fr)u.pattern.test(n)&&(a={...a,...u.caps},r=u.family);return{capabilities:Ei(a),family:r}}function Ei(e){return e.contextTokens===null?{...e,contextTokens:en}:e}function _i(e,t,n){let i={...Bn(t,n).capabilities};for(let[o,a]of Object.entries(e))o==="contextTokens"?typeof a=="number"&&a>0&&(i.contextTokens=a):typeof a=="boolean"&&o in i&&(i[o]=a);return i}function Bo(e,t,n,i={}){let o=i.addEnabled??!0,a=new Map;for(let d of t)a.has(d.id)||a.set(d.id,d);let r=e.map(d=>{let b=a.get(d.id);if(!b)return d.manual?d:{...d,missing:!0};let k={...d,label:d.label??b.label};return delete k.missing,k.label===void 0&&delete k.label,d.capabilitiesSource!=="user"&&(k.capabilities=_i(b.capabilities,b.id,n),k.capabilitiesSource=b.source),k}),u=new Set(e.map(d=>d.id));for(let d of a.values()){if(u.has(d.id))continue;let b={id:d.id,enabled:o,capabilities:_i(d.capabilities,d.id,n),capabilitiesSource:d.source};d.label!==void 0&&(b.label=d.label),r.push(b)}return r}var Ki=[{family:"local",label:"Run on this machine",explainer:"Your own model server, on this computer or your network. Text never leaves it."},{family:"cloud",label:"Cloud API key",explainer:"Paste a key from the provider. It bills your account for what you use."}],zo={family:"host",label:"Built into VS Code",explainer:"A model VS Code already offers through your GitHub Copilot plan. No key to paste; text goes to GitHub\u2019s Copilot service."},Ti=(e,t)=>({label:t,match:new RegExp(`^claude-${e}-\\d`)}),ft=[{id:"omlx",name:"oMLX",kind:"openai-compatible",baseUrl:"http://127.0.0.1:8000/v1",apiKeyEnv:"OMLX_API_KEY",apiKeyFile:{path:"~/.omlx/settings.json",jsonPath:"auth.api_key"},needsKey:!0,family:"local",caption:"MLX models on Apple silicon",keyHint:"oMLX keeps its key in ~/.omlx/settings.json, which is read automatically.",installUrl:"https://omlx.ai"},{id:"lmstudio",name:"LM Studio",kind:"lmstudio",baseUrl:"http://127.0.0.1:1234/v1",needsKey:!1,family:"local",caption:"The LM Studio app\u2019s local server",keyHint:"Only needed if you turned on authentication in LM Studio.",installUrl:"https://lmstudio.ai/download",detectPath:"/api/v0/models"},{id:"ollama",name:"Ollama",kind:"ollama",baseUrl:"http://127.0.0.1:11434/v1",needsKey:!1,family:"local",caption:"Models pulled with ollama",keyHint:"Ollama needs no key.",installUrl:"https://ollama.com/download",detectPath:"/api/tags"},{id:"llamacpp",name:"llama.cpp server",kind:"openai-compatible",baseUrl:"http://127.0.0.1:8080/v1",needsKey:!1,family:"local",caption:"llama-server with a GGUF model",keyHint:"Only needed if you started llama-server with --api-key.",installUrl:"https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md"},{id:"vllm",name:"vLLM",kind:"openai-compatible",baseUrl:"http://127.0.0.1:8000/v1",apiKeyEnv:"VLLM_API_KEY",needsKey:!1,family:"local",caption:"vllm serve on a GPU box",keyHint:"Only needed if you started vLLM with --api-key.",installUrl:"https://docs.vllm.ai/en/latest/getting_started/installation/"},{id:"custom",name:"Custom OpenAI-compatible",kind:"openai-compatible",baseUrl:"http://127.0.0.1:8000/v1",needsKey:!1,family:"local",caption:"Any server that speaks the OpenAI API",keyHint:"Leave blank if the server has no auth."},{id:"anthropic",name:"Anthropic",kind:"anthropic",baseUrl:"https://api.anthropic.com",apiKeyEnv:"ANTHROPIC_API_KEY",needsKey:!0,family:"cloud",caption:"Claude models, API key from Anthropic",keyHint:"Get an API key in the Claude Console",keyUrl:"https://platform.claude.com/settings/keys",pricingUrl:"https://platform.claude.com/docs/en/about-claude/pricing",policy:{label:"Anthropic privacy and data use",url:"https://privacy.claude.com/en/collections/10663361-commercial-customers"},popular:[Ti("sonnet","Sonnet"),Ti("opus","Opus"),Ti("haiku","Haiku")]},{id:"openai",name:"OpenAI",kind:"openai",baseUrl:"https://api.openai.com/v1",apiKeyEnv:"OPENAI_API_KEY",needsKey:!0,family:"cloud",caption:"GPT models, API key from OpenAI",keyHint:"Get an API key on the OpenAI platform",keyUrl:"https://platform.openai.com/api-keys",pricingUrl:"https://developers.openai.com/api/docs/pricing",policy:{label:"OpenAI API data controls",url:"https://developers.openai.com/api/docs/guides/your-data"},popular:[{label:"Flagship",match:/^gpt-\d+(\.\d+)?$/},{label:"Mini",match:/^gpt-\d+(\.\d+)?-mini$/}]},{id:"openrouter",name:"OpenRouter",kind:"openai-compatible",baseUrl:"https://openrouter.ai/api/v1",apiKeyEnv:"OPENROUTER_API_KEY",needsKey:!0,family:"cloud",caption:"Models from many providers with one key",keyHint:"Get an API key on OpenRouter",keyUrl:"https://openrouter.ai/keys",pricingUrl:"https://openrouter.ai/pricing",policy:{label:"OpenRouter privacy policy",url:"https://openrouter.ai/privacy",note:"OpenRouter passes each request on to the provider that serves the model, whose own terms apply as well."},popular:[{label:"Claude Sonnet",match:/^anthropic\/claude-sonnet-\d/},{label:"GPT",match:/^openai\/gpt-\d+(\.\d+)?$/},{label:"Gemini Pro",match:/^google\/gemini-\d+(\.\d+)?-pro$/},{label:"Gemini Flash",match:/^google\/gemini-\d+(\.\d+)?-flash$/}]},{id:"gemini",name:"Google Gemini",kind:"openai-compatible",baseUrl:"https://generativelanguage.googleapis.com/v1beta/openai",apiKeyEnv:"GEMINI_API_KEY",needsKey:!0,family:"cloud",caption:"Gemini models, API key from Google AI Studio",keyHint:"Get an API key in Google AI Studio",keyUrl:"https://aistudio.google.com/apikey",pricingUrl:"https://ai.google.dev/gemini-api/docs/pricing",policy:{label:"Gemini API terms and data use",url:"https://ai.google.dev/gemini-api/terms"},popular:[{label:"Flash",match:/(^|\/)gemini-\d+(\.\d+)?-flash$/},{label:"Pro",match:/(^|\/)gemini-\d+(\.\d+)?-pro$/},{label:"Flash-Lite",match:/(^|\/)gemini-\d+(\.\d+)?-flash-lite$/}]},{id:"groq",name:"Groq",kind:"openai-compatible",baseUrl:"https://api.groq.com/openai/v1",apiKeyEnv:"GROQ_API_KEY",needsKey:!0,family:"cloud",caption:"Fast open models such as Llama and Qwen",keyHint:"Get an API key in the Groq console",keyUrl:"https://console.groq.com/keys",pricingUrl:"https://console.groq.com/docs/models",policy:{label:"Groq: your data in GroqCloud",url:"https://console.groq.com/docs/your-data"},popular:[{label:"GPT-OSS",match:/^openai\/gpt-oss-\d+b$/},{label:"Llama",match:/^(meta-llama\/)?llama-\d/,exclude:/guard|prompt/},{label:"Qwen",match:/^qwen\/qwen\d/}]},{id:"mistral",name:"Mistral",kind:"openai-compatible",baseUrl:"https://api.mistral.ai/v1",apiKeyEnv:"MISTRAL_API_KEY",needsKey:!0,family:"cloud",caption:"Mistral models, API key from Mistral",keyHint:"Get an API key in the Mistral console",keyUrl:"https://console.mistral.ai/api-keys",pricingUrl:"https://mistral.ai/pricing",policy:{label:"Mistral AI privacy policy",url:"https://legal.mistral.ai/terms/privacy-policy/"},popular:[{label:"Medium",match:/^mistral-medium-/,prefer:/-latest$/},{label:"Large",match:/^mistral-large-/,prefer:/-latest$/},{label:"Small",match:/^mistral-small-/,prefer:/-latest$/}]},{id:"deepseek",name:"DeepSeek",kind:"openai-compatible",baseUrl:"https://api.deepseek.com/v1",apiKeyEnv:"DEEPSEEK_API_KEY",needsKey:!0,family:"cloud",caption:"DeepSeek chat and reasoning models",keyHint:"Get an API key on the DeepSeek platform",keyUrl:"https://platform.deepseek.com/api_keys",pricingUrl:"https://api-docs.deepseek.com/quick_start/pricing",policy:{label:"DeepSeek privacy policy",url:"https://cdn.deepseek.com/policies/en-US/deepseek-privacy-policy.html"},popular:[{label:"Chat",match:/^deepseek-chat/},{label:"Reasoner",match:/^deepseek-reasoner/}]},{id:"vscodelm",name:"GitHub Copilot",kind:"vscode-lm",baseUrl:"",needsKey:!1,family:"host",caption:"Copilot\u2019s models in VS Code, no key needed",keyHint:"No key: VS Code signs in to GitHub Copilot for you. Needs a Copilot plan and the GitHub Copilot Chat extension.",pricingUrl:"https://github.com/features/copilot/plans",policy:{label:"GitHub Copilot Trust Center",url:"https://copilot.github.trust.page/",note:"Text goes to GitHub\u2019s Copilot service under your Copilot plan; individual and business plans handle data differently."}}];function So(e){return e.trim().toLowerCase().replace(/\/+$/,"")}function Bt(e,t=ft){let n=t.filter(a=>a.kind===e.kind),i=n.filter(a=>So(a.baseUrl)===So(e.baseUrl));if(i.length>0)return i.find(a=>a.apiKeyEnv&&a.apiKeyEnv===e.apiKeyEnv)??i.find(a=>!a.apiKeyEnv&&!e.apiKeyEnv)??i[0];let o="";try{o=new URL(e.baseUrl.trim()).hostname.toLowerCase()}catch{}if(o){let a=n.find(r=>r.family==="cloud"&&new URL(r.baseUrl).hostname.toLowerCase()===o);if(a)return a}return e.kind!=="openai-compatible"&&n.length===1?n[0]:void 0}var qo=1500;function Go(e=ft){return e.filter(t=>t.family==="local"&&t.id!=="custom").map(t=>({presetId:t.id,baseUrl:t.baseUrl}))}var Yr=["enabled","allowCloud","engines","routing","features","localNetworks","showToolbarButton"];function xt(e){return Di.includes(e)}function zt(e){return Dr.includes(e)}function vt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cn(e,t){let n={};for(let[i,o]of Object.entries(e))t.includes(i)||(n[i]=o);return n}function $o(e){let t="abcdefghijklmnopqrstuvwxyz0123456789",n=new Uint8Array(e),i=globalThis.crypto;if(i?.getRandomValues)i.getRandomValues(n);else for(let o=0;o<e;o++)n[o]=Math.floor(Math.random()*256);return Array.from(n,o=>t[o%t.length]).join("")}function zn(e=""){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24).replace(/-+$/,"");return t?`${t}-${$o(6)}`:`engine-${$o(8)}`}function Vr(e,t={}){let n=t.onWarning??(u=>console.warn(`[mikedown ai] ${u}`)),i=t.generateId??zn,o=Eo();if(!vt(e))return e!=null&&n("AI settings are not an object; using defaults."),o;let a=Jr(e),r={...cn(a,Yr),...o};return typeof a.enabled=="boolean"&&(r.enabled=a.enabled),typeof a.allowCloud=="boolean"&&(r.allowCloud=a.allowCloud),typeof a.showToolbarButton=="boolean"&&(r.showToolbarButton=a.showToolbarButton),Array.isArray(a.localNetworks)?r.localNetworks=a.localNetworks.filter(u=>typeof u=="string"&&u.trim().length>0):a.localNetworks!==void 0&&n("localNetworks is not an array; using the default."),r.engines=Qr(a.engines,i,n),r.routing=is(a.routing,n),r.features=os(a.features,n),r}function Jr(e){let t=Object.keys(e).filter(i=>i.startsWith("ai."));if(t.length===0)return vt(e.ai)?e.ai:e;let n={};for(let i of t)n[i.slice(3)]=e[i];return n}var Xr=["id","name","kind","baseUrl","enabled","locality","apiKeyEnv","apiKeyFile","discovery","models"];function Zr(e){if(!vt(e)||typeof e.path!="string"||typeof e.jsonPath!="string")return;let t=e.path.trim(),n=e.jsonPath.trim();return t&&n?{...cn(e,["path","jsonPath"]),path:t,jsonPath:n}:void 0}function Qr(e,t,n){if(e===void 0)return[];if(!Array.isArray(e))return n("engines is not an array; ignoring it."),[];let i=[],o=new Set;return e.forEach((a,r)=>{if(!vt(a)||typeof a.baseUrl!="string"){n(`engines[${r}] has no baseUrl; dropped.`);return}let u=typeof a.name=="string"&&a.name.trim()?a.name:a.baseUrl,d=typeof a.kind=="string"?a.kind:"openai-compatible";d.trim()||(d="openai-compatible");let b=typeof a.id=="string"&&a.id.trim()?a.id:"";if(!b||o.has(b)){b&&n(`engines[${r}] repeats id "${b}"; gave it a new one.`);do b=t(u);while(o.has(b))}o.add(b);let k={...cn(a,Xr)};if(k.id=b,k.name=u,k.kind=d,k.baseUrl=a.baseUrl.trim(),k.enabled=typeof a.enabled=="boolean"?a.enabled:!0,k.locality=a.locality==="local"||a.locality==="cloud"?a.locality:"auto",typeof a.apiKeyEnv=="string"&&a.apiKeyEnv.trim()&&(k.apiKeyEnv=a.apiKeyEnv.trim()),a.apiKeyFile!==void 0){let h=Zr(a.apiKeyFile);h?k.apiKeyFile=h:n(`engines[${r}].apiKeyFile needs a path and a jsonPath (both strings); dropped.`)}k.discovery=a.discovery==="manual"?"manual":"auto",k.models=ns(a.models,k.kind,`engines[${r}]`,n),i.push(k)}),i}var es=["id","label","enabled","capabilities","capabilitiesSource","requestOverrides","missing","manual"],ts=["endpoint","heuristic","user"];function ns(e,t,n,i){if(e===void 0)return[];if(!Array.isArray(e))return i(`${n}.models is not an array; ignoring it.`),[];let o=[],a=new Set;return e.forEach((r,u)=>{if(!vt(r)||typeof r.id!="string"||!r.id.trim()){i(`${n}.models[${u}] has no id; dropped.`);return}if(a.has(r.id)){i(`${n}.models[${u}] repeats id "${r.id}"; dropped.`);return}a.add(r.id);let d={...cn(r,es)};d.id=r.id,typeof r.label=="string"&&r.label.trim()&&(d.label=r.label),d.enabled=typeof r.enabled=="boolean"?r.enabled:!0;let b=xt(t)?t:void 0;vt(r.capabilities)?(d.capabilities=_i(r.capabilities,r.id,b),r.capabilities.contextTokens===null&&(d.capabilities.contextTokens=null),d.capabilitiesSource=ts.includes(r.capabilitiesSource)?r.capabilitiesSource:"heuristic"):(d.capabilities=Bn(r.id,b).capabilities,d.capabilitiesSource="heuristic"),vt(r.requestOverrides)?d.requestOverrides=r.requestOverrides:r.requestOverrides!==void 0&&i(`${n}.models[${u}].requestOverrides is not an object; ignoring it.`),r.missing===!0&&(d.missing=!0),r.manual===!0&&(d.manual=!0),o.push(d)}),o}function Io(e){return!vt(e)||typeof e.engineId!="string"||typeof e.modelId!="string"||!e.engineId||!e.modelId?null:{...e,engineId:e.engineId,modelId:e.modelId}}function is(e,t){let n={default:null,fallback:"anyLocal",tasks:{}};if(e===void 0)return n;if(!vt(e))return t("routing is not an object; using the defaults."),n;let i={...cn(e,["default","fallback","tasks"]),...n};if(e.default!==void 0&&e.default!==null&&(i.default=Io(e.default),i.default||t("routing.default needs engineId and modelId; cleared.")),typeof e.fallback=="string"&&Pi.includes(e.fallback)?i.fallback=e.fallback:e.fallback!==void 0&&t(`routing.fallback "${String(e.fallback)}" is not a fallback mode; using anyLocal.`),vt(e.tasks))for(let[o,a]of Object.entries(e.tasks)){let r=Io(a);r?i.tasks[o]=r:a!==null&&t(`routing.tasks.${o} needs engineId and modelId; dropped.`)}else e.tasks!==void 0&&t("routing.tasks is not an object; ignoring it.");return i}function os(e,t){let n={};if(e===void 0)return n;if(!vt(e))return t("features is not an object; ignoring it."),n;for(let[i,o]of Object.entries(e)){if(!vt(o)){t(`features.${i} is not an object; dropped.`);continue}let a={...cn(o,["enabled","task"])};typeof o.enabled=="boolean"&&(a.enabled=o.enabled),typeof o.task=="string"&&o.task.trim()&&(a.task=o.task),n[i]=a}return n}function vn(e){let t={};for(let[n,i]of Object.entries(e))i!==void 0&&(t[`ai.${n}`]=JSON.parse(JSON.stringify(i)));return t}function Fi(e){return!("unusable"in e)}var as={chat:"chat",stream:"streaming",vision:"vision",json:"JSON output",tools:"tools",fim:"fill-in-the-middle",embed:"embeddings",contextTokens:"a large enough context window"};function rs(e){return e.name||e.id}function Si(e){return e.label||e.id}function kn(e,t,n,i){if(!e.enabled)return{unusable:"aiDisabled",reason:"AI is turned off."};let o=bn(e.features,i.feature),a=i.task??o.task;if(!o.enabled)return{unusable:"featureDisabled",reason:`${o.definition?.label??i.feature} is turned off.`,task:a};let r=ln(a),u=Kr(r?.requires??{},o.requires),d=r?.requiresAny,b=r?.prefers,k=new Map(t.map(O=>[O.engineId,O])),h=O=>ss(e,k,n,O,u,d),w=e.routing.tasks[a]??e.routing.default;if(!w)return $(null,{code:"noRoute",reason:"No engine and model is chosen for this task."});let E=h(w);if(!("code"in E))return S(E,!1);return $(w,E);function S(O,F,j){let se={engineId:O.engine.id,modelId:O.model.id,viaFallback:F,task:a,isLocal:O.isLocal,needsConsent:O.needsConsent};return j&&(se.reason=j),se}function $(O,F){let j=e.routing.fallback;if(j==="none")return N(F);let se=O?e.engines.find(ge=>ge.id===O.engineId):void 0,le=se?Zt(se,e.localNetworks)==="local":!0,he=ge=>ge.isLocal||!le||j==="any",ae=new Set;O&&ae.add(Nn(O));let X=[],ee=e.routing.default;if(ee&&!ae.has(Nn(ee))){ae.add(Nn(ee));let ge=h(ee);!("code"in ge)&&he(ge)&&X.push(ge)}if(j==="default"){let ge=$i(X,b);return ge?S(ge,!0,F.reason):N(F)}let Ee=ge=>{let $e=[];for(let ie of e.engines)for(let Ie of ie.models){let Le={engineId:ie.id,modelId:Ie.id};if(ae.has(Nn(Le)))continue;let Re=h(Le);"code"in Re||Re.isLocal!==ge||$e.push(Re)}return $e},Ne=$i([...X,...Ee(!0)],b);if(Ne)return S(Ne,!0,F.reason);if(j==="any"){let ge=$i(Ee(!1),b);if(ge)return S(ge,!0,F.reason)}return N(F)}function N(O){return{unusable:O.code,reason:O.reason,task:a,...O.engineId?{engineId:O.engineId}:{}}}}function $i(e,t){if(e.length===0)return null;if(t){let n=e.find(i=>jn(i.model.capabilities,t).length===0);if(n)return n}return e[0]}function Nn(e){return`${e.engineId}\0${e.modelId}`}function ss(e,t,n,i,o,a){let r=e.engines.find(S=>S.id===i.engineId);if(!r)return{code:"engineMissing",reason:"The routed engine no longer exists."};let u=rs(r),d=r.id;if(!r.enabled)return{code:"engineDisabled",reason:`${u} is turned off.`,engineId:d};if(!xt(r.kind))return{code:"engineUnsupported",reason:`${u} uses an engine kind this version does not support.`};let b=t.get(r.id);if(zt(r.kind)&&!b)return{code:"engineUnsupported",reason:`${u} uses an engine kind this app does not support.`};let k=r.models.find(S=>S.id===i.modelId);if(!k)return{code:"modelMissing",reason:`${u} has no model "${i.modelId}".`,engineId:d};if(!k.enabled)return{code:"modelDisabled",reason:`${Si(k)} is turned off.`};if(k.missing||b?.models.find(S=>S.id===k.id)?.missing)return{code:"modelNotListed",reason:`${u} no longer lists ${Si(k)}.`,engineId:d};let h=jn(k.capabilities,o,a);if(h.length>0)return{code:"capability",reason:`${Si(k)} lacks ${h.map(S=>as[S]??S).join(", ")}.`};let w=Zt(r,e.localNetworks)==="local",E=!1;if(!w){if(!e.allowCloud)return{code:"cloudBlocked",reason:`${u} is a cloud engine and Allow cloud is off.`};let S=n[r.id];if(S===!1)return{code:"consentDenied",reason:`${u} was not allowed in this workspace.`};E=S!==!0}return b?.ok===!1?{code:"probeFailed",reason:b.error?`${u} failed its last connection test: ${b.error}`:`${u} failed its last connection test.`,engineId:d}:{engine:r,model:k,isLocal:w,needsConsent:E}}var ls=4;function Lo(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function Wo(e){let t=e.timing;if(!t||typeof t.totalMs!="number"||!Number.isFinite(t.totalMs)||t.totalMs<0)return null;let n={totalMs:t.totalMs,approximate:!1};typeof t.firstTokenMs=="number"&&Number.isFinite(t.firstTokenMs)&&t.firstTokenMs>=0&&(n.firstTokenMs=t.firstTokenMs);let i=Lo(e.usage?.completionTokens);if(i!==void 0)n.outputTokens=i;else{let u=t.outputChars??e.text.length;u>0&&(n.outputTokens=Math.max(1,Math.round(u/ls)),n.approximate=!0)}let o=Lo(e.usage?.promptTokens);o!==void 0&&(n.inputTokens=o);let a=n.firstTokenMs,r=a!==void 0&&t.totalMs>a?t.totalMs-a:t.totalMs;return n.outputTokens!==void 0&&r>0&&(n.tokensPerSecond=n.outputTokens/(r/1e3)),n}function Oi(e){let t=e/1e3;return t<10?`${t.toFixed(1)} s`:`${Math.round(t)} s`}function Yo(e,t){let n=e<10?e.toFixed(1):String(Math.round(e));return`${t?"~":""}${n} tok/s`}function Vo(e){let t=Oi(e.totalMs);return e.tokensPerSecond===void 0?t:`${t} \xB7 ${Yo(e.tokensPerSecond,e.approximate)}`}function Jo(e){let t=[];return e.firstTokenMs!==void 0&&t.push(`First token after ${Oi(e.firstTokenMs)}`),t.push(`Total ${Oi(e.totalMs)}`),e.outputTokens!==void 0&&t.push(e.approximate?`About ${e.outputTokens.toLocaleString("en-US")} output tokens (estimated from the text)`:`${e.outputTokens.toLocaleString("en-US")} output tokens`),e.inputTokens!==void 0&&t.push(`${e.inputTokens.toLocaleString("en-US")} input tokens`),e.tokensPerSecond!==void 0&&t.push(Yo(e.tokensPerSecond,e.approximate)),t.join(`
|
|
3
|
-
`)}var Un={unreachable:{title:"Engine not reachable",message:"The AI engine did not answer. Check that the server is running and the base URL is right.",action:"openSettings"},auth:{title:"Key rejected",message:"The engine refused the API key. Store a new key in AI settings, or check the environment variable.",action:"openSettings"},modelNotFound:{title:"Model not found",message:"The engine does not serve this model. Refresh models or pick another one in AI settings.",action:"openSettings"},modelLoadFailed:{title:"Model didn't load",message:"The engine couldn't load the model. Load it in the engine's app, or choose another model.",action:"chooseModel"},contextOverflow:{title:"Too much text",message:"The text is longer than the model's context window. Try a shorter selection.",action:"shortenSelection"},rateLimited:{title:"Rate limited",message:"The engine is busy or the rate limit was reached. Wait a moment and try again.",action:"retry"},cloudBlocked:{title:"Cloud engines are off",message:"This task is routed to a cloud engine, and Allow cloud is off in AI settings.",action:"openSettings"},consentDenied:{title:"Not allowed in this workspace",message:"Sending text to this cloud engine was not allowed for this workspace.",action:"openSettings"},cancelled:{title:"Cancelled",message:"The request was cancelled."},badOutput:{title:"No usable answer",message:"The model did not return a usable answer. Try again or pick another model.",action:"retry"},unknown:{title:"Something went wrong",message:"The AI request failed.",action:"retry"}};function qn(e){return e.empty?e.thinking?{title:"No room left to answer",message:"The model used its whole length budget thinking and sent no answer. Lower Thinking, or Retry.",action:"retry"}:{title:"No room left to answer",message:"The model reached its length limit before it sent any text. Retry.",action:"retry"}:e.thinking?{title:"Answer cut off",message:"The answer was cut off at the length limit. Lower Thinking, or Retry, for a full answer.",action:"retry"}:{title:"Answer cut off",message:"The answer was cut off at the length limit.",action:"retry"}}function cs(e){return typeof e=="string"&&Pr.includes(e)}function ds(e){return typeof e=="object"&&e!==null&&cs(e.code)&&typeof e.message=="string"}function Et(e,t){return{code:e,message:t??Un[e].message}}function It(e){return ds(e)?{code:e.code,message:e.message,...typeof e.engineId=="string"?{engineId:e.engineId}:{}}:typeof e=="object"&&e!==null&&e.name==="AbortError"?Et("cancelled"):{code:"unknown",message:e instanceof Error?e.message:typeof e=="string"?e:Un.unknown.message}}var us={unreachable:e=>`${e} did not answer. Check that the server is running and the base URL is right.`,auth:e=>`${e} refused the API key. Store a new key, or check the environment variable.`,modelNotFound:e=>`${e} does not serve this model. Refresh its models or pick another one.`,modelLoadFailed:(e,t)=>`${e} couldn't load ${t}. Load it in ${e}, or choose another model.`};function Gn(e,t={}){let n=Un[e]??Un.unknown,i=t.engine?us[e]:void 0;return!i||!t.engine?n:{...n,message:i(t.engine,t.model||"the model"),action:n.action==="chooseModel"?"chooseModel":"openEngine"}}var Kn=["low","medium","high"],Mo={off:"Off",low:"Low",medium:"Medium",high:"High"};function gn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Lt(e){switch(e){case"openai":case"openai-compatible":case"ollama":return["off",...Kn].map(t=>({level:t,label:Mo[t]}));case"lmstudio":return[{level:"off",label:"Off"},{level:"medium",label:"On"}];case"anthropic":return Kn.map(t=>({level:t,label:Mo[t]}));default:return[]}}function Hi(e,t){let n=Lt(e);return!t||n.length===0?null:n.some(i=>i.level===t)?t:t==="off"?n[0].level:(n.find(i=>i.level!=="off")??n[0]).level}var fs=new Set(["rewrite","translate","title","frontmatter"]);function ps(e){return e&&fs.has(e)?"off":null}function Xo(e,t,n,i,o={}){if(t)return{level:t,auto:!1};if(n)return{level:null,auto:!1};if(e==="openai"&&o.modelId!==void 0&&!qr(o.modelId,"openai"))return{level:null,auto:!1};let a=Hi(e,ps(i));return{level:a,auto:a!==null}}function ms(e,t,n={}){if(!Lt(e).some(i=>i.level===t))return{};switch(e){case"anthropic":return{thinking:{type:"adaptive"},output_config:{effort:t}};case"openai-compatible":return t==="off"&&n.local?{chat_template_kwargs:{enable_thinking:!1}}:{reasoning_effort:t==="off"?"none":t};default:return{reasoning_effort:t==="off"?"none":t}}}function Wn(e,t){if(!t||Lt(e).length===0)return null;if(e==="anthropic"){let o=gn(t.output_config)?t.output_config.effort:void 0;return typeof o=="string"&&Kn.includes(o)?o:null}if((gn(t.chat_template_kwargs)?t.chat_template_kwargs:void 0)?.enable_thinking===!1)return"off";let i=t.reasoning_effort;return i==="none"?"off":typeof i!="string"||!Kn.includes(i)?null:e==="lmstudio"?"medium":i}function hs(e,t){let n={...t},i=(o,a)=>{let r=n[o];if(!gn(r))return;let u={...r};delete u[a],Object.keys(u).length===0?delete n[o]:n[o]=u};return e==="anthropic"?(delete n.thinking,i("output_config","effort")):(delete n.reasoning_effort,i("chat_template_kwargs","enable_thinking")),n}function Zo(e,t){let n={...e};for(let[i,o]of Object.entries(t)){let a=n[i];n[i]=gn(a)&&gn(o)?Zo(a,o):o}return n}function Yn(e,t,n,i={}){let o=hs(e,t??{}),a=n?Zo(o,ms(e,n,i)):o;return Object.keys(a).length>0?a:void 0}var Qo={off:0,low:2048,medium:4096,high:8192},gs=Qo.medium,bs=12288;function ea(e,t,n={}){let i=t?Qo[t]:gs;if(i<=0)return e;let o=bs;return n.contextTokens&&n.contextTokens>0&&(o=Math.min(o,n.contextTokens-Math.ceil(n.promptTokens??0)-256)),Math.max(e,Math.min(e+i,o))}var ji=[{id:"general",label:"General audience",instruction:"Rewrite it for a general audience: plain words, short sentences, jargon explained or avoided. Keep the meaning and every fact, name and link."},{id:"expert",label:"Expert",instruction:"Rewrite it for expert readers: precise terminology, no basic explanations, dense and direct. Keep the meaning and every fact, name and link."},{id:"plain",label:"Plain language",instruction:"Rewrite it in plain language: everyday words, short sentences, active voice, no jargon or idioms. Keep the meaning and every fact, name and link."},{id:"grade8",label:"8th grade",instruction:"Rewrite it at an 8th grade reading level: common words, short sentences, one idea at a time. Keep the meaning and every fact, name and link."},{id:"esl",label:"English learners (ESL)",instruction:"Rewrite it for readers who are learning English: simple vocabulary, short direct sentences, literal wording, no idioms or phrasal verbs. Keep the meaning and every fact, name and link."}];function dn(e){return ji.find(t=>t.id===e)}var Bi=[{id:"shorter",label:"Shorter",instruction:"Make it shorter and tighter. Keep the meaning and every fact, name and link; cut repetition and filler.",group:"length",output:"replace"},{id:"longer",label:"Longer",title:"Longer: the same points, said at more length",instruction:"Make it longer: add detail, examples or explanation that fit the surrounding text. Do not invent facts, numbers, names or links.",group:"length",output:"replace"},{id:"expand",label:"Add detail",title:"Add detail (facts and examples)",instruction:"Expand it: develop each point with the reasoning, detail or an example that the surrounding text supports, so it reads as a fuller passage. Do not invent facts, numbers, names or links.",group:"length",output:"replace"},{id:"simpler",label:"Simpler",instruction:"Make it simpler: shorter sentences, everyday words, one idea at a time. Keep the meaning and every fact, name and link.",group:"tone",output:"replace"},{id:"fixFlow",label:"Fix flow",instruction:"Fix the flow: correct grammar, spelling and punctuation, and smooth awkward sentences and transitions. Keep the length, meaning and tone close to the original.",group:"tone",output:"replace"},{id:"formal",label:"More formal",instruction:"Make the tone more formal and professional: no contractions or slang, precise wording. Keep the meaning, every fact and the length close to the original.",group:"tone",output:"replace"},{id:"casual",label:"More casual",instruction:"Make the tone more casual and conversational: contractions and everyday phrasing. Keep the meaning, every fact and the length close to the original.",group:"tone",output:"replace"},{id:"readingLevel",label:"Reading level\u2026",instruction:"{audience}",group:"audience",output:"replace",param:"audience"},{id:"translate",label:"Translate\u2026",instruction:"Translate the passage into {language}.",group:"translate",output:"replace",param:"language"},{id:"explain",label:"Explain",instruction:"Explain what the passage says and means in plain words, as a short note for the reader. Do not repeat the passage.",group:"explain",output:"readOnly"},{id:"custom",label:"Custom prompt\u2026",instruction:"",group:"custom",output:"replace"}];function Ht(e){return Bi.find(t=>t.id===e)}var Vn=1600,vs=1e3,ks=60,Ii=["You are a writing assistant inside a Markdown editor. You rewrite the passage the user selected, following one instruction.","","Rules:","- Reply with the rewritten passage only. No preamble, no explanation, no quotation marks and no code fence around it.","- Keep it Markdown, and keep the structure of the passage: headings stay headings, list items stay list items with the same markers and indentation, tables stay tables, quotes stay quotes. A passage that is part of a sentence stays part of a sentence.","- Keep every link and image with its exact URL, inline code and code blocks character for character, and inline formatting (bold, italic, strikethrough, ==highlight==, footnote references, [[wikilinks]], #tags, math) on the words it belongs to.","- Write in the language and voice of the passage.","- The text before and after the passage is context only. Do not repeat it and do not continue it.","- If the instruction asks for anything other than a version of the passage, still reply with a version of the passage only."].join(`
|
|
4
|
-
`),ys=['This is a translation. The "write in the language and voice of the passage" rule above does not apply: write in the language named in the instruction.',"- Translate prose only: paragraph text, list item text, table cell text, heading text, image alt text and link text.","- Keep verbatim, untranslated: the Markdown syntax itself (heading marks, list markers and indentation, table pipes and separator rows, quote marks), link and image URLs, inline code and fenced code blocks (including their language tag), [[wikilinks]], #tags, math, footnote markers such as [^1], HTML tags and frontmatter keys.","- Keep the line structure: the same number of lines, blocks and list items in the same order, with blank lines where the passage has them.","- Keep names of people, products and places as they are unless they have a well established translation."].join(`
|
|
5
|
-
`),ws='The instruction asks for an explanation of the passage, not a version of it: the "version of the passage" rules above do not apply. Reply with the explanation only, as Markdown prose, and do not repeat the passage.',As="The passage is a whole document body (its frontmatter has been removed and is handled elsewhere). Translate all of it, from the first line to the last.";function Qt(e,t){return e.split(`</${t}>`).join(`<\\/${t}>`)}function Fn(e,t,n=Vn){if(e.length<=n)return e;if(t==="before"){let a=e.slice(e.length-n),r=a.indexOf(`
|
|
6
|
-
`);return r>=0&&r<n/2?a.slice(r+1):a}let i=e.slice(0,n),o=i.lastIndexOf(`
|
|
7
|
-
`);return o>n/2?i.slice(0,o):i}function xs(e){return(e??"").replace(/[<>\r\n]+/g," ").replace(/\s+/g," ").trim().slice(0,ks)}function Es(e){let t=Ht("fixFlow")?.instruction??"";if(e.variant==="custom")return(e.instruction??"").trim().slice(0,vs)||t;let n=Ht(e.variant);if(!n)return"";if(n.param==="language"){let i=xs(e.params?.language);return i?n.instruction.replace("{language}",()=>i):t}if(n.param==="audience"){let i=e.params?.audience?dn(e.params.audience):void 0;return i?n.instruction.replace("{audience}",()=>i.instruction):t}return n.instruction}function Ts(e,t="selection"){return e==="translate"?[Ii,ys,...t==="document"?[As]:[]].join(`
|
|
8
|
-
|
|
9
|
-
`):e==="explain"?`${Ii}
|
|
10
|
-
|
|
11
|
-
${ws}`:Ii}function ta(e){let t=Es(e),n=e.scope==="document"&&e.variant==="translate"?"document":"selection",i=n==="document"?"":Fn(e.before??"","before").trimEnd(),o=n==="document"?"":Fn(e.after??"","after").trimStart(),a=[];return a.push(e.variant==="custom"?`Instruction (from the user): <instruction>
|
|
12
|
-
${Qt(t,"instruction")}
|
|
13
|
-
</instruction>`:`Instruction: ${t}`),i&&a.push(`Text before the passage (context only, do not rewrite it):
|
|
14
|
-
<before>
|
|
15
|
-
${Qt(i,"before")}
|
|
16
|
-
</before>`),a.push(`${e.variant==="explain"?"Passage to explain":"Passage to rewrite"}:
|
|
17
|
-
<passage>
|
|
18
|
-
${Qt(e.selection,"passage")}
|
|
19
|
-
</passage>`),o&&a.push(`Text after the passage (context only, do not rewrite it):
|
|
20
|
-
<after>
|
|
21
|
-
${Qt(o,"after")}
|
|
22
|
-
</after>`),a.push(e.variant==="explain"?"Reply with the explanation only.":"Reply with the rewritten passage only."),[{role:"system",content:Ts(e.variant,n)},{role:"user",content:a.join(`
|
|
23
|
-
|
|
24
|
-
`)}]}var na=600,Ss={longer:3,expand:3,translate:3,custom:3,simpler:1.8,formal:1.8,casual:1.8};function ia(e,t){if(t==="explain")return na;let n=Math.ceil(e.length/3.5),i=Ss[t]??1.6;return Math.max(256,Math.min(4096,Math.ceil(n*i)+64))}function qt(e){let t=e.replace(/<think>[\s\S]*?<\/think>\s*/g,""),n=t.indexOf("<think>");return n>=0&&(t=t.slice(0,n)),t.replace(/^\s*<passage>\s*\n?/,"").replace(/\n?\s*<\/passage>\s*$/,"")}function oa(e,t){let n=qt(e).trim(),i=/^```(?:markdown|md|text)?[ \t]*\n([\s\S]*?)\n```$/i.exec(n);i&&!t.trimStart().startsWith("```")&&(n=i[1].trim());let o=/^(["“])([\s\S]*)(["”])$/.exec(n);if(o&&!/^\s*["“]/.test(t)&&!o[2].includes(o[1])&&(n=o[2].trim()),!n)return"";let a=/^\s*/.exec(t)?.[0]??"",r=/\s*$/.exec(t)?.[0]??"";return a+n+r}var $s=["You are a writing assistant inside a Markdown editor. The user selected a passage and wants it explained.","","Rules:","- Reply with the explanation only, as short Markdown prose (a few sentences or a short paragraph, a brief list only when the passage has several distinct points). No preamble, no heading, and no code fence around the whole reply.","- Explain what the passage says and means, and define any term a reader may not know. Do not repeat or quote the passage back and do not rewrite it.","- Do not invent facts. If the passage or its context is not enough to explain something, say so in one sentence.","- Write in the language of the passage.","- The text before and after the passage and the document title are context only. Do not explain them."].join(`
|
|
25
|
-
`);function aa(e){let t=Fn(e.before??"","before").trimEnd(),n=Fn(e.after??"","after").trimStart(),i=(e.title??"").replace(/\s+/g," ").trim().slice(0,200),o=[`Instruction: ${Ht("explain")?.instruction??""}`];return i&&o.push(`Document title (context only): ${i}`),t&&o.push(`Text before the passage (context only, do not explain it):
|
|
26
|
-
<before>
|
|
27
|
-
${Qt(t,"before")}
|
|
28
|
-
</before>`),o.push(`Passage to explain:
|
|
29
|
-
<passage>
|
|
30
|
-
${Qt(e.selection,"passage")}
|
|
31
|
-
</passage>`),n&&o.push(`Text after the passage (context only, do not explain it):
|
|
32
|
-
<after>
|
|
33
|
-
${Qt(n,"after")}
|
|
34
|
-
</after>`),o.push("Reply with the explanation only."),[{role:"system",content:$s},{role:"user",content:o.join(`
|
|
35
|
-
|
|
36
|
-
`)}]}function ra(){return na}var Is=/^ {0,3}(`{3,}|~{3,})/,Ls=/^ {0,3}(#{1,6})(?:[ \t]|$)/,Ms=/^[ \t]*(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$)/,Cs=/^[ \t]*\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/,_s=/^ {0,3}\[\^[^\]\s]+\]:/,sa=String.raw`<?((?:[^()\s<>]|\([^()\s]*\))+)>?`,la=String.raw`\[(?:[^\[\]]|\[[^\[\]]*\])*\]`,Co=new RegExp(String.raw`!${la}\(\s*${sa}(?:\s+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\s*\)`,"g"),Os=new RegExp(String.raw`(?<!!)${la}\(\s*${sa}(?:\s+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\s*\)`,"g"),Ns=/^ {0,3}\[(?!\^)[^\]]+\]:[ \t]*<?(\S+?)>?(?:[ \t]+["'(].*)?$/gm,Rs=/<([a-z][a-z0-9+.-]*:[^\s<>]+)>/gi,Ds=/\[\[[^\]\n]+\]\]/g,Ps=/\[\^[^\]\s]+\]/g;function Us(e){let t=[],n=0,i=null;for(let o of e.split(/\r?\n/)){if(i){let r=/^ {0,3}(`{3,}|~{3,})[ \t]*$/.exec(o);r&&r[1][0]===i.char&&r[1].length>=i.length&&(i=null);continue}let a=Is.exec(o);if(a&&!(a[1][0]==="`"&&o.slice(a[0].length).includes("`"))){i={char:a[1][0],length:a[1].length},n++;continue}t.push(o)}return{prose:t,fenced:n}}function Ks(e){let t=0;return{text:e.replace(/(`+)(?!`)([\s\S]*?[^`])\1(?!`)/g,()=>(t++,"")),count:t}}function Fs(e){let t=0;for(let n=1;n<e.length;n++){let i=e[n-1];if(!e[n].includes("|")||!e[n].includes("-")||!Cs.test(e[n])||!i.includes("|"))continue;t++;let o=n+1;for(;o<e.length&&e[o].trim()!==""&&e[o].includes("|");)t++,o++;n=o-1}return t}function Rn(e,t){let n=[];for(let i of t.matchAll(e))n.push(i[1]);return n}function _o(e){let{prose:t,fenced:n}=Us(e),i=[0,0,0,0,0,0],o=0;for(let k of t){let h=Ls.exec(k);h?i[h[1].length-1]++:Ms.test(k)&&o++}let a=Fs(t),r=Ks(t.map(k=>k.replace(_s,"")).join(`
|
|
37
|
-
`)),u=Rn(Co,r.text),d=r.text.replace(Co,""),b=[...Rn(Os,d),...Rn(Ns,d),...Rn(Rs,d)];return{headings:i,fencedCodeBlocks:n,inlineCodeSpans:r.count,links:b,images:u,listItems:o,tableRows:a,wikilinks:(r.text.match(Ds)??[]).length,footnoteReferences:(r.text.match(Ps)??[]).length}}function ca(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function da(e,t,n,i){return`${ca(e,n,i)} in the original, ${t} in the result`}function Oo(e,t){let n=new Map;for(let o of t)n.set(o,(n.get(o)??0)+1);let i=[];for(let o of e){let a=n.get(o)??0;a>0?n.set(o,a-1):i.push(o)}return i}var Li=3;function Mi(e){let t=e.slice(0,Li).join(", ");return e.length>Li?`${t} and ${e.length-Li} more`:t}function No(e,t,n){let i=Oo(t,n),o=Oo(n,t);if(t.length===n.length&&!i.length)return null;let a=`${e}s`,r;return t.length!==n.length?(r=da(t.length,n.length,e,a),i.length&&(r+=` (missing: ${Mi(i)})`)):r=`${ca(t.length,e,a)} point somewhere else in the result (missing: ${Mi(i)}; unexpected: ${Mi(o)})`,{kind:e,original:t.length,result:n.length,message:r}}function ua(e,t){let n=_o(e),i=_o(t),o=[],a=(r,u,d,b,k)=>{u!==d&&o.push({kind:r,original:u,result:d,message:da(u,d,b,k)})};n.headings.forEach((r,u)=>a("heading",r,i.headings[u],`level ${u+1} heading`)),a("fencedCodeBlock",n.fencedCodeBlocks,i.fencedCodeBlocks,"fenced code block"),a("inlineCode",n.inlineCodeSpans,i.inlineCodeSpans,"inline code span");for(let r of[No("link",n.links,i.links),No("image",n.images,i.images)])r&&o.push(r);return a("listItem",n.listItems,i.listItems,"list item"),a("tableRow",n.tableRows,i.tableRows,"table row"),a("wikilink",n.wikilinks,i.wikilinks,"wikilink"),a("footnote",n.footnoteReferences,i.footnoteReferences,"footnote reference"),{ok:o.length===0,mismatches:o,messages:o.map(r=>r.message)}}function fa(e){let t=e.replace(/<think>[\s\S]*?<\/think>/gi,""),n=t.search(/<think>/i);return n>=0&&(t=t.slice(0,n)),t.trim()}function Hs(e){let t=[],n=/```[A-Za-z0-9_-]*[ \t]*\r?\n([\s\S]*?)(?:\r?\n```|$)/g,i;for(;(i=n.exec(e))!==null;)t.push(i[1]),i[0].length===0&&n.lastIndex++;return t}function js(e,t){let n=[],i=null;for(let o=t;o<e.length;o++){let a=e[o];if(i){a==="\\"?o++:a===i&&(i=null);continue}if(a==='"'||a==="'")i=a;else if(a==="{")n.push("}");else if(a==="[")n.push("]");else if(a==="}"||a==="]"){if(n.pop()!==a)return null;if(n.length===0)return{end:o+1}}}return null}function Bs(e){let t="",n=0,i="";for(;n<e.length;){let o=e[n];if(o==='"'||o==="'"){let a=o,r="";for(n++;n<e.length&&e[n]!==a;){let u=e[n];if(u==="\\"&&n+1<e.length){let d=e[n+1];r+=d==="'"?"'":u+d,n+=2;continue}u===`
|
|
38
|
-
`?r+="\\n":u==="\r"?r+="\\r":u===" "?r+="\\t":u==='"'?r+='\\"':r+=u,n++}n++,t+=`"${r}"`,i='"';continue}if(o===","){let a=n+1;for(;a<e.length&&/\s/.test(e[a]);)a++;if(e[a]==="}"||e[a]==="]"){n++;continue}}if((i==="{"||i===",")&&/[A-Za-z_$]/.test(o)){let a=/^([A-Za-z_$][\w$-]*)(\s*):/.exec(e.slice(n));if(a){t+=`"${a[1]}"${a[2]}:`,n+=a[0].length,i=":";continue}}t+=o,/\s/.test(o)||(i=o),n++}return t}function Ro(e){try{return{ok:!0,value:JSON.parse(e)}}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}}var zs=24;function pa(e){let t=fa(typeof e=="string"?e:"");if(!t)return{ok:!1,error:"The reply was empty."};let n="",i=!1,o=!1;for(let a of[...Hs(t),t]){let r=0,u=0;for(;u<zs;){let d=a.slice(r).search(/[{[]/);if(d<0)break;let b=r+d;i=!0,u++;let k=js(a,b);if(!k){o=!0;break}let h=a.slice(b,k.end),w=Ro(h);if(w.ok)return w;let E=Ro(Bs(h));if(E.ok)return E;!n&&!w.ok&&(n=w.error),r=k.end}}return i?n?{ok:!1,error:`Invalid JSON: ${n}`}:{ok:!1,error:o?"The JSON was cut off before it closed.":"No JSON object found in the reply."}:{ok:!1,error:"No JSON object found in the reply."}}var qs=4e3;function ma(e,t){return[{role:"assistant",content:fa(e).slice(0,qs)||"(empty reply)"},{role:"user",content:`Your previous reply was not valid JSON (${t}). Reply with the JSON object only.`}]}function ha(e){return`Reply with a JSON object only, in exactly this shape and with no other text, no code fence and no comments: ${typeof e=="string"?e:JSON.stringify(e)}`}var yn=3.5,Gs=/^ {0,3}(`{3,}|~{3,})/,ga=/^ {0,3}(#{1,6})[ \t]+(.*?)[ \t]*$/,Ws=/^---[ \t]*\r?\n[\s\S]*?\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/;function ba(e){let t=Ws.exec(e);return t?t[0].length:0}function va(e,t){let n=[],i=t;for(;i<e.length;){let o=e.indexOf(`
|
|
39
|
-
`,i),a=o<0?e.length:o;n.push({text:e.slice(i,a).replace(/\r$/,""),start:i}),i=o<0?e.length:o+1}return n}function ka(e){let t=[],n=null;for(let i of e){if(!n){let a=Gs.exec(i.text);a?(n={char:a[1][0],len:a[1].length},t.push(!0)):t.push(!1);continue}t.push(!0);let o=/^ {0,3}(`{3,}|~{3,})[ \t]*$/.exec(i.text);o&&o[1][0]===n.char&&o[1].length>=n.len&&(n=null)}return t}function ya(e){let t=va(e,ba(e)),n=ka(t),i=[];return t.forEach((o,a)=>{if(n[a])return;let r=ga.exec(o.text);if(!r)return;let u=r[2].replace(/[ \t]+#+$/,"").trim();u&&i.push({level:r[1].length,text:u})}),i}function Ys(e,t,n){let i=[0],o=t.length>0?t[0].start:e.length;return t.forEach((a,r)=>{n[r]||!ga.test(a.text)||e.slice(o,a.start).trim()!==""&&i.push(a.start)}),i}function Vs(e,t){let n=[];for(let i=1;i<e.length;i++)e[i].text.trim()!==""&&e[i-1].text.trim()===""&&!t[i-1]&&n.push(e[i].start);return n}function wn(e,t){let n=e.length,i=t.contextTokens-t.outputTokens-t.reserveTokens,o=Math.max(0,Math.floor(i*yn)),a=ba(e),r=va(e,a),u=ka(r),d=Ys(e,r,u),b=d.length;if(n<=o||n===0)return{text:e,coverage:1,truncated:!1,sectionsIncluded:b,sectionsTotal:b};let k=0,h=0;for(let E=1;E<d.length&&!(d[E]>o);E++)k=d[E],h=E;if(k===0){let E=d.length>1?d[1]:n,S=Vs(r,u).filter($=>$<E);k=S.length>0?S[0]:E;for(let $ of S){if($>o)break;k=Math.max(k,$)}h=1}return k>=n?{text:e,coverage:1,truncated:!1,sectionsIncluded:b,sectionsTotal:b}:{text:e.slice(0,k).trimEnd(),coverage:Math.min(.999,Math.max(.001,k/n)),truncated:!0,sectionsIncluded:h,sectionsTotal:b}}var Js=1200,wa=["Reply with Markdown only. No preamble, no closing remarks, no code fence around the answer and no title line.","Use only what the document says. Do not invent facts, names or numbers.","Write in the language of the document."],Xs=["You are a writing assistant inside a Markdown editor. You write a short TL;DR of the document the user gives you.","","Rules:",'- Write 3 to 6 bullet points, one line each, most important first. Each bullet is a list item starting with "- ".','- Plain wording that someone who has not read the document can follow. No heading, no "Summary" label.',...wa.map(e=>`- ${e}`)].join(`
|
|
40
|
-
`),Zs=["You are a writing assistant inside a Markdown editor. You write an outline of the document the user gives you.","","Rules:",'- Reply with a nested Markdown list: top-level items are the main sections, indented items (two spaces per level, "- " markers) are their subsections or key points. At most three levels.',"- If the document has headings, follow them in order and keep their wording. If it has none, propose short headings that fit its parts.","- Each item is a few words, not a sentence. No heading syntax (#) and no numbering.",...wa.map(e=>`- ${e}`)].join(`
|
|
41
|
-
`);function Qs(e,t){return e.split(`</${t}>`).join(`<\\/${t}>`)}function Jn(e){return Math.max(1,Math.min(99,Math.round(e*100)))}function Aa(e){let t=[];return e.kind==="tldr"?t.push(e.document.length<Js?"This document is short: write one paragraph of two to four sentences instead of bullet points.":"Write the TL;DR as 3 to 6 bullet points."):t.push("Write the outline."),e.coverage<1&&t.push(`Only the first ${Jn(e.coverage)}% of the document is included below; it was cut to fit. Cover only what is shown and do not guess at the rest.`),t.push(`Document:
|
|
42
|
-
<document>
|
|
43
|
-
${Qs(e.document,"document")}
|
|
44
|
-
</document>`),t.push(e.kind==="tldr"?"Reply with the TL;DR only.":"Reply with the outline list only."),[{role:"system",content:e.kind==="tldr"?Xs:Zs},{role:"user",content:t.join(`
|
|
45
|
-
|
|
46
|
-
`)}]}function zi(e,t){let n=Math.ceil(t/3.5);return e==="tldr"?Math.max(256,Math.min(700,Math.ceil(n*.2)+128)):Math.max(384,Math.min(1200,Math.ceil(n*.3)+160))}function xa(e){return qt(e)}function Hn(e,t){let n=qt(e).trim(),i=n.split(`
|
|
47
|
-
`),o=()=>{if(i.length>1&&/^(here('s| is| are)|sure|certainly|of course)\b[^\n]*:\s*$/i.test(i[0].trim()))for(i.shift();i.length>0&&i[0].trim()==="";)i.shift()};o(),n=i.join(`
|
|
48
|
-
`).trim();let a=/^```(?:markdown|md|text)?[ \t]*\n([\s\S]*?)\n```$/i.exec(n);return a&&(n=a[1].trim()),i=n.split(`
|
|
49
|
-
`),o(),t==="tldr"&&i.length>1&&/^(?:#{1,6}\s*)?(?:\*\*|__)?\s*(?:summary|tl;?dr)\s*:?\s*(?:\*\*|__)?\s*:?\s*$/i.test(i[0].trim())&&i.shift(),i.join(`
|
|
50
|
-
`).trim()}function Ea(e){let t=e.trimEnd();return!t||(/[.!?;:)\]"'”’`*_]$/.test(t)||(t=t.replace(/\S+$/,"").trimEnd()),t=t.replace(/(^|\n)[ \t]*(?:[-*+]|\d+[.)]|>|#{1,6})?[ \t]*$/,"").trimEnd(),!t)?"":/[\p{L}\p{N}]$/u.test(t)?`${t}\u2026`:`${t} \u2026`}function Ta(e,t,n=!1){return n?Ea(Hn(e,t)):Hn(e,t)}function Sa(e,t,n=1,i=!1){let o=i?Ea(Hn(e,t)):Hn(e,t);if(!o)return"";let a=n<1?`Covers the first ${Jn(n)}% of the document.`:"";return t==="outline"?a?`${o}
|
|
51
|
-
|
|
52
|
-
${a}`:o:["[!NOTE]",["**Summary**","",o,...a?["",a]:[]].join(`
|
|
53
|
-
`)].join(`
|
|
54
|
-
`).split(`
|
|
55
|
-
`).map(u=>u?`> ${u}`:">").join(`
|
|
56
|
-
`)}var Do=120,el=60,tl=["You are a writing assistant inside a Markdown editor. You suggest titles for the document the user gives you.","","Rules:","- Each title is specific to this document, in plain wording, in Title Case or sentence case to match the document, under 80 characters, with no trailing period and no quotation marks.","- Make the titles different from each other in angle (descriptive, benefit-led, short).","- Write in the language of the document.","- Reply with the JSON object only."].join(`
|
|
57
|
-
`);function Po(e,t){return e.split(`</${t}>`).join(`<\\/${t}>`)}function Xn(e,t=el){let n=e.slice(0,t).map(i=>`${" ".repeat(Math.max(0,i.level-1))}- ${i.text}`);return e.length>t&&n.push(`(${e.length-t} more headings)`),n.join(`
|
|
58
|
-
`)}function $a(e){let t=Math.max(1,Math.min(8,e.count??3)),n=Array.from({length:t},(a,r)=>`title ${r+1}`),i=[`Suggest ${t} titles for this document.`],o=(e.existingTitle??"").trim();return o&&i.push(`The current title is "${o.replace(/"/g,"'")}". Do not repeat it.`),e.outline.length>0&&i.push(`Headings of the whole document:
|
|
59
|
-
<headings>
|
|
60
|
-
${Po(Xn(e.outline),"headings")}
|
|
61
|
-
</headings>`),i.push(`Document:
|
|
62
|
-
<document>
|
|
63
|
-
${Po(e.document,"document")}
|
|
64
|
-
</document>`),i.push(ha({titles:n})),[{role:"system",content:tl},{role:"user",content:i.join(`
|
|
65
|
-
|
|
66
|
-
`)}]}function qi(e=3){return 128+48*Math.max(1,e)}function nl(e){let t=e.replace(/\s+/g," ").trim();return t=t.replace(/^["“'‘]+|["”'’]+$/g,"").trim(),t=t.replace(/^#{1,6}\s+/,"").replace(/[.。]+$/,"").trim(),t.length>Do&&(t=t.slice(0,Do).trimEnd()),t}var Uo=(e,t)=>e.toLowerCase()===t.toLowerCase();function Gi(e,t){let n=pa(e);if(!n.ok)return{ok:!1,error:n.error};let i=n.value,o;if(Array.isArray(i))o=i;else if(i&&typeof i=="object"){let u=i;o=u.titles??(typeof u.title=="string"?[u.title]:void 0)}if(!Array.isArray(o))return{ok:!1,error:'The JSON has no "titles" array.'};let a=(t??"").trim(),r=[];for(let u of o){if(typeof u!="string")continue;let d=nl(u);!d||a&&Uo(d,a)||r.some(b=>Uo(b,d))||r.push(d)}return r.length===0?{ok:!1,error:'The "titles" array has no usable title.'}:{ok:!0,titles:r}}var il=8,ol=200,al=120,Ia=80,rl=["You are a writing assistant inside a Markdown editor. You suggest frontmatter properties for the document the user gives you: a title, a description and tags.","","Rules:","- title: specific to the document, under 80 characters, no trailing period and no quotation marks.","- description: one or two plain sentences under 160 characters that say what the document is about. No marketing wording.",'- tags: 3 to 6 short topic tags, lowercase, words joined by hyphens, no "#" and no spaces. Nested tags use a slash, like project/active.',"- Prefer tags from the list of existing tags when they fit. Add a new tag only when none of them does.","- Do not repeat a tag the document already has.","- Write in the language of the document.","- Reply with the JSON object only."].join(`
|
|
67
|
-
`);function Dn(e,t){return e.split(`</${t}>`).join(`<\\/${t}>`)}function Ni(e){return Array.isArray(e)?e.join(", "):e}function sl(e){let t=[];for(let n of e){if(!/^tags?$/i.test(n.key))continue;let i=Array.isArray(n.value)?n.value:n.value.split(/[,\s]+/);for(let o of i){let a=On(o);a&&!t.includes(a)&&t.push(a)}}return t}function ll(e){let t=["Suggest a title, a description and tags for this document."],n=e.existing.filter(o=>Ni(o.value).trim()!=="");n.length>0&&t.push(`Properties it already has:
|
|
68
|
-
<properties>
|
|
69
|
-
${Dn(n.map(o=>`${o.key}: ${Ni(o.value)}`).join(`
|
|
70
|
-
`),"properties")}
|
|
71
|
-
</properties>`);let i=e.vocabulary.slice(0,Ia);return i.length>0&&t.push(`Prefer these existing tags when they fit:
|
|
72
|
-
<tags>
|
|
73
|
-
${Dn(i.join(", "),"tags")}
|
|
74
|
-
</tags>`),e.outline.length>0&&t.push(`Headings of the whole document:
|
|
75
|
-
<headings>
|
|
76
|
-
${Dn(Xn(e.outline),"headings")}
|
|
77
|
-
</headings>`),t.push(`Document:
|
|
78
|
-
<document>
|
|
79
|
-
${Dn(e.document,"document")}
|
|
80
|
-
</document>`),t.push(ha({title:"the title",description:"one or two sentences",tags:["tag-one","tag-two","tag-three"]})),[{role:"system",content:rl},{role:"user",content:t.join(`
|
|
81
|
-
|
|
82
|
-
`)}]}function cl(){return 384}function Ko(e){let t=On(e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9_/#-]/g,""));if(!t)return null;let i=t.split("/").map(o=>o.replace(/^-+|-+$/g,"")).filter(Boolean).join("/");return/[a-z]/.test(i)?i:null}function Pn(e,t){if(typeof e!="string")return"";let n=e.replace(/\s+/g," ").trim().replace(/^["“]+|["”]+$/g,"").trim();return n.length>t?n.slice(0,t).trimEnd():n}function Fo(e,t){let n=e.find(i=>i.key.toLowerCase()===t);return n?Ni(n.value).trim():""}function dl(e,t,n){let i=pa(e);if(!i.ok)return{ok:!1,error:i.error};let o=i.value;if(!o||typeof o!="object"||Array.isArray(o))return{ok:!1,error:"The JSON is not an object."};let a=o,r={tags:[]},u=Pn(a.title,al).replace(/[.。]+$/,"");u&&u.toLowerCase()!==Fo(t,"title").toLowerCase()&&(r.title=u);let d=Pn(a.description,ol);d&&d.toLowerCase()!==Fo(t,"description").toLowerCase()&&(r.description=d);let b=Array.isArray(a.tags)?a.tags:typeof a.tags=="string"?a.tags.split(/[,\n]+/):[],k=new Set(sl(t)),h=new Set;for(let S of n){let $=On(S);$&&h.add($)}let w=new Set;for(let S of b){if(typeof S!="string")continue;let $=Ko(S);if(!(!$||k.has($)||w.has($))&&(w.add($),r.tags.push({tag:$,known:h.has($)}),r.tags.length>=il))break}return Pn(a.title,1)!==""||Pn(a.description,1)!==""||b.some(S=>typeof S=="string"&&Ko(S))?{ok:!0,suggestions:r}:{ok:!1,error:"The JSON has no usable title, description or tags."}}var Mt={leaves:"Text you ask about is sent over the internet to the provider and processed on their servers.",terms:"API traffic is covered by the provider's API terms, which differ from its consumer apps. Whether it is retained or used for training is set by those terms and may change; read them before you decide.",local:"A local engine keeps everything on this machine or your network.",keys:"Your API key stays in this app's secure storage on this machine."},Gt={leaves:"Text you ask about goes through VS Code to GitHub\u2019s Copilot service and is processed on GitHub\u2019s servers, under your Copilot plan.",terms:"Whether it is retained or used for training is set by your plan\u2019s terms, which differ between individual and business plans and may change; read them before you decide.",local:Mt.local,permission:"VS Code also asks for its own permission the first time MikeDown uses Copilot."};function tn(e){return e?"MikeDown asks before a cloud engine's first request in each workspace or folder.":"Once allowed, this app sends requests to cloud engines without asking again."}var ul={selection:"the selected text and the paragraph before and after it",document:"the whole document, up to what fits the model",documentAndTags:"the document, its frontmatter and the tag names used in this workspace"},fl="the text you ask the AI about";function Zn(e,t){let n=t??(e?jo(e)?.sends:void 0);return n?ul[n]:fl}function pl(e,t=ft){let n=e?.trim().toLowerCase();if(n)return t.find(i=>i.family==="cloud"&&i.policy&&Xt(i.baseUrl)===n)?.policy}function An(e,t=ft){return e.kind&&zt(e.kind)?t.find(n=>n.family==="host"&&n.kind===e.kind&&n.policy)?.policy:pl(Xt(e.baseUrl),t)}var ml={"vscode-lm":"GitHub Copilot"};function Qn(e){return(e.kind?ml[e.kind]:void 0)??Xt(e.baseUrl)??e.baseUrl}var La="No cloud engine has been allowed here.",hl={allow:"Allowed",never:"Not allowed",deny:"Not allowed until restart"};function Ma(e,t){let n=e.scope==="folder"?"this folder":"this workspace";return`${t} \xB7 ${n} \xB7 ${hl[e.answer]??"Not allowed"}`}var ei=1024**3,gl=.94,bl=16,vl=32,kl=8;function Ci(e){return`${Math.max(1,Math.round(e/ei))} GB`}function hn(e,t){return typeof e=="number"&&e>=t*ei*gl}function Ca(e){return e.gpu?.vendor==="nvidia"?e.gpu.vramBytes:void 0}function _a(e){return e?e.appleSilicon&&hn(e.totalMemoryBytes,bl)||hn(e.totalMemoryBytes,vl)?!0:hn(Ca(e),kl):!1}function Wi(e){if(e.appleSilicon)return e.totalMemoryBytes;let t=Ca(e);return typeof t=="number"&&t>0?t:e.totalMemoryBytes}function Oa(e){return hn(e,24)?hn(e,48)?"large":"medium":"small"}var yl={small:"Models up to about 8B parameters run well.",medium:"Models up to about 30B parameters run well.",large:"Larger models work, well beyond 30B parameters."};function Na(e){return e?yl[Oa(Wi(e))]:""}function Ri(e){if(e.appleSilicon)return`Apple Silicon, ${Ci(e.totalMemoryBytes)}`;let t=[`${Ci(e.totalMemoryBytes)} of memory`];if(e.gpu&&e.gpu.vendor!=="apple"){let n=e.gpu.name?.trim()||(e.gpu.vendor==="nvidia"?"NVIDIA GPU":e.gpu.vendor==="amd"?"AMD GPU":"GPU");t.push(e.gpu.vramBytes?`${n} (${Ci(e.gpu.vramBytes)})`:n)}return t.join(", ")}var wl="This machine is on the small side for local models; cloud is the easier path.",Al="A rough guess from memory alone; the graphics card was not checked.";function xl(e,t){if(!e)return"";if(!t)return wl;let n=!e.appleSilicon&&!e.gpu?` ${Al}`:"";return`Local is an option on this machine: ${Ri(e)}. ${Na(e)}${n}`}function El(e){return e.ok&&e.models!==0}function Ho(e){return ft.find(t=>t.id===e)?.name??e}function Tl(e){return e===void 0?"":` with ${e} ${e===1?"model":"models"}`}function Yi(e){let t=e.hardware,n=_a(t),i={localCapable:n,localHint:Na(t),hardwareLine:xl(t,n)},o=[],a=e.running.map((u,d)=>({probe:u,index:d})).filter(({probe:u})=>El(u)).sort((u,d)=>(d.probe.models??0)-(u.probe.models??0)||u.index-d.index);if(a.length>0){let u=a[0].probe;return o.push(`${Ho(u.presetId)} is running on this machine${Tl(u.models)}.`),{path:"runningLocal",...i,running:u,reasons:o}}let r=e.running.filter(u=>u.ok&&u.models===0);return o.push(r.length>0?`${r.map(u=>Ho(u.presetId)).join(" and ")} answered but lists no models.`:"No local model server is running."),e.vscodeLm?.available&&e.vscodeLm.models>0?(o.push(`GitHub Copilot offers ${e.vscodeLm.models} ${e.vscodeLm.models===1?"model":"models"} in VS Code.`),{path:"vscodeLm",...i,reasons:o}):(e.vscodeLm&&o.push("GitHub Copilot offers no model in VS Code."),t?o.push(n?`${Ri(t)} can run local models.`:`${Ri(t)} is below the threshold for local models.`):o.push("The host did not report this machine\u2019s hardware."),{path:"cloud",...i,reasons:o})}function Ra(e){let t=e?.find(n=>n.kind==="vscode-lm");return{available:!!t?.ok&&t.models>0,models:t?.ok?t.models:0}}function Sl(e){let t=e.toLowerCase(),n=/(?:^|[^a-z0-9.])(\d+)x(\d+(?:\.\d+)?)b(?![a-z0-9])/.exec(t);if(n)return Number(n[1])*Number(n[2]);let i=/(?:^|[^a-z0-9.])(\d+(?:\.\d+)?)([bm])(?![a-z0-9])/.exec(t);if(!i)return null;let o=Number(i[1]);return!Number.isFinite(o)||o<=0?null:i[2]==="m"?o/1e3:o}var $l=1.75;function Il(e){let t=Wi(e),n=t/ei;switch(Oa(t)){case"small":return _a(e)?8:Math.min(8,n/2);case"medium":return 30;case"large":return n*1.1}}function Da(e,t,n){if(!t)return;if(typeof n=="number"&&n>0)return Cl(n,t);let i=Sl(e);if(i===null)return;let o=Il(t);return i<=o?"fits":i<=o*$l?"tight":"too large"}var Ll=.6,Ml=.8;function Cl(e,t){let n=Wi(t);return e<=n*Ll?"fits":e<=n*Ml?"tight":"too large"}function Pa(e){let t=e/ei;return`${t>=10?Math.round(t):Math.round(t*10)/10} GB`}function _l(e){let t=/(?:^|[^a-z0-9.])a(\d+(?:\.\d+)?)b(?![a-z0-9])/.exec(e.toLowerCase()),n=t?Number(t[1]):NaN;return Number.isFinite(n)&&n>0?n:null}function Ol(e,t){let n=_l(e);return n!==null||t?{activeBillions:n}:null}function Vi(e,t,n){return n!=="fits"?null:Ol(e,t)}function Ua(e){return e.find(t=>t.chat&&!t.missing&&t.loaded)?.id??null}var Ja={"openai-compatible":"OpenAI-compatible",lmstudio:"LM Studio",ollama:"Ollama",anthropic:"Anthropic",openai:"OpenAI","vscode-lm":"GitHub Copilot (VS Code)"};function Tn(e){return xt(e)?Ja[e]:`Unknown (${e})`}var Nl=[{flag:"chat",label:"chat",title:"Chat and instruct completions"},{flag:"vision",label:"vision",title:"Image inputs"},{flag:"json",label:"json",title:"JSON mode or reliable structured output"},{flag:"tools",label:"tools",title:"Function calling"},{flag:"fim",label:"fim",title:"Fill-in-the-middle (inline suggestions)"},{flag:"embed",label:"embed",title:"Embeddings"}],Rl={chat:"chat",stream:"streaming",vision:"vision",json:"JSON output",tools:"tools",fim:"fill-in-the-middle",embed:"embeddings",contextTokens:"a large enough context window"};function Ue(e){return e.name.trim()||e.id}function pt(e){return e.label?.trim()||e.id}function oi(e){return e.trim().replace(/^[a-z][a-z0-9+.-]*:\/\//i,"").split(/[/?#]/,1)[0]||e.trim()}function Ka(e){let t=e??en;return t>=1024*1024&&t%(1024*1024)===0?`${t/(1024*1024)}M`:t>=1e6&&t%1e6===0?`${t/1e6}M`:t>=1024&&t%1024===0?`${t/1024}k`:t>=1e3&&t%1e3===0?`${t/1e3}k`:String(t)}function xn(e){return JSON.parse(JSON.stringify(e))}function Dl(e,t){let n=new Set(t),i=zn(e);for(;n.has(i);)i=zn(e);return i}function io(e,t){let n={id:Dl(e.name,t),name:e.name,kind:e.kind,baseUrl:e.baseUrl,enabled:!0,locality:"auto",discovery:"auto",models:[]};return e.apiKeyEnv&&(n.apiKeyEnv=e.apiKeyEnv),e.apiKeyFile&&(n.apiKeyFile={...e.apiKeyFile}),n}function eo(e){let t={local:[],cloud:[],host:[]};for(let n of e)t[n.family].push(n);return t}function Pt(e,t){return{...e,engines:e.engines.map(n=>n.id===t.id?t:n)}}function Pl(e,t){let n={};for(let[o,a]of Object.entries(e.routing.tasks))a.engineId!==t&&(n[o]=a);let i=e.routing.default?.engineId===t?null:e.routing.default;return{...e,engines:e.engines.filter(o=>o.id!==t),routing:{...e.routing,default:i,tasks:n}}}function Ul(e,t,n){let i=a=>!!a&&a.engineId===t&&a.modelId===n,o={};for(let[a,r]of Object.entries(e.routing.tasks))i(r)||(o[a]=r);return{...e,routing:{...e.routing,default:i(e.routing.default)?null:e.routing.default,tasks:o}}}function Xa(e,t){return{...e,models:e.models.map(n=>n.id===t.id?t:n)}}function Kl(e,t){return{...e,capabilities:{...e.capabilities,[t]:!e.capabilities[t]},capabilitiesSource:"user"}}function Fl(e,t){return{...e,capabilities:{...e.capabilities,contextTokens:t},capabilitiesSource:"user"}}function Hl(e){let t=e.trim().replace(/[_,\s]/g,"");if(!t)return{ok:!0,value:null};let n=/^(\d+(?:\.\d+)?)([kKmM]?)$/.exec(t);if(!n)return{ok:!1,error:"Enter a number of tokens, such as 32768 or 32k."};let i=n[2]===""?1:n[2].toLowerCase()==="k"?1024:1024*1024,o=Math.round(Number(n[1])*i);return!Number.isFinite(o)||o<=0?{ok:!1,error:"Enter a number of tokens, such as 32768 or 32k."}:{ok:!0,value:o}}function Fa(e,t){let n=t.trim();if(!n)return{ok:!1,error:"Enter the model id the server knows it by."};if(e.models.some(o=>o.id===n))return{ok:!1,error:`${n} is already in the list.`};let i={id:n,enabled:!0,capabilities:Bn(n,xt(e.kind)?e.kind:void 0).capabilities,capabilitiesSource:"heuristic",manual:!0};return{ok:!0,engine:{...e,models:[...e.models,i]},model:i}}function Za(e){let t=[...new Set(e.split(/[\s,]+/).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0))];if(t.length===0)return{ok:!0,value:[...xo]};let n=[];for(let i of t)(/^\d/.test(i)?/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?$/.test(i)&&i.split("/")[0].split(".").every(r=>Number(r)<=255)&&Number(i.split("/")[1]??0)<=32:/^\.?[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/.test(i))||n.push(i);return n.length>0?{ok:!1,error:`Not a network or host name: ${n.join(", ")}. Use an IPv4 range like 10.0.98.0/24 or a suffix like .ts.net.`}:{ok:!0,value:t}}function jl(e){let t=e.trim();if(!t)return{ok:!0,value:void 0};let n;try{n=JSON.parse(t)}catch(i){let o=i instanceof Error?i.message.replace(/^JSON\.parse:\s*/,""):"";return{ok:!1,error:o?`Not valid JSON: ${o}`:"Not valid JSON."}}return typeof n!="object"||n===null||Array.isArray(n)?{ok:!1,error:'Must be a JSON object, such as { "reasoning_effort": "low" }.'}:{ok:!0,value:n}}function Bl(e){return e&&Object.keys(e).length>0?JSON.stringify(e,null,2):""}function zl(e,t){let n=t.models.filter(o=>!o.missing).map(o=>{let a={id:o.id,capabilities:o.capabilities,source:o.source==="endpoint"?"endpoint":"heuristic"};return o.label!==void 0&&(a.label=o.label),o.loaded!==void 0&&(a.loaded=o.loaded),a}),i=xt(e.kind)?e.kind:void 0;return{...e,models:Bo(e.models,n,i)}}function Ji(e,t){return!e||!t?e!==t:e.kind!==t.kind||e.baseUrl!==t.baseUrl||(e.apiKeyEnv??"")!==(t.apiKeyEnv??"")||e.locality!==t.locality||e.enabled!==t.enabled||e.discovery!==t.discovery}function Ha(e,t){let n=vn(e),i=vn(t),o={};for(let[a,r]of Object.entries(i))JSON.stringify(r)!==JSON.stringify(n[a])&&(o[a]=r);return o}function nn(e,t){return{locality:Zt(e,t),detected:Ai(e.baseUrl,t),mismatch:_n(e,t)}}function En(e){let t=e.trim();if(!t)return"Enter the server address, such as http://127.0.0.1:8000/v1.";if(!/^https?:\/\//i.test(t))return"Start the address with http:// or https://.";try{if(!new URL(t).hostname)return"The address has no host name."}catch{return"This is not a valid address."}return""}function ql(e,t,n){let i=[];xt(e.kind)||i.push({level:"warning",code:"unsupportedKind",text:`This version does not support the engine kind "${String(e.kind)}". It is kept, but never used.`});let o=zt(e.kind),a=o?"":En(e.baseUrl);a&&i.push({level:"warning",code:"badUrl",text:a});let r=nn(e,t.localNetworks);return!o&&r.locality==="cloud"&&!n&&!e.apiKeyEnv?.trim()&&!e.apiKeyFile?.path.trim()&&i.push({level:"warning",code:"noKey",text:"No API key. Store one, or name the environment variable or key file that holds it."}),r.mismatch&&i.push({level:"warning",code:"localityMismatch",text:r.locality==="cloud"?"Pinned to cloud, but the address looks local.":"Pinned to local, but the address looks like a cloud server. Text sent to it leaves this network."}),r.locality==="cloud"&&!t.allowCloud&&i.push({level:"info",code:"cloudBlocked",text:"Blocked by Allow cloud."}),i}var Qa={requires:{chat:!0}};function Gl(e){let t=ln(e);return t?{requires:t.requires,requiresAny:t.requiresAny}:{requires:{}}}function Wl(e){return`lacks ${e.map(t=>Rl[t]??t).join(", ")}`}function er(e,t,n){let i=new Map(t.map(a=>[a.engineId,a])),o=[];for(let a of e.engines){let r=i.get(a.id),u=Zt(a,e.localNetworks)==="local";for(let d of a.models){let b={engineId:a.id,modelId:d.id,engineName:Ue(a),modelName:pt(d),isLocal:u,selectable:!1},k=jn(d.capabilities,n.requires,n.requiresAny);xt(a.kind)?a.enabled?d.enabled?d.missing||r?.models.find(h=>h.id===d.id)?.missing?b.note="no longer listed":k.length>0?b.note=Wl(k):(b.selectable=!0,!u&&!e.allowCloud?b.note="blocked by Allow cloud":r?.ok===!1&&(b.note="failed its last test")):b.note="model is off":b.note="engine is off":b.note="engine kind not supported",o.push(b)}}return o}function ti(e){return e?`${e.engineId}\0${e.modelId}`:""}function ja(e){let t=e.indexOf("\0");return t<=0||t===e.length-1?null:{engineId:e.slice(0,t),modelId:e.slice(t+1)}}function Kt(e,t){let n=e.engines.find(o=>o.id===t.engineId),i=n?.models.find(o=>o.id===t.modelId);return`${n?Ue(n):t.engineId} \xB7 ${i?pt(i):t.modelId}`}var Ba="\0aiSettingsPreview";function oo(e,t,n){let i={...e,enabled:!0,features:{...e.features,[Ba]:{enabled:!0}}};return kn(i,t,{},{feature:Ba,task:n})}function ai(e,t,n){let i=e.routing.tasks[n];if(!i&&!e.routing.default)return null;let o=oo(e,t,n);if("unusable"in o){if(!i)return{level:"info",text:`No model can serve this yet. ${o.reason}`};let a=e.routing.fallback==="none"?"Fallback is off, so this task will not run.":"No fallback can serve it either.";return{level:"warning",text:`${o.reason} ${a}`}}return o.viaFallback?{level:i?"warning":"info",text:`${o.reason??"The route is unavailable."} Falls back to ${Kt(e,o)}.`}:null}function Yl(e){let t=new Set(jt.map(n=>n.id));return Object.keys(e.routing.tasks).filter(n=>!t.has(n))}function ci(e,t,n){let i=er(e,t,Qa).find(o=>o.engineId===n&&o.selectable);return i?{engineId:i.engineId,modelId:i.modelId}:null}function Vl(e){let t=e.routing.default,n=t&&e.engines.find(o=>o.id===t.engineId);if(!t||!n||!n.enabled||!xt(n.kind))return!1;let i=n.models.find(o=>o.id===t.modelId);return!!i&&i.enabled&&!i.missing&&i.capabilities.chat}function za(e){try{let t=new URL(e.trim()),n=t.hostname==="localhost"||t.hostname==="[::1]"?"127.0.0.1":t.hostname;return`${t.protocol}//${n}:${t.port||(t.protocol==="https:"?"443":"80")}${t.pathname.replace(/\/+$/,"")}`.toLowerCase()}catch{return e.trim().toLowerCase().replace(/\/+$/,"")}}function ao(e,t,n=ft){let i=e.map((a,r)=>{let u=n.find(k=>k.id===a.presetId),d=u&&t.find(k=>k.kind===u.kind&&za(k.baseUrl)===za(a.baseUrl)&&(Bt(k,n)?.id??u.id)===u.id),b={presetId:a.presetId,baseUrl:a.baseUrl,running:a.ok,alreadyAdded:!!d};return d&&(b.engineId=d.id),a.ok&&a.models!==void 0&&(b.models=a.models),a.latencyMs!==void 0&&(b.latencyMs=a.latencyMs),{card:b,index:r}}),o=a=>a.alreadyAdded?2:a.running?0:1;return i.sort((a,r)=>o(a.card)-o(r.card)||(a.card.running&&r.card.running?(r.card.models??0)-(a.card.models??0):0)||a.index-r.index).map(a=>a.card)}function Jl(e,t){if(t.isLocal)return"";let n=t.engineId?e.engines.find(a=>a.id===t.engineId):void 0,i=n?Qn(n):null,o=t.feature||t.sends?Zn(t.feature,t.sends):"";return i?o?` It sent text to ${i}: ${o}.`:` It sent text to ${i}.`:o?` It sent ${o}.`:""}function Xl(e,t){let n=t.engineId?e.engines.find(o=>o.id===t.engineId):void 0,i=n?.models.find(o=>o.id===t.modelId);return{engine:t.engineName||(n?Ue(n):t.engineId??""),model:i?pt(i):t.modelId,warn:n?_n(n,e.localNetworks):!1}}var ni="Click for AI settings.",Zl="Click to choose a model.";function tr(){return ln("rewrite")?"rewrite":jt[0].id}function Ql(e,t,n){let i=o=>{let a=oo(o,n,tr());return"unusable"in a?null:`${a.engineId}
|
|
83
|
-
${a.modelId}`};return i(e)!==i(t)}function ec(e){let{settings:t,statuses:n,tier:i,served:o,viaFallback:a}=e;if(!t.enabled)return t.engines.length===0?null:{text:"AI: off",tone:"off",title:`AI features are turned off. ${ni}`,fallback:!1,warn:!1};if(o){let h=o.isLocal?"local":"cloud",w=Xl(t,o),S=[`AI: ${h}`,w.engine,w.model].filter(Boolean).join(" \xB7 ")+(a?" (fallback)":""),$=`Last request served by ${w.engine} \xB7 ${w.model}, ${o.isLocal?"on this network":"a cloud engine"}${a?", through the fallback route":""}.${Jl(t,o)}${w.warn?" Its pinned locality disagrees with its address.":""} ${ni}`;return{text:S,tone:h,title:$,fallback:a,warn:w.warn}}if(i===1)return{text:"AI: on",tone:"on",title:`AI features are on. ${ni}`,fallback:!1,warn:!1};let r=oo(t,n,tr());if("unusable"in r)return{text:"AI: no model chosen",tone:"none",title:`${r.reason} ${Zl}`,fallback:!1,warn:!1};let u=t.engines.find(h=>h.id===r.engineId),d=r.isLocal?"local":"cloud",b=Kt(t,r),k=u?_n(u,t.localNetworks):!1;return{text:`AI: ${d} \xB7 ${b}${r.viaFallback?" (fallback)":""}`,tone:d,title:`Requests go to ${b}${r.isLocal?"":", a cloud engine"}. Nothing has been sent yet. ${ni}`,fallback:r.viaFallback,warn:k}}function tc(e,t){let n=Bt(e);if(n)return{id:n.id,name:n.name,family:n.family,needsKey:n.needsKey,keyHint:n.keyHint,...n.keyUrl?{keyUrl:n.keyUrl}:{},...n.pricingUrl?{pricingUrl:n.pricingUrl}:{},popular:n.popular??[]};let i=Zt(e,t)==="local"?"local":"cloud";return{id:"custom",name:Ue(e),family:i,needsKey:i==="cloud",keyHint:i==="cloud"?"The API key from the provider\u2019s console.":"Leave blank if the server has no auth.",popular:[]}}function nr(e){if(e.family==="host")return{express:["name","models","defaultModel","enabled"],advanced:["discovery","modelsTable"]};if(e.family==="cloud")return{express:["name","key","models","defaultModel","thinking","enabled"],advanced:["kind","baseUrl","locality","keyEnv","keyFile","discovery","modelsTable"]};let t=e.needsKey||e.id==="custom";return{express:t?["name","baseUrl","key","models","defaultModel","thinking","enabled"]:["name","baseUrl","models","defaultModel","thinking","enabled"],advanced:t?["kind","locality","keyEnv","keyFile","discovery","modelsTable"]:["kind","locality","key","keyEnv","keyFile","discovery","modelsTable"]}}function nc(e,t={}){let{express:n,advanced:i}=nr(e),o=n.filter(a=>a==="key"||a==="baseUrl"||a==="models");return t.key&&e.family==="local"&&!o.includes("key")?(o.splice(o.indexOf("models"),0,"key"),{express:o,advanced:i.filter(a=>a!=="key"&&a!=="modelsTable")}):{express:o,advanced:i.filter(a=>a!=="modelsTable")}}function ic(e,t,n=""){let i=new Map((t?.models??[]).map(u=>[u.id,!!u.loaded])),o=n.trim().toLowerCase(),a=e.models.map((u,d)=>({id:u.id,name:pt(u),hasLabel:!!u.label?.trim()&&u.label.trim()!==u.id,enabled:u.enabled,loaded:i.get(u.id)??!1,missing:!!(u.missing||t?.models.find(b=>b.id===u.id)?.missing),manual:!!u.manual,chat:!!u.capabilities.chat,usable:!!(u.capabilities.chat||u.capabilities.embed),index:d})).filter(u=>!o||u.id.toLowerCase().includes(o)||u.name.toLowerCase().includes(o)),r=u=>u.missing?2:e.kind==="lmstudio"&&u.loaded?0:1;return a.sort((u,d)=>r(u)-r(d)||u.index-d.index),a.map(({index:u,...d})=>d)}function oc(e){let t=e.models.filter(i=>!i.missing),n=t.filter(i=>i.enabled).length;return t.length===0?"No models yet":`${t.length} ${t.length===1?"model":"models"}, ${n} picked`}function ro(e,t,n,i=[]){let o=zl(e,t),a=new Set(e.models.map(h=>h.id)),r=new Set(i),u=new Set(t.models.filter(h=>h.loaded&&!h.missing).map(h=>h.id)),d=h=>r.has(h.id)||n==="local"&&u.has(h.id)&&(h.capabilities.chat||h.capabilities.embed),b=o.models.map(h=>a.has(h.id)?h:{...h,enabled:d(h)}),k=e.models.some(h=>h.enabled&&!h.missing);if(n==="local"&&!k){let h=b.filter(S=>!a.has(S.id)).map(S=>({id:S.id,chat:S.capabilities.chat,missing:S.missing,loaded:u.has(S.id)})),w=Ua(h),E=b.find(S=>S.id===w);E&&(b=[{...E,enabled:!0},...b.filter(S=>S!==E)])}return{...o,models:b}}function qa(e){let t=[],n=0;for(let i of e.match(/\d+/g)??[])i.length>=6?n=Math.max(n,Number(i)):t.push(Number(i));return{version:t,date:n}}function ac(e,t,n){if(n){let a=n.test(e)?0:1,r=n.test(t)?0:1;if(a!==r)return a-r}let i=qa(e),o=qa(t);for(let a=0;a<Math.max(i.version.length,o.version.length);a++){let r=(o.version[a]??0)-(i.version[a]??0);if(r!==0)return r}return i.date!==o.date?i.date===0?-1:o.date===0?1:o.date-i.date:e.length-t.length||e.localeCompare(t)}function ir(e,t){let n=[];for(let i of e.popular??[]){let o=t.filter(a=>!a.missing&&i.match.test(a.id)&&!i.exclude?.test(a.id)&&!n.includes(a));o.length!==0&&n.push(o.slice().sort((a,r)=>ac(a.id,r.id,i.prefer))[0])}return n}function rc(e,t){let n=a=>!a.missing&&a.capabilities.chat,i=ir(e,t).find(n);if(i)return i.id;let o=t.filter(n);return o.length===1?o[0].id:null}function or(e){return e.find(t=>!t.missing&&t.capabilities.chat)?.id??null}function ii(e,t){let n=e.engines.find(o=>o.id===t);if(!n)return null;let i=e.routing.default;return i?.engineId===t&&n.models.some(o=>o.id===i.modelId)?i.modelId:n.models.find(o=>o.enabled&&!o.missing)?.id??null}function un(e,t,n){let i=e.engines.find(d=>d.id===t),o=i?.models.find(d=>d.id===n);if(!i||!o||!o.capabilities.chat)return e;let a=[{...o,enabled:!0},...i.models.filter(d=>d.id!==n)],r=Pt(e,{...i,models:a}),u=e.routing.default;return!u||u.engineId===t?{...r,routing:{...r.routing,default:{...u??{},engineId:t,modelId:n}}}:r}function sc(e){if(!e.enabled)return!1;let t=e.models.filter(n=>!n.missing&&n.capabilities.chat);return t.length>0&&!t.some(n=>n.enabled)}function lc(e){return e.engines.find(sc)??null}function to(e,t,n,i){let o=e.engines.find(b=>b.id===t),a=o?.models.find(b=>b.id===n);if(!o||!a)return e;let r=Pt(e,Xa(o,{...a,enabled:i})),u=r.routing.default;if(i&&!u&&a.capabilities.chat&&o.enabled)return{...r,routing:{...r.routing,default:{engineId:t,modelId:n}}};if(i||u?.engineId!==t||u.modelId!==n)return r;let d=r.engines.find(b=>b.id===t)?.models.find(b=>b.enabled&&!b.missing);return{...r,routing:{...r.routing,default:d?{...u,modelId:d.id}:null}}}function Ga(e,t,n,i){let o=un(e,t,n);return o===e||!i||i===n?o:to(o,t,i,!1)}function cc(e,t,n,i){let o={...e},a=Yn(t,e.requestOverrides,n,{local:i});return a?o.requestOverrides=a:delete o.requestOverrides,o}var dc=600;function no(e,t,n){return e==="cloud"?`key:${t.trim()}`:`url:${n.trim()}`}var Ct=(e,t="")=>({fetch:!1,delayMs:0,storeKey:!1,cancelPending:e,fingerprint:t});function uc(e,t){let n=t.family==="host"||!En(t.baseUrl),i=t.key.trim(),o=no("cloud",i,t.baseUrl),a=no("local",i,t.baseUrl),r=t.family==="cloud"?o:a;return t.event==="save"?Ct(!1):t.event==="manual"||t.event==="retry"?!n||t.discovery==="manual"?Ct(!1):{fetch:!0,delayMs:0,storeKey:t.family==="cloud"?!!i:!1,cancelPending:!0,fingerprint:r}:t.discovery==="manual"||!n?Ct(t.event==="key"&&!i):t.family==="cloud"?t.event==="open"?t.hasKey&&!t.modelCount&&t.neverProbed?{fetch:!0,delayMs:0,storeKey:!1,cancelPending:!0,fingerprint:o}:Ct(!1):t.event!=="key"?Ct(!1):i?(t.fetchedFor??e?.fetchedFor)===o||e&&e.key.trim()===i&&e.event==="key"?Ct(!1,o):{fetch:!0,delayMs:dc,storeKey:!0,cancelPending:!0,fingerprint:o}:Ct(!0):t.event==="open"?t.neverProbed?{fetch:!0,delayMs:0,storeKey:!1,cancelPending:!0,fingerprint:a}:Ct(!1,a):t.event==="url"?(t.fetchedFor??e?.fetchedFor)===a?Ct(!1,a):{fetch:!0,delayMs:0,storeKey:!1,cancelPending:!0,fingerprint:a}:Ct(!1)}var fc=/\bHTTP 40[13]\b|unauthori[sz]ed|forbidden|invalid[^.]*\bkey|incorrect[^.]*\bkey|api key|authentication/i,pc=/could not reach|no answer|timed out|ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|fetch failed|connection refused|network/i;function mc(e,t){if(e&&e!=="unknown")return e;let n=t??"";return fc.test(n)?"auth":pc.test(n)?"unreachable":"unknown"}function Xi(e){if(e.ok)return e.listed===0?{kind:"empty",text:"Server is up but no models are loaded.",retry:!0}:null;let t=mc(e.code,e.message);if(e.family==="host")return{kind:t==="auth"?"auth":"other",text:e.message||`Could not list ${e.presetName}\u2019s models.`,retry:!0};if(t==="auth")return{kind:"auth",text:`Key rejected by ${oi(e.baseUrl)}.`,focus:"key",retry:!0};if(t==="unreachable"&&e.family==="local"){let n=e.presetName.startsWith("Custom")?"the server":e.presetName;return{kind:"unreachable",text:`Nothing answered at ${e.baseUrl.trim()}. Is ${n} running?`,retry:!0}}return t==="unreachable"?{kind:"unreachable",text:`Could not reach ${oi(e.baseUrl)}.`,retry:!0}:{kind:"other",text:e.message?`Could not fetch models: ${e.message}`:"Could not fetch models.",retry:!0}}var hc=4e3;function di(e){let{ai:t}=e,n=xn(e.settings),i=xn(e.settings),o=e.statusMap??new Map(e.statuses.map(w=>[w.engineId,w])),a=e.keyOverride??new Map,r=new Set,u=new Set,d=new Set,b=w=>i.engines.find(E=>E.id===w),k=()=>[...o.values()];return{ai:t,tier:To(t),statuses:o,options:e,get draft(){return i},set draft(w){i=w},get original(){return n},getEngine:b,statusList:k,hasKey:w=>a.get(w)??o.get(w)?.hasKey??!1,keySource:w=>{let E=a.get(w);return E===void 0?o.get(w)?.keySource:E?"stored":void 0},async setKey(w,E){if(!b(w)||!t.setSecret)return"This app cannot store keys.";try{return await t.setSecret(w,E),a.set(w,E!==null),E!==null?u.add(w):u.delete(w),null}catch(S){return`The key could not be ${E!==null?"stored":"cleared"}: ${It(S).message}`}},async ensureSaved(w){let E=b(w);!E||!e.saveNow||Ji(e.getHostSettings().engines.find(S=>S.id===w),E)&&(e.saveNow({"ai.engines":vn(i)["ai.engines"]}),await e.waitForSettings(S=>!Ji(S.engines.find($=>$.id===w),E),hc))},savesFirst(w){let E=b(w);return!!e.saveNow&&!!E&&Ji(e.getHostSettings().engines.find(S=>S.id===w),E)},addEngine(w){i={...i,engines:[...i.engines,w]},d.add(w.id)},deleteEngine(w){b(w)&&(i=Pl(i,w),r.add(w))},updateEngine(w,E){let S=b(w);S&&(i=Pt(i,{...S,...E}))},collect(){let w=Ha(n,i);return e.pendingEnable&&i.enabled&&Object.keys(w).length>0&&(w["ai.enabled"]=!0),w},dirty(){return Object.keys(Ha(n,i)).length>0?!0:e.getHostSettings().engines.some(w=>d.has(w.id)&&!b(w.id))},async refreshStatuses(){if(!t.listEngines)return!1;try{let w=await t.listEngines();for(let E of w)o.set(E.engineId,E);return e.onStatuses(k()),!0}catch{return!1}},fork(){return{...e,settings:xn(i),statuses:k(),keyOverride:a,statusMap:o}},absorb(w,E){i=xn(w),n=ar(n,w,E)},discard(){let w=e.getHostSettings();if(e.saveNow&&w.engines.some(S=>d.has(S.id))){let S={...w,engines:w.engines.filter($=>!d.has($.id))};e.saveNow({"ai.engines":vn(S)["ai.engines"]})}if(!t.setSecret)return;let E=new Set(w.engines.filter(S=>!d.has(S.id)).map(S=>S.id));for(let S of u)E.has(S)||t.setSecret(S,null).catch(()=>{})},commit(){if(t.setSecret)for(let w of r)b(w)||t.setSecret(w,null).catch(()=>{});return xn(i)}}}function ar(e,t,n){let i={...e},o=t;for(let a of Object.keys(n)){let r=a.replace(/^ai\./,"");r in o&&(i[r]=JSON.parse(JSON.stringify(o[r])))}return i}var fn="Looking for local AI servers\u2026",ri="No local AI server found. Start LM Studio, Ollama or oMLX, then choose Look again.",gc=1500;async function so(e,t){if(!e.detectLocalServers||t?.aborted)return null;let n=new AbortController,i=()=>n.abort();t?.addEventListener("abort",i,{once:!0});let o,a=new Promise(r=>{o=setTimeout(()=>{n.abort(),r(null)},qo+gc)});try{let r=await Promise.race([e.detectLocalServers(Go(),n.signal),a]);return!r||n.signal.aborted||!Array.isArray(r)?null:r}catch{return null}finally{clearTimeout(o),t?.removeEventListener("abort",i)}}function bc(e,t){return ao(e,t).find(n=>n.running&&!n.alreadyAdded)??null}async function vc(e,t){let n=ft.find(h=>h.id===t&&h.family==="local");if(!n)throw new Error("That local server is not one MikeDown knows.");let{ai:i}=e;if(!i.discoverModels)throw new Error("This app cannot fetch models.");let o=di(e),a=io(n,o.draft.engines.map(h=>h.id));o.addEngine(a);let r=h=>{throw o.discard(),new Error(h)};await o.ensureSaved(a.id);let u;try{u=await i.discoverModels(a.id)}catch(h){return r(`Could not fetch the models from ${n.name}: ${It(h).message}`)}if(u.ok===!1)return r(`Could not fetch the models from ${n.name}${u.error?`: ${u.error}`:"."}`);o.statuses.set(a.id,u),e.onStatuses(o.statusList()),o.draft=Pt(o.draft,ro(a,u,"local"));let d=ci(o.draft,o.statusList(),a.id);if(!d){let h=o.getEngine(a.id)?.models.some(w=>!w.missing&&w.capabilities.chat);return r(h?`${n.name} has no model loaded. Load one there, or choose Set up to pick one.`:`${n.name} has no chat model loaded or downloaded yet.`)}o.draft={...o.draft,routing:{...o.draft.routing,default:d}};let b={...o.collect(),"ai.enabled":!0},k={...o.commit(),enabled:!0};return{patch:b,settings:k,engineId:a.id,route:d}}var kc=3e3,Wa=new WeakMap,rr=new WeakMap;function Ya(e){return!!(e.detectLocalServers||e.hardwareInfo||e.detectHostEngines)}var sr=new WeakMap;function lr(e){let t=Wa.get(e);return t||(t=e.hardwareInfo?e.hardwareInfo().then(n=>n&&typeof n=="object"?n:null,()=>null):Promise.resolve(null),t=t.then(n=>(n&&sr.set(e,n),n)),Wa.set(e,t)),t}function yc(e){return sr.get(e)??null}async function cr(e,t){if(!e.detectHostEngines||t?.aborted)return null;let n,i=new Promise(o=>{n=setTimeout(()=>o(null),kc)});try{let o=await Promise.race([e.detectHostEngines(),i]);return o&&Array.isArray(o)&&!t?.aborted?Ra(o):null}catch{return null}finally{clearTimeout(n)}}function wc(e){return rr.get(e)??null}function Ac(){return{recommendation:Yi({running:[],hardware:null}),probes:null,hardware:null,vscodeLm:null}}async function dr(e,t,n){let[i,o,a]=await Promise.all([n!==void 0?Promise.resolve(n):so(e,t),lr(e),cr(e,t)]),u={recommendation:Yi({running:i??[],hardware:o,...a?{vscodeLm:a}:{}}),probes:i,hardware:o,vscodeLm:a};return t?.aborted||rr.set(e,u),u}var it=(e,t=14,n="")=>`<svg width="${t}" height="${t}" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"${n}>${e}</svg>`,xe={starOff:it('<path d="M8 1.9l1.86 3.77 4.16.6-3.01 2.94.71 4.14L8 11.4l-3.72 1.95.71-4.14L1.98 6.27l4.16-.6z"/>'),starOn:it('<path d="M8 1.9l1.86 3.77 4.16.6-3.01 2.94.71 4.14L8 11.4l-3.72 1.95.71-4.14L1.98 6.27l4.16-.6z" fill="currentColor"/>'),trash:it('<path d="M2.5 4h11M6.5 4V2.5h3V4M4 4l.7 9.5h6.6L12 4M6.6 6.5v4.5M9.4 6.5v4.5"/>'),chevron:it('<path d="M6 4l4 4-4 4"/>',12),plus:it('<path d="M8 3v10M3 8h10"/>',12),local:it('<path d="M2.5 7.5L8 3l5.5 4.5M4 6.5V13h8V6.5"/>',11),cloud:it('<path d="M4.5 12.5h7a2.75 2.75 0 0 0 .3-5.48A4 4 0 0 0 4.1 7.6 2.5 2.5 0 0 0 4.5 12.5z"/>',11),warn:it('<path d="M8 2.2l6.2 11H1.8z"/><path d="M8 6.5v3M8 11.4v.1"/>',12),info:it('<circle cx="8" cy="8" r="6"/><path d="M8 7.2v3.8M8 5v.1"/>',12),check:it('<path d="M3.5 8.5l3 3 6-7"/>',12),braces:it('<path d="M6 2.5c-1.5 0-2 .7-2 2v1.6c0 .9-.5 1.4-1.4 1.9.9.5 1.4 1 1.4 1.9v1.6c0 1.3.5 2 2 2M10 2.5c1.5 0 2 .7 2 2v1.6c0 .9.5 1.4 1.4 1.9-.9.5-1.4 1-1.4 1.9v1.6c0 1.3-.5 2-2 2"/>',16),close:it('<path d="M4 4l8 8M12 4l-8 8"/>',10),refresh:it('<path d="M13 8a5 5 0 1 1-1.5-3.55M13 2.5v3h-3"/>',12),search:it('<circle cx="7" cy="7" r="4.25"/><path d="M10.2 10.2l3.3 3.3"/>',12),back:it('<path d="M10 3.5L5.5 8l4.5 4.5"/>',14),routing:it('<path d="M3 4h4.5a2 2 0 0 1 2 2v4a2 2 0 0 0 2 2H13M3 12h3M11 2.5L13 4l-2 1.5M11 10.5l2 1.5-2 1.5"/>',16)},xc={lmstudio:"LM",ollama:"Ol",anthropic:"An",openai:"OA","vscode-lm":"Co"},Ec=new Set(["openai-compatible","lmstudio","ollama","anthropic","openai","vscode-lm"]);function Ut(e,t=""){let n=Ec.has(e),i=n?e==="openai-compatible"?xe.braces:xc[e]??"?":"?";return`<span class="ai-glyph ${t}" data-kind="${n?e:"unknown"}" aria-hidden="true">${i}</span>`}var Tc=e=>e.charAt(0).toLowerCase()+e.slice(1),lo=`AI features are experimental and may change or be removed. AI output can be wrong, so review it before you keep it. With a cloud engine, ${Tc(Mt.leaves)} ${Mt.local}`;function ui(){return c("span","ai-experimental-badge","Experimental")}function co(e=""){return c("p",`ai-disclaimer${e?` ${e}`:""}`,lo)}function fi(e,t,n,i=""){let o=c("a",`ai-link-btn${i?` ${i}`:""}`,e);return o.href=t,o.target="_blank",o.rel="noopener noreferrer",o.title=t,n&&o.addEventListener("click",a=>{a.preventDefault(),n(t)}),o}function Sc(e,t){return fi(e.label,e.url,t,"ai-privacy-link")}function Sn(e,t={}){let n=e?Array.isArray(e)?e:[e]:[],i=[];for(let h of n)h.policy&&!i.some(w=>w.url===h.policy.url)&&i.push(h.policy);let o=c("div","ai-privacy-body"),a=c("ul","ai-privacy-lines"),r=t.hostEngine?[Gt.leaves,Gt.terms,Gt.permission,Gt.local]:[Mt.leaves,Mt.terms,Mt.local,Mt.keys];for(let h of r)a.append(c("li","",h));o.append(a);for(let h of i){let w=c("p","ai-privacy-policy");w.append(Sc(h,t.openLink)),h.note&&!t.hostEngine&&w.append(c("span","ai-privacy-policy-note",` ${h.note}`)),o.append(w)}t.extra&&o.append(c("p","ai-privacy-extra",t.extra));let u=`ai-privacy-card${t.className?` ${t.className}`:""}`,d=c("span","ai-privacy-glyph");if(d.innerHTML=xe.cloud,t.collapsed){let h=c("details",u);h.open=!!t.open;let w=c("summary","ai-privacy-summary");return w.append(d,c("span","",typeof t.collapsed=="string"?t.collapsed:"What is sent")),h.append(w,o),t.onToggle&&h.addEventListener("toggle",()=>t.onToggle(h.open)),h}let b=c("div",u),k=c("div","ai-privacy-head");return k.append(d,c("span","",t.hostEngine?"GitHub Copilot and your text":"Cloud engines and your text")),b.append(k,o),b}function $c(e){let t=c("div","ai-cloud-access"),n=c("div","ai-cloud-access-row"),i=pn(e.allowed,"Allow cloud engines",e.fk);i.id=ye("ai-allow-cloud");let o=c("label","ai-cloud-access-label","Allow cloud engines");o.htmlFor=i.id;let a=c("span","ai-cloud-access-line","Text you ask about is sent to the provider over the internet.");a.id=ye("ai-allow-cloud-line"),i.setAttribute("aria-describedby",a.id),i.addEventListener("change",()=>e.onChange(i.checked));let r=c("div","ai-cloud-access-text");return r.append(o,a),n.append(i,r),t.append(n,Sn(e.presets,{collapsed:"What this means",open:e.open,onToggle:u=>e.onToggle?.(u),openLink:e.openLink,extra:tn(e.hostAsks),className:"ai-cloud-access-privacy"})),t}function ur(e){let t=c("p","ai-privacy-line"),n=c("span","ai-privacy-glyph");n.innerHTML=xe.cloud;let i=me("ai-link-btn","Learn more",{fk:"ai-privacy:learn-more"});return i.addEventListener("click",()=>e()),t.append(n,c("span","",`A cloud engine sends text to the provider. ${Mt.local} `),i),t}var Ic=0,ye=e=>`${e}-${++Ic}`;function c(e,t,n){let i=document.createElement(e);return t&&(i.className=t),n!==void 0&&(i.textContent=n),i}function me(e,t,n={}){let i=c("button",e);return i.type="button",n.html!==void 0?(i.innerHTML=n.html,t&&i.append(c("span","ai-btn-text",t))):i.textContent=t,n.ariaLabel&&i.setAttribute("aria-label",n.ariaLabel),n.title&&(i.title=n.title),n.fk&&(i.dataset.fk=n.fk),i}function pn(e,t,n){let i=c("input","ai-switch");return i.type="checkbox",i.setAttribute("role","switch"),i.checked=e,i.setAttribute("aria-label",t),n&&(i.dataset.fk=n),i}function st(e,t,n=""){let i=c("div",`ai-note ai-note--${e}${n?` ${n}`:""}`),o=c("span","ai-note-icon");return o.innerHTML=e==="ok"?xe.check:e==="info"?xe.info:xe.warn,i.append(o,c("span","ai-note-text",t)),i}function rt(e,t){let n=document.activeElement,i=n&&e.contains(n)?n.dataset.fk:void 0,o=null;if(i&&(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement))try{o=[n.selectionStart,n.selectionEnd]}catch{o=null}let a=t()??e;if(!i)return;let r=Array.from(a.querySelectorAll("[data-fk]")).find(u=>u.dataset.fk===i);if(r&&(r.focus({preventScroll:!0}),o&&(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement)))try{r.setSelectionRange(o[0],o[1])}catch{}}function si(e,t,n={}){let i=c("span",`ai-status${n.compact?" ai-status--compact":""}`),o=c("span","ai-status-dot");o.setAttribute("aria-hidden","true");let a=c("span","ai-status-text"),r,u,d;return t?(r="busy",u=t==="test"?"Testing\u2026":"Fetching\u2026",d=t==="test"?"Testing the connection\u2026":"Fetching models\u2026"):!e||e.ok===null?(r="unknown",u="Not tested",d="Not reached yet. Open the engine and fetch its models, or choose Test connection."):e.ok?(r="ok",u=e.latencyMs!==void 0?`${Math.round(e.latencyMs)} ms`:"OK",d=`Connected${e.latencyMs!==void 0?` in ${Math.round(e.latencyMs)} ms`:""} on the last test or model fetch.`):(r="error",u="Failed",d=e.error?`Last test failed: ${e.error}`:"The last test failed."),i.dataset.state=r,i.title=d,a.textContent=u,i.append(o,a),i.setAttribute("aria-label",`Status: ${d}`),i.setAttribute("role","img"),i}function li(e,t,n={}){let i=nn(e,t.localNetworks),o=c("span",`ai-pill ai-pill--${i.locality}`);o.innerHTML=i.locality==="local"?xe.local:xe.cloud,o.append(c("span","",i.locality==="local"?"local":"cloud")),i.mismatch&&(o.classList.add("ai-pill--mismatch"),o.title=i.locality==="cloud"?"Pinned to cloud, but the address looks local.":"Pinned to local, but the address looks like a cloud server.");let a=[o];if(i.locality==="cloud"&&!t.allowCloud&&n.blocked!==!1){let r=c("span","ai-pill ai-pill--blocked","blocked by Allow cloud");r.title="Turn on Allow cloud engines to route tasks here.",a.push(r)}return a}var Zi=8,Va=[{tag:"fits",title:"Runs well on this machine"},{tag:"tight",title:"A tight fit"},{tag:"too large",title:"Likely too large for this machine"},{tag:void 0,title:"Size not in the name"}],Lc={fits:"Its size should run well in this machine\u2019s memory (a 4-bit estimate).",tight:"Near the limit of this machine\u2019s memory: it may run slowly.","too large":"Probably more than this machine\u2019s memory holds. You can still pick it."},Mc={local:"Local",cloud:"Cloud"};function Cc(e){let{ai:t}=e,n=new Map,i=new Set,o=new Map,a=new Map,r=new Set,u=new Set,d=new Map,b=new Map,k=new Map,h=new Map,w=new Set,E=new Set,S=new Set,$=new Map,N=new Map,O=new Set,F=f=>e.getDraft().engines.find(A=>A.id===f),j=f=>tc(f,e.getDraft().localNetworks),se=f=>nn(f,e.getDraft().localNetworks).locality==="local";function le(f){let A=n.get(f);return A||(A={seq:0,running:!1,again:null,problem:null,prev:null},n.set(f,A)),A}function he(f,A){e.setDraft(Pt(e.getDraft(),f),A)}function ae(f,A,s){let l=F(f);l&&he({...l,...A},s)}function X(f,A,s,l){let g=F(f),y=g?.models.find(x=>x.id===A);g&&y&&he(Xa(g,s(y)),l)}function ee(f,A){let s=le(f.id),l=e.statuses.get(f.id);return{event:A,family:j(f).family,key:d.get(f.id)??"",baseUrl:f.baseUrl,discovery:f.discovery,neverProbed:!l||l.ok===null,hasKey:e.hasKey(f.id),modelCount:f.models.length,fetchedFor:s.fetchedFor}}function Ee(f,A){let s=F(f);if(!s||!t.discoverModels)return;let l=le(f),g=ee(s,A),y=uc(l.prev,g);l.prev=g,y.cancelPending&&(window.clearTimeout(l.timer),l.timer=void 0),y.fetch&&(y.delayMs>0?l.timer=window.setTimeout(()=>{l.timer=void 0,Ne(f,A)},y.delayMs):Ne(f,A))}async function Ne(f,A){let s=le(f),l=++s.seq;if(s.lastEvent=A,s.running){s.again=A;return}let g=F(f);if(!g||!t.discoverModels)return;s.running=!0,s.problem=null,e.refresh(f,{form:!0,head:!0});let y=j(g),x=Ue(g);try{let L=(d.get(f)??"").trim();if(t.setSecret&&L&&b.get(f)!==L){let U=await e.setKey(f,L);if(U)throw new Error(U);b.set(f,L)}await e.ensureSaved(f);let _=await t.discoverModels(f);if(!_||typeof _!="object")throw new Error("The app returned no model list.");if(e.statuses.set(f,_),e.onStatuses(),l!==s.seq)return;let R=F(f)??g;if(_.ok===!1)s.problem=Xi({family:y.family,presetName:y.name,baseUrl:R.baseUrl,ok:!1,message:_.error,listed:0});else{let U=R.models.some(_e=>_e.enabled&&!_e.missing),D=Pt(e.getDraft(),ro(R,_,y.family)),Y=D.engines.find(_e=>_e.id===f)??R,Q=null;if(U||(Q=y.family==="local"?Y.models.find(_e=>_e.enabled&&!_e.missing&&_e.capabilities.chat)?.id??null:rc(y,Y.models)??(y.family==="host"?or(Y.models):null),Q&&(D=un(D,f,Q),$.set(f,Q))),!D.routing.default){let _e=ci(D,[...e.statuses.values()],f);_e&&(D=un(D,f,_e.modelId))}let be=Y.models.filter(_e=>!_e.missing).length;s.problem=Xi({family:y.family,presetName:y.name,baseUrl:R.baseUrl,ok:!0,listed:be}),s.fetchedFor=no(y.family,d.get(f)??"",R.baseUrl),ge(f),e.setDraft(D,{head:!0,routing:!0,list:!U&&!!Q});let Ce=Q?pt(Y.models.find(_e=>_e.id===Q)??{id:Q}):"";e.announce(`${x}: ${be} ${be===1?"model":"models"} found${Ce?`. ${Ce} picked as the default model`:""}.`)}}catch(L){if(l!==s.seq)return;let _=It(L),R=F(f)??g;s.problem=Xi({family:y.family,presetName:y.name,baseUrl:R.baseUrl,ok:!1,code:_.code,message:_.message,listed:0})}finally{s.running=!1;let L=s.again;if(s.again=null,L&&l!==s.seq)Ne(f,L);else if(F(f)&&(s.problem&&s.problem.kind!=="empty"&&e.announce(`${x}: ${s.problem.text}`),e.refresh(f,{form:!0,head:!0}),s.problem?.focus==="key")){e.focusKey(`eng:${f}:key`);let _=document.activeElement;_ instanceof HTMLInputElement&&_.select()}}}function ge(f){let A=d.get(f);A!==void 0&&A.trim()===b.get(f)&&d.delete(f)}async function $e(f){window.clearTimeout(k.get(f)),k.delete(f);let A=F(f),s=(d.get(f)??"").trim();if(!A||!s||b.get(f)===s||!t.setSecret)return;let l=await e.setKey(f,s);if(l){a.set(f,{level:"error",text:l}),e.refresh(f,{form:!0});return}b.set(f,s),a.delete(f);let g=le(f);if(g.problem?.kind!=="auth"&&ge(f),j(A).family==="local"){g.problem?.kind==="auth"?Ne(f,"retry"):e.refresh(f,{form:!0});return}e.refresh(f,{form:!0})}async function ie(f){let A=F(f);if(!A||!t.testEngine||i.has(f))return;let s=Ue(A);i.add(f),o.delete(f),e.refresh(f,{form:!0,head:!0});try{await e.ensureSaved(f);let l=await t.testEngine(f);if(e.statuses.set(f,l),e.onStatuses(),l.ok){let g=l.latencyMs!==void 0?` in ${Math.round(l.latencyMs)} ms`:"",y=l.models.filter(L=>!L.missing).length,x=`Connected${g}${y?`. The server lists ${y} ${y===1?"model":"models"}.`:"."}`;o.set(f,{level:"ok",text:x}),e.announce(`${s}: ${x}`)}else{let g=`Failed${l.error?`: ${l.error}`:". The server did not answer."}`;o.set(f,{level:"error",text:g}),e.announce(`${s}: connection ${g.toLowerCase()}`)}}catch(l){let g=It(l),y=Gn(g.code),x=`${y.title}${g.message&&g.message!==y.title?`: ${g.message}`:"."}`;o.set(f,{level:"error",text:x}),e.announce(`${s}: ${x}`)}finally{i.delete(f),e.refresh(f,{form:!0,head:!0,routing:!0}),e.focusKey(`eng:${f}:test`)}}async function Ie(f){let A=F(f);if(!(!A||!t.listEngines||!t.discoverModels||e.hasKey(f)||!e.savesFirst(f))&&!(!A.apiKeyEnv?.trim()&&!A.apiKeyFile?.path.trim()))try{await e.ensureSaved(f);let s=(await t.listEngines()).find(l=>l.engineId===f);if(!s?.hasKey||!F(f)||(d.get(f)??"").trim())return;e.statuses.set(f,s),e.onStatuses(),e.refresh(f,{form:!0,head:!0}),Ee(f,"open")}catch{}}function Le(f,A={}){let s=F(f),l=c("div","ai-form");if(l.id=`ai-engine-editor-${f}`,!s)return l;let g=j(s),y=!!A.setup,x=y?nc(g,{key:le(f).problem?.kind==="auth"||e.hasKey(f)}):nr(g);l.dataset.family=g.family,y&&l.classList.add("ai-form--setup"),l.setAttribute("role","group"),l.setAttribute("aria-label",`${Ue(s)} settings`),(g.family==="cloud"||g.family==="host")&&A.privacy!==!1&&l.append(Sn({policy:An(s)},{hostEngine:g.family==="host",collapsed:"What is sent",open:u.has(f),onToggle:_=>{_?u.add(f):u.delete(f)},openLink:e.openLink,className:"ai-form-privacy"}));let L=c("div","ai-sheet");for(let _ of x.express){let R=_==="key"&&t.setSecret?e.keyNote?.(s,g)??null:null,U=_==="key"?q(s,g,{hint:!R}):Me(s,g,_,y);U&&(R&&L.append(R),L.append(U))}return l.append(L),y||l.append(We(s)),l.append(...lt(s,g,x.advanced)),l}function Re(f,A,s={}){let l=c("div",`ai-sheet-row${s.className?` ${s.className}`:""}`),g=c("label","ai-sheet-label",f);s.forId&&(g.htmlFor=s.forId);let y=c("div","ai-sheet-body");return y.append(A),s.caption&&y.append(typeof s.caption=="string"?c("div","ai-caption",s.caption):s.caption),l.append(g,y),l}function Me(f,A,s,l){switch(s){case"name":return P(f);case"key":return q(f,A);case"baseUrl":return K(f,A,"express");case"models":return Oe(f,A,l);case"defaultModel":return De(f);case"enabled":return Pe(f);default:return null}}function P(f){let A=f.id,s=c("input","settings-input ai-sheet-input");return s.type="text",s.id=ye("ai-name"),s.value=f.name,s.placeholder="Shown in pickers and the indicator",s.dataset.fk=`eng:${A}:name`,s.addEventListener("input",()=>ae(A,{name:s.value},{head:!0,routing:!0})),Re("Name",s,{forId:s.id})}function q(f,A,s={}){if(!t.setSecret)return null;let l=f.id,g=e.hasKey(l),y=c("div","ai-key"),x=c("input","settings-input settings-input--grow ai-mono");x.type="password",x.id=ye("ai-key"),x.autocomplete="off",x.spellcheck=!1,x.dataset.fk=`eng:${l}:key`,x.setAttribute("aria-label",`API key for ${Ue(f)}`),x.value=d.get(l)??"";let L=g?e.keySource?.(l):void 0,_=g&&(L?L==="file":!b.has(l)&&!!f.apiKeyFile?.path),R=g&&L==="env";x.placeholder=_||R?"Found":g?"Stored":"Paste your key",le(l).problem?.kind==="auth"&&x.setAttribute("aria-invalid","true"),x.addEventListener("input",()=>{d.set(l,x.value),x.removeAttribute("aria-invalid"),window.clearTimeout(k.get(l));let be=le(l);j(F(l)??f).family==="cloud"?(Ee(l,"key"),!be.timer&&x.value.trim()&&k.set(l,window.setTimeout(()=>{$e(l)},600))):x.value.trim()&&k.set(l,window.setTimeout(()=>{$e(l)},600))});let D=()=>{let be=le(l);be.timer?(window.clearTimeout(be.timer),be.timer=void 0,Ne(l,"key")):k.has(l)&&$e(l)};if(x.addEventListener("keydown",be=>{be.key==="Enter"&&(be.preventDefault(),D())}),x.addEventListener("blur",D),y.append(x),g&&L!=="env"&&L!=="file"){let be=me("settings-btn","Clear",{fk:`eng:${l}:key-clear`,ariaLabel:`Clear the stored API key for ${Ue(f)}`});be.addEventListener("click",()=>{te(l)}),y.append(be)}let Y=c("div","ai-caption ai-key-caption"),Q=a.get(l);return Q?Y.append(st(Q.level,Q.text)):R?(Y.innerHTML=`<span class="ai-key-state">${xe.check}<span>Key found</span></span>`,Y.append(" in ",c("code","ai-key-env",f.apiKeyEnv??"a variable"),". Paste a key to use another one.")):_?(Y.innerHTML=`<span class="ai-key-state">${xe.check}<span>Key found</span></span>`,Y.append(` in ${f.apiKeyFile?.path??"the key file"}${L?"":" (or stored here)"}. Paste a key to use another one.`)):g?(Y.innerHTML=`<span class="ai-key-state">${xe.check}<span>Stored</span></span>`,Y.append(" in the system\u2019s secure storage. Paste a new key to replace it.")):s.hint===!1||(A.keyUrl?Y.append(fi(A.keyHint,A.keyUrl,e.openLink,"ai-key-link")):Y.textContent=A.keyHint),Re("API key",y,{forId:x.id,caption:Y.childNodes.length>0?Y:void 0,className:"ai-key-row"})}async function te(f){let A=F(f);if(!A)return;d.delete(f),b.delete(f);let s=await e.setKey(f,null);a.set(f,s?{level:"error",text:s}:{level:"info",text:A.apiKeyEnv?`Key cleared. ${A.apiKeyEnv} is used if it is set.`:A.apiKeyFile?"Key cleared. The key file is used if it has a key.":"Key cleared."}),e.refresh(f,{form:!0,head:!0}),e.focusKey(`eng:${f}:key`)}function K(f,A,s){let l=f.id,g=c("input","settings-input ai-sheet-input ai-mono");g.type="url",g.id=ye("ai-url"),g.spellcheck=!1,g.autocomplete="off",g.placeholder="http://127.0.0.1:8000/v1",g.value=f.baseUrl,g.dataset.fk=`eng:${l}:url`;let y=c("div","ai-field-error");y.id=ye("ai-url-error"),y.setAttribute("aria-live","polite"),g.setAttribute("aria-describedby",y.id);let x=()=>{let R=En(g.value);y.textContent=R,g.setAttribute("aria-invalid",String(!!R))};g.addEventListener("input",()=>{ae(l,{baseUrl:g.value.trim()},{head:!0}),y.textContent&&x()}),g.addEventListener("change",()=>{x(),e.refresh(l,{routing:!0}),A.family==="local"&&Ee(l,"url")}),f.baseUrl&&x();let L=c("div","ai-url");L.append(g,y);let _=s==="express"?"The one thing that changes per machine. Usually ends in /v1.":"The server address. Cloud presets fill it in.";return Re("Base URL",L,{forId:g.id,caption:_})}function ke(f,A){if(A.family!=="local"||!e.modelSize)return null;let s=new Map((e.statuses.get(f)?.models??[]).map(l=>[l.id,l.sizeBytes]));return l=>e.modelSize?.(l,s.get(l))}function Z(f,A,s){let l=f.models.filter(D=>!D.missing&&D.capabilities.chat);if(l.length===0)return null;let g=ii(e.getDraft(),f.id);if(s?l.some(D=>D.id===g&&D.enabled):l.some(D=>D.enabled))return O.delete(f.id),null;if(O.has(f.id)){let D=st("error",`Pick at least one model before you choose Done. ${Ue(f)} needs a default model to answer.`,"ai-pick-note");return D.setAttribute("role","alert"),D}if(A.family!=="local")return null;let x=ke(f.id,A),L=new Map((e.statuses.get(f.id)?.models??[]).map(D=>[D.id,D])),_=l.some(D=>x&&x(D.id)!==void 0||!!L.get(D.id)?.sizeBytes||!!Vi(D.id,L.get(D.id)?.moe,x?.(D.id))),R=`Pick a model to start with. No chat model is loaded in ${Ue(f)}, so none was chosen for you${_?"; the tags give size and speed hints":""}.`,U=st("info",R,"ai-pick-note");return U.setAttribute("role","status"),U}function Oe(f,A,s=!1){let l=f.id,g=le(l),y=A.family==="cloud"&&!e.hasKey(l)&&!(d.get(l)??"").trim();if(s&&y&&f.models.length===0&&!g.running&&!g.problem)return null;let x=c("div","ai-picker"),L=ye("ai-models-label"),_=ye("ai-models-list"),R=c("div","ai-picker-head"),U=c("span","ai-picker-label",s?"Model":"Models");if(U.id=L,g.running){let M=c("span","ai-spinner");M.setAttribute("aria-hidden","true"),U.append(M),x.setAttribute("aria-busy","true")}let D=M=>g.running?"Fetching\u2026":s?"":oc(M),Y=c("span","ai-models-count",D(f));if(R.append(U,Y),t.discoverModels&&!(s&&y)){let M=me("ai-link-btn",f.models.length>0?"Refresh models":"Fetch models",{html:xe.refresh,fk:`eng:${l}:fetch`}),J=!zt(f.kind)&&!!En(f.baseUrl);g.running&&M.setAttribute("aria-disabled","true"),M.disabled=f.discovery==="manual"||J,f.discovery==="manual"&&(M.title="The model list is manual for this engine (see Advanced)."),M.addEventListener("click",()=>{g.running||Ee(l,"manual")}),R.append(M)}x.append(R);let Q=Z(f,A,s);Q&&!g.running&&!g.problem&&x.append(Q);let be=f.models.filter(M=>!M.missing).length,Ce=A.family==="cloud"?ir(A,f.models).map(M=>M.id):[],_e=()=>s?ii(e.getDraft(),l):null,Qe=_e(),Ke=s&&Ce.length>0&&!S.has(l)&&(!Qe||Ce.includes(Qe)),dt=s?!Ke&&(f.models.length>0?f.models.length>Zi||w.has(l)||!!h.get(l):!y&&!g.running):f.models.length>Zi||f.models.length===0||w.has(l)||!!h.get(l),ht=ke(l,A),we=null;if(dt){let M=c("div","ai-combo"),J=c("span","ai-combo-icon");J.innerHTML=xe.search,we=c("input","settings-input ai-combo-input"),we.type="text",we.spellcheck=!1,we.autocomplete="off",we.dataset.fk=`eng:${l}:pick`,we.setAttribute("role","combobox"),we.setAttribute("aria-expanded","true"),we.setAttribute("aria-controls",_),we.setAttribute("aria-autocomplete","list"),we.setAttribute("aria-label",f.models.length>0?`Filter models of ${Ue(f)}, or type a model id to add it`:`Type a model id for ${Ue(f)}`),we.placeholder=f.models.length>Zi?`Search ${be} models, or type an id`:"Type a model id, then Enter",we.value=h.get(l)??"",M.append(J,we),x.append(M)}let Fe=c("ul","ai-listbox");Fe.id=_,Fe.setAttribute("role","listbox"),Fe.setAttribute("aria-multiselectable",String(!s)),s&&Fe.classList.add("ai-listbox--single"),Fe.setAttribute("aria-labelledby",L),we||(Fe.tabIndex=0,Fe.dataset.fk=`eng:${l}:models`),x.append(Fe);let ne=-1,de=[],qe=M=>`${_}-o${M}`,at=()=>we??Fe;function Ge(M){ne=M>=0&&M<de.length?M:-1,Fe.querySelectorAll(".ai-option.is-active").forEach(Te=>Te.classList.remove("is-active"));let J=at();if(ne<0){J.removeAttribute("aria-activedescendant");return}let ve=Array.from(Fe.querySelectorAll(".ai-option")).find(Te=>Te.id===qe(ne));ve?.classList.add("is-active"),ve?.scrollIntoView?.({block:"nearest"}),J.setAttribute("aria-activedescendant",qe(ne))}function Ye(){let M=Ke?"":h.get(l)??"",J=F(l)??f,ve=ic(J,e.statuses.get(l),M),Te=ve.filter(Ae=>Ce.includes(Ae.id)).sort((Ae,Se)=>Ce.indexOf(Ae.id)-Ce.indexOf(Se.id)),Be=Ke?[]:ve.filter(Ae=>!Ce.includes(Ae.id)),Ve=ht?new Map(Be.map(Ae=>[Ae.id,ht(Ae.id)])):null,et=!!Ve&&[...Ve.values()].some(Ae=>Ae!==void 0),Je=Ae=>Be.filter(Se=>Ve?.get(Se.id)===Ae);de=et?[...Va.flatMap(Ae=>Je(Ae.tag))]:[...Te,...Be],Fe.replaceChildren();let Ze=0,tt=(Ae,Se)=>{if(Se.length===0)return;let Nt=c("li","ai-listbox-group");Nt.setAttribute("role","presentation");let Rt=c("div","ai-listbox-heading",Ae);Rt.id=ye("ai-group");let wt=c("ul","ai-listbox-items");wt.setAttribute("role","group"),wt.setAttribute("aria-labelledby",Rt.id);for(let on of Se)wt.append(ut(on,Ze++));Nt.append(Rt,wt),Fe.append(Nt)};if(et)for(let Ae of Va)tt(Ae.title,Je(Ae.tag));else if(Te.length>0)tt("Popular",Te),tt("All models",Be);else for(let Ae of Be)Fe.append(ut(Ae,Ze++));if(de.length===0){let Ae=c("li","ai-listbox-empty");Ae.setAttribute("role","presentation"),Ae.textContent=M.trim()?`No model matches \u201C${M.trim()}\u201D. Press Enter to add it by id.`:g.running?"Fetching models\u2026":y?"Paste your key and the models appear here.":s?"No models yet. Fetch them from the server.":"No models yet. Fetch them from the server, or type an id.",Fe.append(Ae)}Ge(Math.min(ne,de.length-1))}function ut(M,J){let ve=c("li","ai-option");ve.id=qe(J),ve.setAttribute("role","option");let Te=s?M.id===_e():M.enabled;ve.setAttribute("aria-selected",String(Te)),ve.dataset.modelId=M.id,ve.classList.toggle("is-missing",M.missing),ve.classList.toggle("is-on",Te);let Be=!(s?M.chat:M.usable);Be&&(ve.classList.add("is-unusable"),ve.setAttribute("aria-disabled","true"));let Ve=c("span","ai-option-check");Ve.setAttribute("aria-hidden","true"),Ve.innerHTML=xe.check;let et=c("span","ai-option-names");et.append(c("span","ai-option-name",M.name)),M.hasLabel&&et.append(c("span","ai-option-id",M.id)),ve.append(Ve,et);let Je=c("span","ai-option-tags");if(M.loaded){let Se=c("span","ai-tag ai-tag--loaded","loaded");Se.title="Loaded in memory on the server right now.",Je.append(Se)}if(M.missing){let Se=c("span","ai-tag ai-tag--missing","not listed");Se.title="The last fetch did not list this model. It is kept, but never routed.",Je.append(Se)}if(M.manual&&Je.append(c("span","ai-tag","typed in")),Be){let Se=c("span","ai-tag ai-tag--unusable",M.usable?"not for chat":"not a chat model");Se.title=M.usable?"An embeddings model: it cannot be the model this engine answers with.":"This model cannot answer (a converter or a draft model for another model), so it cannot be picked.",Je.append(Se)}let Ze=A.family==="local"?e.statuses.get(l)?.models.find(Se=>Se.id===M.id):void 0,tt=ht?.(M.id),Ae=A.family==="local"?Vi(M.id,Ze?.moe,tt):null;if(Ae){let Se=c("span","ai-tag ai-tag--moe","MoE \xB7 fast");Se.title=Ae.activeBillions!==null?`A mixture of experts: about ${Ae.activeBillions}B parameters work per token, so it runs much faster than its size suggests.`:"A mixture of experts: only part of it works per token, so it runs much faster than its size suggests.",Je.append(Se)}if(Ze?.sizeBytes){let Se=c("span","ai-tag ai-tag--bytes",Pa(Ze.sizeBytes));Se.title="Its size, as the server reports it.",Je.append(Se)}if(tt){let Se=c("span",`ai-tag ai-tag--size ai-tag--${tt.replace(" ","-")}`,tt);Se.title=Lc[tt],Je.append(Se)}return Je.childElementCount>0&&ve.append(Je),ve.addEventListener("mousedown",Se=>Se.preventDefault()),ve.addEventListener("click",()=>{ne=J,bt(M.id)}),ve}function bt(M){let J=de.find(ve=>ve.id===M);if(J&&!(s?J.chat:J.usable)){e.announce(`${J.name} is not a chat model, so it cannot be picked.`);return}s?Ft(M):Yt(M)}function Ft(M){let J=F(l)?.models.find(ve=>ve.id===M);!J||_e()===M||(e.setDraft(Ga(e.getDraft(),l,M,$.get(l)),{head:!0,list:!0,routing:!0}),$.set(l,M),e.announce(`${pt(J)} chosen.`),Ot())}function Yt(M){let J=F(l),ve=J?.models.find(Be=>Be.id===M);if(!J||!ve)return;let Te=!ve.enabled;e.setDraft(to(e.getDraft(),l,M,Te),{head:!0,routing:!0}),e.announce(`${pt(ve)} ${Te?"picked":"removed"}.`),Ot()}function Ot(){let M=Fe.scrollTop,J=F(l)??f;Y.textContent=D(J),Ye(),Fe.scrollTop=M;let ve=Z(J,A,s),Te=x.querySelector(":scope > .ai-pick-note");Te&&!ve?Te.remove():!Te&&ve&&R.after(ve);let Ve=x.closest(".ai-form")?.querySelector(".ai-default-row"),et=De(J);Ve&&et&&rt(Ve,()=>(Ve.replaceWith(et),et)),at().focus({preventScroll:!0})}function Vt(M){let J=F(l);if(!J)return;let ve=J.models.find(Ve=>Ve.id===M);if(ve){s?Ft(ve.id):ve.enabled||Yt(ve.id);return}let Te=Fa(J,M);if(!Te.ok){e.announce(Te.error);return}let Be=Pt(e.getDraft(),Te.engine);!Be.routing.default&&Te.model.capabilities.chat&&Te.engine.enabled&&(Be=un(Be,l,Te.model.id)),s&&(Be=Ga(Be,l,Te.model.id,$.get(l)),$.set(l,Te.model.id)),e.setDraft(Be,{head:!0,list:!e.getDraft().routing.default&&!!Be.routing.default,routing:!0}),h.delete(l),w.add(l),e.announce(`Added ${Te.model.id}.`),e.refresh(l,{form:!0}),e.focusKey(`eng:${l}:pick`)}let Xe=M=>{if(M.key==="ArrowDown"||M.key==="ArrowUp"){if(M.preventDefault(),de.length===0)return;let J=M.key==="ArrowDown"?1:-1;Ge(ne<0?J>0?0:de.length-1:(ne+J+de.length)%de.length)}else if(M.key==="Home"&&!we)M.preventDefault(),Ge(0);else if(M.key==="End"&&!we)M.preventDefault(),Ge(de.length-1);else if(M.key==="Enter"||M.key===" "&&!we){M.preventDefault();let J=we?.value.trim()??"";ne>=0&&de[ne]?bt(de[ne].id):J&&Vt(J)}else M.key==="Escape"&&(we?.value?(M.preventDefault(),M.stopPropagation(),we.value="",h.delete(l),ne=-1,Ye()):ne>=0&&(M.preventDefault(),M.stopPropagation(),Ge(-1)))};if(we){let M=we;M.addEventListener("keydown",Xe),M.addEventListener("input",()=>{h.set(l,M.value),ne=M.value.trim()?0:-1,Ye()})}else Fe.addEventListener("keydown",Xe),Fe.addEventListener("focus",()=>{ne<0&&de.length>0&&Ge(0)});if(Ye(),s&&Ce.length>0&&(Ke||S.has(l))){let M=me("ai-link-btn ai-show-all",Ke?`Show all models (${be})`:"Show popular only",{fk:`eng:${l}:show-all`});M.setAttribute("aria-expanded",String(!Ke)),M.setAttribute("aria-controls",_),M.addEventListener("click",()=>{Ke?S.add(l):(S.delete(l),h.delete(l)),e.refresh(l,{form:!0}),e.focusKey(`eng:${l}:show-all`)}),x.append(M)}if(!we&&(!s||!Ke&&f.models.length>0)){let M=me("ai-link-btn ai-type-btn","Type a model id\u2026",{fk:`eng:${l}:type-open`});M.addEventListener("click",()=>{w.add(l),e.refresh(l,{form:!0}),e.focusKey(`eng:${l}:pick`)}),x.append(M)}let St=g.problem;if(St&&!g.running){let M=c("div",`ai-fetch-note ai-fetch-note--${St.kind}`);if(M.setAttribute("role","status"),M.append(st(St.kind==="empty"?"info":"error",St.text)),St.retry&&t.discoverModels){let J=me("ai-link-btn","Retry",{fk:`eng:${l}:retry`});J.addEventListener("click",()=>{Ne(l,g.lastEvent??"retry")}),M.append(J)}x.append(M)}let Jt=c("div","ai-sheet-row ai-sheet-row--block");return Jt.append(x),Jt}function De(f){let A=f.id,s=e.getDraft(),l=f.models.filter(Y=>Y.enabled&&!Y.missing&&Y.capabilities.chat),g=ii(s,A),y=g&&l.some(Y=>Y.id===g)?g:null,x=c("div","ai-default"),L=c("select","settings-input ai-default-select");if(L.id=ye("ai-default"),L.dataset.fk=`eng:${A}:default-model`,l.length===0){let Y=c("option","","Pick a model above");Y.value="",L.append(Y),L.disabled=!0}else{for(let Y of l){let Q=c("option","",pt(Y));Q.value=Y.id,L.append(Q)}L.value=y??l[0].id}L.addEventListener("change",()=>{e.setDraft(un(e.getDraft(),A,L.value),{head:!0,list:!0,routing:!0});let Y=F(A)?.models.find(Q=>Q.id===L.value);Y&&e.announce(`Default model: ${pt(Y)}.`)}),x.append(L);let _=f.models.find(Y=>Y.id===(y??l[0]?.id)),R=_?pe(f,_,"express"):null;if(R){let Y=c("label","ai-thinking");Y.append(c("span","ai-thinking-label","Thinking"),R),x.append(Y)}let U=s.routing.default?.engineId===A,D=l.length===0?"Pick at least one model to use this engine.":U?"Serves every task without its own route.":s.routing.default?"Used when this engine is picked for a task, or made the default (the star).":"Becomes the default route once you pick it.";return Re("Default model",x,{forId:L.id,caption:D,className:"ai-default-row"})}function pe(f,A,s){let l=Lt(f.kind);if(l.length===0)return null;let g=f.id,y=c("select",`settings-input ${s==="table"?"settings-input--small ":""}ai-thinking-select`);y.dataset.fk=s==="express"?`eng:${g}:thinking`:`model:${g}:${A.id}:thinking`,y.setAttribute("aria-label",`Thinking for ${pt(A)}`),y.title="How hard the model thinks before it answers. Default sends nothing (the model decides).";let x=c("option","","Default");x.value="",y.append(x);for(let L of l){let _=c("option","",L.label);_.value=L.level,y.append(_)}return y.value=Wn(f.kind,A.requestOverrides)??"",y.addEventListener("change",()=>{let L=y.value||null,_=F(g);_&&(X(g,A.id,R=>cc(R,_.kind,L,se(_)),{}),r.has(g)&&e.refresh(g,{form:!0}))}),y}function Pe(f){let A=f.id,s=pn(f.enabled,`Enable ${Ue(f)}`,`eng:${A}:enabled`);s.id=ye("ai-enabled"),s.addEventListener("change",()=>ae(A,{enabled:s.checked},{list:!0,routing:!0}));let l=c("div","ai-enabled-line");return l.append(s,c("span","ai-caption","Engines that are off are never routed.")),Re("Enabled",l,{forId:s.id})}function We(f){let A=f.id,s=c("div","ai-form-actions");if(t.testEngine){let g=i.has(A),y=me("settings-btn settings-btn--secondary",g?"Testing\u2026":"Test connection",{fk:`eng:${A}:test`});g&&y.setAttribute("aria-disabled","true"),y.disabled=!zt(f.kind)&&!!En(f.baseUrl),y.addEventListener("click",()=>{ie(A)}),s.append(y),e.savesFirst(A)&&s.append(c("span","ai-caption","Testing saves this engine first, so the app can reach it."))}let l=o.get(A);return l&&s.append(st(l.level,l.text,"ai-result")),s}function lt(f,A,s){let l=f.id,g=r.has(l),y=`ai-advanced-${l}`,x=me("ai-disclosure","Advanced",{html:xe.chevron,fk:`eng:${l}:advanced`});x.setAttribute("aria-expanded",String(g)),x.setAttribute("aria-controls",y),x.addEventListener("click",()=>{r.has(l)?r.delete(l):r.add(l),e.refresh(l,{form:!0}),e.focusKey(`eng:${l}:advanced`)});let L=c("div","ai-advanced");if(L.id=y,L.hidden=!g,!g)return[x,L];let _=[];for(let U of s){if(U==="kind"&&_.push(gt(f)),U==="baseUrl"&&_.push(K(f,A,"advanced")),U==="locality"&&_.push(ze(f)),U==="key"){let D=q(f,A);D&&_.push(D)}U==="keyEnv"&&_.push(kt(f)),U==="keyFile"&&_.push(Tt(f)),U==="discovery"&&_.push(mt(f))}let R=c("div","ai-sheet ai-sheet--advanced");return R.append(..._),L.append(R),s.includes("modelsTable")&&L.append(ct(f)),[x,L]}function gt(f){let A=f.id,s=c("select","settings-input");s.id=ye("ai-kind"),s.dataset.fk=`eng:${A}:kind`;for(let l of Di){if(zt(l)&&l!==f.kind)continue;let g=c("option","",Ja[l]);g.value=l,s.append(g)}if(!xt(f.kind)){let l=c("option","",Tn(f.kind));l.value=f.kind,s.prepend(l)}return s.value=f.kind,s.addEventListener("change",()=>ae(A,{kind:s.value},{form:!0,head:!0,routing:!0})),Re("Kind",s,{forId:s.id,caption:"How MikeDown talks to the server."})}function ze(f){let A=f.id,s=c("select","settings-input");s.id=ye("ai-locality"),s.dataset.fk=`eng:${A}:locality`;let l=c("option");l.value="auto",s.append(l);for(let[x,L]of Object.entries(Mc)){let _=c("option","",L);_.value=x,s.append(_)}s.value=f.locality;let g=nn(f,e.getDraft().localNetworks);l.textContent=`Auto (detected: ${g.detected})`;let y=c("div","ai-locality");return y.append(s),g.mismatch&&y.append(st("warning",g.locality==="cloud"?"Pinned to cloud, but the address looks local.":"Pinned to local, but the address looks like a cloud server. Text sent to it leaves this network.","ai-locality-note")),s.addEventListener("change",()=>ae(A,{locality:s.value},{form:!0,head:!0,routing:!0})),Re("Locality",y,{forId:s.id,caption:"Auto decides from the address. Cloud engines need Allow cloud."})}function kt(f){let A=f.id,s=c("input","settings-input settings-input--medium ai-mono");return s.type="text",s.id=ye("ai-env"),s.spellcheck=!1,s.autocomplete="off",s.placeholder="NAME_OF_VARIABLE",s.value=f.apiKeyEnv??"",s.dataset.fk=`eng:${A}:env`,s.addEventListener("input",()=>{let l=s.value.trim(),g=F(A);if(!g)return;let y={...g};l?y.apiKeyEnv=l:delete y.apiKeyEnv,he(y,{head:!0})}),Re("Key from variable",s,{forId:s.id,caption:t.shellEnv===!1?"This app does not read shell variables when opened from the Dock; use the key file or paste the key.":"Used when no key is stored, for example OMLX_API_KEY. Apps opened from the Dock or Start menu may not see variables set in a shell profile."})}function Tt(f){let A=f.id,s=c("div","ai-key"),l=c("input","settings-input settings-input--grow ai-mono"),g=c("input","settings-input settings-input--medium ai-mono");for(let x of[l,g])x.type="text",x.spellcheck=!1,x.autocomplete="off";l.id=ye("ai-keyfile"),l.placeholder="~/path/to/settings.json",g.placeholder="auth.api_key",l.value=f.apiKeyFile?.path??"",g.value=f.apiKeyFile?.jsonPath??"",l.dataset.fk=`eng:${A}:keyfile-path`,g.dataset.fk=`eng:${A}:keyfile-json`,l.setAttribute("aria-label",`Key file path for ${Ue(f)}`),g.setAttribute("aria-label",`Key file JSON path for ${Ue(f)}`);let y=()=>{let x=F(A);if(!x)return;let L=l.value.trim(),_=g.value.trim(),R={...x};L&&_?R.apiKeyFile={...x.apiKeyFile,path:L,jsonPath:_}:delete R.apiKeyFile,he(R,{head:!0})};return l.addEventListener("input",y),g.addEventListener("input",y),s.append(l,g),Re("Key file",s,{forId:l.id,caption:"Used when no key is stored and the variable is unset: a JSON file in your home folder and the dotted path to the key inside it. Works for apps opened from the Dock or Start menu."})}function mt(f){let A=f.id,s=c("select","settings-input");s.id=ye("ai-discovery"),s.dataset.fk=`eng:${A}:discovery`;for(let[l,g]of[["auto","Ask the server"],["manual","Manual only"]]){let y=c("option","",g);y.value=l,s.append(y)}return s.value=f.discovery,s.addEventListener("change",()=>ae(A,{discovery:s.value},{form:!0})),Re("Model list",s,{forId:s.id,caption:"Ask the server which models it has (merged with any you add), or keep only the models you add by hand."})}function ct(f){let A=f.id,s=c("div","ai-models"),l=c("div","ai-models-head"),g=f.models.filter(U=>U.missing).length;if(l.append(c("span","settings-label","All models")),l.append(c("span","ai-models-count",f.models.length===0?"none yet":`${f.models.length}${g?`, ${g} not listed`:""}`)),s.append(l),f.models.length===0)s.append(c("div","ai-models-empty",f.discovery==="auto"&&t.discoverModels?"Fetch models to list what the server offers, or add one by id.":"Add the models this engine serves by id."));else{let U=c("div","ai-model-list");U.setAttribute("role","list"),U.setAttribute("aria-label",`Models of ${Ue(f)}`);let D=new Map((e.statuses.get(A)?.models??[]).map(Y=>[Y.id,Y.loaded]));for(let Y of f.models)U.append(yt(f,Y,D.get(Y.id)));s.append(U)}let y=c("div","ai-model-add"),x=c("input","settings-input settings-input--small settings-input--grow ai-mono");x.type="text",x.placeholder="Model id, such as qwen3-coder-30b",x.spellcheck=!1,x.setAttribute("aria-label",`Add a model to ${Ue(f)} by id`),x.dataset.fk=`eng:${A}:add-model`;let L=me("settings-btn","Add model",{html:xe.plus,fk:`eng:${A}:add-model-btn`}),_=c("div","ai-field-error");_.id=ye("ai-add-model-error"),x.setAttribute("aria-describedby",_.id);let R=()=>{let U=F(A);if(!U)return;let D=Fa(U,x.value);if(!D.ok){_.textContent=D.error,x.setAttribute("aria-invalid","true"),x.focus();return}he(D.engine,{form:!0,routing:!0}),e.announce(`Added ${D.model.id}.`),e.focusKey(`eng:${A}:add-model`)};return L.addEventListener("click",R),x.addEventListener("keydown",U=>{U.key==="Enter"&&(U.preventDefault(),R())}),x.addEventListener("input",()=>{_.textContent="",x.removeAttribute("aria-invalid")}),y.append(x,L),s.append(y,_),s}function yt(f,A,s){let l=f.id,g=ne=>`model:${l}:${A.id}:${ne}`,y=pt(A),x=c("div","ai-model");x.setAttribute("role","listitem"),x.classList.toggle("is-missing",!!A.missing),x.classList.toggle("is-off",!A.enabled);let L=c("div","ai-model-top"),_=c("input","ai-model-check");_.type="checkbox",_.checked=A.enabled,_.dataset.fk=g("enabled"),_.setAttribute("aria-label",`Use ${y}`),!A.capabilities.chat&&!A.capabilities.embed&&!A.enabled&&(_.disabled=!0,_.title="Not a chat model: it cannot be picked."),_.addEventListener("change",()=>{e.setDraft(to(e.getDraft(),l,A.id,_.checked),{form:!0,head:!0,routing:!0})});let R=c("div","ai-model-names"),U=c("input","ai-model-label");U.type="text",U.value=A.label??"",U.placeholder=A.id,U.spellcheck=!1,U.dataset.fk=g("label"),U.setAttribute("aria-label",`Display name for ${A.id}`),U.addEventListener("input",()=>X(l,A.id,ne=>{let de={...ne};return U.value.trim()?de.label=U.value:delete de.label,de},{routing:!0})),R.append(U),A.label&&R.append(c("span","ai-model-id",A.id));let D=c("div","ai-model-tags");if(s){let ne=c("span","ai-tag ai-tag--loaded","loaded");ne.title="Loaded in memory on the server right now.",D.append(ne)}if(A.missing){let ne=c("span","ai-tag ai-tag--missing","not listed");ne.title="The last discovery did not list this model. It is kept, but never routed.",D.append(ne)}A.manual&&D.append(c("span","ai-tag","added by hand"));let Y=c("label","ai-model-context"),Q=c("input","settings-input settings-input--small ai-context-input");Q.type="text",Q.inputMode="numeric",Q.value=A.capabilities.contextTokens!==null?String(A.capabilities.contextTokens):"",Q.placeholder=Ka(null),Q.dataset.fk=g("context"),Q.setAttribute("aria-label",`Context window of ${y}, in tokens`),Q.title=`Context window in tokens (${Ka(A.capabilities.contextTokens)}). Blank means unknown.`,Q.addEventListener("change",()=>{let ne=Hl(Q.value);if(!ne.ok){Q.setAttribute("aria-invalid","true"),Q.title=ne.error,e.announce(ne.error);return}Q.removeAttribute("aria-invalid"),X(l,A.id,de=>Fl(de,ne.value),{form:!0,routing:!0})}),Y.append(Q,c("span","ai-context-unit","ctx"));let be=!!A.requestOverrides&&Object.keys(A.requestOverrides).length>0,Ce=`${l}\0${A.id}`,_e=E.has(Ce)||N.has(Ce),Qe=ye("ai-overrides"),Ke=me(`ai-icon-btn ai-overrides-btn${be?" has-value":""}`,"",{html:'<span aria-hidden="true">{ }</span>',ariaLabel:`Request overrides for ${y}`,title:be?"Request overrides (set)":"Request overrides",fk:g("overrides")});Ke.setAttribute("aria-expanded",String(_e)),Ke.setAttribute("aria-controls",Qe),Ke.addEventListener("click",()=>{E.has(Ce)?E.delete(Ce):E.add(Ce),e.refresh(l,{form:!0}),E.has(Ce)&&e.focusKey(g("overrides-text"))});let dt=c("div","ai-model-right"),ht=pe(f,A,"table");if(ht&&dt.append(ht),dt.append(Y,Ke),A.manual||A.missing){let ne=me("ai-icon-btn ai-model-remove","",{html:xe.close,ariaLabel:`Remove ${y}`,title:"Remove model",fk:g("remove")});ne.addEventListener("click",()=>{let de=F(l);if(!de)return;let qe=de.models.findIndex(ut=>ut.id===A.id),at=Ul(e.getDraft(),l,A.id);e.setDraft(Pt(at,{...de,models:de.models.filter(ut=>ut.id!==A.id)}),{form:!0,head:!0,routing:!0}),e.announce(`Removed ${y}.`);let Ge=F(l)?.models??[],Ye=Ge[Math.min(qe,Ge.length-1)];e.focusKey(Ye?`model:${l}:${Ye.id}:enabled`:`eng:${l}:add-model`)}),dt.append(ne)}L.append(_,R,D,dt);let we=c("div","ai-chips");we.setAttribute("role","group"),we.setAttribute("aria-label",`Capabilities of ${y}`);for(let ne of Nl){let de=A.capabilities[ne.flag],qe=me(`ai-chip${de?" is-on":""}`,ne.label,{title:`${ne.title}. Click to ${de?"turn off":"turn on"}.`,fk:g(`chip-${ne.flag}`)});qe.setAttribute("aria-pressed",String(de)),qe.setAttribute("aria-label",`${ne.label}: ${ne.title}`),qe.addEventListener("click",()=>X(l,A.id,at=>Kl(at,ne.flag),{form:!0,routing:!0})),we.append(qe)}let Fe=c("span",`ai-source ai-source--${A.capabilitiesSource}`,A.capabilitiesSource==="user"?"edited":A.capabilitiesSource==="endpoint"?"from server":"guessed");if(Fe.title=A.capabilitiesSource==="user"?"You edited these; discovery leaves them alone.":A.capabilitiesSource==="endpoint"?"Reported by the server; refreshed on discovery.":"Guessed from the model id; refreshed on discovery.",we.append(Fe),x.append(L,we),_e){let ne=c("div","ai-overrides");ne.id=Qe;let de=c("textarea","settings-input ai-mono ai-overrides-text");de.rows=3,de.spellcheck=!1,de.dataset.fk=g("overrides-text"),de.placeholder='{ "reasoning_effort": "low" }';let qe=N.get(Ce);de.value=qe?qe.text:Bl(A.requestOverrides);let at=c("div","settings-desc","JSON merged into every request body for this model, last, so it wins. The Thinking menu writes its fields here too."),Ge=c("div","ai-field-error");Ge.id=ye("ai-overrides-error"),Ge.setAttribute("aria-live","polite"),de.setAttribute("aria-describedby",Ge.id),de.setAttribute("aria-label",`Request overrides for ${y}, as JSON`),qe&&(Ge.textContent=qe.error,de.setAttribute("aria-invalid","true")),de.addEventListener("input",()=>{let Ye=jl(de.value);if(!Ye.ok){N.set(Ce,{text:de.value,error:Ye.error}),Ge.textContent=Ye.error,de.setAttribute("aria-invalid","true");return}N.delete(Ce),Ge.textContent="",de.removeAttribute("aria-invalid"),X(l,A.id,ut=>{let bt={...ut};return Ye.value?bt.requestOverrides=Ye.value:delete bt.requestOverrides,bt},{}),Ke.classList.toggle("has-value",!!Ye.value)}),ne.append(de,Ge,at),x.append(ne)}return x}return{build:Le,opened(f,A={}){let s=F(f);if(!s)return`eng:${f}:name`;let l=j(s).family;return Ee(f,"open"),A.isNew&&l==="cloud"&&Ie(f),A.isNew?l==="cloud"&&t.setSecret?`eng:${f}:key`:l!=="local"?`eng:${f}:name`:j(s).id==="custom"?`eng:${f}:url`:null:`eng:${f}:name`},busy(f){return i.has(f)?"test":n.get(f)?.running?"discover":void 0},requirePick(f){O.add(f)},forget(f){O.delete(f);let A=n.get(f);A&&(window.clearTimeout(A.timer),A.seq++),window.clearTimeout(k.get(f));for(let s of[n,d,b,k,h,o])s.delete(f);r.delete(f),w.delete(f),S.delete(f),$.delete(f)},dispose(){for(let f of n.values())window.clearTimeout(f.timer),f.seq++;for(let f of k.values())window.clearTimeout(f);k.clear(),d.clear()}}}var _c={none:"Nothing (the feature is unavailable)",default:"Use the default model",anyLocal:"Default, then any local model",any:"Default, any local, then cloud"};function Oc(e,t){let n=c("div","ai-routing");function i(a,r,u){let d=t.getDraft(),b=c("select","settings-input ai-route-select");b.dataset.fk=u.fk,b.setAttribute("aria-label",u.ariaLabel);let k=er(d,t.statusList(),r),h=c("option","",u.defaultText??(k.some(S=>S.selectable)?"Choose a model\u2026":d.engines.length===0?"Add an engine first":"No model can serve this"));h.value="",b.append(h);let w=ti(a);if(a&&!k.some(S=>ti(S)===w)){let S=c("option","",`${Kt(d,a)} (not found)`);S.value=w,b.append(S)}let E=new Map;for(let S of k){let $=E.get(S.engineId)??[];$.push(S),E.set(S.engineId,$)}for(let S of E.values()){let $=c("optgroup");$.label=`${S[0].engineName} (${S[0].isLocal?"local":"cloud"})`;for(let N of S){let O=c("option","",`${N.engineName} \xB7 ${N.modelName}${N.note?` (${N.note})`:""}`);O.value=ti(N),O.disabled=!N.selectable&&ti(N)!==w,$.append(O)}b.append($)}return b.value=w,b.value!==w&&(b.value=""),b}function o(){rt(n,()=>{n.replaceChildren();let a=t.getDraft(),r=e.makeRow("Default model","Serves every task without its own route. Needs chat.","inline"),u=i(a.routing.default,Qa,{fk:"route:default",ariaLabel:"Default model"});u.addEventListener("change",()=>{let $=t.getDraft();t.setDraft({...$,routing:{...$.routing,default:ja(u.value)}},{defaultChanged:!0}),o()}),r.append(u);let d=ai({...a,routing:{...a.routing,tasks:{}}},t.statusList(),"chat");a.routing.default&&d&&r.append(st(d.level,d.text,"ai-row-note"));let b=e.makeSelectRow("When a route is unavailable","What to try when a task\u2019s model is off, unreachable or lacks what the task needs. Fallback never moves a local route to a cloud engine unless you pick the last option.",a.routing.fallback,Pi.map($=>({value:$,label:_c[$]})));b.select.dataset.fk="route:fallback",b.select.addEventListener("change",()=>{let $=t.getDraft();t.setDraft({...$,routing:{...$.routing,fallback:b.select.value}},{defaultChanged:!1}),o()});let k=e.makeGroup(r,b.row),h=a.routing.default?`Default: ${Kt(a,a.routing.default)}`:"Default (none set)",w=[],E=($,N,O,F,j)=>{let se=e.makeRow(N,O,"inline");if(se.classList.add("ai-task-row"),j){se.append(c("span","ai-muted","Handled by the app")),w.push(se);return}let le=i(a.routing.tasks[$],F,{fk:`route:task:${$}`,ariaLabel:`Model for ${N}`,defaultText:h});le.addEventListener("change",()=>{let ae=t.getDraft(),X={...ae.routing.tasks},ee=ja(le.value);ee?X[$]={...X[$]??{},...ee}:delete X[$],t.setDraft({...ae,routing:{...ae.routing,tasks:X}},{defaultChanged:!1}),o()}),se.append(le);let he=ai(a,t.statusList(),$);he&&se.append(st(he.level,he.text,"ai-row-note")),w.push(se)};for(let $ of jt)E($.id,$.label,$.description,Gl($.id),$.hostMethod==="transcribe");for(let $ of Yl(a))E($,$,"Saved by a newer version of MikeDown. Kept as is.",{requires:{}},!1);let S=c("div","ai-subhead","Model per task");n.append(k,S,e.makeGroup(...w))})}return{element:n,render:o}}var Qi=3;function Nc(e){return e==="path"?1:e==="done"?3:2}var Rc="Consumer subscriptions such as ChatGPT Plus or Claude Pro do not include API access. An API key is billed separately by the provider, per use.";function Dc(e,t,n){let i=c("div","ai-wizard-subscription");i.append(c("p","ai-wizard-subscription-text",Rc));let o=[];if(e.keyUrl&&o.push([`${e.name} API keys`,e.keyUrl]),e.pricingUrl&&o.push(["Pricing",e.pricingUrl]),n?.url&&o.push(["Privacy",n.url]),o.length>0){let a=c("p","ai-wizard-subscription-links");a.append("Get a key: "),o.forEach(([r,u],d)=>{d>0&&a.append(c("span","ai-wizard-sep"," \xB7 ")),a.append(fi(r,u,t,"ai-wizard-link"))}),i.append(a)}return n?.note&&i.append(c("p","ai-wizard-subscription-links",n.note)),i}function Pc(e){let{session:t,form:n,ctx:i}=e,{ai:o}=t,a=eo(ft),r="path",u=[],d=null,b=new Set,k=Ya(o)?wc(o):Ac(),h=!1,w=null,E=null,S=null,$=!1,N=!1,O=!1,F=c("div","ai-wizard"),j=c("div","ai-wizard-column");F.append(j);function se(){if(!Ya(o)||O)return;w?.abort();let s=new AbortController;w=s,h=!0,r==="local"&&e.announce(fn),le(),dr(o,s.signal).then(l=>{O||s.signal.aborted||(w=null,h=!1,k=l,le(),r==="local"&&e.announce(ae()))})}function le(){(r==="path"||r==="local")&&K()}function he(){return k?.probes?ao(k.probes,t.draft.engines):null}function ae(){let s=he();if(!s)return"Could not look for local AI servers.";let l=s.filter(g=>g.running);return l.length===0?ri:`Running on this computer: ${l.map(g=>ee(g.presetId)).join(", ")}.`}let X=s=>ft.find(l=>l.id===s),ee=s=>X(s)?.name??s,Ee=()=>k?.hardware?.platform==="darwin"?"Mac":"computer";function Ne(s){let l=s.family==="local"?he()?.find(x=>x.presetId===s.id&&x.alreadyAdded&&x.engineId):void 0,g=l?.engineId&&t.getEngine(l.engineId)?t.getEngine(l.engineId):s.family!=="local"?t.draft.engines.find(x=>Bt(x)?.id===s.id):void 0;if(g)return{id:g.id,isNew:!1};let y=io(s,t.draft.engines.map(x=>x.id));return t.addEngine(y),b.add(y.id),{id:y.id,isNew:!0}}function ge(s){d&&d!==s&&b.has(d)&&(t.deleteEngine(d),n.forget(d),b.delete(d)),d=s,S=null}let $e=()=>d?t.getEngine(d):void 0;function ie(s){if(!s||!s.enabled||!xt(s.kind))return null;let l=x=>!!x&&x.enabled&&!x.missing&&x.capabilities.chat,g=ii(t.draft,s.id),y=g?s.models.find(x=>x.id===g):void 0;return l(y)?y.id:s.models.find(l)?.id??null}function Ie(s){return!t.draft.allowCloud&&nn(s,t.draft.localNetworks).locality==="cloud"}function Le(s,l){let g=un(t.draft,s,l);t.draft={...g,routing:{...g.routing,default:{engineId:s,modelId:l}}}}function Re(s){s.family!=="local"&&!t.draft.allowCloud&&e.setAllowCloud(!0)}function Me(s,l={}){l.push!==!1&&s!==r&&u.push(r),r=s,K({fresh:!0}),e.onStep(r)}async function P(s){if(E)return;Re(s);let{id:l}=Ne(s);ge(l);let g=s.family==="host"?"copilot":"local";if(!o.discoverModels){Me(g);return}E=s.id,K(),e.announce(`Setting up ${s.name}\u2026`);try{await t.ensureSaved(l);let y=await o.discoverModels(l);if(O||d!==l)return;if(y&&typeof y=="object"&&(t.statuses.set(l,y),e.onStatuses()),!y||y.ok===!1)throw new Error(y?.error||`Could not fetch the models from ${s.name}.`);let x=t.getEngine(l);if(!x)return;t.draft=Pt(t.draft,ro(x,y,s.family));let L=t.getEngine(l),_=s.family==="local"?ci(t.draft,t.statusList(),l)?.modelId??null:or(L.models);if(!_&&s.family==="local"&&L.models.some(R=>!R.missing&&R.capabilities.chat)){E=null,Me(g),n.opened(l),e.announce(`${s.name}: pick a model to start with.`);return}if(!_)throw new Error(s.family==="host"?"Copilot lists no chat model for this account yet.":`${s.name} has no chat model loaded or downloaded yet.`);Le(l,_),E=null,Me("done")}catch(y){if(O)return;E=null,S=y instanceof Error&&y.message?y.message:`${s.name} could not be set up.`,e.announce(S),Me(g),n.opened(l)}}function q(s){Re(s);let{id:l,isNew:g}=Ne(s);ge(l);let y=s.family==="local"?"local":s.family==="host"?"copilot":"cloud";r!==y?Me(y):K();let x=n.opened(l,{isNew:g&&s.family==="cloud"});g&&s.family==="cloud"&&x&&e.focusKey(x),e.announce(s.family==="cloud"?`${s.name}: paste your API key.`:`${s.name}: fetching its models.`)}function te(){let s=$e(),l=ie(s);!s||!l||Ie(s)||(Le(s.id,l),Me("done"))}function K(s={}){O||(rt(j,()=>{j.replaceChildren(...ke())}),F.dataset.step=r,s.fresh&&(F.scrollTop=0,j.querySelector(".ai-wizard-title")?.focus({preventScroll:!0})))}function ke(){switch(r){case"path":return pe();case"cloud":return Tt();case"local":return mt();case"copilot":return yt();case"done":return f()}}function Z(s,l){let g=c("div","ai-wizard-head"),y=c("h3","ai-wizard-title",s);return y.id=ye("ai-wizard-title"),y.tabIndex=-1,F.setAttribute("aria-labelledby",y.id),g.append(y),l&&g.append(c("p","ai-wizard-lede",l)),g}function Oe(s){let l=me(`ai-wizard-option${s.lead?" is-lead":""}`,"",{fk:s.fk});s.state&&(l.dataset.state=s.state);let g=c("span","ai-wizard-option-glyph");g.innerHTML=s.glyph;let y=c("span","ai-wizard-option-text"),x=c("span","ai-wizard-option-name");if(s.state==="running"){let _=c("span","ai-card-dot");_.setAttribute("aria-hidden","true"),x.append(_)}x.append(c("span","",s.name)),y.append(x,c("span","ai-wizard-option-caption",s.caption));let L=c("span","ai-wizard-option-chevron");return s.state==="busy"?(L.append(c("span","ai-spinner")),l.setAttribute("aria-busy","true")):L.innerHTML=xe.chevron,L.setAttribute("aria-hidden","true"),l.append(g,y,L),l.addEventListener("click",()=>{E||s.onClick()}),l}function De(){return`<span class="ai-glyph ai-wizard-glyph-cloud" aria-hidden="true">${xe.cloud}</span>`}function pe(){let s=[Z("How should MikeDown reach a model?","You can change it later in AI Engines.")];if(!k){let L=c("div","ai-wizard-scanning");return L.setAttribute("role","status"),L.append(c("span","ai-spinner"),c("span","","Checking this machine\u2026")),s.push(L),s}let l=k.recommendation,g=k.vscodeLm?.available?a.host.find(L=>L.kind==="vscode-lm"):void 0,y=l.path==="runningLocal"&&l.running?X(l.running.presetId):void 0,x=c("div","ai-wizard-options");if(y&&l.running){let L=l.running.models;x.append(Oe({fk:`wiz:use:${y.id}`,glyph:Ut(y.kind),name:`${y.name} is running on this ${Ee()}${L!==void 0?` \xB7 ${L} ${L===1?"model":"models"}`:""}`,caption:E===y.id?`Setting up ${y.name}\u2026`:"Use it. Text stays on this machine.",lead:!0,state:E===y.id?"busy":"running",onClick:()=>{P(y)}}))}if(g&&x.append(Oe({fk:"wiz:use:copilot",glyph:Ut(g.kind),name:"Use GitHub Copilot, no key needed",caption:E===g.id?"Fetching Copilot\u2019s models\u2026":`Through your Copilot plan in VS Code. ${Gt.permission}`,lead:l.path==="vscodeLm",...E===g.id?{state:"busy"}:{},onClick:()=>{P(g)}})),x.childElementCount>0?(x.append(Oe({fk:"wiz:cloud",glyph:De(),name:"Connect a cloud provider",caption:"Paste an API key from Anthropic, OpenAI or another provider.",onClick:()=>Me("cloud")})),s.push(x)):s.push(Pe()),s.push(We()),h){let L=c("div","ai-wizard-quiet","Checking this machine again\u2026");L.setAttribute("role","status"),s.push(L)}return s}function Pe(s={}){let l=c("section","ai-wizard-group"),g=ye("ai-wizard-group");if(s.title!==!1){let R=c("div","ai-cards-heading");R.id=g,R.innerHTML=xe.cloud,R.append(c("span","","Connect a cloud provider")),l.append(R,c("div","ai-cards-explainer","Paste a key from the provider. It bills your account for what you use.")),l.setAttribute("aria-labelledby",g)}let y=c("div","ai-cloud-access ai-wizard-cloud-access");y.append(c("p","ai-wizard-cloud-line",o.requestCloudConsent?"Choosing a provider turns on cloud engines; MikeDown still asks before the first request in each workspace.":"Choosing a provider turns on cloud engines."),Sn(null,{collapsed:"What this means",open:N,onToggle:R=>{N=R},openLink:i.openLink,...o.requestCloudConsent?{}:{extra:tn(!1)},className:"ai-cloud-access-privacy"})),l.append(y);let x=c("div","ai-cards-grid");x.setAttribute("role","group"),x.setAttribute("aria-label","Cloud providers");let L=$e(),_=L?Bt(L)?.id:void 0;for(let R of a.cloud){let U=me("ai-card","",{fk:`wiz:card:${R.id}`});U.innerHTML=Ut(R.kind);let D=c("span","ai-card-text");D.append(c("span","ai-card-name",R.name),c("span","ai-card-caption",R.caption)),U.append(D);let Y=r==="cloud"&&_===R.id;U.setAttribute("aria-pressed",String(Y)),U.classList.toggle("is-selected",Y),U.addEventListener("click",()=>q(R)),x.append(U)}return l.append(x),l}function We(){let s=c("div","ai-wizard-advanced"),l=ye("ai-wizard-advanced"),g=me("ai-disclosure","Advanced: run models on this machine",{html:xe.chevron,fk:"wiz:advanced"});g.setAttribute("aria-expanded",String($)),g.setAttribute("aria-controls",l),g.addEventListener("click",()=>{$=!$,K()});let y=c("div","ai-wizard-advanced-panel");y.id=l,y.hidden=!$;let x=k?.recommendation.hardwareLine;x&&y.append(c("p","ai-wizard-hardware",x)),y.append(c("p","ai-wizard-quiet","Your own model server, such as LM Studio or Ollama. Text never leaves this machine."));let L=me("settings-btn","Choose a local server",{fk:"wiz:local"});return L.addEventListener("click",()=>Me("local")),y.append(L),s.append(g,y),s}function lt(){let s=$e();if(!s)return null;let l=c("div","ai-wizard-form");return S&&l.append(st("error",S,"ai-wizard-error")),l.append(gt(s.id)),l}function gt(s){return n.build(s,{privacy:r!=="cloud",setup:!0})}function ze(s){let l=c("div","ai-wizard-footer"),g=c("span","ai-wizard-hint",s.ready?"":s.hint??"");g.id=ye("ai-wizard-hint");let y=me("settings-btn settings-btn--primary ai-wizard-next",s.label,{fk:s.fk});return s.ready||(y.setAttribute("aria-disabled","true"),y.setAttribute("aria-describedby",g.id)),y.addEventListener("click",()=>{s.ready?s.onClick():s.hint&&e.announce(s.hint)}),l.append(g,y),l}function kt(){let s=$e(),l=s?Ie(s):!1,g=!!s&&!!ie(s)&&!l,y=s?l?"Turn on Allow cloud engines to use it.":r==="cloud"&&!t.hasKey(s.id)?"Paste your API key; the models appear, then Continue.":"Pick a chat model to continue.":r==="local"?"Pick a server to continue.":"Pick a provider to continue.";return ze({label:"Continue",fk:"wiz:continue",ready:g,hint:y,onClick:te})}function Tt(){let s=[Z("Connect a cloud provider","Pick a provider and paste an API key. Text you ask about is sent to that provider."),Pe({title:!1})],l=lt();return l&&s.push(l),s.push(kt()),s}function mt(){let s=k?.recommendation.hardwareLine||"Your own model server, on this computer or your network. Text never leaves it.",l=[Z("Run models on this machine",s)],g=c("div","ai-wizard-servers");g.setAttribute("role","group"),g.setAttribute("aria-label","Local servers");let y=he(),x=new Map(y?.map(D=>[D.presetId,D])??[]),L=y?[...y.map(D=>X(D.presetId)).filter(D=>!!D&&D.family==="local"),...a.local.filter(D=>!x.has(D.id))]:a.local;for(let D of L)g.append(ct(D,x.get(D.id)));l.push(g);let _=c("div","ai-cards-detect"),R=c("span","ai-cards-detect-text",h?fn:y&&!y.some(D=>D.running)?ri:"");if(_.append(R),o.detectLocalServers){let D=me("ai-link-btn ai-cards-again","Look again",{fk:"wiz:look-again"});h&&D.setAttribute("aria-disabled","true"),D.addEventListener("click",()=>{h||se()}),_.append(D)}l.push(_);let U=lt();return U&&l.push(U),l.push(kt()),l}function ct(s,l){let g=c("div","ai-wizard-server"),y=me("ai-card","",{fk:`wiz:card:${s.id}`});y.innerHTML=Ut(s.kind);let x=c("span","ai-card-text");x.append(c("span","ai-card-name",s.name),c("span","ai-card-caption",s.caption));let L=l?l.alreadyAdded&&l.engineId&&t.getEngine(l.engineId)?"added":l.running?"running":"stopped":null;if(L){y.dataset.state=L;let U=c("span","ai-card-state");if(L==="running"){let Y=c("span","ai-card-dot");Y.setAttribute("aria-hidden","true"),U.append(Y)}let D=l?.models!==void 0?` \xB7 ${l.models} ${l.models===1?"model":"models"}`:"";U.append(c("span","",L==="added"?"Added":L==="running"?`Running${D}`:"Not running")),x.append(U)}y.append(x);let _=$e(),R=!!_&&(_.id===l?.engineId||b.has(_.id)&&Bt(_)?.id===s.id);if(y.setAttribute("aria-pressed",String(R)),y.classList.toggle("is-selected",R),y.addEventListener("click",()=>q(s)),g.append(y),L==="stopped"&&s.installUrl){let U=c("div","ai-wizard-install");U.append(fi(`Install ${s.name}`,s.installUrl,i.openLink,"ai-wizard-link"),c("span","",", then come back and choose Look again.")),g.append(U)}return g}function yt(){let s=[Z("GitHub Copilot",`Copilot\u2019s models through your Copilot plan in VS Code. No key needed. ${Gt.permission}`)],l=lt();return l&&s.push(l),s.push(kt()),s}function f(){let s=$e(),l=ie(s);if(!s||!l)return[Z("Set up AI","Something changed. Go back and choose again.")];let g=nn(s,t.draft.localNetworks).locality==="local",y=s.models.find(be=>be.id===l),x=[],L=c("span","ai-wizard-done-icon");L.innerHTML=xe.check,L.setAttribute("aria-hidden","true");let _=Z(`Ready: ${Ue(s)} \xB7 ${pt(y)} \xB7 ${g?"Local":"Cloud"}`);_.prepend(L),x.push(_);let R=s.models.filter(be=>be.enabled&&!be.missing&&be.capabilities.chat);if(R.length>1){let be=c("div","ai-wizard-model"),Ce=c("select","settings-input ai-wizard-model-select");Ce.id=ye("ai-wizard-model"),Ce.dataset.fk="wiz:model";for(let Qe of R){let Ke=c("option","",pt(Qe));Ke.value=Qe.id,Ce.append(Ke)}Ce.value=l,Ce.addEventListener("change",()=>{Le(s.id,Ce.value),K();let Qe=s.models.find(Ke=>Ke.id===Ce.value);Qe&&e.announce(`Default model: ${pt(Qe)}.`)});let _e=c("label","ai-wizard-model-label","Model");_e.htmlFor=Ce.id,be.append(_e,Ce),x.push(be)}let U=c("p","ai-wizard-privacy"),D=c("span","ai-privacy-glyph");D.innerHTML=g?xe.local:xe.cloud,U.append(D,c("span","",A(s,g))),x.push(U);let Y=c("p","ai-wizard-quiet");e.turnsOn||Y.append("Choose Done to save. ");let Q=me("ai-link-btn","Change settings in AI Engines",{fk:"wiz:open-engine"});return Q.addEventListener("click",()=>e.openEngine(s.id)),Y.append(Q),x.push(Y),x.push(ze({label:e.turnsOn?"Turn on AI":"Done",fk:"wiz:done",ready:!0,onClick:()=>e.finish()})),x}function A(s,l){return l?Mt.local:Bt(s)?.family==="host"?`${Gt.leaves} ${tn(!!o.requestCloudConsent)}`:`Text you ask about is sent over the internet to ${Qn(s)||Xt(s.baseUrl)||"the provider"}. ${tn(!!o.requestCloudConsent)}`}return K(),se(),{element:F,step:()=>r,engineId:()=>d,back(){if(E)return;let s=u.pop();if(!s){e.leave();return}r=s,S=null,K({fresh:!0}),e.onStep(r)},refresh(s,l){if(O)return;if(l.form&&s&&s===d){let y=j.querySelector(".ai-form");y&&rt(y,()=>{let x=gt(s);return y.replaceWith(x),x})}let g=j.querySelector(".ai-wizard-footer");g&&r!=="done"&&r!=="path"&&rt(g,()=>{let y=kt();return g.replaceWith(y),y})},focus(){(j.querySelector(".ai-wizard-option.is-lead")??j.querySelector(".ai-wizard-option, .ai-card, .ai-wizard-next")??j.querySelector(".ai-wizard-title"))?.focus({preventScroll:!0})},dispose(){O=!0,w?.abort(),F.remove()}}}var Uc=720;function Kc(e,t,n){let i=di(n),{ai:o}=i,a=p=>i.getEngine(p),r=null,u=yc(o),d=$(),b=!1,k=n.initial?.engineId||n.initial?.section==="routing"?"detail":"list",h=null,w=!1,E=!1,S=new Map;function $(){let p=i.draft.engines;if(n.initial?.section==="routing")return{kind:"routing"};let v=n.initial?.engineId&&p.find(C=>C.id===n.initial?.engineId);return v?{kind:"engine",id:v.id}:p[0]?{kind:"engine",id:p[0].id}:{kind:"add"}}let N=()=>d.kind==="engine"?d.id:null,O=c("div","ai-page"),F=ye("ai-page-title"),j=c("div","ai-page-header"),se=me("ai-page-back","Back",{html:xe.back,fk:"page:back"});se.addEventListener("click",()=>J());let le=c("h2","ai-page-title","AI Engines");le.id=F;let he=me("settings-btn settings-btn--primary ai-page-done","Done",{fk:"page:done"});he.addEventListener("click",()=>Be());let ae=me("settings-btn ai-page-done ai-page-skip","Skip",{fk:"page:skip",title:"Leave setup; AI stays off"});ae.addEventListener("click",()=>ve()),ae.hidden=!0;let X=c("div","ai-page-title-line"),ee=n.turnOnWhenDone?c("span","ai-page-title-note","AI turns on when you choose Done"):null,Ee=c("span","ai-wizard-steps");Ee.hidden=!0,X.append(le,ui(),Ee),ee&&X.append(ee),j.append(se,X,he,ae);let Ne=co("ai-page-disclaimer"),ge=c("div","ai-page-body"),$e=c("nav","ai-page-nav");$e.setAttribute("aria-label","Engines and tasks");let ie=c("section","ai-page-detail"),Ie=ye("ai-page-detail");ie.id=Ie,ge.append($e,ie);let Le=c("div","ai-live");Le.setAttribute("role","status"),Le.setAttribute("aria-live","polite");let Re;function Me(p){window.clearTimeout(Re),Le.textContent="",Re=window.setTimeout(()=>{Le.textContent=p},40)}let P=c("div","ai-page-confirm-host");O.append(j,Ne,ge,P,Le);let q=Cc({ai:o,getDraft:()=>i.draft,setDraft:(p,v)=>{i.draft=p,ke(r?r.engineId():N(),v)},refresh:(p,v)=>ke(p,v),statuses:i.statuses,onStatuses:()=>n.onStatuses(i.statusList()),hasKey:p=>i.hasKey(p),keySource:p=>i.keySource(p),setKey:K,ensureSaved:p=>i.ensureSaved(p),savesFirst:p=>i.savesFirst(p),announce:Me,focusKey:pe,openLink:t.openLink,keyNote:(p,v)=>v.family==="cloud"&&(r||!i.hasKey(p.id))?Dc(v,t.openLink,An(p)):null,modelSize:(p,v)=>u?Da(p,u,v):void 0}),te=Oc(t,{getDraft:()=>i.draft,setDraft:(p,v)=>{i.draft=p,v.defaultChanged?ze():f()},statusList:()=>i.statusList()});async function K(p,v){let C=a(p),H=await i.setKey(p,v);if(C){let ce=Ue(C);Me(H?`The key for ${ce} could not be ${v!==null?"stored":"cleared"}.`:v!==null?`API key stored for ${ce}.`:`API key cleared for ${ce}.`),De(p)}return H}function ke(p,v){if(r){r.refresh(p,v);return}if(v.list)ze(),R();else if(v.head){for(let C of i.draft.engines)mt(C.id);f(),R()}v.form&&p&&be(p),(v.routing||v.list)&&Oe()}let Z=!1;function Oe(){Z||(Z=!0,queueMicrotask(()=>{Z=!1,!(E||r)&&(f(),d.kind==="routing"&&te.render())}))}function De(p){mt(p),N()===p&&R()}function pe(p){Array.from(O.querySelectorAll("[data-fk]")).find(C=>C.dataset.fk===p)?.focus({preventScroll:!0})}let Pe=c("div","ai-nav-list");Pe.setAttribute("role","list"),Pe.setAttribute("aria-label","Engines");let We=c("div","ai-nav-group"),lt=c("div","ai-nav-group ai-nav-group--tools");$e.append(We,lt),$e.addEventListener("keydown",s);function gt(p,v){let C=me("ai-nav-btn","",{fk:p});return C.setAttribute("aria-controls",Ie),v&&C.setAttribute("aria-current","true"),C}function ze(){r||rt($e,()=>{We.replaceChildren();let p=c("div","ai-nav-heading","Engines");if(p.setAttribute("aria-hidden","true"),We.append(p),Pe.replaceChildren(),i.draft.engines.length===0)We.append(c("div","ai-nav-empty","No engines yet"));else{for(let v of i.draft.engines)Pe.append(kt(v));We.append(Pe)}lt.replaceChildren(yt(),A())})}function kt(p){let v=c("div","ai-nav-item");return v.setAttribute("role","listitem"),v.dataset.engineId=p.id,Tt(v,p),v}function Tt(p,v){p.replaceChildren();let C=d.kind==="engine"&&d.id===v.id,H=Ue(v);p.classList.toggle("is-selected",C),p.classList.toggle("is-disabled",!v.enabled);let ce=gt(`nav:eng:${v.id}`,C);ce.setAttribute("aria-label",`${H}, ${Tn(v.kind)}`),ce.title=H,ce.innerHTML=Ut(v.kind);let fe=c("span","ai-nav-text"),He=c("span","ai-nav-name-line");if(He.append(c("span","ai-nav-name",H)),i.draft.routing.default?.engineId===v.id){let B=c("span","ai-nav-star");B.innerHTML=xe.starOn,B.title="Default engine",He.append(B)}let T=c("span","ai-nav-sub-line");T.append(...li(v,i.draft).slice(0,1),c("span","ai-nav-sub",oi(v.baseUrl)||"no address")),fe.append(He,T),ce.append(fe,si(i.statuses.get(v.id),q.busy(v.id),{compact:!0})),ce.addEventListener("click",()=>y({kind:"engine",id:v.id}));let I=pn(v.enabled,`Enable ${H}`,`nav:eng:${v.id}:enabled`);I.addEventListener("change",()=>{i.updateEngine(v.id,{enabled:I.checked}),ke(v.id,{list:!0,form:!0,routing:!0})}),p.append(ce,I)}function mt(p){if(r)return;let v=a(p),C=Array.from(Pe.querySelectorAll(".ai-nav-item")).find(H=>H.dataset.engineId===p);!v||!C||rt(C,()=>Tt(C,v))}function ct(){let p=i.draft.routing.default;return p?Kt(i.draft,p):"No default model"}function yt(){let p=gt("nav:routing",d.kind==="routing");p.classList.add("ai-nav-btn--routing");let v=c("span","ai-nav-icon");v.innerHTML=xe.routing;let C=c("span","ai-nav-text");return C.append(c("span","ai-nav-name","Tasks"),c("span","ai-nav-sub",ct())),p.append(v,C),p.addEventListener("click",()=>y({kind:"routing"})),p}function f(){let p=lt.querySelector(".ai-nav-btn--routing .ai-nav-sub");p&&(p.textContent=ct())}function A(){let p=gt("nav:add",d.kind==="add");p.classList.add("ai-nav-btn--add");let v=c("span","ai-nav-icon");return v.innerHTML=xe.plus,p.append(v,c("span","ai-nav-name","Add engine")),p.addEventListener("click",()=>y({kind:"add"})),p}function s(p){if(!["ArrowDown","ArrowUp","Home","End"].includes(p.key))return;let v=Array.from($e.querySelectorAll(".ai-nav-btn")),C=v.indexOf(p.target);if(C<0)return;p.preventDefault();let H=p.key==="Home"?0:p.key==="End"?v.length-1:Math.max(0,Math.min(v.length-1,C+(p.key==="ArrowDown"?1:-1)));v[H]?.focus()}let l=c("div","ai-detail-head"),g=c("div","ai-detail-body");ie.append(l,g);function y(p,v={}){let C=p.kind==="engine"&&d.kind==="engine"&&d.id===p.id;d=p,h=null,p.kind==="engine"&&S.delete(p.id),b&&(k="detail"),Ze(),ze(),(!C||v.isNew)&&L();let H=null;p.kind==="engine"&&(!C||v.isNew)&&(H=q.opened(p.id,v)),v.isNew&&H?(pe(H),H.endsWith(":url")&&O.querySelector(`[data-fk="${H}"]`)?.select()):(v.isNew||b)&&x(),ie.scrollTop=0}function x(){l.querySelector(".ai-detail-title")?.focus({preventScroll:!0})}function L(){if(!r)if(R(),g.replaceChildren(),ie.dataset.kind=d.kind,d.kind==="engine"){let p=a(d.id);p&&g.append(q.build(p.id))}else d.kind==="routing"?(te.render(),g.append(te.element)):(g.append(Ye()),ht&&!Qe&&we(),o.detectHostEngines&&at===null&&Ge())}function _(p){let v=c("h3","ai-detail-title",p);return v.id=ye("ai-detail-title"),v.tabIndex=-1,ie.setAttribute("aria-labelledby",v.id),v}function R(){r||rt(l,()=>{if(l.replaceChildren(),d.kind==="routing"){let v=c("span","ai-detail-icon");v.innerHTML=xe.routing;let C=c("div","ai-detail-main");C.append(_("Tasks"),c("div","ai-detail-sub","Which model does what. Tasks on Default use the default model.")),l.append(v,C);return}if(d.kind==="add"){let v=c("span","ai-detail-icon");v.innerHTML=xe.plus;let C=c("div","ai-detail-main"),H=i.draft.engines.length===0;C.append(_(H?"No engines yet":"Add an engine"),c("div","ai-detail-sub",`Two ways to connect: paste a cloud API key, or run models on your own machine.${i.draft.enabled?"":" Nothing is sent until AI is on."}`)),l.append(v,C);return}let p=a(d.id);p&&U(p)})}function U(p){let v=Ue(p),C=c("span","ai-detail-glyph");C.innerHTML=Ut(p.kind);let H=c("div","ai-detail-main"),ce=c("div","ai-detail-title-line");ce.append(_(v),...li(p,i.draft,{blocked:!1}));let fe=p.models.filter(V=>!V.missing).length,He=p.models.filter(V=>!V.missing&&V.enabled).length,m=[Tn(p.kind),oi(p.baseUrl)||"no address"];p.models.length>0&&m.push(He===fe?`${fe} ${fe===1?"model":"models"}`:`${He} of ${fe} models`),H.append(ce,c("div","ai-detail-sub",m.join(" \xB7 ")));let T=i.draft.routing.default?.engineId===p.id,I;T?(I=c("span","ai-default-badge"),I.innerHTML=xe.starOn,I.append(c("span","ai-btn-text","Default")),I.title=`Default: ${Kt(i.draft,i.draft.routing.default)}. To change it, choose Use by default on another engine, or pick the default model under Tasks.`,I.setAttribute("aria-label",`${v} is the default engine`),I.dataset.fk=`eng:${p.id}:star`,I.tabIndex=-1):(I=me("settings-btn ai-default-btn","Use by default",{html:xe.starOff,title:"Use this engine by default",fk:`eng:${p.id}:star`}),I.addEventListener("click",()=>M(p.id)));let B=me("ai-icon-btn ai-delete-btn","",{html:xe.trash,ariaLabel:`Delete ${v}`,title:"Delete engine",fk:`eng:${p.id}:delete`});B.addEventListener("click",()=>{h=p.id,R(),pe(`eng:${p.id}:confirm-cancel`)});let G=c("div","ai-detail-actions");G.append(si(i.statuses.get(p.id),q.busy(p.id)),I,B);let oe=c("div","ai-detail-top");oe.append(C,H,G),l.append(oe);let W=ql(p,i.draft,i.hasKey(p.id)).filter(V=>!["cloudBlocked","badUrl","localityMismatch","noKey"].includes(V.code)),ue=S.get(p.id);if(W.length>0||ue){let V=c("div","ai-engine-issues");for(let re of W)V.append(st(re.level,re.text));ue&&V.append(st(ue.level,ue.text,"ai-result")),l.append(V)}D(p)&&l.append(Y(p)),h===p.id&&l.append(Ce(p))}function D(p){return!i.draft.allowCloud&&nn(p,i.draft.localNetworks).locality==="cloud"}function Y(p){let v=c("div","ai-cloud-off");v.append(st("info",`Cloud engines are off, so nothing is sent to ${Ue(p)} yet.`));let C=me("settings-btn ai-cloud-off-btn","Turn on cloud engines",{fk:`eng:${p.id}:allow-cloud`});return C.addEventListener("click",()=>{Q(!0),S.set(p.id,{level:"info",text:"Cloud engines are on. Choose Done to save."}),R(),pe(`eng:${p.id}:star`)}),v.append(C),v}function Q(p){if(i.draft.allowCloud===p)return;i.draft={...i.draft,allowCloud:p},ze();let v=r?r.engineId():N();v&&be(v),Oe(),Me(p?"Cloud engines turned on. Choose Done to save.":"Cloud engines turned off. Choose Done to save.")}function be(p){if(r){r.refresh(p,{form:!0});return}if(N()!==p)return;let v=g.querySelector(".ai-form");v&&rt(v,()=>{let C=q.build(p);return v.replaceWith(C),C})}function Ce(p){let v=c("div","ai-confirm");v.setAttribute("role","group");let C=Ue(p);v.setAttribute("aria-label",`Delete ${C}?`);let H=c("span","ai-confirm-text",`Delete ${C}? Routes to it are cleared${o.setSecret?" and its stored API key is removed":""} when you choose Done.`),ce=me("settings-btn ai-btn--danger","Delete",{fk:`eng:${p.id}:confirm-delete`}),fe=me("settings-btn","Cancel",{fk:`eng:${p.id}:confirm-cancel`});return ce.addEventListener("click",()=>Jt(p.id)),fe.addEventListener("click",()=>{h=null,R(),pe(`eng:${p.id}:delete`)}),v.addEventListener("keydown",He=>{He.key==="Escape"&&(He.preventDefault(),He.stopPropagation(),fe.click())}),v.append(H,ce,fe),v}let _e=null,Qe=!1,Ke=!1,dt=null,ht=typeof o.detectLocalServers=="function";function we(){if(!ht||E)return;dt?.abort();let p=new AbortController;dt=p,Qe=!0,Ke=!0,Xe(),Me(fn),so(o,p.signal).then(v=>{E||p.signal.aborted||(Ke=!1,dt=null,_e=v,Xe(),Me(ne(Fe())))})}function Fe(){return _e?ao(_e,i.draft.engines):null}function ne(p){if(!p)return"Could not look for local AI servers.";let v=p.filter(C=>C.running);return v.length===0?ri:`Running on this computer: ${v.map(C=>`${de(C.presetId)}${C.models!==void 0?`, ${qe(C.models)}`:""}${C.alreadyAdded?", added":""}`).join("; ")}.`}function de(p){return ft.find(v=>v.id===p)?.name??p}function qe(p){return`${p} ${p===1?"model":"models"}`}let at=null;function Ge(){at=!1,cr(o).then(p=>{E||!p?.available||(at=!0,d.kind==="add"&&!r&&rt(g,()=>{g.replaceChildren(Ye())}))})}function Ye(){let p=eo(ft),v=c("div","ai-cards"),C=at?[zo,...Ki]:[...Ki];for(let H of C){let ce=p[H.family];if(ce.length===0)continue;let fe=c("section","ai-cards-group");fe.dataset.family=H.family;let He=ye("ai-cards-heading"),m=c("div","ai-cards-heading");m.id=He,m.innerHTML=H.family==="local"?xe.local:xe.cloud,m.append(c("span","",H.label)),fe.setAttribute("aria-labelledby",He);let T=c("div","ai-cards-grid");if(T.setAttribute("role","group"),T.setAttribute("aria-labelledby",He),fe.append(m,c("div","ai-cards-explainer",H.explainer)),H.family==="local")fe.append(T),Yt(T,ce),ht&&fe.append(Vt());else if(H.family==="host"){fe.append(T);for(let I of ce)T.append(Ot(I))}else{fe.append(Ft(ce),T);for(let I of ce)T.append(Ot(I))}v.append(fe)}return ut(v),v}function ut(p){let C=!!Fe()?.some(H=>H.running&&!H.alreadyAdded)?["host","local","cloud"]:["host","cloud","local"];for(let H of C){let ce=p.querySelector(`:scope > .ai-cards-group[data-family="${H}"]`);ce&&p.append(ce)}}let bt=!1;function Ft(p){return $c({allowed:i.draft.allowCloud,onChange:v=>Q(v),presets:p,hostAsks:!!o.requestCloudConsent,open:bt,onToggle:v=>{bt=v},openLink:t.openLink,fk:"cards:allow-cloud"})}function Yt(p,v){p.replaceChildren();let C=Fe(),H=new Map(C?.map(fe=>[fe.presetId,fe])??[]),ce=C?[...C.map(fe=>v.find(He=>He.id===fe.presetId)).filter(fe=>!!fe),...v.filter(fe=>!H.has(fe.id))]:v;for(let fe of ce)p.append(Ot(fe,H.get(fe.id)))}function Ot(p,v){let C=me("ai-card","",{fk:`card:${p.id}`,ariaLabel:`Add ${p.name}`});C.innerHTML=Ut(p.kind);let H=c("span","ai-card-text");H.append(c("span","ai-card-name",p.name),c("span","ai-card-caption",p.caption)),C.append(H),C.title=p.caption;let ce=p.family==="cloud"?i.draft.engines.find(He=>Bt(He)?.id===p.id):void 0,fe=ce?ce.id:v?.alreadyAdded&&v.engineId&&a(v.engineId)?v.engineId:null;if(ce)C.dataset.state="added",H.append(c("span","ai-card-state","Added")),C.setAttribute("aria-label",`${p.name}, added. Open it`),C.title=`${p.name} is already set up. Open it.`;else if(v){let He=fe?"added":v.running?"running":"stopped";C.dataset.state=He;let m=He==="added"?"Added":He==="running"?`Running${v.models!==void 0?` \xB7 ${qe(v.models)}`:""}`:"Not running",T=c("span","ai-card-state");if(He==="running"){let I=c("span","ai-card-dot");I.setAttribute("aria-hidden","true"),T.append(I)}T.append(c("span","",m)),H.append(T),C.setAttribute("aria-label",fe?`${p.name}, added. Open it`:`Add ${p.name}, ${m.replace(" \xB7 ",", ").toLowerCase()}`),fe&&(C.title=`${p.name} is already set up. Open it.`)}return C.addEventListener("click",()=>{fe&&a(fe)?y({kind:"engine",id:fe}):St(p)}),C}function Vt(){let p=c("div","ai-cards-detect"),v=c("span","ai-cards-detect-text",Ke?fn:_e&&!_e.some(H=>H.ok)?ri:""),C=me("ai-link-btn ai-cards-again","Look again",{fk:"cards:look-again"});return Ke&&C.setAttribute("aria-disabled","true"),C.addEventListener("click",()=>{Ke||we()}),p.append(v,C),p}function Xe(){let p=g.querySelector('.ai-cards-group[data-family="local"]');if(!p||d.kind!=="add")return;rt(p,()=>{let C=p.querySelector(".ai-cards-grid");C&&Yt(C,eo(ft).local);let H=p.querySelector(".ai-cards-detect");H&&H.replaceWith(Vt())});let v=p.parentElement;v&&rt(v,()=>{ut(v)})}function St(p){let v=io(p,i.draft.engines.map(C=>C.id));i.addEngine(v),y({kind:"engine",id:v.id},{isNew:!0}),Oe(),Me(p.family==="cloud"?`Added ${v.name}. Paste your API key.`:p.family==="host"?`Added ${v.name}. Fetching its models.`:`Added ${v.name}. Check the address; models are fetched from it.`)}function Jt(p){let v=a(p);if(!v)return;let C=i.draft.engines.findIndex(ce=>ce.id===p);i.deleteEngine(p),S.delete(p),q.forget(p),h=null;let H=i.draft.engines[Math.min(C,i.draft.engines.length-1)];d=H?{kind:"engine",id:H.id}:{kind:"add"},ze(),L(),H&&q.opened(H.id),Me(`Deleted ${Ue(v)}. Choose Done to apply.`),pe(H?`nav:eng:${H.id}`:"nav:add")}function M(p){let v=a(p);if(!v)return;let C=Ue(v),H=i.draft;if(H.routing.default?.engineId===p)return;let ce=ci(H,i.statusList(),p);if(!ce){S.set(p,{level:"info",text:"No model here can be the default yet. Pick or add a chat model first."}),Me(`${C} has no chat model to make the default yet.`),R();return}i.draft={...H,routing:{...H.routing,default:ce}},Me(`Default model: ${Kt(i.draft,ce)}.`),S.delete(p),ze(),R(),be(p),pe(`eng:${p}:star`)}function J(){if(w){Je();return}if(r){r.back();return}if(b&&k==="detail"){k="list",Ze(),Ae();return}if(i.dirty()){et();return}Te()}function ve(){i.dirty()?et():Te()}function Te(){E||(E=!0,i.discard(),n.onCancel())}function Be(){if(E)return;let p=lc(i.draft);if(p){Ve(p.id);return}E=!0;let v=i.collect(),C=i.commit();n.turnOnWhenDone&&!C.enabled&&Vl(C)&&(v["ai.enabled"]=!0,C.enabled=!0),n.onDone(v,C)}function Ve(p){let v=a(p);if(!v)return;q.requirePick(p),r?on(p):d.kind!=="engine"||d.id!==p?(d={kind:"engine",id:p},k="detail",Ze(),ze(),L()):be(p),Me(`Pick at least one model for ${Ue(v)} before you choose Done.`),Array.from(O.querySelectorAll("[data-fk]")).find(H=>H.dataset.fk===`eng:${p}:pick`||H.dataset.fk===`eng:${p}:models`)?.focus({preventScroll:!1})}function et(){w=!0;let p=c("div","ai-page-confirm-scrim"),v=c("div","ai-page-confirm");v.setAttribute("role","alertdialog");let C=ye("ai-discard-title"),H=ye("ai-discard-text");v.setAttribute("aria-labelledby",C),v.setAttribute("aria-describedby",H);let ce=c("div","ai-page-confirm-title","Discard changes?");ce.id=C;let fe=c("div","ai-page-confirm-text","Your changes to engines and tasks have not been saved. Engines added here and their keys are removed.");fe.id=H;let He=me("settings-btn","Keep editing",{fk:"page:keep"});He.addEventListener("click",()=>Je());let m=me("settings-btn ai-btn--danger","Discard",{fk:"page:discard"});m.addEventListener("click",()=>Te());let T=c("div","ai-page-confirm-actions");T.append(He,m),v.append(ce,fe,T),p.append(v),P.replaceChildren(p),j.inert=!0,ge.inert=!0,r&&(r.element.inert=!0),He.focus()}function Je(){w=!1,P.replaceChildren(),j.inert=!1,ge.inert=!1,r&&(r.element.inert=!1),se.focus()}O.addEventListener("keydown",p=>{p.key!=="Escape"||p.defaultPrevented||(p.preventDefault(),p.stopPropagation(),J())});function Ze(){O.classList.toggle("is-narrow",b),O.dataset.view=b?k:"both",se.setAttribute("aria-label",b&&k==="detail"?"Back to the list":"Back")}function tt(p){let v=p>0&&p<Uc;v!==b&&(b=v,Ze())}function Ae(){let p=d.kind==="engine"?`nav:eng:${d.id}`:d.kind==="routing"?"nav:routing":"nav:add";pe(p)}let Se=null;typeof ResizeObserver=="function"&&(Se=new ResizeObserver(p=>{let v=p[p.length-1];v&&tt(v.contentRect.width)}),Se.observe(e));let Nt=n.subscribeStatuses?.(p=>{if(!E){for(let v of p)q.busy(v.engineId)||i.statuses.set(v.engineId,v);for(let v of i.draft.engines)mt(v.id);R(),Oe(),r?.refresh(null,{})}});function Rt(){let p=Pc({session:i,form:q,ctx:t,announce:Me,focusKey:pe,setAllowCloud:Q,onStatuses:()=>n.onStatuses(i.statusList()),onStep:v=>wt(v),finish:()=>Be(),leave:ve,openEngine:v=>on(v),turnsOn:!!n.turnOnWhenDone});r=p,O.classList.add("ai-page--wizard"),Ne.hidden=!0,ge.hidden=!0,O.insertBefore(p.element,ge),wt(p.step())}function wt(p){let v=Nc(p);le.textContent="Set up AI",Ee.hidden=!1,Ee.replaceChildren(),Ee.setAttribute("role","img"),Ee.setAttribute("aria-label",`Step ${v} of ${Qi}`);for(let C=1;C<=Qi;C++){let H=c("span",`ai-wizard-dot${C===v?" is-current":C<v?" is-done":""}`);Ee.append(H)}Ee.append(c("span","ai-wizard-steps-text",`${v} of ${Qi}`)),ee&&(ee.hidden=!0),he.hidden=!0,ae.hidden=p==="done",se.setAttribute("aria-label",v===1?"Back":"Back to the previous step")}function on(p){let v=r;v&&(r=null,v.dispose(),O.classList.remove("ai-page--wizard"),Ne.hidden=!1,ge.hidden=!1,le.textContent="AI Engines",Ee.hidden=!0,ee&&(ee.hidden=!1),he.hidden=!1,ae.hidden=!0,d=a(p)?{kind:"engine",id:p}:$(),k="detail",Ze(),ze(),L(),d.kind==="engine"&&q.opened(d.id),b?x():Ae())}return e.replaceChildren(O),tt(e.getBoundingClientRect().width),Ze(),n.initial?.section==="wizard"&&i.tier===2?Rt():(ze(),L(),d.kind==="engine"&&q.opened(d.id)),o.hardwareInfo&&!u&&lr(o).then(p=>{if(E||!p)return;u=p;let v=r?r.engineId():N();v&&be(v)}),i.tier===2&&i.refreshStatuses().then(p=>{if(!(!p||E)){for(let v of i.draft.engines)mt(v.id);R(),Oe()}}),{dispose(){E||(E=!0,i.discard()),E=!0,dt?.abort(),r?.dispose(),window.clearTimeout(Re),Nt?.(),Se?.disconnect(),q.dispose(),e.replaceChildren()},focus(){w?pe("page:keep"):r?r.focus():b&&k==="detail"?x():!b&&d.kind==="routing"?pe("route:default"):!b&&d.kind==="add"&&i.draft.engines.length===0?g.querySelector(".ai-card")?.focus({preventScroll:!0}):Ae()}}}var Sr="mikedown.ai.recentLanguages",$r="mikedown.ai.audience",go="mikedown.ai.thinking",Ir=3,Fc=60,Hc=["English","Spanish","French","German","Portuguese","Italian","Dutch","Japanese","Chinese (Simplified)","Korean","Arabic","Hindi"],vo=(e,t)=>e.toLocaleLowerCase()===t.toLocaleLowerCase();function Lr(e){return e.replace(/\s+/g," ").trim().slice(0,Fc)}function Mr(){try{let e=localStorage.getItem(Sr);if(!e)return[];let t=JSON.parse(e);if(!Array.isArray(t))return[];let n=[];for(let i of t){if(typeof i!="string")continue;let o=Lr(i);if(o&&!n.some(a=>vo(a,o))&&n.push(o),n.length>=Ir)break}return n}catch{return[]}}function jc(e){let t=Lr(e);if(t)try{let n=[t,...Mr().filter(i=>!vo(i,t))].slice(0,Ir);localStorage.setItem(Sr,JSON.stringify(n))}catch{}}function Bc(e=Mr()){return{recents:e,languages:Hc.filter(t=>!e.some(n=>vo(n,t)))}}function zc(){try{let e=localStorage.getItem($r);return e&&dn(e)?e:null}catch{return null}}function qc(e){if(dn(e))try{localStorage.setItem($r,e)}catch{}}var Gc=["off","low","medium","high"];function Wc(){try{let e=localStorage.getItem(go);return e&&Gc.includes(e)?e:null}catch{return null}}function Yc(e){try{e?localStorage.setItem(go,e):localStorage.removeItem(go)}catch{}}function uo(e){return Hi(e,Wc())}function Wd(e,t){let n=di(t),{tier:i}=n,o=i===2&&!!t.openEnginesPage,a=c("div","ai-live");a.setAttribute("role","status"),a.setAttribute("aria-live","polite");let r;function u(P){window.clearTimeout(r),a.textContent="",r=window.setTimeout(()=>{a.textContent=P},40)}let d=[],b=c("div","ai-experimental-intro"),k=c("div","ai-experimental-head");k.append(c("span","ai-experimental-title","AI features"),ui()),b.append(k,co()),d.push(b);let h=e.makeCheckboxRow("Enable AI features",i===2?"Writing help from engines you choose. While this is off, nothing is sent anywhere.":"Writing help from the AI service this app provides. While this is off, nothing is sent anywhere.",n.draft.enabled);h.row.classList.add("ai-master"),h.input.dataset.fk="ai-enabled",h.input.addEventListener("change",()=>{n.draft={...n.draft,enabled:h.input.checked}});let w=e.makeCheckboxRow("Show AI button on the toolbar","Opens the AI actions. While AI is off, it offers to turn AI on and set it up.",n.draft.showToolbarButton);w.input.dataset.fk="ai-toolbar-button",w.input.addEventListener("change",()=>{n.draft={...n.draft,showToolbarButton:w.input.checked}});let E=e.makeCheckboxRow("Allow cloud engines","Lets tasks use engines outside this network, such as Anthropic or OpenAI. Local engines never need it.",n.draft.allowCloud);E.input.dataset.fk="ai-allow-cloud",E.row.append(Sn(n.draft.engines.map(P=>({policy:An(P)})),{openLink:e.openLink,extra:tn(!!n.ai.requestCloudConsent),className:"ai-row-note"})),E.input.addEventListener("change",()=>{n.draft={...n.draft,allowCloud:E.input.checked},X()});let S=n.ai.listConsents?.bind(n.ai),$=n.ai.forgetConsent?.bind(n.ai),N=e.makeRow("Cloud consents","Cloud engines you have allowed or refused here. Forget an answer to be asked again.");N.classList.add("ai-section");let O=c("div","ai-consents");N.append(O);function F(P){let q=n.draft.engines.find(te=>te.id===P);return q?Ue(q):P}function j(P,q){rt(O,()=>{if(O.replaceChildren(),q&&O.append(st("error",q)),P.length===0){q||O.append(c("div","ai-consents-empty",La));return}let te=c("ul","ai-consents-list");te.setAttribute("aria-label","Cloud consents");for(let K of P){let ke=F(K.engineId),Z=c("li","ai-consent"),Oe=me("settings-btn settings-btn--secondary ai-consent-forget","Forget",{ariaLabel:`Forget the answer for ${ke}`,fk:`consent-forget:${K.engineId}`});Oe.addEventListener("click",()=>{Oe.disabled=!0,$?.(K.engineId).then(()=>(t.onConsentForgotten?.(K.engineId),u(`Forgot the answer for ${ke}.`),se()),De=>se(It(De).message))}),Z.append(c("span","ai-consent-text",Ma(K,ke)),Oe),te.append(Z)}O.append(te)})}async function se(P){if(S)try{j(await S(),P)}catch(q){j([],It(q).message)}}let le=e.makeRow("Engines","Servers that run the models. Local engines keep your text on this network.");le.classList.add("ai-section");let he=c("div","ai-engines-body");le.append(he);function ae(P){let q=n.draft.enabled&&!n.original.enabled;t.openEnginesPage?.({initial:P,session:{...n.fork(),pendingEnable:q},onDone:(te,K)=>{n.absorb(K,te),E.input.checked=n.draft.allowCloud,h.input.checked=n.draft.enabled,X(),Object.keys(te).length>0&&u("Engines and tasks saved.")}})}function X(){rt(he,()=>{he.replaceChildren();let P=n.draft;if(P.engines.length===0){let K=c("div","ai-summary-empty");K.append(c("div","ai-empty-title","No engines yet"),c("div","ai-empty-text",`Two ways to connect: paste a cloud API key, or run models on your own machine.${P.enabled?"":" Nothing is sent until AI is on."}`)),he.append(K)}else{let K=c("div","ai-engines ai-engines--compact");K.setAttribute("role","list"),K.setAttribute("aria-label","Engines");for(let ke of P.engines)K.append(ee(ke));he.append(K,Ee())}let q=me("settings-btn settings-btn--secondary ai-manage-btn",P.engines.length===0?"Add engine\u2026":"Manage engines\u2026",{fk:"manage-engines"});q.addEventListener("click",()=>ae());let te=c("div","ai-summary-actions");te.append(q),he.append(te)})}function ee(P){let q=c("div","ai-engine ai-engine--compact");q.setAttribute("role","listitem"),q.dataset.engineId=P.id,q.classList.toggle("is-disabled",!P.enabled);let te=Ue(P),K=c("div","ai-engine-head"),ke=c("span","ai-engine-glyph");ke.innerHTML=Ut(P.kind,"ai-glyph--sm");let Z=me("ai-engine-main ai-engine-open","",{ariaLabel:`${te}: open in AI Engines`,fk:`eng:${P.id}:open`}),Oe=c("span","ai-engine-title");Oe.append(c("span","ai-engine-name",te),...li(P,n.draft)),Z.title=Tn(P.kind),Z.append(Oe),Z.addEventListener("click",()=>ae({engineId:P.id}));let De=pn(P.enabled,`Enable ${te}`,`eng:${P.id}:enabled-row`);De.addEventListener("change",()=>{n.updateEngine(P.id,{enabled:De.checked}),X()});let pe=c("div","ai-engine-actions");return pe.append(si(n.statuses.get(P.id),void 0,{compact:!0}),De),K.append(ke,Z,pe),q.append(K),q}function Ee(){let P=n.draft,q=c("div","ai-route-line"),te=ye("ai-route-line"),K=c("span","ai-route-line-label","Default model");K.id=te;let ke=c("span","ai-route-line-value",P.routing.default?Kt(P,P.routing.default):"None set");ke.classList.toggle("is-none",!P.routing.default);let Z=me("ai-link-btn","Change\u2026",{fk:"route:change",ariaLabel:"Change the default model"});Z.setAttribute("aria-describedby",te),Z.addEventListener("click",()=>ae({section:"routing"})),q.append(K,ke,Z);let Oe=P.routing.default?ai({...P,routing:{...P.routing,tasks:{}}},n.statusList(),"chat"):{level:"info",text:"Tasks have nowhere to go until a default model is set."};return Oe&&q.append(st(Oe.level,Oe.text,"ai-row-note")),q}let Ne=e.makeRow("Features","Turn each feature on or off.");Ne.classList.add("ai-section");let ge=[],$e=[];for(let P of Ui){let q=P.status==="planned",te=bn(n.draft.features,P.id),K=c("div","settings-row settings-row--inline ai-feature");K.classList.toggle("is-planned",q);let ke=c("div","settings-row-text"),Z=ye("ai-feature"),Oe=c("span","settings-label",P.label);Oe.id=Z,ke.append(Oe,c("span","settings-desc",P.description));let De=c("div","ai-feature-controls");if(q)De.append(c("span","ai-pill ai-pill--soon","Coming later")),K.setAttribute("aria-disabled","true");else{i===2&&$e.push(ie(P));let pe=pn(te.enabled,P.label,`feature:${P.id}:enabled`);pe.setAttribute("aria-labelledby",Z),pe.removeAttribute("aria-label"),pe.addEventListener("change",()=>{let Pe=n.draft;n.draft={...Pe,features:{...Pe.features,[P.id]:{...Pe.features[P.id]??{},enabled:pe.checked}}}}),De.append(pe)}K.append(ke,De),ge.push(K)}Ne.append(e.makeGroup(...ge)),$e.length>0&&Ne.append(...Ie($e));function ie(P){let q=ln(P.defaultTask),te=c("div","settings-row settings-row--inline ai-feature-task"),K=ye("ai-feature-task"),ke=c("span","settings-label",P.label);ke.id=K;let Z=c("select","settings-input settings-input--small");Z.dataset.fk=`feature:${P.id}:task`,Z.setAttribute("aria-label",`Task route for ${P.label}`);let Oe=c("option","",`Default task (${q?.label??P.defaultTask})`);Oe.value="",Z.append(Oe);for(let pe of jt){if(pe.hostMethod)continue;let Pe=c("option","",pe.label);Pe.value=pe.id,Z.append(Pe)}let De=n.draft.features[P.id]?.task;if(De&&!jt.some(pe=>pe.id===De)){let pe=c("option","",De);pe.value=De,Z.append(pe)}return Z.value=De??"",Z.addEventListener("change",()=>{let pe=n.draft,Pe={...pe.features[P.id]??{}};Z.value?Pe.task=Z.value:delete Pe.task,n.draft={...pe,features:{...pe.features,[P.id]:Pe}}}),te.append(ke,Z),te}function Ie(P){let q=ye("ai-feature-tasks"),te=me("ai-disclosure ai-feature-tasks-toggle","Advanced: task per feature",{html:xe.chevron,fk:"features:advanced"});te.setAttribute("aria-expanded","false"),te.setAttribute("aria-controls",q);let K=c("div","ai-advanced ai-feature-tasks");return K.id=q,K.hidden=!0,K.append(c("div","settings-desc","Each feature uses its own task\u2019s model (see Tasks on the AI Engines page). Pick another task to borrow its model."),e.makeGroup(...P)),te.addEventListener("click",()=>{K.hidden=!K.hidden,te.setAttribute("aria-expanded",String(!K.hidden))}),[te,K]}let Le=e.makeRow("Local networks","Networks and host names that count as local, so an engine there never needs Allow cloud.");Le.classList.add("ai-section");{let P=ye("ai-local-networks"),q=me("ai-disclosure ai-local-networks-toggle","Advanced: local networks",{html:xe.chevron,fk:"local-networks:advanced"});q.setAttribute("aria-expanded","false"),q.setAttribute("aria-controls",P);let te=c("div","ai-advanced ai-local-networks");te.id=P,te.hidden=!0;let K=c("textarea","settings-input ai-mono ai-overrides-text");K.rows=4,K.spellcheck=!1,K.dataset.fk="ai-local-networks",K.placeholder=`10.0.98.0/24
|
|
84
|
-
.ts.net`,K.value=n.draft.localNetworks.join(`
|
|
85
|
-
`),K.setAttribute("aria-label","Local networks, one per line");let ke=c("div","ai-field-error");ke.id=ye("ai-local-networks-error"),ke.setAttribute("aria-live","polite"),K.setAttribute("aria-describedby",ke.id),K.addEventListener("input",()=>{let Z=Za(K.value);if(!Z.ok){ke.textContent=Z.error,K.setAttribute("aria-invalid","true");return}ke.textContent="",K.removeAttribute("aria-invalid"),n.draft={...n.draft,localNetworks:Z.value},o&&X()}),K.addEventListener("blur",()=>{K.getAttribute("aria-invalid")!=="true"&&(K.value=n.draft.localNetworks.join(`
|
|
86
|
-
`))}),te.append(c("div","settings-desc","One per line. An IPv4 range such as 10.0.98.0/24 (a WireGuard network, say) or a host-name suffix such as .ts.net. Loopback, link-local, .local, .lan and .home.arpa always count. Leave it blank for the defaults (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16). Saved to your user settings only, never to a folder."),K,ke),q.addEventListener("click",()=>{te.hidden=!te.hidden,q.setAttribute("aria-expanded",String(!te.hidden))}),Le.append(q,te)}d.push(h.row),i===2&&(o&&(d.push(le),X()),d.push(E.row),S&&$&&(d.push(N),se())),d.push(w.row,Ne),i===2&&d.push(Le),d.push(a);let Re=o?t.subscribeStatuses?.(P=>{if(le.isConnected){for(let q of P)n.statuses.set(q.engineId,q);X()}}):void 0;o&&n.refreshStatuses().then(P=>{P&&le.isConnected&&X()});let Me=()=>{window.clearTimeout(r),Re?.()};return{rows:d,collect:()=>n.collect(),onDiscarded:()=>{Me(),n.discard()},onSaved:()=>{Me(),t.onSaved(n.commit())}}}var Yd={"ai.enabled":!0};function Vd(e,t){if(e!==2)return{kind:"tab"};let n=t.routing.default?.engineId,i=n&&t.engines.some(o=>o.id===n)?n:t.engines[0]?.id;return i?{kind:"page",engineId:i}:{kind:"wizard"}}var fo="default";function Vc(e){let t=n=>n==="Medium"?"Med":n;return{type:"segmented",id:"ai-thinking",label:"Thinking",title:"Thinking level for the next AI requests",options:[{value:fo,label:"Default",title:"Thinking: the model's default",spoken:"Default"},...e.choices.map(n=>({value:n.level,label:t(n.label),title:`Thinking: ${n.label}`,spoken:n.label}))],value:()=>e.value()??fo,onChange:n=>e.onChange(n===fo?null:n),classes:{group:"ai-rw-think",label:"ai-rw-think-label",segment:"ai-rw-think-seg"}}}var Jc="Select text first",Xc=/could not reach|no answer|timed out|ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|fetch failed|connection refused/i;function Zc(e){let t=/^(.+?) failed its last connection test/.exec(e);return t?Xc.test(e)?{label:`${t[1]} isn't reachable`,detail:e}:{label:`${t[1]} failed its last connection test`,detail:e.slice(t[0].length).replace(/^[:.\s]+/,"")||void 0}:{label:e}}function Qc(e){let t=new Map;for(let i of e)i&&!i.enabled&&i.hint!==Jc&&t.set(i.hint,(t.get(i.hint)??0)+1);let n=null;for(let[i,o]of t)o>=2&&(n===null||o>t.get(n))&&(n=i);return n}function Jd(e){let t=[],n=()=>{t.length>0&&t[t.length-1].type!=="separator"&&t.push({type:"separator"})},i=Qc([e.rewrite,e.explain,e.translate,e.summarize,e.titles,e.properties]);if(i){let{label:a,detail:r}=Zc(i);t.push({type:"status",id:"ai-status",label:a,...r?{detail:r}:{}}),e.onRetest&&t.push({type:"action",id:"ai-retest",label:"Look again",action:()=>e.onRetest?.()}),t.push({type:"separator"})}let o=(a,r,u,d,b)=>{d&&t.push({type:"action",id:a,label:r,icon:u??e.icons.rewrite,hint:d.enabled||d.hint===i?void 0:d.hint,isDisabled:()=>!d.enabled,action:b})};return o("ai-rewrite","Rewrite selection",e.icons.rewrite,e.rewrite,()=>e.onRewrite()),o("ai-explain","Explain selection",e.icons.explain,e.explain,()=>e.onExplain?.()),o("ai-translate","Translate\u2026",e.icons.translate,e.translate,()=>e.onTranslate?.()),n(),o("ai-summarize","Summarize document\u2026",e.icons.summarize,e.summarize,()=>e.onSummarize?.()),o("ai-titles","Suggest titles\u2026",e.icons.titles,e.titles,()=>e.onSuggestTitles?.()),o("ai-properties","Suggest properties",e.icons.properties,e.properties,()=>e.onSuggestProperties?.()),e.thinking&&e.thinking.choices.length>0&&(n(),t.push(Vc(e.thinking))),n(),t.push({type:"action",id:"ai-manage",label:e.canManageEngines?"Manage engines\u2026":"AI settings\u2026",icon:e.icons.manage,action:()=>e.onManage()}),t}var ed="Rewrite, translate, explain, summarize, suggest titles and tags.",td="AI features are experimental, and AI output can be wrong, so review it.",nd="Connect a provider you already use. Running models on this machine is under Advanced.";function id(e,t){let n=t===void 0?"":`, ${t} ${t===1?"model":"models"}`;return`${e} is running on this computer${n}.`}var Ln=null;function Xd(){return Ln!==null}function od(){Ln?.close(!1)}function Zd(e){od();let{anchor:t}=e,n=e.tier===1,i=n?"Turn on":"Set up",o=c("div","ai-first-run");o.setAttribute("role","dialog");let a=ye("ai-first-run-title"),r=ye("ai-first-run-text");o.setAttribute("aria-labelledby",a),o.setAttribute("aria-describedby",r);let u=c("div","ai-experimental-head"),d=c("span","ai-experimental-title","AI features");d.id=a,u.append(d,ui());let b=c("p","ai-first-run-verbs",ed),k=c("p","ai-disclaimer ai-first-run-notice",`${td} `);k.id=r;let h=me("ai-link-btn ai-first-run-notice-toggle","Read the full notice",{fk:"ai-first-run:notice"});h.setAttribute("aria-expanded","false"),k.append(h);let w=c("p","ai-disclaimer ai-first-run-notice-full",lo);w.id=ye("ai-first-run-notice-full"),w.hidden=!0,h.setAttribute("aria-controls",w.id);let E=c("div","ai-first-run-status");E.setAttribute("role","status"),E.setAttribute("aria-live","polite"),E.hidden=!0;let S=c("div","ai-first-run-actions"),$=me("ai-link-btn ai-first-run-other","Set up another way\u2026",{fk:"ai-first-run:other"});$.hidden=!0;let N=me("settings-btn settings-btn--secondary","Cancel",{fk:"ai-first-run:cancel"}),O=me("settings-btn settings-btn--primary",i,{fk:"ai-first-run:turn-on"});S.append($,N,O);let F=ur(()=>ge());F.hidden=!0;let j=F.querySelector("button");o.append(u,b,k,w,E,F,S);let se=null,le=!1,he=new AbortController;function ae(ie,Ie=""){if(E.hidden=ie==="hidden",E.dataset.state=ie,E.replaceChildren(),ie!=="hidden"){if(ie==="found"){let Le=c("span","ai-first-run-dot");Le.setAttribute("aria-hidden","true"),E.append(Le)}E.append(c("span","",Ie))}}let X=!1;function ee(ie){X||(X=!0,he.abort(),document.removeEventListener("mousedown",Ee,!0),o.removeEventListener("keydown",Ne),o.remove(),Ln?.element===o&&(Ln=null),ie&&t.isConnected&&t.focus({preventScroll:!0}))}function Ee(ie){let Ie=ie.target;!le&&!o.contains(Ie)&&!t.contains(Ie)&&ee(!1)}function Ne(ie){if(ie.key==="Escape")ie.preventDefault(),ie.stopPropagation(),le||ee(!0);else if(ie.key==="Tab"){let Ie=[h,j,$,N,O].filter(Me=>!Me.hidden&&!Me.closest("[hidden]")&&!Me.disabled);if(Ie.length===0)return;ie.preventDefault();let Le=Ie.indexOf(document.activeElement),Re=Le<0?0:(Le+(ie.shiftKey?Ie.length-1:1))%Ie.length;Ie[Re].focus()}}function ge(){ee(!1),e.onTurnOn()}async function $e(ie){if(e.onUseLocal){le=!0;for(let Ie of[h,j,$,N,O])Ie.disabled=!0;ae("working",`Setting up ${ie.name}\u2026`);try{await e.onUseLocal(ie.presetId),le=!1,ee(!0)}catch(Ie){if(le=!1,X)return;se=null;for(let Le of[h,j,$,N,O])Le.disabled=!1;$.hidden=!0,F.hidden=!0,O.textContent=i,ae("error",Ie instanceof Error&&Ie.message?Ie.message:`${ie.name} could not be set up.`),O.focus({preventScroll:!0})}}}return h.addEventListener("click",()=>{w.hidden=!w.hidden,h.setAttribute("aria-expanded",String(!w.hidden)),h.textContent=w.hidden?"Read the full notice":"Hide the full notice",po(o,t)}),N.addEventListener("click",()=>ee(!0)),$.addEventListener("click",()=>ge()),O.addEventListener("click",()=>{se?$e(se):ge()}),o.addEventListener("keydown",Ne),document.addEventListener("mousedown",Ee,!0),e.detect&&!n&&(ae("looking",fn),e.detect(he.signal).then(ie=>{X||le||(ie.kind==="found"&&e.onUseLocal?(se=ie,O.textContent=`Use ${ie.name}`,$.hidden=!1,F.hidden=!1,ae("found",id(ie.name,ie.models))):ie.kind==="none"?ae("none",nd):ae("hidden"),po(o,t))},()=>{!X&&!le&&ae("hidden")})),yi().appendChild(o),po(o,t),Ln={element:o,close:ee},O.focus({preventScroll:!0}),{element:o,close:()=>ee(!0)}}function po(e,t){let n=t.getBoundingClientRect(),i=e.getBoundingClientRect(),o=window.innerWidth,a=window.innerHeight,r=t.closest(".mikedown-root")?.getBoundingClientRect(),u=Math.max(8,(r?.left??0)+8),d=Math.min(o,r?.right??o)-i.width-8,b=Math.max(u,Math.min(n.left+n.width/2-i.width/2,d)),h=a-n.bottom>=i.height+6||a-n.bottom>=n.top?n.bottom+6:n.top-i.height-6;e.style.left=`${b}px`,e.style.top=`${Math.max(8,Math.min(h,a-i.height-8))}px`}function mo(e){return!!e&&(e.sent??e.configured)!=="off"}var fr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ad(e,t,n,i={}){let o=Yn(e,void 0,n,i);if(!o||e==="anthropic"||!t)return o;t.reasoning_effort!==void 0&&o.reasoning_effort===void 0&&(o.reasoning_effort="none");let a=t.chat_template_kwargs,r=fr(o.chat_template_kwargs)?o.chat_template_kwargs:{};return fr(a)&&a.enable_thinking!==void 0&&r.enable_thinking===void 0&&(o.chat_template_kwargs={...r,enable_thinking:!0}),o}function rd(e,t,n){let i=e.engines.find(h=>h.id===t.engineId);if(!i||Lt(i.kind).length===0)return null;let o=i.models.find(h=>h.id===t.modelId),a=Wn(i.kind,o?.requestOverrides),r=n.thinking,u=typeof r=="function"?r(i.kind):r??null,{level:d,auto:b}=Xo(i.kind,u,a,n.job??n.feature,{modelId:t.modelId}),k=d?ad(i.kind,o?.requestOverrides,d,{local:t.isLocal}):void 0;return{info:{kind:i.kind,configured:a,sent:k?d:null,...k&&b?{auto:!0}:{}},...k?{overrides:k}:{},contextTokens:o?.capabilities.contextTokens??null}}function sd(e){let t=0;for(let n of e)if(typeof n.content=="string")t+=n.content.length;else for(let i of n.content)i.type==="text"&&(t+=i.text.length);return Math.ceil(t/yn)}function ld(e,t){if(e.maxTokens===void 0||!t)return e.maxTokens;let n=t.info.sent??t.info.configured;return ea(e.maxTokens,n,{contextTokens:t.contextTokens,promptTokens:sd(e.messages)})}var pr=0;function cd(e){return pr+=1,`ai-${e}-${Date.now().toString(36)}-${pr}`}function dd(e){let n=Et({cloudBlocked:"cloudBlocked",consentDenied:"consentDenied",probeFailed:"unreachable",modelMissing:"modelNotFound",modelNotListed:"modelNotFound"}[e.unusable]??"unknown",e.reason);return e.engineId?{...n,engineId:e.engineId}:n}function Cr(e){return typeof e.listEngines=="function"}function ud(e,t){if(t.size===0)return[...e];let n=e.map(i=>t.has(i.engineId)?{...i,ok:!1,error:t.get(i.engineId)}:i);for(let[i,o]of t)n.some(a=>a.engineId===i)||n.push({engineId:i,ok:!1,isLocal:!0,hasKey:!1,error:o,models:[]});return n}async function Qd(e,t,n,i){let o=Cr(e.ai),a=new Map,r={},u={},d=!1;for(let b=0;b<12;b++){if(i.aborted)throw Et("cancelled");let k=null;if(o){let $={...e.consent,...u,...r},N=kn(e.settings(),ud(e.statuses(),a),$,{feature:t.feature,...t.task?{task:t.task}:{}});if(!Fi(N))throw dd(N);if(N.needsConsent){let O=e.ai.requestCloudConsent?await e.ai.requestCloudConsent(N.engineId,{feature:t.feature,...t.sends?{sends:t.sends}:{}}):!0;if(i.aborted)throw Et("cancelled");O===!0?e.consent[N.engineId]=!0:O==="once"?u[N.engineId]=!0:(r[N.engineId]=!1,O==="never"&&(e.consent[N.engineId]=!1));continue}k=N}let h=k?rd(e.settings(),k,t):null,w=ld(t,h);n.onRoute?.(k,h?.info??null);let E="",S=!1;try{return{result:await e.ai.complete({requestId:cd(t.feature),feature:t.feature,task:k?.task??t.task??bn(e.settings().features,t.feature).task,...k?{route:{engineId:k.engineId,modelId:k.modelId}}:{},messages:t.messages,...t.format?{format:t.format}:{},...w!==void 0?{maxTokens:w}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...h?.overrides?{requestOverrides:h.overrides}:{}},N=>{i.aborted||(S=!0,E+=N,n.onToken?.(N,E))},i),route:k,viaFallback:k?.viaFallback??!1,thinking:h?.info??null}}catch($){let N=i.aborted?Et("cancelled"):It($);if(N.code==="unreachable"&&!S&&!d&&k){d=!0,a.set(k.engineId,N.message);continue}throw k&&!N.engineId&&N.code!=="cancelled"?{...N,engineId:k.engineId}:N}}throw Et("unknown","No engine answered.")}function eu(e,t,n,i,o){if(!e||!t.enabled)return{state:"hidden"};if(!bn(t.features,o).enabled)return{state:"hidden"};if(!Cr(e))return{state:"enabled"};let a={};for(let[u,d]of Object.entries(i))typeof d=="boolean"&&(a[u]=d);let r=kn(t,n,a,{feature:o});return Fi(r)?{state:"enabled"}:{state:"disabled",reason:r.reason}}var mr=/^ {0,3}(`{3,}|~{3,})/,hr=/^ {0,3}(#{1,6})[ \t]+(.*?)(?:[ \t]+#+)?[ \t]*$/,pi=/^([ \t]*)([-*+]|\d{1,9}[.)])[ \t]+(.*)$/,mi=/^ {0,3}>[ \t]?(.*)$/,gr=/^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/,bo=e=>e===void 0||/\s/.test(e),_r=e=>e!==void 0&&/[\p{L}\p{N}]/u.test(e);function _t(e,t){let n=document.createElement(e);return t&&(n.className=t),n}function br(e,t,n){for(let i=e.indexOf(t,n);i!==-1;i=e.indexOf(t,i+1))if(!(e[i-1]==="\\"||bo(e[i-1]))&&!(t.length===1&&(e[i+1]===t||e[i-1]===t))&&!(t==="_"&&_r(e[i+1])))return i;return-1}function fd(e,t){if(e[t+1]!=="(")return-1;let n=0;for(let i=t+1;i<e.length;i++){if(e[i]===`
|
|
87
|
-
`)return-1;if(e[i]==="(")n++;else if(e[i]===")"&&--n===0)return i+1}return-1}function pd(e,t){let n=0;for(let i=t;i<e.length;i++)if(e[i]==="\\")i++;else if(e[i]==="[")n++;else if(e[i]==="]"&&--n===0)return i;return-1}function hi(e,t){let n="",i=()=>{n&&(e.appendChild(document.createTextNode(n)),n="")},o=(r,u,d)=>{i();let b=_t(r,d);hi(b,u),e.appendChild(b)},a=0;for(;a<t.length;){let r=t[a];if(r==="\\"&&a+1<t.length&&/[\\`*_{}[\]()#+\-.!~>|]/.test(t[a+1])){n+=t[a+1],a+=2;continue}if(r==="`"){let u=1;for(;t[a+u]==="`";)u++;let d="`".repeat(u),b=t.indexOf(d,a+u);if(b!==-1&&t[b+u]!=="`"){i();let k=_t("code");k.textContent=t.slice(a+u,b).replace(/^ (.*) $/,"$1"),e.appendChild(k),a=b+u;continue}n+=d,a+=u;continue}if(r==="*"||r==="_"){let u=t[a+1]===r,d=u?r+r:r,b=t[a+d.length];if((r==="*"||!_r(t[a-1]))&&!bo(b)&&b!==r){let h=br(t,d,a+d.length);if(h>a+d.length){o(u?"strong":"em",t.slice(a+d.length,h)),a=h+d.length;continue}}n+=d,a+=d.length;continue}if(r==="~"&&t[a+1]==="~"&&!bo(t[a+2])){let u=br(t,"~~",a+2);if(u>a+2){o("del",t.slice(a+2,u)),a=u+2;continue}}if(r==="["||r==="!"&&t[a+1]==="["){let u=r==="!"?a+1:a,d=pd(t,u),b=d===-1?-1:fd(t,d);if(b!==-1){o("span",t.slice(u+1,d),r==="!"?"ai-rw-md-image":"ai-rw-md-link"),a=b;continue}}n+=r,a++}i()}var md=e=>e.replace(/\t/g," ").length;function Or(e,t){let n=[],i=t.replace(/\r\n?/g,`
|
|
88
|
-
`).split(`
|
|
89
|
-
`),o=0,a=r=>mr.test(r)||hr.test(r)||pi.test(r)||mi.test(r)||gr.test(r);for(;o<i.length;){let r=i[o];if(!r.trim()){o++;continue}let u=mr.exec(r);if(u){let h=u[1],w=[];for(o++;o<i.length&&!new RegExp(`^ {0,3}${h[0]}{${h.length},}[ \\t]*$`).test(i[o]);)w.push(i[o++]);o++;let E=_t("pre","ai-rw-md-pre"),S=_t("code");S.textContent=w.join(`
|
|
90
|
-
`),E.appendChild(S),n.push(E);continue}let d=hr.exec(r);if(d){let h=_t("div","ai-rw-md-h");h.dataset.level=String(d[1].length),hi(h,d[2]),n.push(h),o++;continue}if(gr.test(r)){n.push(_t("hr","ai-rw-md-hr")),o++;continue}if(mi.test(r)){let h=[];for(;o<i.length&&mi.test(i[o]);)h.push(mi.exec(i[o++])[1]);let w=_t("blockquote","ai-rw-md-quote");Or(w,h.join(`
|
|
91
|
-
`)),n.push(w);continue}if(pi.test(r)){let h=[],w=[];for(;o<i.length;){let E=pi.exec(i[o]);if(!E){if(i[o].trim()&&/^[ \t]+\S/.test(i[o])&&!a(i[o])&&h.length){h[h.length-1].item.appendChild(document.createTextNode(`
|
|
92
|
-
${i[o].trim()}`)),o++;continue}if(!i[o].trim()&&pi.test(i[o+1]??"")){o++;continue}break}let S=md(E[1]),$=/\d/.test(E[2]);for(;h.length&&S<h[h.length-1].indent;)h.pop();let N=h[h.length-1];if(N&&S===N.indent&&$!==N.ordered&&(h.pop(),N=h[h.length-1]),!N||S>N.indent){let F=_t($?"ol":"ul","ai-rw-md-list");if($){let j=parseInt(E[2],10);j!==1&&F.setAttribute("start",String(j))}N?.item?N.item.appendChild(F):w.push(F),N={indent:S,ordered:$,list:F,item:null},h.push(N)}let O=_t("li");hi(O,E[3]),N.list.appendChild(O),N.item=O,o++}n.push(...w);continue}let b=[];for(;o<i.length&&i[o].trim()&&(b.length===0||!a(i[o]));)b.push(i[o++]);let k=_t("p","ai-rw-md-p");hi(k,b.join(`
|
|
93
|
-
`)),n.push(k)}e.replaceChildren(...n)}var gi=0;function vr(e,t){let n=e.storage.markdown;try{let i=n?.serializer?.serialize(t);if(typeof i=="string")return i}catch{}return t.textBetween(0,t.size,`
|
|
94
|
-
|
|
95
|
-
`)}function ho(e,t,n,i){let o=t.slice(n,i).content,a=t.resolve(n).parent,r=e.state.schema.nodes.paragraph;return o.firstChild?.isInline&&!a.type.spec.code&&r?vr(e,wo.from(r.create(null,o))):vr(e,o)}function ko(e){return e.storage.markdown}function yo(e,t){let n=ko(e)?.parser?.parse(t)??t;return bi.fromSchema(e.state.schema).parse(vi(n)).content}function Nr(e){return e.trim().split(`
|
|
96
|
-
`).map(t=>t.trim()?`> ${t}`:">").join(`
|
|
97
|
-
`)}function Rr(e){let t=e.getBoundingClientRect(),n=Math.max(t.top,8);return new DOMRect(t.left,n,Math.max(1,t.width),1)}function $n(e,t){let n=Math.min(e.left,t.left),i=Math.min(e.top,t.top);return new DOMRect(n,i,Math.max(e.right,t.right)-n,Math.max(e.bottom,t.bottom)-i)}function su(e){let{state:t}=e,n=t.selection;if("$anchorCell"in n)return null;let i=n.from,o=n.to;if(n.empty){let $=n.$from;if(!$.parent.isTextblock||$.parent.type.spec.code||!$.parent.textContent.trim())return null;i=$.start(),o=$.end()}let a=t.doc;if(!a.textBetween(i,o," ").trim())return null;let r=ho(e,a,i,o);if(!r.trim())return null;let u=a.resolve(i),d=a.resolve(o),b=u.depth>0?u.posAtIndex(Math.max(0,u.index(0)-1),0):0,k=d.depth>0?d.posAtIndex(Math.min(a.childCount,d.index(0)+2),0):a.content.size,h=b<i?ho(e,a,b,i):"",w=k>o?ho(e,a,o,k):"",E=++gi;e.view.dispatch(t.tr.setMeta(At,{range:{from:i,to:o,id:E}}).setMeta("addToHistory",!1));let S=()=>{if(e.isDestroyed)return null;let $=At.getState(e.state);return $&&$.id===E?$:null};return{mode:"rich",scope:"selection",text:r,before:h,after:w,multiline:r.trim().includes(`
|
|
98
|
-
`),alive:()=>!!S(),rect(){let $=S();if(!$)return null;try{return ki(e.view,$.from,$.to)}catch{return null}},accept($){let N=S();if(!N||e.isDestroyed)return!1;let O=e.state,F=ko(e)?.parser?.parse($,{inline:!0})??$,j=bi.fromSchema(O.schema).parseSlice(vi(F),{preserveWhitespace:!0,context:O.doc.resolve(N.from)}),{from:se,to:le}=N,he=O.doc.resolve(se),ae=O.doc.resolve(le);j.content.firstChild?.isBlock&&he.parent.isTextblock&&ae.parent.isTextblock&&he.parentOffset===0&&ae.parentOffset===ae.parent.content.size&&he.depth===ae.depth&&he.node(he.depth-1)===ae.node(ae.depth-1)&&(se=he.before(),le=ae.after());let X=rn(O.tr).replaceRange(se,le,j);X.setMeta(At,{range:null});let ee=X.mapping.map(le,1);try{X.setSelection(Cn.between(X.doc.resolve(Math.min(se,X.doc.content.size)),X.doc.resolve(Math.min(ee,X.doc.content.size))))}catch{}return e.view.dispatch(X.scrollIntoView()),!0},insertBelow($){let N=S();if(!N||e.isDestroyed)return!1;let O=e.state,F=yo(e,Nr($));if(!F.size)return!1;let j=O.doc.resolve(N.to),se=j.depth>0?j.after(1):N.to;return e.view.dispatch(rn(O.tr).insert(se,F).scrollIntoView()),!0},release(){S()&&e.view.dispatch(e.state.tr.setMeta(At,{range:null}).setMeta("addToHistory",!1))},focus(){e.isDestroyed||e.view.focus()}}}function lu(e){let{state:t}=e,n=t.selection.main,{from:i,to:o}=n;if(n.empty){let k=t.doc.lineAt(i);if(!k.text.trim())return null;i=k.from,o=k.to}let a=t.sliceDoc(i,o);if(!a.trim())return null;let r=t.sliceDoc(Math.max(0,i-Vn*2),i),u=t.sliceDoc(o,Math.min(t.doc.length,o+Vn*2)),d=++gi;e.dispatch({effects:Dt.of({from:i,to:o,id:d})});let b=()=>{let k=e.state.field(wi,!1);return k&&k.id===d?k:null};return{mode:"source",scope:"selection",text:a,before:r,after:u,multiline:a.trim().includes(`
|
|
99
|
-
`),alive:()=>!!b(),rect(){let k=b();if(!k)return null;let h=e.coordsAtPos(k.from),w=e.coordsAtPos(k.to,-1);if(!h||!w)return h?$n(h,h):w?$n(w,w):null;if(w.top>h.top+1){let E=e.contentDOM.getBoundingClientRect();return $n(h,{...w,left:E.left,right:Math.max(h.right,w.right)})}return $n(h,w)},accept(k){let h=b();return h?(e.dispatch({changes:{from:h.from,to:h.to,insert:k},selection:{anchor:h.from,head:h.from+k.length},effects:Dt.of(null),annotations:sn.of("full"),userEvent:"input.ai",scrollIntoView:!0}),!0):!1},insertBelow(k){let h=b();if(!h)return!1;let w=e.state.doc,E=w.lineAt(h.to),S=h.to>h.from&&E.from===h.to?w.lineAt(h.to-1):E,$=S.number<w.lines?w.line(S.number+1):null,N=`
|
|
100
|
-
|
|
101
|
-
${Nr(k)}${$&&$.text.trim()?`
|
|
102
|
-
`:""}`;return e.dispatch({changes:{from:S.to,insert:N},annotations:sn.of("full"),userEvent:"input.ai",scrollIntoView:!0}),!0},release(){b()&&e.dispatch({effects:Dt.of(null)})},focus(){e.focus()}}}function cu(e,t={}){if(e.isDestroyed)return null;let n=ko(e)?.getMarkdown?.()??e.state.doc.textBetween(0,e.state.doc.content.size,`
|
|
103
|
-
|
|
104
|
-
`);return n.trim()?{mode:"rich",scope:"document",text:n,before:"",after:"",multiline:!1,alive:()=>!e.isDestroyed,rect:()=>e.isDestroyed?null:Rr(e.view.dom),accept(i){if(e.isDestroyed)return!1;let o=e.state,a=yo(e,i);if(!a.size)return!1;let r=rn(o.tr).replaceWith(0,o.doc.content.size,a);return r.setMeta(At,{range:null}),r.setSelection(Cn.atStart(r.doc)),e.view.dispatch(r.scrollIntoView()),t.scrollToTop?.(),!0},insertBelow:()=>!1,release(){},focus(){e.isDestroyed||e.view.focus()}}:null}function du(e,t){let n=e.state.doc.toString(),i=n.slice(t(n));return i.trim()?{mode:"source",scope:"document",text:i,before:"",after:"",multiline:!1,alive:()=>e.dom.isConnected,rect:()=>Rr(e.scrollDOM),accept(o){let a=e.state.doc.toString(),r=t(a);return e.dispatch({changes:{from:r,to:a.length,insert:o},selection:{anchor:r},effects:[Dt.of(null),Ao.scrollIntoView(0,{y:"start"})],annotations:sn.of("full"),userEvent:"input.ai"}),!0},insertBelow:()=>!1,release(){},focus(){e.focus()}}:null}function uu(e,t){if(e.isDestroyed)return null;let{state:n}=e,i=++gi,o=n.selection.head,a=t&&t.to>t.from?{from:t.from,to:t.to,id:i}:{from:o,to:o,id:i,anchor:!0};e.view.dispatch(n.tr.setMeta(At,{range:a}).setMeta("addToHistory",!1));let r=()=>{if(e.isDestroyed)return null;let u=At.getState(e.state);return u&&u.id===i?u:null};return{mode:"rich",scope:"cursor",text:"",before:"",after:"",multiline:!1,alive:()=>!!r(),range(){let u=r();return u?{from:u.from,to:u.to}:null},rect(){let u=r();if(!u)return null;try{return ki(e.view,u.from,u.to)}catch{return null}},accept(u){let d=r();if(!d||e.isDestroyed)return!1;let b=yo(e,u);if(!b.size)return!1;let k=e.state,h=rn(k.tr),w=d.from;d.to>d.from&&(k.doc.resolve(d.from).parentOffset>0&&k.doc.textBetween(d.from-1,d.from)===" "&&(w=d.from-1),h.delete(w,d.to)),h.setMeta(At,{range:null});let E=h.doc.resolve(Math.min(w,h.doc.content.size)),S=E.pos,$=E.pos;if(E.depth>0){let O=E.node(1),F=O.type.name==="paragraph"&&O.content.size===0;S=F?E.before(1):E.after(1),$=F?E.after(1):S}h.replaceWith(S,$,b);let N=Math.min(S+b.size,h.doc.content.size);try{h.setSelection(Cn.near(h.doc.resolve(N),-1))}catch{}return e.view.dispatch(h.scrollIntoView()),!0},insertBelow:()=>!1,release(){r()&&e.view.dispatch(e.state.tr.setMeta(At,{range:null}).setMeta("addToHistory",!1))},focus(){e.isDestroyed||e.view.focus()}}}function fu(e,t){let n=++gi,i=e.state.selection.main.head;e.dispatch({effects:Dt.of({from:i,to:i,id:n,anchor:!0})});let o=()=>{let a=e.state.field(wi,!1);return a&&a.id===n?a:null};return{mode:"source",scope:"cursor",text:"",before:"",after:"",multiline:!1,alive:()=>!!o()&&e.dom.isConnected,range(){let a=o();return a?{from:a.from,to:a.to}:null},rect(){let a=o(),r=a?e.coordsAtPos(a.from):null;return r?$n(r,r):null},accept(a){let r=o(),u=a.trim();if(!r||!u)return!1;let d=e.state.doc,b=t?t(d.toString()):0,k=d.lineAt(Math.max(r.from,Math.min(b,d.length))),h=k.number>1?d.line(k.number-1):null,w=k.number<d.lines?d.line(k.number+1):null,E=!!w&&!!w.text.trim(),S,$;if(k.text.trim())S={from:k.to,insert:`
|
|
105
|
-
|
|
106
|
-
${u}${E?`
|
|
107
|
-
`:""}`},$=k.to+2+u.length;else{let N=h&&h.text.trim()&&k.from>=b?`
|
|
108
|
-
`:"";S={from:k.from,to:k.to,insert:`${N}${u}${E?`
|
|
109
|
-
`:""}`},$=k.from+N.length+u.length}return e.dispatch({changes:S,selection:{anchor:$},effects:Dt.of(null),annotations:sn.of("full"),userEvent:"input.ai",scrollIntoView:!0}),!0},insertBelow:()=>!1,release(){o()&&e.dispatch({effects:Dt.of(null)})},focus(){e.focus()}}}var kr={frontmatter:"Sets title: in Properties",h1:"Replaces the H1",insertH1:"Inserts an H1"};function hd(e){return/^title[ \t]*:/m.test(e??"")}function gd(e,t){let n=e.split(`
|
|
110
|
-
`),i=n.findIndex(a=>/^title[ \t]*:/.test(a));if(i<0)return e;let o=i+1;for(;o<n.length&&/^[ \t]+\S/.test(n[o]);)o++;return n.splice(i,o-i,`title: ${bd(t)}`),n.join(`
|
|
111
|
-
`)}function bd(e){return!/[:#[\]{},&*!|>'"%@`]/.test(e)&&!/^\s|\s$/.test(e)&&!/^(-?\d+(\.\d+)?|true|false|null|yes|no|on|off|~|-.*)$/i.test(e)&&e?e:`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function pu(e,t,n,i){if(e.isDestroyed||!n.trim())return!1;let{schema:o}=e.state,a=o.nodes.heading;if(!a)return!1;let r=rn(e.state.tr);i&&i.to>i.from&&r.delete(i.from,i.to),r.setMeta(At,{range:null});let u=null;t==="h1"&&r.doc.descendants((b,k)=>u?!1:b.type===a&&b.attrs.level===1?(u={pos:k,size:b.content.size},!1):!b.isTextblock);let d=u;return d?r.replaceWith(d.pos+1,d.pos+1+d.size,o.text(n)):r.insert(0,a.create({level:1},o.text(n))),e.view.dispatch(r.scrollIntoView()),!0}function vd(e,t){let n=t,i=null;for(;n<=e.length;){let o=e.indexOf(`
|
|
112
|
-
`,n),a=o<0?e.length:o,r=e.slice(n,a),u=/^ {0,3}(`{3,}|~{3,})/.exec(r);if(i)u&&u[1][0]===i[0]&&u[1].length>=i.length&&!r.trim().slice(u[1].length).trim()&&(i=null);else if(u)i=u[1];else{let d=/^( {0,3}#[ \t]+)/.exec(r);if(d)return{from:n,to:a,prefix:d[1]}}if(o<0)break;n=o+1}return null}function mu(e,t,n,i){if(!n.trim())return!1;let o=e.state.doc.toString(),a;if(t==="frontmatter"&&i.yaml!==null&&hd(i.yaml)){let r=o.indexOf(`
|
|
113
|
-
`)+1;a={from:r,to:r+i.yaml.length,insert:gd(i.yaml,n)}}else{let r=t==="insertH1"?null:vd(o,i.bodyStart);a=r?{from:r.from+r.prefix.length,to:r.to,insert:n}:{from:i.bodyStart,to:i.bodyStart,insert:`# ${n}
|
|
114
|
-
|
|
115
|
-
`}}return e.dispatch({changes:a,effects:Dt.of(null),annotations:sn.of("full"),userEvent:"input.ai"}),!0}var Wt=(e,t=14)=>`<svg width="${t}" height="${t}" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${e}</svg>`,kd=Wt('<path d="M8 2.2l1.25 3.3 3.3 1.25-3.3 1.25L8 11.3 6.75 8 3.45 6.75 6.75 5.5z"/><path d="M12.6 10.6l.5 1.3 1.3.5-1.3.5-.5 1.3-.5-1.3-1.3-.5 1.3-.5z"/>'),yd=Wt('<path d="M4.5 4.5l7 7M11.5 4.5l-7 7"/>',12),wd=Wt('<path d="M2.5 7.5L8 3l5.5 4.5M4 6.5V13h8V6.5"/>',11),Ad=Wt('<path d="M4.5 12.5h7a2.75 2.75 0 0 0 .3-5.48A4 4 0 0 0 4.1 7.6 2.5 2.5 0 0 0 4.5 12.5z"/>',11),xd=Wt('<path d="M8 2.5l6 10.5H2z"/><path d="M8 6.5v3M8 11.4v.1"/>',16),Ed=Wt('<path d="M8 2.5l6 10.5H2z"/><path d="M8 6.5v3M8 11.4v.1"/>',12),Td=Wt('<path d="M9.5 4L5.5 8l4 4"/>',14),Sd=Wt('<path d="M3.5 8.5l3 3 6-7"/>',12);function z(e,t,n){let i=document.createElement(e);return t&&(i.className=t),n!==void 0&&(i.textContent=n),i}function ot(e,t,n){let i=z("button",e,t);return i.type="button",i.addEventListener("mousedown",o=>o.preventDefault()),i.addEventListener("click",()=>{i.getAttribute("aria-disabled")!=="true"&&n()}),i}var $d={length:"Length",tone:"Tone",audience:"Audience",translate:"Translate",explain:"Explain",custom:"Custom"};function Id(){let e=[];for(let t of Bi){let n=e.find(i=>i.group===t.group);n||(n={group:t.group,label:$d[t.group],variants:[]},e.push(n)),n.variants.push(t)}return e}var Ld=new Set(["translate","simpler","formal","casual","expand"]),Md={heading:["heading","headings"],fencedCodeBlock:["code block","code blocks"],inlineCode:["inline code span","inline code spans"],link:["link","links"],image:["image","images"],listItem:["list item","list items"],tableRow:["table row","table rows"],wikilink:["wikilink","wikilinks"],footnote:["footnote reference","footnote references"]};function Cd(e){if(e.ok)return"";let t=new Map;for(let i of e.mismatches){let o=t.get(i.kind);o?(o.original+=i.original,o.result+=i.result):t.set(i.kind,{original:i.original,result:i.result,message:i.message})}let n=[];for(let[i,o]of t){let[a,r]=Md[i],u=o.original-o.result,d=Math.abs(u)===1?a:r;u>0?n.push(`${u} ${d} missing in the result`):u<0?n.push(`${-u} extra ${d} in the result`):i==="link"||i==="image"?n.push(`${r} point somewhere else in the result`):n.push(`${r} differ in the result`)}return`Check: ${n.join("; ")}`}function yr(e){return Math.max(1024,Math.min(16384,Math.ceil(e.length/yn*1.6)+256))}var Mn=768;function _d(e,t){let n=yr(e),i=wn(e,{contextTokens:t,outputTokens:n,reserveTokens:Mn});if(i.truncated){let o=Math.max(0,t-Mn);n=Math.max(1024,Math.min(16384,Math.floor(o*1.6/2.6))),i=wn(e,{contextTokens:t,outputTokens:n,reserveTokens:Mn}),i.truncated&&(n=Math.min(n,yr(i.text)))}return i.truncated?{text:i.text,rest:e.slice(i.text.length),coverage:i.coverage,maxTokens:n}:{text:e,rest:"",coverage:1,maxTokens:n}}function Od(e,t){if(t>=1)return"";let n=Jn(t);return e==="translate"?`Translates the first ${n}% of the document; the rest did not fit the model's context and stays as it is.`:e==="titles"?`Based on the first ${n}% of the document and all of its headings; the rest did not fit the model's context.`:`Covers the first ${n}% of the document; the rest did not fit the model's context.`}var Nd={tldr:"TL;DR",outline:"Outline"},wr="Fixing the answer format\u2026";function Ar(e,t){return e?.param==="language"?!!t.language?.trim():e?.param==="audience"?!!t.audience&&!!dn(t.audience):!0}var Rd=e=>e.replace(/…$/,""),Dd=e=>e==="Medium"?"Med":e;function xr(e){return e?e.sent??e.configured:null}var In="default",Er=e=>(e&&!e.auto?e.sent:null)??In,Tr=e=>e.charAt(0).toUpperCase()+e.slice(1);function hu(e){let t=null,n=null,i="choose",o="shorter",a="",r={},u=null,d=!1,b=!1,k=null,h=0,w="",E="",S=!1,$=null,N=null,O=null,F=!1,j=null,se=null,le=null,he=!1,ae="",X=null,ee="rewrite",Ee=null,Ne=null,ge=[],$e=1,ie="",Ie="",Le=!1,Re=null,Me=0,P,q=[],te,K,ke,Z,Oe,De,pe,Pe,We,lt,gt,ze,kt,Tt,mt,ct,yt,f,A,s,l,g,y,x,L,_,R,U,D;function Y(){h+=1,k?.abort(),k=null}function Q(m={}){if(!t)return;Y(),cancelAnimationFrame(Me),window.clearTimeout(P);for(let I of q)I();q=[],n?.remove(),n=null,Vt();let T=t;t=null,u=null,T.release(),m.refocus!==!1&&T.focus()}function be(){return ee==="summary"?"insert":ee==="titles"?"choose":Ht(o)?.output==="readOnly"?"readOnly":t?.scope==="document"?"replaceDocument":"replace"}function Ce(){let m=z("div","mikedown-ai-rewrite");m.setAttribute("role","dialog"),m.setAttribute("aria-label","Rewrite with AI"),m.tabIndex=-1;let T=z("div","ai-rw-head"),I=z("span","ai-rw-spark");I.innerHTML=kd,te=z("span","ai-rw-title","Rewrite"),Z=z("div","ai-rw-think"),Z.setAttribute("role","radiogroup"),Z.setAttribute("aria-label","Thinking"),Z.hidden=!0,Z.addEventListener("keydown",Ye),K=z("span","ai-rw-badge"),K.hidden=!0,y=ot("ai-rw-icon-btn","",()=>Q()),y.innerHTML=yd,L=z("div","ai-rw-kind"),L.setAttribute("role","group"),L.setAttribute("aria-label","Summary kind"),L.hidden=!0;for(let W of["tldr","outline"]){let ue=ot("ai-rw-kind-seg",Nd[W],()=>on(W));ue.dataset.kind=W,ue.title=W==="tldr"?"A short TL;DR of the document (runs again)":"An outline of the document (runs again)",L.append(ue)}T.append(I,te,L,Z,y),Oe=z("div","ai-rw-choose"),De=z("div","ai-rw-menu"),De.setAttribute("role","menu"),De.setAttribute("aria-label","Rewrite options");for(let W of Id()){if(W.group==="custom")continue;let ue=z("div","ai-rw-group");ue.dataset.group=W.group,ue.setAttribute("role","group"),ue.setAttribute("aria-label",W.label);let V=z("div","ai-rw-group-label",W.label);V.setAttribute("aria-hidden","true");let re=z("div","ai-rw-chips");for(let je of W.variants){let nt=ot("ai-rw-chip",je.label,()=>Qe(je));nt.setAttribute("role","menuitem"),je.title&&(nt.title=je.title),nt.dataset.variant=je.id,je.param&&nt.setAttribute("aria-haspopup","menu"),re.append(nt)}ue.append(V,re),De.append(ue)}pe=z("form","ai-rw-form"),We=z("input","ai-rw-input"),We.type="text",We.placeholder='Describe a change, e.g. "make it friendlier"',We.setAttribute("aria-label","Custom rewrite instruction"),We.maxLength=1e3;let B=ot("ai-rw-btn ai-rw-btn--primary","Rewrite",()=>_e());pe.append(We,B),pe.addEventListener("submit",W=>{W.preventDefault(),_e()}),Pe=z("div","ai-rw-picker"),Oe.append(De,pe,Pe),lt=z("div","ai-rw-body");let G=z("div","ai-rw-pane ai-rw-pane--old");gt=z("div","ai-rw-text"),G.append(z("div","ai-rw-label","Original"),gt),mt=z("div","ai-rw-pane ai-rw-pane--new");let oe=z("div","ai-rw-text");return ze=z("div","ai-rw-out"),kt=z("span","ai-rw-caret"),oe.append(ze),Tt=z("div","ai-rw-label","Rewrite"),mt.append(Tt,oe),lt.append(G,mt),R=z("div","ai-rw-titles-box"),U=z("div","ai-rw-titles"),U.setAttribute("role","menu"),U.setAttribute("aria-label","Suggested titles"),D=z("div","ai-rw-titles-hint"),R.append(U,D),ct=z("div","ai-rw-error"),ct.setAttribute("role","alert"),_=z("div","ai-rw-coverage"),yt=z("div","ai-rw-warn"),f=z("div","ai-rw-foot"),A=ot("ai-rw-btn ai-rw-btn--primary","Accept",()=>fe()),s=ot("ai-rw-btn","Retry",()=>Ve()),l=ot("ai-rw-btn","Copy",()=>He()),g=z("span","ai-rw-note"),ke=z("span","ai-rw-stats"),ke.hidden=!0,f.append(A,s,l,g,ke,K),x=z("div","ai-rw-sr"),x.setAttribute("aria-live","polite"),m.append(T,Oe,lt,R,ct,_,yt,f,x),m}function _e(){let m=We.value.trim();if(!m){We.focus();return}ce("custom",m)}function Qe(m){if(m.param){we(m.param==="language"?"language":"audience");return}ce(m.id)}function Ke(m,T,I){let B=ot("ai-rw-option","",I);B.setAttribute("role","menuitemradio"),B.setAttribute("aria-checked",T?"true":"false");let G=z("span","ai-rw-option-check");return G.innerHTML=Sd,B.append(G,z("span","ai-rw-option-label",m)),B}function dt(){let m=z("div","ai-rw-option-sep");return m.setAttribute("role","separator"),m}function ht(){if(!u){Pe.replaceChildren();return}let m=z("div","ai-rw-picker-head"),T=ot("ai-rw-icon-btn ai-rw-back","",()=>Fe());T.innerHTML=Td,T.setAttribute("aria-label","Back (Esc)"),T.title="Back (Esc)",T.hidden=b,m.append(T,z("span","ai-rw-picker-title",u==="language"?"Translate to":"Reading level"));let I=z("div","ai-rw-picker-list");I.setAttribute("role","menu"),I.setAttribute("aria-label",u==="language"?"Language":"Audience");let B=[m,I];if(u==="language"){let{recents:G,languages:oe}=Bc();G.forEach((re,je)=>I.append(Ke(re,je===0,()=>ne(re)))),G.length&&I.append(dt());for(let re of oe)I.append(Ke(re,!1,()=>ne(re)));I.append(dt());let W=z("form","ai-rw-form ai-rw-other");W.hidden=!0;let ue=z("input","ai-rw-input");ue.type="text",ue.placeholder="Language, e.g. Swahili",ue.setAttribute("aria-label","Other language"),ue.maxLength=60,W.append(ue,ot("ai-rw-btn ai-rw-btn--primary","Translate",()=>ne(ue.value))),W.addEventListener("submit",re=>{re.preventDefault(),ne(ue.value)});let V=ot("ai-rw-option ai-rw-option--other","",()=>{W.hidden=!1,V.setAttribute("aria-expanded","true"),ue.focus(),J()});if(V.setAttribute("role","menuitem"),V.setAttribute("aria-expanded","false"),V.append(z("span","ai-rw-option-check"),z("span","ai-rw-option-label","Other\u2026")),I.append(V),B.push(W),b||e.documentTarget){let re=z("label","ai-rw-toggle"),je=z("input");je.type="checkbox",je.checked=d,je.disabled=b,je.addEventListener("change",()=>{d=je.checked}),re.append(je,z("span","","Whole document")),re.title=b?"Nothing is selected, so the whole document is translated.":"Translate the whole document instead of the selection (frontmatter is kept).";let nt=z("div","ai-rw-picker-foot");nt.append(re),B.push(nt)}}else{let G=zc();for(let oe of ji)I.append(Ke(oe.label,oe.id===G,()=>de(oe.id)))}Pe.replaceChildren(...B)}function we(m){u=m,o=m==="language"?"translate":"readingLevel",i="choose",ht(),Xe(),J();let T=[...Pe.querySelectorAll(".ai-rw-picker-list > button")];(T.find(I=>I.getAttribute("aria-checked")==="true")??T[0])?.focus({preventScroll:!0})}function Fe(){if(b){Q();return}let m=o;u=null,ht(),Xe(),J(),De.querySelector(`.ai-rw-chip[data-variant="${m}"]`)?.focus({preventScroll:!0})}function ne(m){let T=m.replace(/\s+/g," ").trim();if(!T){Pe.querySelector(".ai-rw-other .ai-rw-input")?.focus();return}r={language:T},!(d&&!qe())&&ce("translate")}function de(m){r={audience:m},ce("readingLevel")}function qe(){if(!t)return!1;if(t.scope==="document")return!0;let m=e.documentTarget?.()??null;return m?(t.release(),t=m,Re=null,!0):!1}function at(){return ee==="summary"?Ee?.kind==="outline"?"Outline":"Summary":ee==="titles"?"Suggest titles":he?"Rewrite":i==="choose"?u==="language"?"Translate":u==="audience"?"Reading level":"Rewrite":o==="explain"?"Explain":o==="custom"?"Rewrite \xB7 Custom":o==="translate"?`Translate \xB7 ${r.language??""}${t?.scope==="document"?" \xB7 Whole document":""}`:o==="readingLevel"?`Reading level \xB7 ${(r.audience&&dn(r.audience)?.label)??""}`:`Rewrite \xB7 ${Rd(Ht(o)?.label??"")}`}function Ge(){let m=j&&i!=="choose"?Lt(j.kind):[];if(Z.hidden=m.length===0,m.length===0)return;let T=Er(j),I=Z.contains(document.activeElement)?document.activeElement.dataset.level:void 0,B=z("span","ai-rw-think-label","Thinking");B.setAttribute("aria-hidden","true");let G=[{level:In,label:"Default",title:"Thinking: picked for the task"},...m.map(V=>({level:V.level,label:Dd(V.label),title:`Thinking: ${V.label}`}))],oe=I&&G.some(V=>V.level===I)?I:T,W=G.map(V=>{let re=ot("ai-rw-think-seg",V.label,()=>Be(V.level===In?null:V.level));return re.dataset.level=V.level,re.setAttribute("role","radio"),re.setAttribute("aria-checked",V.level===T?"true":"false"),re.setAttribute("aria-label",V.level===In?"Default":m.find(je=>je.level===V.level)?.label??V.label),re.tabIndex=V.level===oe?0:-1,re.title=`${V.title} (runs again)`,re}),ue=xr(j);Z.title=j?.sent&&j.auto?`Thinking: Default, ${m.find(V=>V.level===j?.sent)?.label??j.sent} for this task`:j?.sent?`Thinking: ${m.find(V=>V.level===j?.sent)?.label??j.sent}`:ue?`Thinking: the model's setting (${m.find(V=>V.level===ue)?.label??ue})`:"Thinking: the model's default",Z.replaceChildren(B,...W),I&&W.find(V=>V.dataset.level===I)?.focus({preventScroll:!0})}function Ye(m){if(!/^(Arrow(Left|Right|Up|Down)|Home|End)$/.test(m.key))return;let T=[...Z.querySelectorAll(".ai-rw-think-seg")],I=T.indexOf(document.activeElement);if(I<0)return;m.preventDefault(),m.stopPropagation();let B=m.key==="ArrowRight"||m.key==="ArrowDown",G=m.key==="Home"?0:m.key==="End"?T.length-1:(I+(B?1:-1)+T.length)%T.length;for(let[oe,W]of T.entries())W.tabIndex=oe===G?0:-1;T[G].focus({preventScroll:!0})}function ut(){Ge();let m=e.badge($,N,N?F:$?.viaFallback??!1,tt());if(K.hidden=!m,!m)return;K.dataset.where=m.where??"",K.classList.toggle("is-pending",!N);let T=N?xr(j):null,I=T&&j?Lt(j.kind).find(V=>V.level===T)?.label:void 0,B=m.title;if(m.where==="cloud"){let V=tt(),re=Zn(V.feature,V.sends);B.includes(re)||(B=`${B} ${N?"Sent":"Sends"} ${re}.`)}K.title=I?`${B} Thinking: ${I.toLowerCase()}.`:B;let G=z("span","ai-rw-badge-glyph");G.innerHTML=m.where==="cloud"?Ad:wd;let oe=z("span","ai-rw-badge-text"),W=Tr(m.text).split(" \xB7 ");W.length>=3?oe.append(z("span","ai-rw-badge-engine",`${W.slice(0,2).join(" \xB7 ")} \xB7 `),z("span","ai-rw-badge-model",W.slice(2).join(" \xB7 "))):oe.append(z("span","ai-rw-badge-engine",Tr(m.text)));let ue=[G,oe];m.fallback&&ue.push(z("span","ai-rw-badge-fallback","(fallback)")),K.replaceChildren(...ue)}function bt(){let m=ze;for(let T=m.lastElementChild;T&&/^(UL|OL|LI|BLOCKQUOTE|P|DIV)$/.test(T.tagName);T=m.lastElementChild)m=T;m.append(kt)}function Ft(){let m=ee==="titles"?"":ee==="summary"?(i==="done"&&Ee?Ta(w,Ee.kind,S):xa(w)).trim():i==="done"?E.trim():qt(w).trimStart();if(Or(ze,m),bt(),mt.classList.toggle("is-waiting",i==="running"&&!m),i==="running"&&!m){let I=e.badge($,null,!1)?.text.split(" \xB7 ")[1];ze.replaceChildren(),bt(),ze.dataset.placeholder=Le?wr:ee==="titles"&&w?"Suggesting titles\u2026":I?`Waiting for ${I}\u2026`:"Waiting for the engine\u2026"}else delete ze.dataset.placeholder;let T=ze.parentElement;T&&i==="running"&&T.scrollHeight-T.scrollTop-T.clientHeight<40&&(T.scrollTop=T.scrollHeight)}function Yt(){Me||(Me=requestAnimationFrame(()=>{Me=0,n&&Ft()}))}let Ot=!1;function Vt(){let m=!!n&&i==="running";m!==Ot&&(Ot=m,e.onBusy?.(m))}function Xe(){if(Vt(),!n||!t)return;let m=be();n.dataset.phase=i,n.dataset.output=m,n.dataset.layout=m==="replace"&&t.multiline?"split":"single",n.setAttribute("aria-busy",i==="running"?"true":"false"),n.setAttribute("aria-label",ee==="summary"?"Summarize with AI":ee==="titles"?"Suggest titles with AI":o==="explain"&&i!=="choose"?"Explain with AI":"Rewrite with AI"),te.textContent=at(),o==="custom"&&a&&i!=="choose"?te.title=a:te.title=te.textContent,Oe.hidden=i!=="choose",De.hidden=!!u,pe.hidden=!!u,Pe.hidden=!u,lt.hidden=i==="choose"||i==="error"||m==="choose"&&i==="done",R.hidden=!(m==="choose"&&i==="done"),L.hidden=ee!=="summary";for(let oe of L.querySelectorAll(".ai-rw-kind-seg"))oe.setAttribute("aria-pressed",oe.dataset.kind===Ee?.kind?"true":"false");ct.hidden=i!=="error",f.hidden=i==="choose"||i==="error",Tt.textContent=m==="readOnly"?"Explanation":o==="translate"?"Translation":"Rewrite",ut(),Ft();let T=i==="done"&&!!E.trim();A.hidden=i==="error"||m==="choose",A.setAttribute("aria-disabled",T?"false":"true"),A.textContent=m==="readOnly"?"Insert below":m==="insert"?"Insert":m==="replaceDocument"?"Replace document":"Accept",A.title=m==="readOnly"?"Insert the explanation as a quote below the selection":m==="insert"?"Insert at the cursor (Enter)":m==="replaceDocument"?"Replace the document body; frontmatter is kept (Enter)":"Replace the selection (Enter)",l.hidden=i==="error"||m==="choose",l.setAttribute("aria-disabled",(i==="done"?E:qt(w)).trim()?"false":"true"),s.hidden=i==="error",g.textContent=Le?wr:ae,ke.hidden=!(i==="done"&&O),i==="done"&&O&&(ke.textContent=Vo(O),ke.title=Jo(O));let I=ee==="rewrite"?t.scope==="document"?"translate":null:ee,B=I&&(i==="running"||i==="done")?Od(I,$e):"";_.hidden=!B,_.textContent=B;let G=m==="readOnly"?"Close (Esc)":"Cancel (Esc)";if(y.setAttribute("aria-label",G),y.title=G,yt.hidden=!(i==="done"&&X),i==="done"&&X){let oe=z("span","ai-rw-warn-icon");oe.innerHTML=Ed,yt.replaceChildren(oe,z("span","ai-rw-warn-text",X.text)),yt.title=X.title}i==="error"&&se&&M(se)}function St(m){return m.engineId?e.engineName?.(m.engineId)??null:null}function Jt(m){if(he)return{title:"No engine can rewrite right now",message:m.message,action:"openSettings"};let T=St(m),I=$&&(!m.engineId||$.engineId===m.engineId)?$.modelId:void 0;return le??Gn(m.code,{...T?{engine:T}:{},...I?{model:I}:{}})}function M(m){let T=Jt(m),I=z("span","ai-rw-error-icon");I.innerHTML=xd;let B=z("div","ai-rw-error-text");B.append(z("div","ai-rw-error-title",T.title));let G=m.message&&m.message!==T.message?m.message:"";if(B.append(z("div","ai-rw-error-message",m.code==="unknown"&&G?G:T.message)),G&&m.code==="modelLoadFailed"){let je=z("details","ai-rw-error-more");je.append(z("summary",void 0,"Details"),z("div","ai-rw-error-detail",G)),B.append(je)}else G&&m.code!=="unknown"&&B.append(z("div","ai-rw-error-detail",G));if(m.code==="contextOverflow"&&t){let je=t.scope==="selection"?"The selection":"The document",nt=ee==="summary"?Ee?.markdown.length??0:ee==="titles"?Ne?.markdown.length??0:t.text.length;B.append(z("div","ai-rw-error-detail",`${je} is ${nt.toLocaleString()} characters.`))}let oe=z("div","ai-rw-error-actions"),W=(T.action==="openEngine"||T.action==="chooseModel")&&!!m.engineId,ue=T.action==="chooseModel"?"Choose model":W?`Open ${St(m)??"engine"}`:"Open AI settings",V=T.action==="openSettings"||T.action==="chooseModel"||W,re=ot(`ai-rw-btn${V?" ai-rw-btn--primary":""}`,ue,()=>{Q({refocus:!1}),W?e.openSettings(m.engineId):e.openSettings()});oe.append(re),!he&&T.action!=="shortenSelection"&&m.code!=="cloudBlocked"&&oe.append(ot(`ai-rw-btn${T.action==="retry"?" ai-rw-btn--primary":""}`,m.code==="badOutput"?"Try again":"Retry",()=>Ve())),oe.append(ot("ai-rw-btn","Close",()=>Q())),ct.replaceChildren(I,B,oe)}function J(){if(!n||!t)return;if(!t.alive()){Q({refocus:!1});return}let m=t.rect();if(!m)return;let T=window.innerWidth,I=window.innerHeight,B=8,G=n.offsetWidth||440,oe=n.offsetHeight||200;if(!Re){let V=Math.min(I*.55,380);Re=m.bottom+B+V<=I-B||m.top-B-V<B?"below":"above"}let W=Re==="below"?m.bottom+B:m.top-B-oe;W=Math.max(B,Math.min(W,I-oe-B));let ue=Math.max(B,Math.min(m.left,T-G-B));n.style.top=`${Math.round(W)}px`,n.style.left=`${Math.round(ue)}px`}function ve(m){let T=be()==="choose"&&i==="done";if(!n||i!=="choose"&&!T||!/^(Arrow(Up|Down|Left|Right)|Home|End)$/.test(m.key))return!1;let I=T?".ai-rw-titles > button":u?".ai-rw-picker-list > button":".ai-rw-menu .ai-rw-chip",B=[...n.querySelectorAll(I)],G=B.indexOf(m.target);if(G<0)return!1;let oe=m.key==="ArrowDown"||m.key==="ArrowRight",W=m.key==="Home"?0:m.key==="End"?B.length-1:(G+(oe?1:-1)+B.length)%B.length;return B[W].focus({preventScroll:!0}),!0}function Te(m){Q({refocus:!1}),t=m,Re=null,w="",E="",S=!1,$=null,N=null,O=null,F=!1,j=null,se=null,he=!1,ae="",X=null,u=null,r={},o="shorter",a="",b=m.scope==="document",d=b,ee="rewrite",Ee=null,Ne=null,ge=[],$e=1,ie="",Ie="",Le=!1,n=Ce(),yi().appendChild(n);let T=G=>{if(!n)return;if(G.key==="Escape"){G.preventDefault(),G.stopPropagation(),i==="choose"&&u?Fe():Q();return}if(n.contains(G.target)&&ve(G)){G.preventDefault();return}let oe=be();if(G.key==="Enter"&&i==="done"&&oe!=="readOnly"&&oe!=="choose"&&!G.shiftKey&&!G.altKey){let W=G.target,ue=!!W&&(W.tagName==="INPUT"||W.tagName==="TEXTAREA"),V=!!W&&W.tagName==="BUTTON"&&W!==A&&n.contains(W);(!ue&&!V||G.metaKey||G.ctrlKey)&&(G.preventDefault(),G.stopPropagation(),fe())}},I=G=>{n&&!n.contains(G.target)&&Q({refocus:!1})},B=()=>J();document.addEventListener("keydown",T,!0),document.addEventListener("mousedown",I,!0),window.addEventListener("resize",B),document.addEventListener("scroll",B,!0),q.push(()=>document.removeEventListener("keydown",T,!0),()=>document.removeEventListener("mousedown",I,!0),()=>window.removeEventListener("resize",B),()=>document.removeEventListener("scroll",B,!0))}function Be(m){if(!j||i==="choose"||(m??In)===Er(j))return;Yc(m),j={...j,sent:m,auto:!1};let T=m?Lt(j.kind).find(I=>I.level===m)?.label??m:"Default";Ve(),x.textContent=`Thinking: ${T}`}function Ve(){ee==="summary"?p():ee==="titles"?v():ce(o,a)}function et(m){return e.routeInfo?.(m).contextTokens??en}function Je(){Y();let m=new AbortController;return k=m,i="running",w="",E="",S=!1,N=null,O=null,se=null,le=null,ae="",X=null,Le=!1,{seq:h,signal:m.signal}}function Ze(m){return{onRoute:(T,I)=>{m===h&&($=T,j=I,w="",ut(),Ft())},onToken:(T,I)=>{m===h&&(w=I,Yt())}}}function tt(){return ee==="summary"?{feature:"summary",sends:"document"}:ee==="titles"?{feature:"title",sends:"document"}:{feature:"rewrite",sends:t?.scope==="document"?"document":"selection"}}function Ae(m){let T={...m.result.served,...tt()};N=T,O=Wo(m.result),F=m.viaFallback,j=m.thinking,e.onServed(T,m.viaFallback)}function Se(m){let T=m.result.finishReason;return T==="length"?qn({thinking:mo(m.thinking),empty:!1}).message:T==="error"?"The stream ended early.":""}function Nt(m){let T=qn({thinking:mo(m.thinking),empty:!0});le=T,Rt(Et("badOutput",T.message))}function Rt(m){i="error",se=m,Le=!1,Xe(),J(),x.textContent=`${Jt(m).title}.`,ct.querySelector(".ai-rw-btn--primary, .ai-rw-btn")?.focus({preventScroll:!0})}function wt(m){return T=>{if(m!==h||!n)return;k=null;let I=It(T);I.code!=="cancelled"&&Rt(I)}}function on(m){!Ee||Ee.kind===m||(Ee.kind=m,p())}function p(){let m=t,T=Ee;if(!m||!n||!T)return;let{seq:I,signal:B}=Je(),G=T.kind,oe=wn(T.markdown,{contextTokens:et("summary"),outputTokens:zi(G,T.markdown.length),reserveTokens:Mn});$e=oe.coverage,Xe(),J(),n.focus({preventScroll:!0}),e.run({feature:"summary",messages:Aa({document:oe.text,kind:G,coverage:oe.coverage}),maxTokens:zi(G,oe.text.length),temperature:.3,thinking:uo,job:"summary"},Ze(I),B).then(W=>{if(I!==h||!n)return;k=null,Ae(W),w=W.result.text||w;let ue=W.result.finishReason==="length";if(S=ue,E=Sa(w,G,$e,ue),!E.trim()){ue?Nt(W):Rt(Et("badOutput"));return}i="done",ae=Se(W),Xe(),J(),x.textContent=`${G==="outline"?"Outline":"Summary"} ready. Press Enter to insert or Escape to cancel.`,A.focus({preventScroll:!0})},wt(I))}function v(){let m=t,T=Ne;if(!m||!n||!T)return;let{seq:I,signal:B}=Je();ge=[];let G=e.routeInfo?.("title"),oe=ya(T.markdown),W=wn(T.markdown,{contextTokens:G?.contextTokens??en,outputTokens:qi(3),reserveTokens:Mn+Math.ceil(Xn(oe).length/yn)});$e=W.coverage,Xe(),J(),n.focus({preventScroll:!0});let ue=$a({document:W.text,outline:oe,existingTitle:T.existingTitle,count:3}),V=re=>e.run({feature:"title",messages:re,maxTokens:qi(3),temperature:.7,thinking:uo,job:"title",...G?.json?{format:"json"}:{}},Ze(I),B);V(ue).then(async re=>{if(I!==h||!n)return;Ae(re);let je=re.result.text||w;if(!qt(je).trim()&&re.result.finishReason==="length"){k=null,Nt(re);return}let nt=re,an=Gi(je,T.existingTitle);if(!an.ok){Le=!0,Xe();let mn=await V([...ue,...ma(je,an.error)]);if(I!==h||!n)return;if(Ae(mn),Le=!1,nt=mn,an=Gi(mn.result.text||w,T.existingTitle),!an.ok){if(mn.result.finishReason==="length"){k=null,Nt(mn);return}throw Et("badOutput",an.error)}}k=null,ge=an.titles.slice(0,3),i="done",ae=Se(nt),C(),Xe(),J(),x.textContent=`${ge.length} ${ge.length===1?"title":"titles"} ready. ${kr[T.effect]}. Escape cancels.`,U.querySelector("button")?.focus({preventScroll:!0})}).catch(wt(I))}function C(){U.replaceChildren(...ge.map(m=>{let T=ot("ai-rw-option ai-rw-title-option","",()=>H(m));return T.setAttribute("role","menuitem"),T.append(z("span","ai-rw-option-label",m)),T})),D.textContent=Ne?kr[Ne.effect]:""}function H(m){let T=t,I=Ne;if(!T||!I||i!=="done")return;let B=I.apply(m);Q({refocus:!0}),B||T.focus()}function ce(m,T){let I=t;if(!I||!n)return;let{seq:B,signal:G}=Je();o=m,a=m==="custom"?T??a:"",u=null,gt.textContent=I.scope==="document"?"":I.text.trim();let oe=Ht(m);oe?.param==="language"&&r.language&&jc(r.language),oe?.param==="audience"&&r.audience&&qc(r.audience);let W=oe?.output==="readOnly";ie=I.text,Ie="",$e=1;let ue=W?ra():ia(I.text,m);if(I.scope==="document"&&!W){let re=_d(I.text,et("rewrite"));ie=re.text,Ie=re.rest,$e=re.coverage,ue=re.maxTokens}Xe(),J(),n.focus({preventScroll:!0});let V=W?aa({selection:I.text,before:I.before,after:I.after,title:I.title}):ta({variant:m,instruction:a,selection:ie,before:I.before,after:I.after,params:oe?.param?r:void 0,scope:I.scope==="document"?"document":"selection"});e.run({feature:"rewrite",...I.scope==="document"?{sends:"document"}:{},messages:V,maxTokens:ue,temperature:m==="fixFlow"||m==="translate"?.2:.5,thinking:uo,job:W?"explain":m==="translate"?"translate":"rewrite"},Ze(B),G).then(re=>{if(!(B!==h||!n)){if(k=null,Ae(re),E=oa(re.result.text||w,W?"":ie),!E.trim())i="error",re.result.finishReason==="length"?(le=qn({thinking:mo(re.thinking),empty:!0}),se=Et("badOutput",le.message)):se={code:"unknown",message:"The engine sent back no text."};else if(i="done",ae=Se(re),Ld.has(m)){let je=ua(ie,E),nt=Cd(je);X=nt?{text:nt,title:je.messages.join(`
|
|
116
|
-
`)}:null}Xe(),J(),x.textContent=i!=="done"?"Rewrite failed.":W?"Explanation ready. Insert below adds it to the document; Escape closes.":`${o==="translate"?"Translation":"Rewrite"} ready. Press Enter to accept or Escape to cancel.${X?` ${X.text}.`:""}`,i==="done"&&(W?n:A).focus({preventScroll:!0})}},wt(B))}function fe(){let m=t,T=be();if(!m||i!=="done"||!E.trim()||T==="choose")return;let I=T==="readOnly"?m.insertBelow(E):T==="replaceDocument"&&Ie.trim()?m.accept(`${E.trimEnd()}
|
|
117
|
-
|
|
118
|
-
${Ie.trimStart()}`):m.accept(E);Q({refocus:!0}),I||m.focus()}function He(){let m=(i==="done"?E:qt(w)).trim();m&&navigator.clipboard?.writeText(m).then(()=>{n&&(l.textContent="Copied",window.clearTimeout(P),P=window.setTimeout(()=>{l.textContent="Copy"},1200))},()=>{})}return{open(m,T){Te(m),r={...T?.params},d=b||!!T?.wholeDocument;let I=T?Ht(T.variant):void 0;if(b&&(!I||I.id!=="translate"||!Ar(I,r))){we("language");return}if(I&&I.param&&!Ar(I,r)){we(I.param==="language"?"language":"audience");return}if(I&&(I.id!=="custom"||T?.instruction?.trim())){if(I.id==="translate"&&d&&!qe()){d=!1,we("language");return}ce(I.id,T?.instruction);return}i="choose",Xe(),J(),We.focus({preventScroll:!0})},openSummary(m,T){Te(m),ee="summary",Ee={...T},p()},openTitles(m,T){Te(m),ee="titles",Ne=T,v()},openUnavailable(m,T){Te(m),i="error",se={code:"unknown",message:T},he=!0,Xe(),J(),ct.querySelector(".ai-rw-btn")?.focus({preventScroll:!0})},close:()=>Q(),isOpen:()=>!!t,destroy(){Q({refocus:!1})}}}export{ft as AI_ENGINE_PRESETS,Yd as AI_TURN_ON_PATCH,yn as CHARS_PER_TOKEN,en as DEFAULT_CONTEXT_TOKENS,Ia as PROPERTY_VOCABULARY_MAX,Qn as aiConsentHost,Gn as aiErrorCopy,eu as aiFeatureAvailability,ec as aiIndicatorState,qn as aiLengthLimitCopy,Ql as aiNextRouteChanged,Id as aiRewriteMenuGroups,mo as aiRunThinkingOn,Vd as aiSetupTarget,Jd as aiToolbarMenuEntries,pu as applyRichTitle,mu as applySourceTitle,bc as bestLocalServer,wn as budgetDocument,Wd as buildAiSettingsSection,ll as buildPropertiesMessages,hu as createAiRewritePopover,uu as cursorInsertTarget,so as detectLocalServers,Ue as engineDisplayName,ui as experimentalBadge,ya as headingsOutline,od as hideAiFirstRunPanel,Xt as hostOfUrl,Xd as isAiFirstRunPanelOpen,zt as isHostEngineKind,Fi as isRouteUsable,ma as jsonRepairMessages,Wc as loadThinkingLevel,Et as makeAiError,Kc as mountAiEnginesPage,Vr as parseAiSettings,dl as parsePropertySuggestions,Sn as privacyCard,ur as privacyLine,cl as propertiesMaxTokens,Yc as rememberThinkingLevel,Xn as renderHeadingOutline,kn as resolveRoute,qt as rewriteVisibleText,cu as richDocumentTarget,su as richRewriteTarget,Qd as runAiCompletion,dr as scanForSetup,vc as setUpLocalEngine,gd as setYamlTitle,Zd as showAiFirstRunPanel,fu as sourceCursorTarget,du as sourceDocumentTarget,lu as sourceRewriteTarget,Lt as thinkingChoices,uo as thinkingLevelFor,It as toAiError,Zn as whatIsSent,ar as withSavedAiKeys,hd as yamlHasTitle};
|