agent-afk 5.202.0 → 5.203.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.
Files changed (38) hide show
  1. package/dist/agent/session/agent-session.d.ts +1 -0
  2. package/dist/agent/session-ledger-project.d.ts +103 -0
  3. package/dist/agent/session-ledger-reader.d.ts +8 -0
  4. package/dist/agent/session-ledger.d.ts +4 -63
  5. package/dist/agent/subagent/fork-types.d.ts +2 -1
  6. package/dist/agent/subagent.d.ts +3 -0
  7. package/dist/agent/types/session-types.d.ts +20 -0
  8. package/dist/agent/workspace/index.d.ts +1 -1
  9. package/dist/agent/workspace/workspace-tools.d.ts +2 -1
  10. package/dist/cli.mjs +685 -685
  11. package/dist/index.mjs +239 -239
  12. package/dist/telegram.mjs +302 -302
  13. package/dist/web-server/frontend/app-approvals.d.ts +7 -0
  14. package/dist/web-server/frontend/app-views.d.ts +3 -0
  15. package/dist/web-server/frontend/at-file-panel.d.ts +5 -0
  16. package/dist/web-server/frontend/bg-jobs-panel.d.ts +14 -0
  17. package/dist/web-server/frontend/diff-viewer.d.ts +17 -0
  18. package/dist/web-server/frontend/ledger-adapter.d.ts +7 -2
  19. package/dist/web-server/frontend/memory-panel.d.ts +6 -0
  20. package/dist/web-server/frontend/model-selector.d.ts +10 -0
  21. package/dist/web-server/frontend/render-approvals.d.ts +22 -0
  22. package/dist/web-server/frontend/render-incremental.d.ts +1 -0
  23. package/dist/web-server/frontend/render.d.ts +3 -22
  24. package/dist/web-server/frontend/schedules-view.d.ts +1 -0
  25. package/dist/web-server/frontend/session-status.d.ts +11 -0
  26. package/dist/web-server/frontend/subagent-tree.d.ts +27 -0
  27. package/dist/web-server/frontend/thinking-panel.d.ts +3 -0
  28. package/dist/web-server/frontend/tool-trace-panel.d.ts +2 -0
  29. package/dist/web-server/frontend/view-model.d.ts +19 -1
  30. package/dist/web-server/routes.bg-jobs.d.ts +3 -0
  31. package/dist/web-server/routes.memory.d.ts +3 -0
  32. package/dist/web-server/routes.models.d.ts +6 -0
  33. package/dist/web-ui-assets/app.js +45 -45
  34. package/dist/web-ui-assets/approvals.css +3 -1
  35. package/dist/web-ui-assets/index.html +19 -10
  36. package/dist/web-ui-assets/schedules.css +2 -3
  37. package/dist/web-ui-assets/styles.css +263 -1
  38. package/package.json +1 -1
@@ -1,65 +1,65 @@
1
- var Xt="__AFK_WEB_TOKEN__",Ge="afk_web_token",Ve="";function Xe(){let t=new URLSearchParams(location.search);(t.get("token")||t.get("k"))&&history.replaceState(null,"",location.pathname);let e=Jt();return e?(Yt(e),e):en()}function Jt(){let t=document.querySelector('meta[name="afk-token"]')?.getAttribute("content");return!t||t===Xt?"":t}function Yt(t){Ve=t;try{sessionStorage.setItem(Ge,t)}catch{}}function en(){try{let t=sessionStorage.getItem(Ge);if(t)return t}catch{}return Ve}var As=Object.freeze({end:!0,reason:"session_closed"});function Je(t){return typeof t=="object"&&t!==null&&t.end===!0}function Ye(t){let n=t.replace(/\r\n/g,`
1
+ var Mn="__AFK_WEB_TOKEN__",mt="afk_web_token",ft="";function gt(){let t=new URLSearchParams(location.search);(t.get("token")||t.get("k"))&&history.replaceState(null,"",location.pathname);let e=An();return e?(Rn(e),e):$n()}function An(){let t=document.querySelector('meta[name="afk-token"]')?.getAttribute("content");return!t||t===Mn?"":t}function Rn(t){ft=t;try{sessionStorage.setItem(mt,t)}catch{}}function $n(){try{let t=sessionStorage.getItem(mt);if(t)return t}catch{}return ft}var Fr=Object.freeze({end:!0,reason:"session_closed"});function bt(t){return typeof t=="object"&&t!==null&&t.end===!0}function kt(t){let n=t.replace(/\r\n/g,`
2
2
  `).split(`
3
3
 
4
- `),r=n.pop()??"",s=[];for(let i of n){if(i.trim()==="")continue;let o,l;for(let a of i.split(`
5
- `))a.startsWith("id: ")?o=a.slice(4):a.startsWith("id:")?o=a.slice(3).trimStart():a.startsWith("data: ")?l=a.slice(6):a.startsWith("data:")&&(l=a.slice(5).trimStart());l!==void 0&&s.push({id:o,data:l})}return{events:s,remainder:r}}var tn=15e3,nn=500,ie=class{constructor(e,n,r){this.sessionId=e;this.token=n;this.handlers=r}sessionId;token;handlers;controller;lastEventId;attempt=0;stopped=!1;start(){this.stopped=!1,this.connect()}stop(){this.stopped=!0,this.controller?.abort(),this.handlers.onStatus?.("closed")}async connect(){if(this.stopped)return;this.handlers.onStatus?.(this.attempt===0?"connecting":"reconnecting");let e=!1;this.controller=new AbortController;let n={authorization:`Bearer ${this.token}`};this.lastEventId!==void 0&&(n["last-event-id"]=this.lastEventId);try{let i=await fetch(`/api/sessions/${encodeURIComponent(this.sessionId)}/stream`,{headers:n,signal:this.controller.signal});if(!i.ok){if(i.status===401||i.status===403||i.status===404){this.stopped=!0;let d=i.status===401?"unauthorized":i.status===403?"forbidden":"not-found";this.handlers.onStatus?.("closed",d);return}throw new Error(`stream failed: ${i.status}`)}if(i.body===null)throw new Error("stream failed: no body");this.attempt=0,this.handlers.onStatus?.("open");let o=i.body.getReader(),l=new TextDecoder,a="";e:for(;;){let{done:d,value:c}=await o.read();if(d)break;a+=l.decode(c,{stream:!0});let{events:p,remainder:u}=Ye(a);a=u;for(let f of p){if(f.id!==void 0&&(this.lastEventId=f.id),f.data===void 0)continue;let m;try{m=JSON.parse(f.data)}catch{continue}if(Je(m)){e=!0,this.stopped=!0;break e}this.handlers.onEvent(m,{id:f.id})}}}catch{}if(this.stopped){e&&this.handlers.onStatus?.("ended");return}this.attempt+=1;let r=.75+Math.random()*.5,s=Math.min(nn*2**(this.attempt-1),tn)*r;setTimeout(()=>{this.connect()},s)}};var et=/(?:^|\s)(\/[A-Za-z][A-Za-z0-9_:-]*)/g,sn=Number.POSITIVE_INFINITY;function nt(t){let e=new Map;for(let n=0;n<t.length;n++){let r=t[n];if(!r)continue;et.lastIndex=0;let s;for(;(s=et.exec(r))!==null;){let i=s[1]?.toLowerCase();i!==void 0&&!e.has(i)&&e.set(i,n)}}return e}function tt(t,e){let n=t.startsWith("/")?t.toLowerCase():`/${t.toLowerCase()}`;return e.get(n)??sn}function st(t,e,n){let r=tt(t,n),s=tt(e,n);return r!==s?r-s:t.localeCompare(e)}var rn=20;function on(t,e){if(t.length===0)return!0;let n=0;for(let r=0;r<e.length&&n<t.length;r++)e[r]===t[n]&&(n+=1);return n===t.length}function rt(t,e,n=[]){let r=e.toLowerCase(),s=t.map(c=>({key:c.name.replace(/^\//,"").toLowerCase(),cand:{value:c.name,...c.summary!==void 0?{summary:c.summary}:{},...c.hint!==void 0?{hint:c.hint}:{}}})),i=s.filter(c=>c.key.startsWith(r)),o=new Set(i.map(c=>c.cand.value)),l=r.length===0?[]:s.filter(c=>!o.has(c.cand.value)&&on(r,c.key)),a=nt(n),d=(c,p)=>st(c.cand.value,p.cand.value,a);return i.sort(d),l.sort(d),[...i,...l].map(c=>c.cand).slice(0,rn)}function oe(t){t.dispatchEvent(new Event("input"))}var it=new Set(["/clear","/compact","/editor","/exit","/fast","/font-size","/fork","/keys","/model","/reauth","/resume","/rewind","/sh","/theme","/thinking"]);function ot(t,e,n,r){let s=document.createElement("div");s.id=e,s.setAttribute("role","option"),s.setAttribute("aria-selected",String(n)),s.className=n?"slash-row is-selected":"slash-row";let i=document.createElement("span");if(i.className="slash-name",i.textContent=t.value,s.appendChild(i),it.has(t.value)){let o=document.createElement("span");o.className="slash-badge",o.textContent="REPL only",o.title="Drives terminal-only machinery; cannot act in the browser.",s.appendChild(o)}if(t.summary!==void 0&&t.summary!==""){let o=document.createElement("span");o.className="slash-summary",o.textContent=t.summary,s.appendChild(o)}return s.addEventListener("mousedown",o=>{o.button===0&&(o.preventDefault(),r(t))}),s}var at=/^\/(?:[A-Za-z][\w:-]*)?$/,ae=class{constructor(e){this.deps=e;this.menuId=e.menu.id||"slash-autocomplete-listbox",this.focused=document.activeElement===e.input,e.menu.id=this.menuId,e.menu.setAttribute("role","listbox"),e.input.removeAttribute("role"),e.input.setAttribute("aria-autocomplete","list"),e.input.setAttribute("aria-haspopup","listbox"),e.input.setAttribute("aria-controls",this.menuId),this.status=document.createElement("div"),this.status.className="slash-status",this.status.setAttribute("role","status"),this.status.setAttribute("aria-live","polite"),this.status.setAttribute("aria-atomic","true"),e.menu.insertAdjacentElement("afterend",this.status),this.syncAria()}deps;commands=null;loading=null;candidates=[];selected=0;open=!1;openIntent=!1;focused=!1;composing=!1;generation=0;menuId;status;isOpen(){return this.open&&this.candidates.length>0}knows(e){return this.commands?.some(n=>n.name===e)??!1}async preload(){await this.ensureCommands()}current(){return this.isOpen()?this.candidates[this.selected]:void 0}wire(){this.deps.input.addEventListener("focus",()=>{this.focused=!0}),this.deps.input.addEventListener("keydown",e=>this.onKeyDown(e)),this.deps.input.addEventListener("compositionstart",()=>{this.composing=!0}),this.deps.input.addEventListener("compositionend",()=>{this.composing=!1,this.openIntent&&this.refresh()}),this.deps.input.addEventListener("input",()=>{this.openIntent=!0,this.composing||this.refresh()}),this.deps.input.addEventListener("blur",()=>{this.focused=!1,this.composing=!1,this.close(!0)})}onKeyDown(e){if(!(e.isComposing||e.keyCode===229)){if(e.key==="Escape"&&(this.openIntent||this.loading!==null)){this.close(!0),e.preventDefault(),e.stopImmediatePropagation();return}if(this.isOpen()&&!(e.key==="Enter"&&(e.metaKey||e.ctrlKey))){switch(e.key){case"ArrowDown":this.move(1);break;case"ArrowUp":this.move(-1);break;case"Tab":case"Enter":this.accept();break;case"Escape":this.close();break;default:return}e.preventDefault(),e.stopImmediatePropagation()}}}move(e){let n=this.candidates.length;this.selected=(this.selected+e+n)%n,this.render(),this.revealSelected()}revealSelected(){let e=this.deps.menu.children[this.selected];e instanceof HTMLElement&&typeof e.scrollIntoView=="function"&&e.scrollIntoView({block:"nearest"})}accept(){let e=this.current();e&&(this.deps.input.value=`${e.value} `,this.close(!0),this.deps.input.focus(),oe(this.deps.input))}close(e=!1){e&&(this.openIntent=!1,this.generation+=1),this.open=!1,this.candidates=[],this.selected=0,this.deps.menu.hidden=!0,this.deps.menu.textContent="",this.status.textContent="",this.syncAria()}syncAria(){let e=this.isOpen();if(this.deps.input.setAttribute("aria-expanded",String(e)),e){this.deps.input.setAttribute("aria-activedescendant",this.optionId(this.selected));let n=this.candidates[this.selected];this.status.textContent=n?`${this.candidates.length} suggestions. ${n.value}, ${this.selected+1} of ${this.candidates.length}.`:""}else this.deps.input.removeAttribute("aria-activedescendant"),this.status.textContent=""}optionId(e){return`${this.menuId}-option-${e}`}async refresh(){!this.focused&&document.activeElement===this.deps.input&&(this.focused=!0);let e=this.deps.input.value;if(!at.test(e)){this.close(!0);return}this.openIntent=!0;let n=++this.generation;if(await this.ensureCommands(),n!==this.generation||!this.openIntent||!this.focused||!at.test(this.deps.input.value)){n===this.generation&&this.close();return}let r=this.deps.input.value.slice(1);this.candidates=rt(this.commands??[],r),this.selected=0,this.open=this.candidates.length>0,this.openIntent=this.open,this.render()}async ensureCommands(){this.commands===null&&(this.loading??=this.deps.loadCommands().then(e=>{this.commands=e,this.deps.onCommandsLoaded?.()}).catch(e=>{console.error("[web] failed to load slash-command autocomplete:",e)}).finally(()=>{this.loading=null}),await this.loading)}render(){let e=this.deps.menu;if(e.textContent="",!this.isOpen()){e.hidden=!0,this.syncAria();return}this.candidates.forEach((n,r)=>{e.appendChild(this.row(n,r,r===this.selected))}),e.hidden=!1,this.syncAria()}row(e,n,r){return ot(e,this.optionId(n),r,s=>{this.selected=this.candidates.indexOf(s),this.accept()})}};var an=/^\/[A-Za-z][\w:-]*$/;function ln(t,e){return t===""?[]:t.split(/(\s+)/).filter(n=>n!=="").map(n=>an.test(n)?{text:n,kind:e(n)?"known":"slash"}:{text:n,kind:"plain"})}function cn(t,e){t.textContent="";for(let n of e){if(n.kind==="plain"){t.appendChild(document.createTextNode(n.text));continue}let r=document.createElement("span");r.className=n.kind==="known"?"tok-known":"tok-slash",r.textContent=n.text,t.appendChild(r)}t.appendChild(document.createTextNode("\u200B"))}function Se(t,e,n){cn(e,ln(t.value,n)),e.scrollTop=t.scrollTop,e.scrollLeft=t.scrollLeft}function lt(t,e,n){let r=()=>{Se(t,e,n)},s=()=>{e.scrollTop=t.scrollTop,e.scrollLeft=t.scrollLeft},i=()=>{t.removeEventListener("input",r),t.removeEventListener("scroll",s),e.textContent=""};return t.addEventListener("input",r),t.addEventListener("scroll",s),r(),i}var dn="slash-menu",pn="prompt-mirror";function ct(t){let e=document.getElementById(dn),n=document.getElementById(pn);if(!e||!n)return;let r;return r=new ae({input:t.input,menu:e,loadCommands:t.loadCommands,onCommandsLoaded:()=>Se(t.input,n,s=>r.knows(s))}),r.wire(),lt(t.input,n,s=>r.knows(s)),t.input.classList.add("slash-highlight-active"),r.preload(),r}function Y(t){return document.getElementById(t)}function y(t){let e=document.getElementById(t);if(!e)throw new ReferenceError(`missing required element #${t}`);return e}function E(t,e=5e3){let n=Y("toast");n&&(n.textContent=t,n.hidden=!1,n.classList.add("is-visible"),setTimeout(()=>{n.classList.remove("is-visible"),setTimeout(()=>{n.hidden=!0},300)},e))}function dt(){let t=Y("sidebar-backdrop"),e=Y("sidebar");t?.addEventListener("click",()=>{e?.classList.remove("is-open")}),document.addEventListener("keydown",n=>{n.key==="Escape"&&!n.defaultPrevented&&e?.classList.remove("is-open")})}function pt(t){let e=document.getElementById("new-session-form");if(e){e.remove();return}let n=Y("sidebar");if(!n)return;let r=document.createElement("div");r.id="new-session-form",r.className="new-session-form";let s=document.createElement("select");s.className="nsf-select";for(let a of["haiku","sonnet","opus"]){let d=document.createElement("option");d.value=a,d.textContent=a,a==="sonnet"&&(d.selected=!0),s.appendChild(d)}let i=document.createElement("input");i.type="text",i.className="nsf-input",i.placeholder="working directory (optional)";let o=document.createElement("button");o.className="nsf-btn",o.textContent="Create";let l=()=>{r.remove(),t(s.value,i.value.trim())};o.addEventListener("click",l),i.addEventListener("keydown",a=>{a.key==="Enter"&&l(),a.key==="Escape"&&r.remove()}),r.append(s,i,o),n.insertAdjacentElement("afterbegin",r),i.focus()}var un=/\x1B\][^\x07\x1B\x9C]*(?:\x07|\x1B\\|\x9C)|\x1B[P^_X][^\x1B\x9C]*(?:\x1B\\|\x9C)|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[6-_]/g;function ut(t){return t.replace(un,"")}function le(t){return ut(t)}function Re(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var U=Re();function vt(t){U=t}var O={exec:()=>null};function k(t,e=""){let n=typeof t=="string"?t:t.source,r={replace:(s,i)=>{let o=typeof i=="string"?i:i.source;return o=o.replace(T.caret,"$1"),n=n.replace(s,o),r},getRegex:()=>new RegExp(n,e)};return r}var hn=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),T={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}#`),htmlBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}>`)},mn=/^(?:[ \t]*(?:\n|$))+/,fn=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,gn=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,se=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,kn=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,$e=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,xt=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,yt=k(xt).replace(/bull/g,$e).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),bn=k(xt).replace(/bull/g,$e).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Ae=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,vn=/^[^\n]+/,Ie=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,xn=k(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Ie).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),yn=k(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,$e).getRegex(),he="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Me=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,wn=k("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Me).replace("tag",he).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),wt=k(Ae).replace("hr",se).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",he).getRegex(),Cn=k(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",wt).getRegex(),Pe={blockquote:Cn,code:fn,def:xn,fences:gn,heading:kn,hr:se,html:wn,lheading:yt,list:yn,newline:mn,paragraph:wt,table:O,text:vn},ht=k("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",se).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",he).getRegex(),Sn={...Pe,lheading:bn,table:ht,paragraph:k(Ae).replace("hr",se).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",ht).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",he).getRegex()},En={...Pe,html:k(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Me).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:O,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:k(Ae).replace("hr",se).replace("heading",` *#{1,6} *[^
6
- ]`).replace("lheading",yt).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Tn=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ln=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Ct=/^( {2,}|\\)\n(?!\s*$)/,Rn=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Q=/[\p{P}\p{S}]/u,me=/[\s\p{P}\p{S}]/u,He=/[^\s\p{P}\p{S}]/u,$n=k(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,me).getRegex(),St=/(?!~)[\p{P}\p{S}]/u,An=/(?!~)[\s\p{P}\p{S}]/u,In=/(?:[^\s\p{P}\p{S}]|~)/u,Mn=k(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",hn?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Et=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Pn=k(Et,"u").replace(/punct/g,Q).getRegex(),Hn=k(Et,"u").replace(/punct/g,St).getRegex(),Tt="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",_n=k(Tt,"gu").replace(/notPunctSpace/g,He).replace(/punctSpace/g,me).replace(/punct/g,Q).getRegex(),Nn=k(Tt,"gu").replace(/notPunctSpace/g,In).replace(/punctSpace/g,An).replace(/punct/g,St).getRegex(),Bn=k("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,He).replace(/punctSpace/g,me).replace(/punct/g,Q).getRegex(),zn=k(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Q).getRegex(),qn="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Dn=k(qn,"gu").replace(/notPunctSpace/g,He).replace(/punctSpace/g,me).replace(/punct/g,Q).getRegex(),On=k(/\\(punct)/,"gu").replace(/punct/g,Q).getRegex(),Fn=k(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Un=k(Me).replace("(?:-->|$)","-->").getRegex(),jn=k("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Un).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),de=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Kn=k(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",de).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Lt=k(/^!?\[(label)\]\[(ref)\]/).replace("label",de).replace("ref",Ie).getRegex(),Rt=k(/^!?\[(ref)\](?:\[\])?/).replace("ref",Ie).getRegex(),Zn=k("reflink|nolink(?!\\()","g").replace("reflink",Lt).replace("nolink",Rt).getRegex(),mt=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,_e={_backpedal:O,anyPunctuation:On,autolink:Fn,blockSkip:Mn,br:Ct,code:Ln,del:O,delLDelim:O,delRDelim:O,emStrongLDelim:Pn,emStrongRDelimAst:_n,emStrongRDelimUnd:Bn,escape:Tn,link:Kn,nolink:Rt,punctuation:$n,reflink:Lt,reflinkSearch:Zn,tag:jn,text:Rn,url:O},Wn={..._e,link:k(/^!?\[(label)\]\((.*?)\)/).replace("label",de).getRegex(),reflink:k(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",de).getRegex()},Ee={..._e,emStrongRDelimAst:Nn,emStrongLDelim:Hn,delLDelim:zn,delRDelim:Dn,url:k(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",mt).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:k(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",mt).getRegex()},Qn={...Ee,br:k(Ct).replace("{2,}","*").getRegex(),text:k(Ee.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},ce={normal:Pe,gfm:Sn,pedantic:En},ee={normal:_e,gfm:Ee,breaks:Qn,pedantic:Wn},Gn={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},ft=t=>Gn[t];function N(t,e){if(e){if(T.escapeTest.test(t))return t.replace(T.escapeReplace,ft)}else if(T.escapeTestNoEncode.test(t))return t.replace(T.escapeReplaceNoEncode,ft);return t}function gt(t){try{t=encodeURI(t).replace(T.percentDecode,"%")}catch{return null}return t}function kt(t,e){let n=t.replace(T.findPipe,(i,o,l)=>{let a=!1,d=o;for(;--d>=0&&l[d]==="\\";)a=!a;return a?"|":" |"}),r=n.split(T.splitPipe),s=0;if(r[0].trim()||r.shift(),r.length>0&&!r.at(-1)?.trim()&&r.pop(),e)if(r.length>e)r.splice(e);else for(;r.length<e;)r.push("");for(;s<r.length;s++)r[s]=r[s].trim().replace(T.slashPipe,"|");return r}function te(t,e,n){let r=t.length;if(r===0)return"";let s=0;for(;s<r;){let i=t.charAt(r-s-1);if(i===e&&!n)s++;else if(i!==e&&n)s++;else break}return t.slice(0,r-s)}function Vn(t,e){if(t.indexOf(e[1])===-1)return-1;let n=0;for(let r=0;r<t.length;r++)if(t[r]==="\\")r++;else if(t[r]===e[0])n++;else if(t[r]===e[1]&&(n--,n<0))return r;return n>0?-2:-1}function Xn(t,e=0){let n=e,r="";for(let s of t)if(s===" "){let i=4-n%4;r+=" ".repeat(i),n+=i}else r+=s,n++;return r}function bt(t,e,n,r,s){let i=e.href,o=e.title||null,l=t[1].replace(s.other.outputLinkReplace,"$1");r.state.inLink=!0;let a={type:t[0].charAt(0)==="!"?"image":"link",raw:n,href:i,title:o,text:l,tokens:r.inlineTokens(l)};return r.state.inLink=!1,a}function Jn(t,e,n){let r=t.match(n.other.indentCodeCompensation);if(r===null)return e;let s=r[1];return e.split(`
7
- `).map(i=>{let o=i.match(n.other.beginningSpace);if(o===null)return i;let[l]=o;return l.length>=s.length?i.slice(s.length):i}).join(`
8
- `)}var pe=class{options;rules;lexer;constructor(t){this.options=t||U}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let n=e[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:e[0],codeBlockStyle:"indented",text:this.options.pedantic?n:te(n,`
9
- `)}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let n=e[0],r=Jn(n,e[3]||"",this.rules);return{type:"code",raw:n,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:r}}}heading(t){let e=this.rules.block.heading.exec(t);if(e){let n=e[2].trim();if(this.rules.other.endingHash.test(n)){let r=te(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:e[0],depth:e[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(t){let e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:te(e[0],`
10
- `)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=te(e[0],`
4
+ `),s=n.pop()??"",r=[];for(let i of n){if(i.trim()==="")continue;let o,l;for(let a of i.split(`
5
+ `))a.startsWith("id: ")?o=a.slice(4):a.startsWith("id:")?o=a.slice(3).trimStart():a.startsWith("data: ")?l=a.slice(6):a.startsWith("data:")&&(l=a.slice(5).trimStart());l!==void 0&&r.push({id:o,data:l})}return{events:r,remainder:s}}var In=15e3,Hn=500,ge=class{constructor(e,n,s){this.sessionId=e;this.token=n;this.handlers=s}sessionId;token;handlers;controller;lastEventId;attempt=0;stopped=!1;start(){this.stopped=!1,this.connect()}stop(){this.stopped=!0,this.controller?.abort(),this.handlers.onStatus?.("closed")}async connect(){if(this.stopped)return;this.handlers.onStatus?.(this.attempt===0?"connecting":"reconnecting");let e=!1;this.controller=new AbortController;let n={authorization:`Bearer ${this.token}`};this.lastEventId!==void 0&&(n["last-event-id"]=this.lastEventId);try{let i=await fetch(`/api/sessions/${encodeURIComponent(this.sessionId)}/stream`,{headers:n,signal:this.controller.signal});if(!i.ok){if(i.status===401||i.status===403||i.status===404){this.stopped=!0;let c=i.status===401?"unauthorized":i.status===403?"forbidden":"not-found";this.handlers.onStatus?.("closed",c);return}throw new Error(`stream failed: ${i.status}`)}if(i.body===null)throw new Error("stream failed: no body");this.attempt=0,this.handlers.onStatus?.("open");let o=i.body.getReader(),l=new TextDecoder,a="";e:for(;;){let{done:c,value:d}=await o.read();if(c)break;a+=l.decode(d,{stream:!0});let{events:u,remainder:p}=kt(a);a=p;for(let m of u){if(m.id!==void 0&&(this.lastEventId=m.id),m.data===void 0)continue;let h;try{h=JSON.parse(m.data)}catch{continue}if(bt(h)){e=!0,this.stopped=!0;break e}this.handlers.onEvent(h,{id:m.id})}}}catch{}if(this.stopped){e&&this.handlers.onStatus?.("ended");return}this.attempt+=1;let s=.75+Math.random()*.5,r=Math.min(Hn*2**(this.attempt-1),In)*s;setTimeout(()=>{this.connect()},r)}};var vt=/(?:^|\s)(\/[A-Za-z][A-Za-z0-9_:-]*)/g,Nn=Number.POSITIVE_INFINITY;function xt(t){let e=new Map;for(let n=0;n<t.length;n++){let s=t[n];if(!s)continue;vt.lastIndex=0;let r;for(;(r=vt.exec(s))!==null;){let i=r[1]?.toLowerCase();i!==void 0&&!e.has(i)&&e.set(i,n)}}return e}function yt(t,e){let n=t.startsWith("/")?t.toLowerCase():`/${t.toLowerCase()}`;return e.get(n)??Nn}function wt(t,e,n){let s=yt(t,n),r=yt(e,n);return s!==r?s-r:t.localeCompare(e)}var Pn=20;function _n(t,e){if(t.length===0)return!0;let n=0;for(let s=0;s<e.length&&n<t.length;s++)e[s]===t[n]&&(n+=1);return n===t.length}function Ct(t,e,n=[]){let s=e.toLowerCase(),r=t.map(d=>({key:d.name.replace(/^\//,"").toLowerCase(),cand:{value:d.name,...d.summary!==void 0?{summary:d.summary}:{},...d.hint!==void 0?{hint:d.hint}:{}}})),i=r.filter(d=>d.key.startsWith(s)),o=new Set(i.map(d=>d.cand.value)),l=s.length===0?[]:r.filter(d=>!o.has(d.cand.value)&&_n(s,d.key)),a=xt(n),c=(d,u)=>wt(d.cand.value,u.cand.value,a);return i.sort(c),l.sort(c),[...i,...l].map(d=>d.cand).slice(0,Pn)}function be(t){t.dispatchEvent(new Event("input"))}var Et=new Set(["/clear","/compact","/editor","/exit","/fast","/font-size","/fork","/keys","/model","/reauth","/resume","/rewind","/sh","/theme","/thinking"]);function St(t,e,n,s){let r=document.createElement("div");r.id=e,r.setAttribute("role","option"),r.setAttribute("aria-selected",String(n)),r.className=n?"slash-row is-selected":"slash-row";let i=document.createElement("span");if(i.className="slash-name",i.textContent=t.value,r.appendChild(i),Et.has(t.value)){let o=document.createElement("span");o.className="slash-badge",o.textContent="REPL only",o.title="Drives terminal-only machinery; cannot act in the browser.",r.appendChild(o)}if(t.summary!==void 0&&t.summary!==""){let o=document.createElement("span");o.className="slash-summary",o.textContent=t.summary,r.appendChild(o)}return r.addEventListener("mousedown",o=>{o.button===0&&(o.preventDefault(),s(t))}),r}var Tt=/^\/(?:[A-Za-z][\w:-]*)?$/,ke=class{constructor(e){this.deps=e;this.menuId=e.menu.id||"slash-autocomplete-listbox",this.focused=document.activeElement===e.input,e.menu.id=this.menuId,e.menu.setAttribute("role","listbox"),e.input.removeAttribute("role"),e.input.setAttribute("aria-autocomplete","list"),e.input.setAttribute("aria-haspopup","listbox"),e.input.setAttribute("aria-controls",this.menuId),this.status=document.createElement("div"),this.status.className="slash-status",this.status.setAttribute("role","status"),this.status.setAttribute("aria-live","polite"),this.status.setAttribute("aria-atomic","true"),e.menu.insertAdjacentElement("afterend",this.status),this.syncAria()}deps;commands=null;loading=null;candidates=[];selected=0;open=!1;openIntent=!1;focused=!1;composing=!1;generation=0;menuId;status;isOpen(){return this.open&&this.candidates.length>0}knows(e){return this.commands?.some(n=>n.name===e)??!1}async preload(){await this.ensureCommands()}current(){return this.isOpen()?this.candidates[this.selected]:void 0}wire(){this.deps.input.addEventListener("focus",()=>{this.focused=!0}),this.deps.input.addEventListener("keydown",e=>this.onKeyDown(e)),this.deps.input.addEventListener("compositionstart",()=>{this.composing=!0}),this.deps.input.addEventListener("compositionend",()=>{this.composing=!1,this.openIntent&&this.refresh()}),this.deps.input.addEventListener("input",()=>{this.openIntent=!0,this.composing||this.refresh()}),this.deps.input.addEventListener("blur",()=>{this.focused=!1,this.composing=!1,this.close(!0)})}onKeyDown(e){if(!(e.isComposing||e.keyCode===229)){if(e.key==="Escape"&&(this.openIntent||this.loading!==null)){this.close(!0),e.preventDefault(),e.stopImmediatePropagation();return}if(this.isOpen()&&!(e.key==="Enter"&&(e.metaKey||e.ctrlKey))){switch(e.key){case"ArrowDown":this.move(1);break;case"ArrowUp":this.move(-1);break;case"Tab":case"Enter":this.accept();break;case"Escape":this.close();break;default:return}e.preventDefault(),e.stopImmediatePropagation()}}}move(e){let n=this.candidates.length;this.selected=(this.selected+e+n)%n,this.render(),this.revealSelected()}revealSelected(){let e=this.deps.menu.children[this.selected];e instanceof HTMLElement&&typeof e.scrollIntoView=="function"&&e.scrollIntoView({block:"nearest"})}accept(){let e=this.current();e&&(this.deps.input.value=`${e.value} `,this.close(!0),this.deps.input.focus(),be(this.deps.input))}close(e=!1){e&&(this.openIntent=!1,this.generation+=1),this.open=!1,this.candidates=[],this.selected=0,this.deps.menu.hidden=!0,this.deps.menu.textContent="",this.status.textContent="",this.syncAria()}syncAria(){let e=this.isOpen();if(this.deps.input.setAttribute("aria-expanded",String(e)),e){this.deps.input.setAttribute("aria-activedescendant",this.optionId(this.selected));let n=this.candidates[this.selected];this.status.textContent=n?`${this.candidates.length} suggestions. ${n.value}, ${this.selected+1} of ${this.candidates.length}.`:""}else this.deps.input.removeAttribute("aria-activedescendant"),this.status.textContent=""}optionId(e){return`${this.menuId}-option-${e}`}async refresh(){!this.focused&&document.activeElement===this.deps.input&&(this.focused=!0);let e=this.deps.input.value;if(!Tt.test(e)){this.close(!0);return}this.openIntent=!0;let n=++this.generation;if(await this.ensureCommands(),n!==this.generation||!this.openIntent||!this.focused||!Tt.test(this.deps.input.value)){n===this.generation&&this.close();return}let s=this.deps.input.value.slice(1);this.candidates=Ct(this.commands??[],s),this.selected=0,this.open=this.candidates.length>0,this.openIntent=this.open,this.render()}async ensureCommands(){this.commands===null&&(this.loading??=this.deps.loadCommands().then(e=>{this.commands=e,this.deps.onCommandsLoaded?.()}).catch(e=>{console.error("[web] failed to load slash-command autocomplete:",e)}).finally(()=>{this.loading=null}),await this.loading)}render(){let e=this.deps.menu;if(e.textContent="",!this.isOpen()){e.hidden=!0,this.syncAria();return}this.candidates.forEach((n,s)=>{e.appendChild(this.row(n,s,s===this.selected))}),e.hidden=!1,this.syncAria()}row(e,n,s){return St(e,this.optionId(n),s,r=>{this.selected=this.candidates.indexOf(r),this.accept()})}};var Bn=/^\/[A-Za-z][\w:-]*$/;function Dn(t,e){return t===""?[]:t.split(/(\s+)/).filter(n=>n!=="").map(n=>Bn.test(n)?{text:n,kind:e(n)?"known":"slash"}:{text:n,kind:"plain"})}function qn(t,e){t.textContent="";for(let n of e){if(n.kind==="plain"){t.appendChild(document.createTextNode(n.text));continue}let s=document.createElement("span");s.className=n.kind==="known"?"tok-known":"tok-slash",s.textContent=n.text,t.appendChild(s)}t.appendChild(document.createTextNode("\u200B"))}function qe(t,e,n){qn(e,Dn(t.value,n)),e.scrollTop=t.scrollTop,e.scrollLeft=t.scrollLeft}function Lt(t,e,n){let s=()=>{qe(t,e,n)},r=()=>{e.scrollTop=t.scrollTop,e.scrollLeft=t.scrollLeft},i=()=>{t.removeEventListener("input",s),t.removeEventListener("scroll",r),e.textContent=""};return t.addEventListener("input",s),t.addEventListener("scroll",r),s(),i}var zn="slash-menu",On="prompt-mirror";function Mt(t){let e=document.getElementById(zn),n=document.getElementById(On);if(!e||!n)return;let s;return s=new ke({input:t.input,menu:e,loadCommands:t.loadCommands,onCommandsLoaded:()=>qe(t.input,n,r=>s.knows(r))}),s.wire(),Lt(t.input,n,r=>s.knows(r)),t.input.classList.add("slash-highlight-active"),s.preload(),s}function ae(t){return document.getElementById(t)}function E(t){let e=document.getElementById(t);if(!e)throw new ReferenceError(`missing required element #${t}`);return e}var jn=[{id:"sonnet",label:"Sonnet"},{id:"haiku",label:"Haiku"},{id:"opus",label:"Opus"}],Fn="sonnet",At={opus:"model-badge--opus",sonnet:"model-badge--sonnet",haiku:"model-badge--haiku"};function Kn(t){let e=t.toLowerCase();for(let n of Object.keys(At))if(e.includes(n))return At[n]??"model-badge--default";return"model-badge--default"}function Rt(t,e=jn){let n=document.createElement("div");n.className="model-selector";let s=document.createElement("label");s.className="model-selector__label",s.textContent="Model";let r=document.createElement("select");r.className="model-selector__select",r.setAttribute("aria-label","Model");let i=t.current??Fn;for(let o of e){let l=document.createElement("option");l.value=o.id,l.textContent=o.label,o.id===i&&(l.selected=!0),r.appendChild(l)}return t.onSelect(r.value),r.addEventListener("change",()=>{t.onSelect(r.value)}),s.appendChild(r),n.appendChild(s),n}function $t(t){let e=document.createElement("span");return e.className=`model-badge ${Kn(t)}`,e.textContent=Un(t),e}function Un(t){let e=t.toLowerCase();for(let n of["opus","sonnet","haiku"])if(e.includes(n))return n;return t.length>12?`${t.slice(0,12)}\u2026`:t}function T(t,e=5e3){let n=ae("toast");n&&(n.textContent=t,n.hidden=!1,n.classList.add("is-visible"),setTimeout(()=>{n.classList.remove("is-visible"),setTimeout(()=>{n.hidden=!0},300)},e))}function It(){let t=ae("sidebar-backdrop"),e=ae("sidebar");t?.addEventListener("click",()=>{e?.classList.remove("is-open")}),document.addEventListener("keydown",n=>{n.key==="Escape"&&!n.defaultPrevented&&e?.classList.remove("is-open")})}function Ht(t){let e=document.getElementById("new-session-form");if(e){e.remove();return}let n=ae("sidebar");if(!n)return;let s=document.createElement("div");s.id="new-session-form",s.className="new-session-form";let r="sonnet",i=Rt({onSelect:c=>{r=c}}),o=document.createElement("input");o.type="text",o.className="nsf-input",o.placeholder="working directory (optional)",o.setAttribute("aria-label","Working directory");let l=document.createElement("button");l.type="button",l.className="nsf-btn",l.textContent="Create";let a=()=>{s.remove(),t(r,o.value.trim())};l.addEventListener("click",a),o.addEventListener("keydown",c=>{c.key==="Enter"&&a(),c.key==="Escape"&&s.remove()}),s.append(i,o,l),n.insertAdjacentElement("afterbegin",s),o.focus()}var Gn=/\x1B\][^\x07\x1B\x9C]*(?:\x07|\x1B\\|\x9C)|\x1B[P^_X][^\x1B\x9C]*(?:\x1B\\|\x9C)|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[6-_]/g;function Nt(t){return t.replace(Gn,"")}function ve(t){return Nt(t)}function Fe(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Q=Fe();function Ot(t){Q=t}var Z={exec:()=>null};function v(t,e=""){let n=typeof t=="string"?t:t.source,s={replace:(r,i)=>{let o=typeof i=="string"?i:i.source;return o=o.replace(N.caret,"$1"),n=n.replace(r,o),s},getRegex:()=>new RegExp(n,e)};return s}var Wn=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),N={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}#`),htmlBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}>`)},Vn=/^(?:[ \t]*(?:\n|$))+/,Zn=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Jn=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,pe=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Qn=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Ke=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,jt=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Ft=v(jt).replace(/bull/g,Ke).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Xn=v(jt).replace(/bull/g,Ke).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Ue=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Yn=/^[^\n]+/,Ge=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,es=v(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Ge).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),ts=v(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Ke).getRegex(),Ee="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",We=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,ns=v("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",We).replace("tag",Ee).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Kt=v(Ue).replace("hr",pe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ee).getRegex(),ss=v(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Kt).getRegex(),Ve={blockquote:ss,code:Zn,def:es,fences:Jn,heading:Qn,hr:pe,html:ns,lheading:Ft,list:ts,newline:Vn,paragraph:Kt,table:Z,text:Yn},Pt=v("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",pe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ee).getRegex(),rs={...Ve,lheading:Xn,table:Pt,paragraph:v(Ue).replace("hr",pe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Pt).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ee).getRegex()},is={...Ve,html:v(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",We).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Z,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:v(Ue).replace("hr",pe).replace("heading",` *#{1,6} *[^
6
+ ]`).replace("lheading",Ft).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},os=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,as=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Ut=/^( {2,}|\\)\n(?!\s*$)/,ls=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Y=/[\p{P}\p{S}]/u,Se=/[\s\p{P}\p{S}]/u,Ze=/[^\s\p{P}\p{S}]/u,ds=v(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Se).getRegex(),Gt=/(?!~)[\p{P}\p{S}]/u,cs=/(?!~)[\s\p{P}\p{S}]/u,ps=/(?:[^\s\p{P}\p{S}]|~)/u,us=v(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Wn?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Wt=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,hs=v(Wt,"u").replace(/punct/g,Y).getRegex(),ms=v(Wt,"u").replace(/punct/g,Gt).getRegex(),Vt="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",fs=v(Vt,"gu").replace(/notPunctSpace/g,Ze).replace(/punctSpace/g,Se).replace(/punct/g,Y).getRegex(),gs=v(Vt,"gu").replace(/notPunctSpace/g,ps).replace(/punctSpace/g,cs).replace(/punct/g,Gt).getRegex(),bs=v("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Ze).replace(/punctSpace/g,Se).replace(/punct/g,Y).getRegex(),ks=v(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Y).getRegex(),vs="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",ys=v(vs,"gu").replace(/notPunctSpace/g,Ze).replace(/punctSpace/g,Se).replace(/punct/g,Y).getRegex(),xs=v(/\\(punct)/,"gu").replace(/punct/g,Y).getRegex(),ws=v(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Cs=v(We).replace("(?:-->|$)","-->").getRegex(),Es=v("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Cs).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),xe=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Ss=v(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",xe).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Zt=v(/^!?\[(label)\]\[(ref)\]/).replace("label",xe).replace("ref",Ge).getRegex(),Jt=v(/^!?\[(ref)\](?:\[\])?/).replace("ref",Ge).getRegex(),Ts=v("reflink|nolink(?!\\()","g").replace("reflink",Zt).replace("nolink",Jt).getRegex(),_t=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Je={_backpedal:Z,anyPunctuation:xs,autolink:ws,blockSkip:us,br:Ut,code:as,del:Z,delLDelim:Z,delRDelim:Z,emStrongLDelim:hs,emStrongRDelimAst:fs,emStrongRDelimUnd:bs,escape:os,link:Ss,nolink:Jt,punctuation:ds,reflink:Zt,reflinkSearch:Ts,tag:Es,text:ls,url:Z},Ls={...Je,link:v(/^!?\[(label)\]\((.*?)\)/).replace("label",xe).getRegex(),reflink:v(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",xe).getRegex()},ze={...Je,emStrongRDelimAst:gs,emStrongLDelim:ms,delLDelim:ks,delRDelim:ys,url:v(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",_t).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:v(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",_t).getRegex()},Ms={...ze,br:v(Ut).replace("{2,}","*").getRegex(),text:v(ze.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},ye={normal:Ve,gfm:rs,pedantic:is},le={normal:Je,gfm:ze,breaks:Ms,pedantic:Ls},As={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Bt=t=>As[t];function O(t,e){if(e){if(N.escapeTest.test(t))return t.replace(N.escapeReplace,Bt)}else if(N.escapeTestNoEncode.test(t))return t.replace(N.escapeReplaceNoEncode,Bt);return t}function Dt(t){try{t=encodeURI(t).replace(N.percentDecode,"%")}catch{return null}return t}function qt(t,e){let n=t.replace(N.findPipe,(i,o,l)=>{let a=!1,c=o;for(;--c>=0&&l[c]==="\\";)a=!a;return a?"|":" |"}),s=n.split(N.splitPipe),r=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),e)if(s.length>e)s.splice(e);else for(;s.length<e;)s.push("");for(;r<s.length;r++)s[r]=s[r].trim().replace(N.slashPipe,"|");return s}function de(t,e,n){let s=t.length;if(s===0)return"";let r=0;for(;r<s;){let i=t.charAt(s-r-1);if(i===e&&!n)r++;else if(i!==e&&n)r++;else break}return t.slice(0,s-r)}function Rs(t,e){if(t.indexOf(e[1])===-1)return-1;let n=0;for(let s=0;s<t.length;s++)if(t[s]==="\\")s++;else if(t[s]===e[0])n++;else if(t[s]===e[1]&&(n--,n<0))return s;return n>0?-2:-1}function $s(t,e=0){let n=e,s="";for(let r of t)if(r===" "){let i=4-n%4;s+=" ".repeat(i),n+=i}else s+=r,n++;return s}function zt(t,e,n,s,r){let i=e.href,o=e.title||null,l=t[1].replace(r.other.outputLinkReplace,"$1");s.state.inLink=!0;let a={type:t[0].charAt(0)==="!"?"image":"link",raw:n,href:i,title:o,text:l,tokens:s.inlineTokens(l)};return s.state.inLink=!1,a}function Is(t,e,n){let s=t.match(n.other.indentCodeCompensation);if(s===null)return e;let r=s[1];return e.split(`
7
+ `).map(i=>{let o=i.match(n.other.beginningSpace);if(o===null)return i;let[l]=o;return l.length>=r.length?i.slice(r.length):i}).join(`
8
+ `)}var we=class{options;rules;lexer;constructor(t){this.options=t||Q}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let n=e[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:e[0],codeBlockStyle:"indented",text:this.options.pedantic?n:de(n,`
9
+ `)}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let n=e[0],s=Is(n,e[3]||"",this.rules);return{type:"code",raw:n,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:s}}}heading(t){let e=this.rules.block.heading.exec(t);if(e){let n=e[2].trim();if(this.rules.other.endingHash.test(n)){let s=de(n,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(n=s.trim())}return{type:"heading",raw:e[0],depth:e[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(t){let e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:de(e[0],`
10
+ `)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=de(e[0],`
11
11
  `).split(`
12
- `),r="",s="",i=[];for(;n.length>0;){let o=!1,l=[],a;for(a=0;a<n.length;a++)if(this.rules.other.blockquoteStart.test(n[a]))l.push(n[a]),o=!0;else if(!o)l.push(n[a]);else break;n=n.slice(a);let d=l.join(`
13
- `),c=d.replace(this.rules.other.blockquoteSetextReplace,`
14
- $1`).replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}
15
- ${d}`:d,s=s?`${s}
16
- ${c}`:c;let p=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(c,i,!0),this.lexer.state.top=p,n.length===0)break;let u=i.at(-1);if(u?.type==="code")break;if(u?.type==="blockquote"){let f=u,m=f.raw+`
12
+ `),s="",r="",i=[];for(;n.length>0;){let o=!1,l=[],a;for(a=0;a<n.length;a++)if(this.rules.other.blockquoteStart.test(n[a]))l.push(n[a]),o=!0;else if(!o)l.push(n[a]);else break;n=n.slice(a);let c=l.join(`
13
+ `),d=c.replace(this.rules.other.blockquoteSetextReplace,`
14
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}
15
+ ${c}`:c,r=r?`${r}
16
+ ${d}`:d;let u=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(d,i,!0),this.lexer.state.top=u,n.length===0)break;let p=i.at(-1);if(p?.type==="code")break;if(p?.type==="blockquote"){let m=p,h=m.raw+`
17
17
  `+n.join(`
18
- `),x=this.blockquote(m);i[i.length-1]=x,r=r.substring(0,r.length-f.raw.length)+x.raw,s=s.substring(0,s.length-f.text.length)+x.text;break}else if(u?.type==="list"){let f=u,m=f.raw+`
18
+ `),g=this.blockquote(h);i[i.length-1]=g,s=s.substring(0,s.length-m.raw.length)+g.raw,r=r.substring(0,r.length-m.text.length)+g.text;break}else if(p?.type==="list"){let m=p,h=m.raw+`
19
19
  `+n.join(`
20
- `),x=this.list(m);i[i.length-1]=x,r=r.substring(0,r.length-u.raw.length)+x.raw,s=s.substring(0,s.length-f.raw.length)+x.raw,n=m.substring(i.at(-1).raw.length).split(`
21
- `);continue}}return{type:"blockquote",raw:r,tokens:i,text:s}}}list(t){let e=this.rules.block.list.exec(t);if(e){let n=e[1].trim(),r=n.length>1,s={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let i=this.rules.other.listItemRegex(n),o=!1;for(;t;){let a=!1,d="",c="";if(!(e=i.exec(t))||this.rules.block.hr.test(t))break;d=e[0],t=t.substring(d.length);let p=Xn(e[2].split(`
22
- `,1)[0],e[1].length),u=t.split(`
23
- `,1)[0],f=!p.trim(),m=0;if(this.options.pedantic?(m=2,c=p.trimStart()):f?m=e[1].length+1:(m=p.search(this.rules.other.nonSpaceChar),m=m>4?1:m,c=p.slice(m),m+=e[1].length),f&&this.rules.other.blankLine.test(u)&&(d+=u+`
24
- `,t=t.substring(u.length+1),a=!0),!a){let x=this.rules.other.nextBulletRegex(m),L=this.rules.other.hrRegex(m),A=this.rules.other.fencesBeginRegex(m),K=this.rules.other.headingBeginRegex(m),Z=this.rules.other.htmlBeginRegex(m),X=this.rules.other.blockquoteBeginRegex(m);for(;t;){let W=t.split(`
25
- `,1)[0],I;if(u=W,this.options.pedantic?(u=u.replace(this.rules.other.listReplaceNesting," "),I=u):I=u.replace(this.rules.other.tabCharGlobal," "),A.test(u)||K.test(u)||Z.test(u)||X.test(u)||x.test(u)||L.test(u))break;if(I.search(this.rules.other.nonSpaceChar)>=m||!u.trim())c+=`
26
- `+I.slice(m);else{if(f||p.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||A.test(p)||K.test(p)||L.test(p))break;c+=`
27
- `+u}f=!u.trim(),d+=W+`
28
- `,t=t.substring(W.length+1),p=I.slice(m)}}s.loose||(o?s.loose=!0:this.rules.other.doubleBlankLine.test(d)&&(o=!0)),s.items.push({type:"list_item",raw:d,task:!!this.options.gfm&&this.rules.other.listIsTask.test(c),loose:!1,text:c,tokens:[]}),s.raw+=d}let l=s.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;s.raw=s.raw.trimEnd();for(let a of s.items){if(this.lexer.state.top=!1,a.tokens=this.lexer.blockTokens(a.text,[]),a.task){if(a.text=a.text.replace(this.rules.other.listReplaceTask,""),a.tokens[0]?.type==="text"||a.tokens[0]?.type==="paragraph"){a.tokens[0].raw=a.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),a.tokens[0].text=a.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let c=this.lexer.inlineQueue.length-1;c>=0;c--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[c].src)){this.lexer.inlineQueue[c].src=this.lexer.inlineQueue[c].src.replace(this.rules.other.listReplaceTask,"");break}}let d=this.rules.other.listTaskCheckbox.exec(a.raw);if(d){let c={type:"checkbox",raw:d[0]+" ",checked:d[0]!=="[ ]"};a.checked=c.checked,s.loose?a.tokens[0]&&["paragraph","text"].includes(a.tokens[0].type)&&"tokens"in a.tokens[0]&&a.tokens[0].tokens?(a.tokens[0].raw=c.raw+a.tokens[0].raw,a.tokens[0].text=c.raw+a.tokens[0].text,a.tokens[0].tokens.unshift(c)):a.tokens.unshift({type:"paragraph",raw:c.raw,text:c.raw,tokens:[c]}):a.tokens.unshift(c)}}if(!s.loose){let d=a.tokens.filter(p=>p.type==="space"),c=d.length>0&&d.some(p=>this.rules.other.anyLine.test(p.raw));s.loose=c}}if(s.loose)for(let a of s.items){a.loose=!0;for(let d of a.tokens)d.type==="text"&&(d.type="paragraph")}return s}}html(t){let e=this.rules.block.html.exec(t);if(e)return{type:"html",block:!0,raw:e[0],pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:e[0]}}def(t){let e=this.rules.block.def.exec(t);if(e){let n=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:n,raw:e[0],href:r,title:s}}}table(t){let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let n=kt(e[1]),r=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),s=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
29
- `):[],i={type:"table",raw:e[0],header:[],align:[],rows:[]};if(n.length===r.length){for(let o of r)this.rules.other.tableAlignRight.test(o)?i.align.push("right"):this.rules.other.tableAlignCenter.test(o)?i.align.push("center"):this.rules.other.tableAlignLeft.test(o)?i.align.push("left"):i.align.push(null);for(let o=0;o<n.length;o++)i.header.push({text:n[o],tokens:this.lexer.inline(n[o]),header:!0,align:i.align[o]});for(let o of s)i.rows.push(kt(o,i.header.length).map((l,a)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:i.align[a]})));return i}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let n=e[1].trim();return{type:"heading",raw:e[0],depth:e[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(t){let e=this.rules.block.paragraph.exec(t);if(e){let n=e[1].charAt(e[1].length-1)===`
30
- `?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:n,tokens:this.lexer.inline(n)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let n=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let i=te(n.slice(0,-1),"\\");if((n.length-i.length)%2===0)return}else{let i=Vn(e[2],"()");if(i===-2)return;if(i>-1){let o=(e[0].indexOf("!")===0?5:4)+e[1].length+i;e[2]=e[2].substring(0,i),e[0]=e[0].substring(0,o).trim(),e[3]=""}}let r=e[2],s="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(r);i&&(r=i[1],s=i[3])}else s=e[3]?e[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),bt(e,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:s&&s.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(t,e){let n;if((n=this.rules.inline.reflink.exec(t))||(n=this.rules.inline.nolink.exec(t))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),s=e[r.toLowerCase()];if(!s){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return bt(n,s,n[0],this.lexer,this.rules)}}emStrong(t,e,n=""){let r=this.rules.inline.emStrongLDelim.exec(t);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let s=[...r[0]].length-1,i,o,l=s,a=0,d=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,e=e.slice(-1*t.length+s);(r=d.exec(e))!=null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(o=[...i].length,r[3]||r[4]){l+=o;continue}else if((r[5]||r[6])&&s%3&&!((s+o)%3)){a+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l+a);let c=[...r[0]][0].length,p=t.slice(0,s+r.index+c+o);if(Math.min(s,o)%2){let f=p.slice(1,-1);return{type:"em",raw:p,text:f,tokens:this.lexer.inlineTokens(f)}}let u=p.slice(2,-2);return{type:"strong",raw:p,text:u,tokens:this.lexer.inlineTokens(u)}}}}codespan(t){let e=this.rules.inline.code.exec(t);if(e){let n=e[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),s=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&s&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:e[0],text:n}}}br(t){let e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t,e,n=""){let r=this.rules.inline.delLDelim.exec(t);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let s=[...r[0]].length-1,i,o,l=s,a=this.rules.inline.delRDelim;for(a.lastIndex=0,e=e.slice(-1*t.length+s);(r=a.exec(e))!=null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(o=[...i].length,o!==s))continue;if(r[3]||r[4]){l+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l);let d=[...r[0]][0].length,c=t.slice(0,s+r.index+d+o),p=c.slice(s,-s);return{type:"del",raw:c,text:p,tokens:this.lexer.inlineTokens(p)}}}}autolink(t){let e=this.rules.inline.autolink.exec(t);if(e){let n,r;return e[2]==="@"?(n=e[1],r="mailto:"+n):(n=e[1],r=n),{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(t){let e;if(e=this.rules.inline.url.exec(t)){let n,r;if(e[2]==="@")n=e[0],r="mailto:"+n;else{let s;do s=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(s!==e[0]);n=e[0],e[1]==="www."?r="http://"+e[0]:r=e[0]}return{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let n=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:n}}}},$=class Te{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||U,this.options.tokenizer=this.options.tokenizer||new pe,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:T,block:ce.normal,inline:ee.normal};this.options.pedantic?(n.block=ce.pedantic,n.inline=ee.pedantic):this.options.gfm&&(n.block=ce.gfm,this.options.breaks?n.inline=ee.breaks:n.inline=ee.gfm),this.tokenizer.rules=n}static get rules(){return{block:ce,inline:ee}}static lex(e,n){return new Te(n).lex(e)}static lexInline(e,n){return new Te(n).inlineTokens(e)}lex(e){e=e.replace(T.carriageReturn,`
31
- `),this.blockTokens(e,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,n=[],r=!1){for(this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(T.tabCharGlobal," ").replace(T.spaceLine,""));e;){let s;if(this.options.extensions?.block?.some(o=>(s=o.call({lexer:this},e,n))?(e=e.substring(s.raw.length),n.push(s),!0):!1))continue;if(s=this.tokenizer.space(e)){e=e.substring(s.raw.length);let o=n.at(-1);s.raw.length===1&&o!==void 0?o.raw+=`
32
- `:n.push(s);continue}if(s=this.tokenizer.code(e)){e=e.substring(s.raw.length);let o=n.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(`
20
+ `),g=this.list(h);i[i.length-1]=g,s=s.substring(0,s.length-p.raw.length)+g.raw,r=r.substring(0,r.length-m.raw.length)+g.raw,n=h.substring(i.at(-1).raw.length).split(`
21
+ `);continue}}return{type:"blockquote",raw:s,tokens:i,text:r}}}list(t){let e=this.rules.block.list.exec(t);if(e){let n=e[1].trim(),s=n.length>1,r={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");let i=this.rules.other.listItemRegex(n),o=!1;for(;t;){let a=!1,c="",d="";if(!(e=i.exec(t))||this.rules.block.hr.test(t))break;c=e[0],t=t.substring(c.length);let u=$s(e[2].split(`
22
+ `,1)[0],e[1].length),p=t.split(`
23
+ `,1)[0],m=!u.trim(),h=0;if(this.options.pedantic?(h=2,d=u.trimStart()):m?h=e[1].length+1:(h=u.search(this.rules.other.nonSpaceChar),h=h>4?1:h,d=u.slice(h),h+=e[1].length),m&&this.rules.other.blankLine.test(p)&&(c+=p+`
24
+ `,t=t.substring(p.length+1),a=!0),!a){let g=this.rules.other.nextBulletRegex(h),R=this.rules.other.hrRegex(h),C=this.rules.other.fencesBeginRegex(h),ne=this.rules.other.headingBeginRegex(h),se=this.rules.other.htmlBeginRegex(h),re=this.rules.other.blockquoteBeginRegex(h);for(;t;){let W=t.split(`
25
+ `,1)[0],U;if(p=W,this.options.pedantic?(p=p.replace(this.rules.other.listReplaceNesting," "),U=p):U=p.replace(this.rules.other.tabCharGlobal," "),C.test(p)||ne.test(p)||se.test(p)||re.test(p)||g.test(p)||R.test(p))break;if(U.search(this.rules.other.nonSpaceChar)>=h||!p.trim())d+=`
26
+ `+U.slice(h);else{if(m||u.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||C.test(u)||ne.test(u)||R.test(u))break;d+=`
27
+ `+p}m=!p.trim(),c+=W+`
28
+ `,t=t.substring(W.length+1),u=U.slice(h)}}r.loose||(o?r.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(o=!0)),r.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(d),loose:!1,text:d,tokens:[]}),r.raw+=c}let l=r.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let a of r.items){if(this.lexer.state.top=!1,a.tokens=this.lexer.blockTokens(a.text,[]),a.task){if(a.text=a.text.replace(this.rules.other.listReplaceTask,""),a.tokens[0]?.type==="text"||a.tokens[0]?.type==="paragraph"){a.tokens[0].raw=a.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),a.tokens[0].text=a.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}}let c=this.rules.other.listTaskCheckbox.exec(a.raw);if(c){let d={type:"checkbox",raw:c[0]+" ",checked:c[0]!=="[ ]"};a.checked=d.checked,r.loose?a.tokens[0]&&["paragraph","text"].includes(a.tokens[0].type)&&"tokens"in a.tokens[0]&&a.tokens[0].tokens?(a.tokens[0].raw=d.raw+a.tokens[0].raw,a.tokens[0].text=d.raw+a.tokens[0].text,a.tokens[0].tokens.unshift(d)):a.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):a.tokens.unshift(d)}}if(!r.loose){let c=a.tokens.filter(u=>u.type==="space"),d=c.length>0&&c.some(u=>this.rules.other.anyLine.test(u.raw));r.loose=d}}if(r.loose)for(let a of r.items){a.loose=!0;for(let c of a.tokens)c.type==="text"&&(c.type="paragraph")}return r}}html(t){let e=this.rules.block.html.exec(t);if(e)return{type:"html",block:!0,raw:e[0],pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:e[0]}}def(t){let e=this.rules.block.def.exec(t);if(e){let n=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:n,raw:e[0],href:s,title:r}}}table(t){let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let n=qt(e[1]),s=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
29
+ `):[],i={type:"table",raw:e[0],header:[],align:[],rows:[]};if(n.length===s.length){for(let o of s)this.rules.other.tableAlignRight.test(o)?i.align.push("right"):this.rules.other.tableAlignCenter.test(o)?i.align.push("center"):this.rules.other.tableAlignLeft.test(o)?i.align.push("left"):i.align.push(null);for(let o=0;o<n.length;o++)i.header.push({text:n[o],tokens:this.lexer.inline(n[o]),header:!0,align:i.align[o]});for(let o of r)i.rows.push(qt(o,i.header.length).map((l,a)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:i.align[a]})));return i}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let n=e[1].trim();return{type:"heading",raw:e[0],depth:e[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(t){let e=this.rules.block.paragraph.exec(t);if(e){let n=e[1].charAt(e[1].length-1)===`
30
+ `?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:n,tokens:this.lexer.inline(n)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let n=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let i=de(n.slice(0,-1),"\\");if((n.length-i.length)%2===0)return}else{let i=Rs(e[2],"()");if(i===-2)return;if(i>-1){let o=(e[0].indexOf("!")===0?5:4)+e[1].length+i;e[2]=e[2].substring(0,i),e[0]=e[0].substring(0,o).trim(),e[3]=""}}let s=e[2],r="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(s);i&&(s=i[1],r=i[3])}else r=e[3]?e[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?s=s.slice(1):s=s.slice(1,-1)),zt(e,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:r&&r.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(t,e){let n;if((n=this.rules.inline.reflink.exec(t))||(n=this.rules.inline.nolink.exec(t))){let s=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),r=e[s.toLowerCase()];if(!r){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return zt(n,r,n[0],this.lexer,this.rules)}}emStrong(t,e,n=""){let s=this.rules.inline.emStrongLDelim.exec(t);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!n||this.rules.inline.punctuation.exec(n))){let r=[...s[0]].length-1,i,o,l=r,a=0,c=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,e=e.slice(-1*t.length+r);(s=c.exec(e))!=null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i)continue;if(o=[...i].length,s[3]||s[4]){l+=o;continue}else if((s[5]||s[6])&&r%3&&!((r+o)%3)){a+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l+a);let d=[...s[0]][0].length,u=t.slice(0,r+s.index+d+o);if(Math.min(r,o)%2){let m=u.slice(1,-1);return{type:"em",raw:u,text:m,tokens:this.lexer.inlineTokens(m)}}let p=u.slice(2,-2);return{type:"strong",raw:u,text:p,tokens:this.lexer.inlineTokens(p)}}}}codespan(t){let e=this.rules.inline.code.exec(t);if(e){let n=e[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(n),r=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&r&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:e[0],text:n}}}br(t){let e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t,e,n=""){let s=this.rules.inline.delLDelim.exec(t);if(s&&(!s[1]||!n||this.rules.inline.punctuation.exec(n))){let r=[...s[0]].length-1,i,o,l=r,a=this.rules.inline.delRDelim;for(a.lastIndex=0,e=e.slice(-1*t.length+r);(s=a.exec(e))!=null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i||(o=[...i].length,o!==r))continue;if(s[3]||s[4]){l+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l);let c=[...s[0]][0].length,d=t.slice(0,r+s.index+c+o),u=d.slice(r,-r);return{type:"del",raw:d,text:u,tokens:this.lexer.inlineTokens(u)}}}}autolink(t){let e=this.rules.inline.autolink.exec(t);if(e){let n,s;return e[2]==="@"?(n=e[1],s="mailto:"+n):(n=e[1],s=n),{type:"link",raw:e[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}url(t){let e;if(e=this.rules.inline.url.exec(t)){let n,s;if(e[2]==="@")n=e[0],s="mailto:"+n;else{let r;do r=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(r!==e[0]);n=e[0],e[1]==="www."?s="http://"+e[0]:s=e[0]}return{type:"link",raw:e[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let n=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:n}}}},_=class Oe{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Q,this.options.tokenizer=this.options.tokenizer||new we,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:N,block:ye.normal,inline:le.normal};this.options.pedantic?(n.block=ye.pedantic,n.inline=le.pedantic):this.options.gfm&&(n.block=ye.gfm,this.options.breaks?n.inline=le.breaks:n.inline=le.gfm),this.tokenizer.rules=n}static get rules(){return{block:ye,inline:le}}static lex(e,n){return new Oe(n).lex(e)}static lexInline(e,n){return new Oe(n).inlineTokens(e)}lex(e){e=e.replace(N.carriageReturn,`
31
+ `),this.blockTokens(e,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let s=this.inlineQueue[n];this.inlineTokens(s.src,s.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,n=[],s=!1){for(this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(N.tabCharGlobal," ").replace(N.spaceLine,""));e;){let r;if(this.options.extensions?.block?.some(o=>(r=o.call({lexer:this},e,n))?(e=e.substring(r.raw.length),n.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let o=n.at(-1);r.raw.length===1&&o!==void 0?o.raw+=`
32
+ `:n.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let o=n.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(`
33
33
  `)?"":`
34
- `)+s.raw,o.text+=`
35
- `+s.text,this.inlineQueue.at(-1).src=o.text):n.push(s);continue}if(s=this.tokenizer.fences(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.heading(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.hr(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.blockquote(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.list(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.html(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.def(e)){e=e.substring(s.raw.length);let o=n.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(`
34
+ `)+r.raw,o.text+=`
35
+ `+r.text,this.inlineQueue.at(-1).src=o.text):n.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);let o=n.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(`
36
36
  `)?"":`
37
- `)+s.raw,o.text+=`
38
- `+s.raw,this.inlineQueue.at(-1).src=o.text):this.tokens.links[s.tag]||(this.tokens.links[s.tag]={href:s.href,title:s.title},n.push(s));continue}if(s=this.tokenizer.table(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.lheading(e)){e=e.substring(s.raw.length),n.push(s);continue}let i=e;if(this.options.extensions?.startBlock){let o=1/0,l=e.slice(1),a;this.options.extensions.startBlock.forEach(d=>{a=d.call({lexer:this},l),typeof a=="number"&&a>=0&&(o=Math.min(o,a))}),o<1/0&&o>=0&&(i=e.substring(0,o+1))}if(this.state.top&&(s=this.tokenizer.paragraph(i))){let o=n.at(-1);r&&o?.type==="paragraph"?(o.raw+=(o.raw.endsWith(`
37
+ `)+r.raw,o.text+=`
38
+ `+r.raw,this.inlineQueue.at(-1).src=o.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},n.push(r));continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),n.push(r);continue}let i=e;if(this.options.extensions?.startBlock){let o=1/0,l=e.slice(1),a;this.options.extensions.startBlock.forEach(c=>{a=c.call({lexer:this},l),typeof a=="number"&&a>=0&&(o=Math.min(o,a))}),o<1/0&&o>=0&&(i=e.substring(0,o+1))}if(this.state.top&&(r=this.tokenizer.paragraph(i))){let o=n.at(-1);s&&o?.type==="paragraph"?(o.raw+=(o.raw.endsWith(`
39
39
  `)?"":`
40
- `)+s.raw,o.text+=`
41
- `+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):n.push(s),r=i.length!==e.length,e=e.substring(s.raw.length);continue}if(s=this.tokenizer.text(e)){e=e.substring(s.raw.length);let o=n.at(-1);o?.type==="text"?(o.raw+=(o.raw.endsWith(`
40
+ `)+r.raw,o.text+=`
41
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):n.push(r),s=i.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let o=n.at(-1);o?.type==="text"?(o.raw+=(o.raw.endsWith(`
42
42
  `)?"":`
43
- `)+s.raw,o.text+=`
44
- `+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):n.push(s);continue}if(e){let o="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(o);break}else throw new Error(o)}}return this.state.top=!0,n}inline(e,n=[]){return this.inlineQueue.push({src:e,tokens:n}),n}inlineTokens(e,n=[]){this.tokenizer.lexer=this;let r=e,s=null;if(this.tokens.links){let a=Object.keys(this.tokens.links);if(a.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(r))!=null;)a.includes(s[0].slice(s[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(s=this.tokenizer.rules.inline.anyPunctuation.exec(r))!=null;)r=r.slice(0,s.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(s=this.tokenizer.rules.inline.blockSkip.exec(r))!=null;)i=s[2]?s[2].length:0,r=r.slice(0,s.index+i)+"["+"a".repeat(s[0].length-i-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let o=!1,l="";for(;e;){o||(l=""),o=!1;let a;if(this.options.extensions?.inline?.some(c=>(a=c.call({lexer:this},e,n))?(e=e.substring(a.raw.length),n.push(a),!0):!1))continue;if(a=this.tokenizer.escape(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.tag(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.link(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(a.raw.length);let c=n.at(-1);a.type==="text"&&c?.type==="text"?(c.raw+=a.raw,c.text+=a.text):n.push(a);continue}if(a=this.tokenizer.emStrong(e,r,l)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.codespan(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.br(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.del(e,r,l)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.autolink(e)){e=e.substring(a.raw.length),n.push(a);continue}if(!this.state.inLink&&(a=this.tokenizer.url(e))){e=e.substring(a.raw.length),n.push(a);continue}let d=e;if(this.options.extensions?.startInline){let c=1/0,p=e.slice(1),u;this.options.extensions.startInline.forEach(f=>{u=f.call({lexer:this},p),typeof u=="number"&&u>=0&&(c=Math.min(c,u))}),c<1/0&&c>=0&&(d=e.substring(0,c+1))}if(a=this.tokenizer.inlineText(d)){e=e.substring(a.raw.length),a.raw.slice(-1)!=="_"&&(l=a.raw.slice(-1)),o=!0;let c=n.at(-1);c?.type==="text"?(c.raw+=a.raw,c.text+=a.text):n.push(a);continue}if(e){let c="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(c);break}else throw new Error(c)}}return n}},ue=class{options;parser;constructor(t){this.options=t||U}space(t){return""}code({text:t,lang:e,escaped:n}){let r=(e||"").match(T.notSpaceStart)?.[0],s=t.replace(T.endingNewline,"")+`
45
- `;return r?'<pre><code class="language-'+N(r)+'">'+(n?s:N(s,!0))+`</code></pre>
46
- `:"<pre><code>"+(n?s:N(s,!0))+`</code></pre>
43
+ `)+r.raw,o.text+=`
44
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):n.push(r);continue}if(e){let o="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(o);break}else throw new Error(o)}}return this.state.top=!0,n}inline(e,n=[]){return this.inlineQueue.push({src:e,tokens:n}),n}inlineTokens(e,n=[]){this.tokenizer.lexer=this;let s=e,r=null;if(this.tokens.links){let a=Object.keys(this.tokens.links);if(a.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(s))!=null;)a.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(s))!=null;)s=s.slice(0,r.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(s))!=null;)i=r[2]?r[2].length:0,s=s.slice(0,r.index+i)+"["+"a".repeat(r[0].length-i-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let o=!1,l="";for(;e;){o||(l=""),o=!1;let a;if(this.options.extensions?.inline?.some(d=>(a=d.call({lexer:this},e,n))?(e=e.substring(a.raw.length),n.push(a),!0):!1))continue;if(a=this.tokenizer.escape(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.tag(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.link(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(a.raw.length);let d=n.at(-1);a.type==="text"&&d?.type==="text"?(d.raw+=a.raw,d.text+=a.text):n.push(a);continue}if(a=this.tokenizer.emStrong(e,s,l)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.codespan(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.br(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.del(e,s,l)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.autolink(e)){e=e.substring(a.raw.length),n.push(a);continue}if(!this.state.inLink&&(a=this.tokenizer.url(e))){e=e.substring(a.raw.length),n.push(a);continue}let c=e;if(this.options.extensions?.startInline){let d=1/0,u=e.slice(1),p;this.options.extensions.startInline.forEach(m=>{p=m.call({lexer:this},u),typeof p=="number"&&p>=0&&(d=Math.min(d,p))}),d<1/0&&d>=0&&(c=e.substring(0,d+1))}if(a=this.tokenizer.inlineText(c)){e=e.substring(a.raw.length),a.raw.slice(-1)!=="_"&&(l=a.raw.slice(-1)),o=!0;let d=n.at(-1);d?.type==="text"?(d.raw+=a.raw,d.text+=a.text):n.push(a);continue}if(e){let d="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(d);break}else throw new Error(d)}}return n}},Ce=class{options;parser;constructor(t){this.options=t||Q}space(t){return""}code({text:t,lang:e,escaped:n}){let s=(e||"").match(N.notSpaceStart)?.[0],r=t.replace(N.endingNewline,"")+`
45
+ `;return s?'<pre><code class="language-'+O(s)+'">'+(n?r:O(r,!0))+`</code></pre>
46
+ `:"<pre><code>"+(n?r:O(r,!0))+`</code></pre>
47
47
  `}blockquote({tokens:t}){return`<blockquote>
48
48
  ${this.parser.parse(t)}</blockquote>
49
49
  `}html({text:t}){return t}def(t){return""}heading({tokens:t,depth:e}){return`<h${e}>${this.parser.parseInline(t)}</h${e}>
50
50
  `}hr(t){return`<hr>
51
- `}list(t){let e=t.ordered,n=t.start,r="";for(let o=0;o<t.items.length;o++){let l=t.items[o];r+=this.listitem(l)}let s=e?"ol":"ul",i=e&&n!==1?' start="'+n+'"':"";return"<"+s+i+`>
52
- `+r+"</"+s+`>
51
+ `}list(t){let e=t.ordered,n=t.start,s="";for(let o=0;o<t.items.length;o++){let l=t.items[o];s+=this.listitem(l)}let r=e?"ol":"ul",i=e&&n!==1?' start="'+n+'"':"";return"<"+r+i+`>
52
+ `+s+"</"+r+`>
53
53
  `}listitem(t){return`<li>${this.parser.parse(t.tokens)}</li>
54
54
  `}checkbox({checked:t}){return"<input "+(t?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:t}){return`<p>${this.parser.parseInline(t)}</p>
55
- `}table(t){let e="",n="";for(let s=0;s<t.header.length;s++)n+=this.tablecell(t.header[s]);e+=this.tablerow({text:n});let r="";for(let s=0;s<t.rows.length;s++){let i=t.rows[s];n="";for(let o=0;o<i.length;o++)n+=this.tablecell(i[o]);r+=this.tablerow({text:n})}return r&&(r=`<tbody>${r}</tbody>`),`<table>
55
+ `}table(t){let e="",n="";for(let r=0;r<t.header.length;r++)n+=this.tablecell(t.header[r]);e+=this.tablerow({text:n});let s="";for(let r=0;r<t.rows.length;r++){let i=t.rows[r];n="";for(let o=0;o<i.length;o++)n+=this.tablecell(i[o]);s+=this.tablerow({text:n})}return s&&(s=`<tbody>${s}</tbody>`),`<table>
56
56
  <thead>
57
57
  `+e+`</thead>
58
- `+r+`</table>
58
+ `+s+`</table>
59
59
  `}tablerow({text:t}){return`<tr>
60
60
  ${t}</tr>
61
61
  `}tablecell(t){let e=this.parser.parseInline(t.tokens),n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>
62
- `}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${N(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:n}){let r=this.parser.parseInline(n),s=gt(t);if(s===null)return r;t=s;let i='<a href="'+t+'"';return e&&(i+=' title="'+N(e)+'"'),i+=">"+r+"</a>",i}image({href:t,title:e,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let s=gt(t);if(s===null)return N(n);t=s;let i=`<img src="${t}" alt="${N(n)}"`;return e&&(i+=` title="${N(e)}"`),i+=">",i}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:N(t.text)}},Ne=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},P=class Le{options;renderer;textRenderer;constructor(e){this.options=e||U,this.options.renderer=this.options.renderer||new ue,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ne}static parse(e,n){return new Le(n).parse(e)}static parseInline(e,n){return new Le(n).parseInline(e)}parse(e){this.renderer.parser=this;let n="";for(let r=0;r<e.length;r++){let s=e[r];if(this.options.extensions?.renderers?.[s.type]){let o=s,l=this.options.extensions.renderers[o.type].call({parser:this},o);if(l!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(o.type)){n+=l||"";continue}}let i=s;switch(i.type){case"space":{n+=this.renderer.space(i);break}case"hr":{n+=this.renderer.hr(i);break}case"heading":{n+=this.renderer.heading(i);break}case"code":{n+=this.renderer.code(i);break}case"table":{n+=this.renderer.table(i);break}case"blockquote":{n+=this.renderer.blockquote(i);break}case"list":{n+=this.renderer.list(i);break}case"checkbox":{n+=this.renderer.checkbox(i);break}case"html":{n+=this.renderer.html(i);break}case"def":{n+=this.renderer.def(i);break}case"paragraph":{n+=this.renderer.paragraph(i);break}case"text":{n+=this.renderer.text(i);break}default:{let o='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return n}parseInline(e,n=this.renderer){this.renderer.parser=this;let r="";for(let s=0;s<e.length;s++){let i=e[s];if(this.options.extensions?.renderers?.[i.type]){let l=this.options.extensions.renderers[i.type].call({parser:this},i);if(l!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(i.type)){r+=l||"";continue}}let o=i;switch(o.type){case"escape":{r+=n.text(o);break}case"html":{r+=n.html(o);break}case"link":{r+=n.link(o);break}case"image":{r+=n.image(o);break}case"checkbox":{r+=n.checkbox(o);break}case"strong":{r+=n.strong(o);break}case"em":{r+=n.em(o);break}case"codespan":{r+=n.codespan(o);break}case"br":{r+=n.br(o);break}case"del":{r+=n.del(o);break}case"text":{r+=n.text(o);break}default:{let l='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return r}},ne=class{options;block;constructor(t){this.options=t||U}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(){return this.block?$.lex:$.lexInline}provideParser(){return this.block?P.parse:P.parseInline}},Yn=class{defaults=Re();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=P;Renderer=ue;TextRenderer=Ne;Lexer=$;Tokenizer=pe;Hooks=ne;constructor(...t){this.use(...t)}walkTokens(t,e){let n=[];for(let r of t)switch(n=n.concat(e.call(this,r)),r.type){case"table":{let s=r;for(let i of s.header)n=n.concat(this.walkTokens(i.tokens,e));for(let i of s.rows)for(let o of i)n=n.concat(this.walkTokens(o.tokens,e));break}case"list":{let s=r;n=n.concat(this.walkTokens(s.items,e));break}default:{let s=r;this.defaults.extensions?.childTokens?.[s.type]?this.defaults.extensions.childTokens[s.type].forEach(i=>{let o=s[i].flat(1/0);n=n.concat(this.walkTokens(o,e))}):s.tokens&&(n=n.concat(this.walkTokens(s.tokens,e)))}}return n}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(s=>{if(!s.name)throw new Error("extension name required");if("renderer"in s){let i=e.renderers[s.name];i?e.renderers[s.name]=function(...o){let l=s.renderer.apply(this,o);return l===!1&&(l=i.apply(this,o)),l}:e.renderers[s.name]=s.renderer}if("tokenizer"in s){if(!s.level||s.level!=="block"&&s.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=e[s.level];i?i.unshift(s.tokenizer):e[s.level]=[s.tokenizer],s.start&&(s.level==="block"?e.startBlock?e.startBlock.push(s.start):e.startBlock=[s.start]:s.level==="inline"&&(e.startInline?e.startInline.push(s.start):e.startInline=[s.start]))}"childTokens"in s&&s.childTokens&&(e.childTokens[s.name]=s.childTokens)}),r.extensions=e),n.renderer){let s=this.defaults.renderer||new ue(this.defaults);for(let i in n.renderer){if(!(i in s))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let o=i,l=n.renderer[o],a=s[o];s[o]=(...d)=>{let c=l.apply(s,d);return c===!1&&(c=a.apply(s,d)),c||""}}r.renderer=s}if(n.tokenizer){let s=this.defaults.tokenizer||new pe(this.defaults);for(let i in n.tokenizer){if(!(i in s))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let o=i,l=n.tokenizer[o],a=s[o];s[o]=(...d)=>{let c=l.apply(s,d);return c===!1&&(c=a.apply(s,d)),c}}r.tokenizer=s}if(n.hooks){let s=this.defaults.hooks||new ne;for(let i in n.hooks){if(!(i in s))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let o=i,l=n.hooks[o],a=s[o];ne.passThroughHooks.has(i)?s[o]=d=>{if(this.defaults.async&&ne.passThroughHooksRespectAsync.has(i))return(async()=>{let p=await l.call(s,d);return a.call(s,p)})();let c=l.call(s,d);return a.call(s,c)}:s[o]=(...d)=>{if(this.defaults.async)return(async()=>{let p=await l.apply(s,d);return p===!1&&(p=await a.apply(s,d)),p})();let c=l.apply(s,d);return c===!1&&(c=a.apply(s,d)),c}}r.hooks=s}if(n.walkTokens){let s=this.defaults.walkTokens,i=n.walkTokens;r.walkTokens=function(o){let l=[];return l.push(i.call(this,o)),s&&(l=l.concat(s.call(this,o))),l}}this.defaults={...this.defaults,...r}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return $.lex(t,e??this.defaults)}parser(t,e){return P.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let r={...n},s={...this.defaults,...r},i=this.onError(!!s.silent,!!s.async);if(this.defaults.async===!0&&r.async===!1)return i(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(s.hooks&&(s.hooks.options=s,s.hooks.block=t),s.async)return(async()=>{let o=s.hooks?await s.hooks.preprocess(e):e,l=await(s.hooks?await s.hooks.provideLexer():t?$.lex:$.lexInline)(o,s),a=s.hooks?await s.hooks.processAllTokens(l):l;s.walkTokens&&await Promise.all(this.walkTokens(a,s.walkTokens));let d=await(s.hooks?await s.hooks.provideParser():t?P.parse:P.parseInline)(a,s);return s.hooks?await s.hooks.postprocess(d):d})().catch(i);try{s.hooks&&(e=s.hooks.preprocess(e));let o=(s.hooks?s.hooks.provideLexer():t?$.lex:$.lexInline)(e,s);s.hooks&&(o=s.hooks.processAllTokens(o)),s.walkTokens&&this.walkTokens(o,s.walkTokens);let l=(s.hooks?s.hooks.provideParser():t?P.parse:P.parseInline)(o,s);return s.hooks&&(l=s.hooks.postprocess(l)),l}catch(o){return i(o)}}}onError(t,e){return n=>{if(n.message+=`
63
- Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error occurred:</p><pre>"+N(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},F=new Yn;function v(t,e){return F.parse(t,e)}v.options=v.setOptions=function(t){return F.setOptions(t),v.defaults=F.defaults,vt(v.defaults),v};v.getDefaults=Re;v.defaults=U;v.use=function(...t){return F.use(...t),v.defaults=F.defaults,vt(v.defaults),v};v.walkTokens=function(t,e){return F.walkTokens(t,e)};v.parseInline=F.parseInline;v.Parser=P;v.parser=P.parse;v.Renderer=ue;v.TextRenderer=Ne;v.Lexer=$;v.lexer=$.lex;v.Tokenizer=pe;v.Hooks=ne;v.parse=v;var er=v.options,tr=v.setOptions,nr=v.use,sr=v.walkTokens,rr=v.parseInline;var ir=P.parse,or=$.lex;var es=["http:","https:","mailto:"];function ts(t){try{let e=new URL(t);return es.includes(e.protocol)?e.href:void 0}catch{return}}function b(t,e){let n=document.createElement(t);return e&&(n.className=e),n}function H(t,e){if(e)for(let n of e)switch(n.type){case"strong":{let r=b("strong");H(r,n.tokens),t.appendChild(r);break}case"em":{let r=b("em");H(r,n.tokens),t.appendChild(r);break}case"del":{let r=b("s");H(r,n.tokens),t.appendChild(r);break}case"codespan":{let r=b("code","md-code-inline");r.textContent=n.text,t.appendChild(r);break}case"link":{let r=n,s=ts(r.href);if(s===void 0){let o=b("span");H(o,r.tokens),t.appendChild(o);break}let i=b("a","md-link");i.href=s,i.target="_blank",i.rel="noopener noreferrer",H(i,r.tokens),t.appendChild(i);break}case"image":{let r=b("span","md-image");r.textContent=`[image: ${n.text||"untitled"}]`,t.appendChild(r);break}case"br":t.appendChild(b("br"));break;default:{let r=n.text??"",s=n.tokens;s&&s.length>0&&n.type==="text"?H(t,s):r&&t.appendChild(document.createTextNode(r));break}}}function ns(t){let e=t.ordered?b("ol","md-list"):b("ul","md-list");t.ordered&&typeof t.start=="number"&&t.start>1&&(e.start=t.start);for(let n of t.items){let r=b("li");if(n.task){let s=b("input","md-task");s.type="checkbox",s.checked=!!n.checked,s.disabled=!0,r.appendChild(s)}Be(r,n.tokens),e.appendChild(r)}return e}function ss(t){let e=b("pre","md-pre"),n=b("code");if(t.lang){let r=t.lang.split(/\s+/)[0]??"";r&&(n.className=`md-lang-${r}`,e.dataset.lang=r)}return n.textContent=t.text,e.appendChild(n),e}function rs(t){let e=b("table","md-table"),n=b("thead"),r=b("tr");for(let i of t.header){let o=b("th");H(o,i.tokens),r.appendChild(o)}n.appendChild(r),e.appendChild(n);let s=b("tbody");for(let i of t.rows){let o=b("tr");for(let l of i){let a=b("td");H(a,l.tokens),o.appendChild(a)}s.appendChild(o)}return e.appendChild(s),e}function Be(t,e){for(let n of e)switch(n.type){case"heading":{let r=Math.min(Math.max(n.depth,1),6),s=b(`h${r}`,"md-heading");H(s,n.tokens),t.appendChild(s);break}case"paragraph":{let r=b("p","md-p");H(r,n.tokens),t.appendChild(r);break}case"code":t.appendChild(ss(n));break;case"list":t.appendChild(ns(n));break;case"blockquote":{let r=b("blockquote","md-quote");Be(r,n.tokens),t.appendChild(r);break}case"table":t.appendChild(rs(n));break;case"hr":t.appendChild(b("hr","md-hr"));break;case"space":break;case"html":{let r=b("p","md-p");r.textContent=n.text,t.appendChild(r);break}default:{let r=n.tokens;if(r&&r.length>0){let i=b("p","md-p");H(i,r),t.appendChild(i);break}let s=n.text??"";if(s.trim()){let i=b("p","md-p");i.textContent=s,t.appendChild(i)}break}}}function $t(t,e="md"){let n=b("div",e);try{Be(n,new $().lex(t))}catch{n.textContent=t}return n}var fe=new Map;function is(t,e){return t.kind!=="tool"?!1:e.className!==`tool tool-${t.status}`}function At(t,e,n){e.length<t.childElementCount&&(fe.clear(),t.textContent="");for(let r of e){let s=fe.get(r.id);if(s===void 0){let i=n(r);fe.set(r.id,i),t.appendChild(i)}else if(is(r,s)){let i=n(r);fe.set(r.id,i),t.replaceChild(i,s)}}}var It=2e3,Mt=2e3;function h(t,e,n){let r=document.createElement(t);return e&&(r.className=e),n!==void 0&&(r.textContent=n),r}function os(t){if(!t)return;let e=t.replace(/[/\\]+$/,"").split(/[/\\]/).pop()??"";return e&&e!=="."?e:void 0}function as(t){return(t.title??"").replace(/^\s*\[[^\]]{0,80}\]\s*/,"").trim()||t.title||t.id.slice(0,8)}function qe(t,e,n,r){t.textContent="";for(let s of e){let i=h("button","session-row");s.id===n&&i.classList.add("is-active");let o=h("span","session-title",as(s));i.appendChild(o);let l=h("span","session-meta"),a=os(s.cwd);if(a){let c=h("span","session-cwd",a);c.title=s.cwd??a,l.appendChild(c)}let d=h("span",s.mode==="live"?"badge badge-live":"badge badge-readonly");d.textContent=s.mode==="live"?"live":"read-only",l.appendChild(d),s.alive&&l.appendChild(h("span","badge badge-alive","running")),s.updatedAt&&l.appendChild(h("span","session-time",us(s.updatedAt))),i.appendChild(l),i.addEventListener("click",()=>r(s.id)),t.appendChild(i)}e.length===0&&t.appendChild(h("div","empty","No sessions found."))}function De(t,e){At(t,e,ls)}function ls(t){switch(t.kind){case"user":{let e=h("div","msg msg-user");return e.appendChild(h("div","msg-role","you")),e.appendChild(h("div","msg-body",t.text)),e}case"assistant":{let e=h("div","msg msg-assistant");e.appendChild(h("div","msg-role","agent"));let n=h("div","msg-body md-body");return n.appendChild($t(t.text)),e.appendChild(n),e}case"thinking":{let e=h("details","msg msg-thinking");return e.appendChild(h("summary","msg-role","thinking")),e.appendChild(h("div","msg-body",t.text)),e}case"error":{let e=h("div","msg msg-error");return e.appendChild(h("div","msg-role","error")),e.appendChild(h("div","msg-body",t.message)),e}case"notice":return h("div","notice",t.text);case"tool":return cs(t)}}function cs(t){let e=h("details",`tool tool-${t.status}`),n=h("summary","tool-summary");n.appendChild(h("span",`tool-dot tool-dot-${t.status}`,"")),n.appendChild(h("span","tool-name",t.name)),t.inputPreview&&n.appendChild(h("span","tool-target",ps(t.name,t.inputPreview))),e.appendChild(n);let r=h("div","tool-body");if(t.inputPreview){r.appendChild(h("div","tool-label","input"));let s=le(t.inputPreview);if(s.length>Mt){let i=h("pre","tool-pre",s.slice(0,Mt));r.appendChild(i);let o=h("button","tool-more",`Show full input (${s.length.toLocaleString()} chars)`);o.addEventListener("click",()=>{i.textContent=s,o.remove()}),r.appendChild(o)}else r.appendChild(h("pre","tool-pre",s))}if(t.outputUnavailable===!0)r.appendChild(h("div","tool-unavailable","Result not available after refresh \u2014 successful tool output is not persisted to the session ledger."));else if(t.output!==void 0&&t.output!==""){r.appendChild(h("div","tool-label","output"));let s=le(t.output);if(s.length>It){let i=h("pre","tool-pre",s.slice(0,It));r.appendChild(i);let o=h("button","tool-more",`Show full output (${s.length.toLocaleString()} chars)`);o.addEventListener("click",()=>{i.textContent=s,o.remove()}),r.appendChild(o)}else r.appendChild(h("pre","tool-pre",s))}return t.diff!==void 0&&(r.appendChild(h("div","tool-label","diff")),r.appendChild(ds(le(String(t.diff))))),e.appendChild(r),e}function ze(t,e){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}function ds(t){let e=h("pre","tool-pre tool-diff");for(let n of t.split(`
64
- `)){let r=document.createElement("span");r.textContent=n,r.className=n.startsWith("+++")||n.startsWith("---")?"diff-ctx":n.startsWith("+")?"diff-add":n.startsWith("-")?"diff-del":n.startsWith("@@")?"diff-hunk":"diff-ctx",e.appendChild(r)}return e}function ps(t,e){try{let n=JSON.parse(e);if((t==="bash"||t==="shell")&&typeof n.command=="string")return ze(n.command,80);if((t==="edit_file"||t==="write_file"||t==="read_file")&&typeof n.file_path=="string")return n.file_path;if(t==="agent"&&typeof n.prompt=="string")return ze(n.prompt,60);if((t==="grep"||t==="glob")&&typeof n.pattern=="string")return n.pattern}catch{}return ze(e,90)}function us(t){let e=Date.parse(t);if(Number.isNaN(e))return"";let n=Math.max(0,(Date.now()-e)/1e3);return n<60?"just now":n<3600?`${Math.floor(n/60)}m ago`:n<86400?`${Math.floor(n/3600)}h ago`:`${Math.floor(n/86400)}d ago`}var Pt=/bash|delete|remove|overwrite|rm |drop/i;function hs(t){if(!t)return"";let e=Math.floor((Date.now()-new Date(t).getTime())/6e4);return e>=1?`waiting ${e}m`:""}function Oe(t,e,n){t.textContent="",t.classList.toggle("has-pending",e.length>0);for(let r of e){let s=r.request??{},i=s.title??s.message??"The agent is waiting for a response.",o=Pt.test(i)||Pt.test(s.serverName??""),l=h("div",o?"approval-card approval-card--destructive":"approval-card"),a=h("div","approval-head");a.appendChild(h("span","approval-badge",s.origin==="agent"?"question":"approval")),s.serverName&&a.appendChild(h("span","approval-source",s.serverName));let d=hs(r.createdAt);d&&a.appendChild(h("span","approval-time",d)),l.appendChild(a),l.appendChild(h("div","approval-title",i)),s.description&&l.appendChild(h("div","approval-desc",s.description));let c=h("div","approval-actions");if(s.type==="choice"&&Array.isArray(s.choices)&&s.choices.length>0)for(let u of s.choices){let f=h("button","approval-btn",u);f.addEventListener("click",()=>n(r.id,{action:"accept",content:{value:u}})),c.appendChild(f)}else if(s.type==="multi_choice"&&Array.isArray(s.choices)&&s.choices.length>0){let u=h("div","approval-checkboxes"),f=[];for(let x of s.choices){let L=h("label","approval-checkbox-row"),A=document.createElement("input");A.type="checkbox",A.value=x,f.push(A),L.appendChild(A),L.appendChild(h("span",void 0,x)),u.appendChild(L)}l.appendChild(u);let m=h("button","approval-btn approval-primary","Submit");m.addEventListener("click",()=>n(r.id,{action:"accept",content:{value:f.filter(x=>x.checked).map(x=>x.value)}})),c.appendChild(m)}else if(s.type==="text"||s.type==="number"){let u=document.createElement("input");u.className="approval-input",u.type=s.type==="number"?"number":"text",s.questionDefault!==void 0&&(u.value=String(s.questionDefault));let f=()=>n(r.id,{action:"accept",content:{value:s.type==="number"?Number(u.value):u.value}});u.addEventListener("keydown",x=>{x.key==="Enter"&&f()}),l.appendChild(u);let m=h("button","approval-btn approval-primary","Submit");m.addEventListener("click",f),c.appendChild(m)}else{let u=h("button","approval-btn approval-primary","Approve");u.addEventListener("click",()=>n(r.id,{action:"accept",content:{value:!0}})),c.appendChild(u)}let p=h("button","approval-btn approval-danger","Deny");p.addEventListener("click",()=>n(r.id,{action:"decline"})),c.appendChild(p),l.appendChild(c),t.appendChild(l)}}var Ht=0;function q(t){return Ht+=1,`${t}_${Ht}`}function j(t){return typeof t=="string"?t:void 0}function _t(t){let e=t;if(typeof e.kind=="string")switch(e.kind){case"user":return{kind:"user",id:q("u"),text:j(e.text)??""};case"assistant":return{kind:"assistant",id:q("a"),text:j(e.text)??""};case"tool":{let n=j(e.input)??"";return n.trim()==="\u2026"?void 0:{kind:"tool",id:q("t"),name:j(e.toolName)??"tool",inputPreview:n,status:"ok",outputUnavailable:!0}}case"tool_error":{let n=j(e.content)??"",r=n.split(`
65
- `,1)[0]??"";return{kind:"tool",id:q("t"),name:j(e.toolName)??"error",inputPreview:r,status:"error",output:n}}case"error":return{kind:"error",id:q("e"),message:j(e.message)??"error"};case"done":{let n=e.costUsd,r=e.durationMs,s=[];return typeof n=="number"&&s.push(`$${n.toFixed(4)}`),typeof r=="number"&&s.push(`${(r/1e3).toFixed(1)}s`),{kind:"notice",id:q("n"),text:s.length?`turn complete \xB7 ${s.join(" \xB7 ")}`:"turn complete"}}case"paused":return{kind:"notice",id:q("n"),text:"paused \u2014 usage limit"};case"resumed":return{kind:"notice",id:q("n"),text:"resumed"};default:return}}function Nt(t,e){let n=e;if(n.kind!=="done")return t;let r=n.costUsd,s=n.durationMs;return{costUsd:t.costUsd+(typeof r=="number"?r:0),durationMs:t.durationMs+(typeof s=="number"?s:0),turns:t.turns+1}}function ge(t,e){return Number.isInteger(e)&&e>=0&&e<t.length}function Bt(t,e){if(!ge(t,e)||e===0)return t.slice();let n=t.slice(),r=n[e-1],s=n[e];return r===void 0||s===void 0?t.slice():(n[e-1]=s,n[e]=r,n)}function zt(t,e){if(!ge(t,e)||e===t.length-1)return t.slice();let n=t.slice(),r=n[e+1],s=n[e];return r===void 0||s===void 0?t.slice():(n[e+1]=s,n[e]=r,n)}function qt(t,e){if(!ge(t,e))return t.slice();let n=t.slice();return n.splice(e,1),n}function Dt(t,e,n){if(!ge(t,e))return t.slice();let r=t.slice();return r[e]=n,r}var ke=class{constructor(e){this.deps=e}deps;queue=[];flushing=!1;entries(){return[...this.queue]}clear(){this.queue=[],this.render()}wire(){let e=()=>{let n=this.deps.input.value.trim();n&&(this.queue=[...this.queue,n],this.deps.input.value="",oe(this.deps.input),this.render(),this.flush())};this.deps.send.addEventListener("click",e),this.deps.input.addEventListener("keydown",n=>{n.key==="Enter"&&(n.metaKey||n.ctrlKey)&&e()})}render(){let e=this.deps.container;e.textContent="",this.queue.forEach((n,r)=>{let s=document.createElement("div");s.className="queue-row";let i=document.createElement("span");i.className="queue-text",i.textContent=n,s.appendChild(i);let o=document.createElement("button");o.className="queue-btn",o.textContent="\u270E",o.title="Edit",o.addEventListener("click",()=>{let l=document.createElement("input");l.className="queue-text queue-edit-input",l.value=n,s.replaceChild(l,i),l.focus();let a=!1,d=()=>{a||(a=!0,this.queue=Dt(this.queue,r,l.value),this.render())};l.addEventListener("keydown",c=>{c.key==="Enter"&&d(),c.key==="Escape"&&(c.preventDefault(),a=!0,s.replaceChild(i,l))}),l.addEventListener("blur",d)}),s.appendChild(o);for(let[l,a]of[["\u2191",()=>{this.queue=Bt(this.queue,r)}],["\u2193",()=>{this.queue=zt(this.queue,r)}],["\u2715",()=>{this.queue=qt(this.queue,r)}]]){let d=document.createElement("button");d.className="queue-btn",d.textContent=l,d.addEventListener("click",()=>{a(),this.render()}),s.appendChild(d)}e.appendChild(s)})}async flush(){if(this.flushing||!this.deps.isLive()||this.deps.isTurnActive())return;let e=this.queue[0];if(e!==void 0){this.flushing=!0;try{await this.deps.submit(e),this.queue=this.queue.slice(1),this.render(),this.deps.onAccepted()}catch(n){this.deps.onError(n instanceof Error?n.message:"send failed")}finally{this.flushing=!1}}}};function Ot(t,e=80){return t.scrollHeight-t.scrollTop-t.clientHeight<=e}function g(t,e,n){let r=document.createElement(t);return e&&(r.className=e),n!==void 0&&(r.textContent=n),r}function ms(t){let e=t.trim().split(/\s+/);if(e.length<5)return t;let[n,r,s,i,o]=e;return s==="*"&&i==="*"&&o==="*"&&r.startsWith("*/")?`Every ${r.slice(2)} hours`:s==="*"&&i==="*"&&o==="*"&&r!=="*"&&n!=="*"?`Daily at ${r.padStart(2,"0")}:${n.padStart(2,"0")}`:s==="*"&&i==="*"&&o!=="*"&&r!=="*"?`${["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][Number(o)]??o} at ${r.padStart(2,"0")}:${n.padStart(2,"0")}`:s==="*"&&i==="*"&&o==="*"&&r==="*"&&n!=="*"?`Every hour at :${n.padStart(2,"0")}`:s==="*"&&i==="*"&&o==="*"&&r==="*"&&n==="*"?"Every minute":t}function fs(t){let e=Date.now()-new Date(t).getTime(),n=Math.floor(e/1e3);if(n<60)return"just now";let r=Math.floor(n/60);if(r<60)return`${r}m ago`;let s=Math.floor(r/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`}var be=class{container;api;onEdit;onShowHistory;schedules=[];daemonStatus={running:!1};constructor(e){this.container=e.container,this.api=e.api,this.onEdit=e.onEdit,this.onShowHistory=e.onShowHistory}async load(){try{let[e,n]=await Promise.all([this.api("/api/schedules"),this.api("/api/daemon/status")]);this.schedules=e.schedules,this.daemonStatus=n}catch(e){E(e instanceof Error?e.message:"failed to load schedules")}this.render()}render(){this.container.textContent="";let e=g("div","sched-header"),n=g("div","sched-title-row");n.appendChild(g("h2","sched-title","Schedules"));let r=g("button","sched-add-btn","+ New Schedule");r.addEventListener("click",()=>this.onEdit({id:"",name:"",command:"",cron:"",enabled:!0,createdAt:"",updatedAt:""})),n.appendChild(r),e.appendChild(n);let s=g("div","sched-daemon-status"),i=g("span",this.daemonStatus.running?"sched-dot-ok":"sched-dot-off");if(s.appendChild(i),s.appendChild(g("span","sched-daemon-text",this.daemonStatus.running?`Daemon running (${this.daemonStatus.tasks??0} tasks)`:"Daemon not running")),e.appendChild(s),this.container.appendChild(e),this.schedules.length===0){let l=g("div","sched-empty");l.appendChild(g("div","sched-empty-icon","\u23F0")),l.appendChild(g("div","sched-empty-title","No schedules yet")),l.appendChild(g("div","sched-empty-sub","Create a schedule to run tasks on a cron timer.")),this.container.appendChild(l);return}let o=g("div","sched-list");for(let l of this.schedules)o.appendChild(this.renderCard(l));this.container.appendChild(o)}renderCard(e){let n=g("div",`sched-card${e.enabled?"":" sched-card-disabled"}`),r=g("div","sched-card-top"),s=g("span","sched-card-name",e.name);r.appendChild(s);let i=g("button",`sched-toggle${e.enabled?" is-on":""}`),o=g("span","sched-toggle-dot");i.appendChild(o),i.title=e.enabled?"Disable":"Enable",i.addEventListener("click",()=>{this.toggleSchedule(e.id)}),r.appendChild(i),n.appendChild(r);let l=g("div","sched-card-details"),a=g("div","sched-detail-row");a.appendChild(g("span","sched-detail-label","Schedule"));let d=g("span","sched-detail-value");d.appendChild(g("span",void 0,ms(e.cron))),d.appendChild(g("span","sched-cron-raw",e.cron)),a.appendChild(d),l.appendChild(a);let c=g("div","sched-detail-row");if(c.appendChild(g("span","sched-detail-label","Command")),c.appendChild(g("code","sched-detail-code",e.command)),l.appendChild(c),e.trigger&&e.trigger!=="cron"){let L=g("div","sched-detail-row");L.appendChild(g("span","sched-detail-label","Trigger")),L.appendChild(g("span","sched-detail-value",e.trigger)),l.appendChild(L)}let p=g("div","sched-card-meta");p.appendChild(g("span","sched-card-id",e.id)),e.updatedAt&&p.appendChild(g("span","sched-card-time",fs(e.updatedAt))),l.appendChild(p),n.appendChild(l);let u=g("div","sched-card-actions"),f=g("button","sched-action-btn","History");f.addEventListener("click",()=>this.onShowHistory(e.id)),u.appendChild(f);let m=g("button","sched-action-btn","Edit");m.addEventListener("click",()=>this.onEdit(e)),u.appendChild(m);let x=g("button","sched-action-btn sched-action-danger","Delete");return x.addEventListener("click",()=>{this.deleteSchedule(e.id,e.name)}),u.appendChild(x),n.appendChild(u),n}async toggleSchedule(e){try{await this.api(`/api/schedules/${encodeURIComponent(e)}/toggle`,{method:"POST"}),await this.load()}catch(n){E(n instanceof Error?n.message:"toggle failed")}}async deleteSchedule(e,n){if(confirm(`Delete schedule "${n}"? This cannot be undone.`))try{await this.api(`/api/schedules/${encodeURIComponent(e)}`,{method:"DELETE"}),await this.load()}catch(r){E(r instanceof Error?r.message:"delete failed")}}};function S(t,e,n){let r=document.createElement(t);return e&&(r.className=e),n!==void 0&&(r.textContent=n),r}var Fe=[{label:"Every hour",value:"0 * * * *"},{label:"Daily at 2:00 AM",value:"0 2 * * *"},{label:"Daily at 9:00 AM",value:"0 9 * * *"},{label:"Every 6 hours",value:"0 */6 * * *"},{label:"Weekly (Monday 9 AM)",value:"0 9 * * 1"},{label:"Custom...",value:""}];function gs(t){let e=t.trim().split(/\s+/);if(e.length<5)return"";let[n,r,s,i,o]=e;return s==="*"&&i==="*"&&o==="*"&&r.startsWith("*/")?`Runs every ${r.slice(2)} hours`:s==="*"&&i==="*"&&o==="*"&&r!=="*"&&n!=="*"?`Runs daily at ${r.padStart(2,"0")}:${n.padStart(2,"0")}`:s==="*"&&i==="*"&&o!=="*"&&r!=="*"?`Runs every ${["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][Number(o)]??o} at ${r.padStart(2,"0")}:${n.padStart(2,"0")}`:s==="*"&&i==="*"&&o==="*"&&r==="*"?n==="*"?"Runs every minute":`Runs every hour at :${n.padStart(2,"0")}`:`Cron: ${t}`}function Ft(t,e){let n=t!==null&&t.id!=="";document.getElementById("sched-form-overlay")?.remove();let r=S("div","sched-overlay");r.id="sched-form-overlay";let s=S("div","sched-modal");s.appendChild(S("h3","sched-modal-title",n?"Edit Schedule":"New Schedule"));let i=S("div","sched-field");i.appendChild(S("label","sched-label","Name"));let o=document.createElement("input");o.type="text",o.className="sched-input",o.placeholder="e.g. Nightly forge",o.value=t?.name??"",i.appendChild(o),s.appendChild(i);let l=S("div","sched-field");l.appendChild(S("label","sched-label","Command"));let a=document.createElement("input");a.type="text",a.className="sched-input sched-input-mono",a.placeholder="e.g. /forge-friction --auto",a.value=t?.command??"",l.appendChild(a),s.appendChild(l);let d=S("div","sched-field");d.appendChild(S("label","sched-label","Schedule"));let c=document.createElement("select");c.className="sched-select";for(let w of Fe){let _=document.createElement("option");_.value=w.value,_.textContent=w.label,c.appendChild(_)}let p=document.createElement("input");p.type="text",p.className="sched-input sched-input-mono",p.placeholder="0 2 * * *",p.value=t?.cron??"";let u=S("div","sched-cron-preview"),f=t?.cron??"",m=Fe.find(w=>w.value===f);m&&m.value!==""?(c.value=m.value,p.style.display="none"):f?(c.value="",p.style.display=""):(c.value=Fe[0]?.value??"",p.style.display="none",p.value=c.value);let x=()=>{let w=p.style.display==="none"?c.value:p.value;u.textContent=w?gs(w):""};c.addEventListener("change",()=>{c.value===""?(p.style.display="",p.focus()):(p.style.display="none",p.value=c.value),x()}),p.addEventListener("input",x),x(),d.appendChild(c),d.appendChild(p),d.appendChild(u),s.appendChild(d);let L=S("div","sched-field");L.appendChild(S("label","sched-label","Trigger"));let A=document.createElement("select");A.className="sched-select";for(let[w,_]of[["cron","Cron schedule only"],["sessionstart","On daemon start"],["both","Both (cron + daemon start)"]]){let M=document.createElement("option");M.value=w,M.textContent=_,w===(t?.trigger??"cron")&&(M.selected=!0),A.appendChild(M)}L.appendChild(A),s.appendChild(L);let K=S("div","sched-field");K.appendChild(S("label","sched-label","Notifications"));let Z=document.createElement("select");Z.className="sched-select";for(let[w,_]of[["failure","On failure only"],["always","On every run"],["never","Never"]]){let M=document.createElement("option");M.value=w,M.textContent=_,w===(t?.notifyOn??"failure")&&(M.selected=!0),Z.appendChild(M)}K.appendChild(Z),s.appendChild(K);let X=S("div","sched-btn-row"),W=S("button","sched-cancel-btn","Cancel");W.addEventListener("click",()=>r.remove());let I=S("button","sched-save-btn",n?"Save Changes":"Create Schedule");I.addEventListener("click",()=>{Vt()}),X.appendChild(W),X.appendChild(I),s.appendChild(X),r.appendChild(s),document.body.appendChild(r),o.focus(),r.addEventListener("click",w=>{w.target===r&&r.remove()});let Ce=w=>{w.key==="Escape"&&(r.remove(),document.removeEventListener("keydown",Ce))};document.addEventListener("keydown",Ce);async function Vt(){let w=o.value.trim(),_=a.value.trim(),M=p.style.display==="none"?c.value:p.value.trim();if(!w||!_||!M){E("Name, command, and schedule are required");return}I.disabled=!0,I.textContent="Saving...";try{let J={name:w,command:_,cron:M,trigger:A.value,notifyOn:Z.value,enabled:t?.enabled??!0};n?await e.api(`/api/schedules/${encodeURIComponent(t.id)}`,{method:"PATCH",body:JSON.stringify(J)}):await e.api("/api/schedules",{method:"POST",body:JSON.stringify(J)}),r.remove(),document.removeEventListener("keydown",Ce),e.onSaved()}catch(J){E(J instanceof Error?J.message:"save failed"),I.disabled=!1,I.textContent=n?"Save Changes":"Create Schedule"}}}function C(t,e,n){let r=document.createElement(t);return e&&(r.className=e),n!==void 0&&(r.textContent=n),r}function ks(t){if(t<1e3)return`${t}ms`;let e=t/1e3;if(e<60)return`${e.toFixed(1)}s`;let n=Math.floor(e/60),r=Math.floor(e%60);return`${n}m ${r}s`}function bs(t){try{return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return t}}function Ut(t,e){document.getElementById("sched-history-overlay")?.remove();let n=C("div","sched-overlay");n.id="sched-history-overlay";let r=C("div","sched-modal sched-modal-wide");r.appendChild(C("h3","sched-modal-title",`History: ${t}`));let s=C("div","sched-history-body");s.appendChild(C("div","sched-history-loading","Loading...")),r.appendChild(s);let i=C("button","sched-cancel-btn","Close");i.addEventListener("click",()=>n.remove()),r.appendChild(i),n.appendChild(r),document.body.appendChild(n),n.addEventListener("click",l=>{l.target===n&&n.remove()});let o=l=>{l.key==="Escape"&&(n.remove(),document.removeEventListener("keydown",o))};document.addEventListener("keydown",o),vs(t,e,s)}async function vs(t,e,n){try{let r=await e(`/api/schedules/${encodeURIComponent(t)}/history`);if(n.textContent="",r.history.length===0){n.appendChild(C("div","sched-empty","No executions recorded yet."));return}let s=[...r.history].reverse();for(let i of s)n.appendChild(xs(i))}catch(r){E(r instanceof Error?r.message:"failed to load history"),n.textContent="",n.appendChild(C("div","sched-empty","Failed to load history."))}}function xs(t){let e=C("div",`sched-hist-row sched-hist-${t.status}`),n=C("div","sched-hist-header"),r=C("span",`sched-hist-dot sched-hist-dot-${t.status}`);if(n.appendChild(r),n.appendChild(C("span","sched-hist-status",t.status)),n.appendChild(C("span","sched-hist-time",bs(t.triggeredAt))),n.appendChild(C("span","sched-hist-duration",ks(t.durationMs))),t.trigger&&n.appendChild(C("span","sched-hist-trigger",t.trigger)),e.appendChild(n),t.status==="error"&&t.errorMessage){let s=C("div","sched-hist-error",t.errorMessage);e.appendChild(s)}if(t.status==="skipped"&&t.skipReason&&e.appendChild(C("div","sched-hist-skip",`Skipped: ${t.skipReason}`)),t.responseExcerpt){let s=C("div","sched-hist-excerpt",t.responseExcerpt);e.appendChild(s)}return e}var Wt=Xe(),G=[],R,ve=[],D={costUsd:0,durationMs:0,turns:0},Ue,z=[],je,V=!1,re=!1,xe,Ke;function Ze(){return Ke||(Ke=new ke({container:y("queue"),input:y("prompt"),send:y("send"),submit:async t=>{if(R===void 0)throw new Error("no active session");await B(`/api/sessions/${encodeURIComponent(R)}/prompt`,{method:"POST",body:JSON.stringify({text:t})})},isLive:Qe,isTurnActive:()=>V,onAccepted:()=>{V=!0,ye()},onError:t=>{E(t)}})),Ke}async function B(t,e){let n=await fetch(t,{...e,headers:{authorization:`Bearer ${Wt}`,"content-type":"application/json",...e?.headers??{}}});if(n.status===401){let r="Session credential missing \u2014 reopen the URL printed by `afk web`. A new tab does not inherit the credential from the first one.";try{let s=document.getElementById("status");s&&(s.textContent=r)}catch{}throw new Error(r)}if(!n.ok)throw new Error(`${n.status} ${await n.text()}`);return await n.json()}function ys(t){t.scrollTop=t.scrollHeight}function ws(){return G.find(t=>t.id===R)}function Qe(){return ws()?.mode==="live"}async function We(){if(G=(await B("/api/sessions")).sessions,R===void 0&&G.length>0){let e=G[0];e&&we(e.id)}qe(y("sessions"),G,R,we)}function we(t){R=t;let e=t;ve=[],Ze().clear(),D={costUsd:0,durationMs:0,turns:0},Ue?.stop(),V=!1,re=!1,qe(y("sessions"),G,R,we),De(y("transcript"),ve),jt(),ye(),Ue=new ie(t,Wt,{onEvent:n=>{if(R!==e)return;let s=n.record;if(!s)return;(s.kind==="done"||s.kind==="error")&&(V=!1,ye(),Ze().flush());let i=_t(s);if(D=Nt(D,s),i){ve.push(i);let o=Ot(y("transcript"));De(y("transcript"),ve),o&&ys(y("transcript"))}Qt()},onStatus:n=>{if(R!==e)return;let r=y("status");r.textContent=n==="ended"?"session ended":n,r.className=`status status-${n}`,n==="ended"&&(V=!1),re=n==="reconnecting"||n==="connecting",jt(),ye()}}),Ue.start()}function Qt(){let t=[`${D.turns} turns`];D.costUsd>0&&t.push(`$${D.costUsd.toFixed(4)}`),D.durationMs>0&&t.push(`${(D.durationMs/1e3).toFixed(1)}s`),y("meter").textContent=t.join(" \xB7 ")}function jt(){let t=Qe(),e=y("prompt"),n=y("send"),r=!t||re;e.disabled=r,n.disabled=r,e.placeholder=t?re?"Reconnecting\u2026":"Message the agent\u2026 (queues while it works)":"Read-only \u2014 this session runs in another process",y("composer").classList.toggle("is-readonly",!t),y("composer").classList.toggle("is-reconnecting",t&&re)}function ye(){y("stop").hidden=!(V&&Qe())}function Kt(t){let e=document.getElementById("nav-sessions"),n=document.getElementById("nav-schedules");e?.classList.toggle("is-active",t==="sessions"),n?.classList.toggle("is-active",t==="schedules");let r=document.getElementById("transcript"),s=document.getElementById("approvals"),i=document.getElementById("composer"),o=document.querySelector(".sidebar-head"),l=document.getElementById("sessions"),a=document.getElementById("schedules-view");t==="sessions"?(r&&(r.style.display=""),s&&(s.style.display=""),i&&(i.style.display=""),o&&(o.style.display=""),l&&(l.style.display=""),a?.classList.remove("is-active")):(r&&(r.style.display="none"),s&&(s.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none"),l&&(l.style.display="none"),a?.classList.add("is-active"),!xe&&a&&(xe=new be({container:a,api:B,onEdit:d=>Ft(d.id?d:null,{api:B,onSaved:()=>{xe?.load()}}),onShowHistory:d=>Ut(d,B)})),xe?.load())}async function Cs(t,e){let n=y("new-session");n.disabled=!0,n.textContent="starting\u2026";let r=R;try{let s={model:t};e&&(s.cwd=e);let{session:i}=await B("/api/sessions",{method:"POST",body:JSON.stringify(s)});if(await We(),R!==r&&R!==i.id)return;we(i.id)}catch(s){E(s instanceof Error?s.message:"could not start session")}finally{n.disabled=!1,n.textContent="+ New"}}async function Zt(){let t=await B("/api/pending"),e=t.pending.length!==z.length||t.pending.some((n,r)=>n.id!==z[r]?.id);z=t.pending,e&&Oe(y("approvals"),z,Gt),document.title=z.length>0?`(${z.length}) afk web`:"afk web"}function Gt(t,e){z=z.filter(n=>n.id!==t),Oe(y("approvals"),z,Gt),B("/api/approve",{method:"POST",body:JSON.stringify({requestId:t,response:e})}).catch(n=>{E(n instanceof Error?n.message:"approval failed")})}async function Ss(){if(R===void 0)return;let t=y("stop");t.disabled=!0,t.textContent="Stopping\u2026";try{await B(`/api/sessions/${encodeURIComponent(R)}/interrupt`,{method:"POST",body:JSON.stringify({})})}catch(e){throw t.disabled=!1,t.textContent="Stop",e}}async function Es(){ct({input:y("prompt"),loadCommands:async()=>(await B("/api/commands")).commands}),Ze().wire(),y("new-session").addEventListener("click",()=>pt((t,e)=>{Cs(t,e)})),document.getElementById("nav-sessions")?.addEventListener("click",()=>Kt("sessions")),document.getElementById("nav-schedules")?.addEventListener("click",()=>Kt("schedules")),dt(),y("stop").addEventListener("click",()=>{Ss().catch(t=>{E(t instanceof Error?t.message:"stop failed")})}),Qt(),await We(),setInterval(()=>{We().catch(()=>{})},1e4),je=setInterval(()=>{Zt().catch(()=>{})},1e3),Zt().catch(()=>{}),window.addEventListener("beforeunload",()=>{je&&clearInterval(je)})}Es().catch(t=>{E(t instanceof Error?t.message:String(t))});
62
+ `}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${O(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:n}){let s=this.parser.parseInline(n),r=Dt(t);if(r===null)return s;t=r;let i='<a href="'+t+'"';return e&&(i+=' title="'+O(e)+'"'),i+=">"+s+"</a>",i}image({href:t,title:e,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let r=Dt(t);if(r===null)return O(n);t=r;let i=`<img src="${t}" alt="${O(n)}"`;return e&&(i+=` title="${O(e)}"`),i+=">",i}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:O(t.text)}},Qe=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},D=class je{options;renderer;textRenderer;constructor(e){this.options=e||Q,this.options.renderer=this.options.renderer||new Ce,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Qe}static parse(e,n){return new je(n).parse(e)}static parseInline(e,n){return new je(n).parseInline(e)}parse(e){this.renderer.parser=this;let n="";for(let s=0;s<e.length;s++){let r=e[s];if(this.options.extensions?.renderers?.[r.type]){let o=r,l=this.options.extensions.renderers[o.type].call({parser:this},o);if(l!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(o.type)){n+=l||"";continue}}let i=r;switch(i.type){case"space":{n+=this.renderer.space(i);break}case"hr":{n+=this.renderer.hr(i);break}case"heading":{n+=this.renderer.heading(i);break}case"code":{n+=this.renderer.code(i);break}case"table":{n+=this.renderer.table(i);break}case"blockquote":{n+=this.renderer.blockquote(i);break}case"list":{n+=this.renderer.list(i);break}case"checkbox":{n+=this.renderer.checkbox(i);break}case"html":{n+=this.renderer.html(i);break}case"def":{n+=this.renderer.def(i);break}case"paragraph":{n+=this.renderer.paragraph(i);break}case"text":{n+=this.renderer.text(i);break}default:{let o='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return n}parseInline(e,n=this.renderer){this.renderer.parser=this;let s="";for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let l=this.options.extensions.renderers[i.type].call({parser:this},i);if(l!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(i.type)){s+=l||"";continue}}let o=i;switch(o.type){case"escape":{s+=n.text(o);break}case"html":{s+=n.html(o);break}case"link":{s+=n.link(o);break}case"image":{s+=n.image(o);break}case"checkbox":{s+=n.checkbox(o);break}case"strong":{s+=n.strong(o);break}case"em":{s+=n.em(o);break}case"codespan":{s+=n.codespan(o);break}case"br":{s+=n.br(o);break}case"del":{s+=n.del(o);break}case"text":{s+=n.text(o);break}default:{let l='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return s}},ce=class{options;block;constructor(t){this.options=t||Q}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(){return this.block?_.lex:_.lexInline}provideParser(){return this.block?D.parse:D.parseInline}},Hs=class{defaults=Fe();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=D;Renderer=Ce;TextRenderer=Qe;Lexer=_;Tokenizer=we;Hooks=ce;constructor(...t){this.use(...t)}walkTokens(t,e){let n=[];for(let s of t)switch(n=n.concat(e.call(this,s)),s.type){case"table":{let r=s;for(let i of r.header)n=n.concat(this.walkTokens(i.tokens,e));for(let i of r.rows)for(let o of i)n=n.concat(this.walkTokens(o.tokens,e));break}case"list":{let r=s;n=n.concat(this.walkTokens(r.items,e));break}default:{let r=s;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(i=>{let o=r[i].flat(1/0);n=n.concat(this.walkTokens(o,e))}):r.tokens&&(n=n.concat(this.walkTokens(r.tokens,e)))}}return n}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let i=e.renderers[r.name];i?e.renderers[r.name]=function(...o){let l=r.renderer.apply(this,o);return l===!1&&(l=i.apply(this,o)),l}:e.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=e[r.level];i?i.unshift(r.tokenizer):e[r.level]=[r.tokenizer],r.start&&(r.level==="block"?e.startBlock?e.startBlock.push(r.start):e.startBlock=[r.start]:r.level==="inline"&&(e.startInline?e.startInline.push(r.start):e.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(e.childTokens[r.name]=r.childTokens)}),s.extensions=e),n.renderer){let r=this.defaults.renderer||new Ce(this.defaults);for(let i in n.renderer){if(!(i in r))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let o=i,l=n.renderer[o],a=r[o];r[o]=(...c)=>{let d=l.apply(r,c);return d===!1&&(d=a.apply(r,c)),d||""}}s.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new we(this.defaults);for(let i in n.tokenizer){if(!(i in r))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let o=i,l=n.tokenizer[o],a=r[o];r[o]=(...c)=>{let d=l.apply(r,c);return d===!1&&(d=a.apply(r,c)),d}}s.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new ce;for(let i in n.hooks){if(!(i in r))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let o=i,l=n.hooks[o],a=r[o];ce.passThroughHooks.has(i)?r[o]=c=>{if(this.defaults.async&&ce.passThroughHooksRespectAsync.has(i))return(async()=>{let u=await l.call(r,c);return a.call(r,u)})();let d=l.call(r,c);return a.call(r,d)}:r[o]=(...c)=>{if(this.defaults.async)return(async()=>{let u=await l.apply(r,c);return u===!1&&(u=await a.apply(r,c)),u})();let d=l.apply(r,c);return d===!1&&(d=a.apply(r,c)),d}}s.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,i=n.walkTokens;s.walkTokens=function(o){let l=[];return l.push(i.call(this,o)),r&&(l=l.concat(r.call(this,o))),l}}this.defaults={...this.defaults,...s}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return _.lex(t,e??this.defaults)}parser(t,e){return D.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let s={...n},r={...this.defaults,...s},i=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&s.async===!1)return i(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=t),r.async)return(async()=>{let o=r.hooks?await r.hooks.preprocess(e):e,l=await(r.hooks?await r.hooks.provideLexer():t?_.lex:_.lexInline)(o,r),a=r.hooks?await r.hooks.processAllTokens(l):l;r.walkTokens&&await Promise.all(this.walkTokens(a,r.walkTokens));let c=await(r.hooks?await r.hooks.provideParser():t?D.parse:D.parseInline)(a,r);return r.hooks?await r.hooks.postprocess(c):c})().catch(i);try{r.hooks&&(e=r.hooks.preprocess(e));let o=(r.hooks?r.hooks.provideLexer():t?_.lex:_.lexInline)(e,r);r.hooks&&(o=r.hooks.processAllTokens(o)),r.walkTokens&&this.walkTokens(o,r.walkTokens);let l=(r.hooks?r.hooks.provideParser():t?D.parse:D.parseInline)(o,r);return r.hooks&&(l=r.hooks.postprocess(l)),l}catch(o){return i(o)}}}onError(t,e){return n=>{if(n.message+=`
63
+ Please report this to https://github.com/markedjs/marked.`,t){let s="<p>An error occurred:</p><pre>"+O(n.message+"",!0)+"</pre>";return e?Promise.resolve(s):s}if(e)return Promise.reject(n);throw n}}},J=new Hs;function x(t,e){return J.parse(t,e)}x.options=x.setOptions=function(t){return J.setOptions(t),x.defaults=J.defaults,Ot(x.defaults),x};x.getDefaults=Fe;x.defaults=Q;x.use=function(...t){return J.use(...t),x.defaults=J.defaults,Ot(x.defaults),x};x.walkTokens=function(t,e){return J.walkTokens(t,e)};x.parseInline=J.parseInline;x.Parser=D;x.parser=D.parse;x.Renderer=Ce;x.TextRenderer=Qe;x.Lexer=_;x.lexer=_.lex;x.Tokenizer=we;x.Hooks=ce;x.parse=x;var fi=x.options,gi=x.setOptions,bi=x.use,ki=x.walkTokens,vi=x.parseInline;var yi=D.parse,xi=_.lex;var Ns=["http:","https:","mailto:"];function Ps(t){try{let e=new URL(t);return Ns.includes(e.protocol)?e.href:void 0}catch{return}}function y(t,e){let n=document.createElement(t);return e&&(n.className=e),n}function q(t,e){if(e)for(let n of e)switch(n.type){case"strong":{let s=y("strong");q(s,n.tokens),t.appendChild(s);break}case"em":{let s=y("em");q(s,n.tokens),t.appendChild(s);break}case"del":{let s=y("s");q(s,n.tokens),t.appendChild(s);break}case"codespan":{let s=y("code","md-code-inline");s.textContent=n.text,t.appendChild(s);break}case"link":{let s=n,r=Ps(s.href);if(r===void 0){let o=y("span");q(o,s.tokens),t.appendChild(o);break}let i=y("a","md-link");i.href=r,i.target="_blank",i.rel="noopener noreferrer",q(i,s.tokens),t.appendChild(i);break}case"image":{let s=y("span","md-image");s.textContent=`[image: ${n.text||"untitled"}]`,t.appendChild(s);break}case"br":t.appendChild(y("br"));break;default:{let s=n.text??"",r=n.tokens;r&&r.length>0&&n.type==="text"?q(t,r):s&&t.appendChild(document.createTextNode(s));break}}}function _s(t){let e=t.ordered?y("ol","md-list"):y("ul","md-list");t.ordered&&typeof t.start=="number"&&t.start>1&&(e.start=t.start);for(let n of t.items){let s=y("li");if(n.task){let r=y("input","md-task");r.type="checkbox",r.checked=!!n.checked,r.disabled=!0,s.appendChild(r)}Xe(s,n.tokens),e.appendChild(s)}return e}function Bs(t){let e=y("pre","md-pre"),n=y("code");if(t.lang){let s=t.lang.split(/\s+/)[0]??"";s&&(n.className=`md-lang-${s}`,e.dataset.lang=s)}return n.textContent=t.text,e.appendChild(n),e}function Ds(t){let e=y("table","md-table"),n=y("thead"),s=y("tr");for(let i of t.header){let o=y("th");q(o,i.tokens),s.appendChild(o)}n.appendChild(s),e.appendChild(n);let r=y("tbody");for(let i of t.rows){let o=y("tr");for(let l of i){let a=y("td");q(a,l.tokens),o.appendChild(a)}r.appendChild(o)}return e.appendChild(r),e}function Xe(t,e){for(let n of e)switch(n.type){case"heading":{let s=Math.min(Math.max(n.depth,1),6),r=y(`h${s}`,"md-heading");q(r,n.tokens),t.appendChild(r);break}case"paragraph":{let s=y("p","md-p");q(s,n.tokens),t.appendChild(s);break}case"code":t.appendChild(Bs(n));break;case"list":t.appendChild(_s(n));break;case"blockquote":{let s=y("blockquote","md-quote");Xe(s,n.tokens),t.appendChild(s);break}case"table":t.appendChild(Ds(n));break;case"hr":t.appendChild(y("hr","md-hr"));break;case"space":break;case"html":{let s=y("p","md-p");s.textContent=n.text,t.appendChild(s);break}default:{let s=n.tokens;if(s&&s.length>0){let i=y("p","md-p");q(i,s),t.appendChild(i);break}let r=n.text??"";if(r.trim()){let i=y("p","md-p");i.textContent=r,t.appendChild(i)}break}}}function Qt(t,e="md"){let n=y("div",e);try{Xe(n,new _().lex(t))}catch{n.textContent=t}return n}var ue=new Map;function Xt(){ue.clear()}function qs(t,e){return t.kind!=="tool"?!1:e.className!==`tool tool-${t.status}`}function Yt(t,e,n){e.length<t.childElementCount&&(ue.clear(),t.textContent="");for(let s of e){let r=ue.get(s.id);if(r===void 0){let i=n(s);ue.set(s.id,i),t.appendChild(i)}else if(qs(s,r)){let i=n(s);ue.set(s.id,i),t.replaceChild(i,r)}}}function X(t,e,n){let s=document.createElement(t);return e&&(s.className=e),n!==void 0&&(s.textContent=n),s}function zs(t){return Math.max(1,Math.round(t.length/800))}function Os(t){return`\u25C6 thought for ${zs(t.text)}s`}function js(t,e){e.textContent="";let n=X("div","thinking-block");n.setAttribute("data-thinking-id",t.id);let s=X("div","thinking-summary"),r=X("span","thinking-label",Os(t)),i=X("span","thinking-chevron","\u203A");s.appendChild(i),s.appendChild(r);let o=X("div","thinking-body"),l=X("pre","thinking-pre",t.text);o.appendChild(l),s.addEventListener("click",()=>{n.classList.toggle("thinking-block--open")}),s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),n.classList.toggle("thinking-block--open"))}),n.appendChild(s),n.appendChild(o),e.appendChild(n)}function en(t){let e=X("div","thinking-host");return js(t,e),e}function tn(t,e){return e?.has(t.id)?"needs-input":t.mode==="live"||t.alive===!0?"active":"completed"}var Fs={"needs-input":{label:"Needs input",dotClass:"status-dot status-dot-needs-input",badgeClass:"badge badge-needs-input"},active:{label:"Active",dotClass:"status-dot status-dot-active",badgeClass:"badge badge-active"},completed:{label:"Completed",dotClass:"status-dot status-dot-completed",badgeClass:"badge badge-completed"}};function Ye(t){let{label:e,dotClass:n,badgeClass:s}=Fs[t],r=document.createElement("span");r.className=s;let i=document.createElement("span");i.className=n,i.setAttribute("aria-hidden","true");let o=document.createElement("span");return o.className="status-badge-label",o.textContent=e,r.appendChild(i),r.appendChild(o),r}function B(t,e,n){let s=document.createElement(t);return e&&(s.className=e),n!==void 0&&(s.textContent=n),s}function Ks(t){let e=/^@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@/.exec(t);return!e||e[1]===void 0||e[2]===void 0?null:{oldStart:parseInt(e[1],10),newStart:parseInt(e[2],10)}}function Us(t){let e=t.split(`
64
+ `),n=[],s=null,r=0,i=0;for(let o of e){if(o.startsWith("@@")){let l=Ks(o);l&&(s={header:o,oldStart:l.oldStart,newStart:l.newStart,lines:[]},n.push(s),r=l.oldStart,i=l.newStart);continue}s&&(o.startsWith("+")&&!o.startsWith("+++")?s.lines.push({type:"add",content:o.slice(1),newNum:i++}):o.startsWith("-")&&!o.startsWith("---")?s.lines.push({type:"del",content:o.slice(1),oldNum:r++}):(o.startsWith(" ")||o==="")&&s.lines.push({type:"ctx",content:o.startsWith(" ")?o.slice(1):"",oldNum:r++,newNum:i++}))}return n}function Gs(t){return/^\+{3}\s+(?:b\/)?(.+)/m.exec(t)?.[1]?.trim()}function nn(t){let e=B("span","dv-gutter");return e.textContent=t!==void 0?String(t):"",e}function Ws(t){let e=B("span",`dv-line dv-line-${t.type}`);e.appendChild(nn(t.oldNum)),e.appendChild(nn(t.newNum));let n=B("span","dv-sigil");n.textContent=t.type==="add"?"+":t.type==="del"?"-":" ",e.appendChild(n);let s=B("span","dv-content");return s.textContent=t.content,e.appendChild(s),e}function Vs(t){let e=0,n=0;for(let s of t)s.type==="add"?e++:s.type==="del"&&n++;return`+${e} / -${n}`}function Zs(t,e){let n=document.createElement("details");n.className="dv-hunk",e||n.setAttribute("open","");let s=document.createElement("summary");s.className="dv-hunk-header";let r=B("span","dv-chevron");r.textContent="\u25B6",s.appendChild(r);let i=B("span","dv-hunk-range",t.header.replace(/^@@\s*/,"").replace(/\s*@@.*$/," @@"));s.appendChild(i);let o=B("span","dv-hunk-stats",Vs(t.lines));s.appendChild(o),n.appendChild(s);let l=B("div","dv-hunk-body");for(let a of t.lines)l.appendChild(Ws(a));return n.appendChild(l),n}function sn(t,e){let n=Us(t),s=n.reduce((l,a)=>l+a.lines.length,0),r=e?.collapsed??s>50,i=B("div","dv-root"),o=e?.fileName??Gs(t);if(o){let l=B("div","dv-file-header"),a=B("span","dv-file-icon");a.textContent="\u{1F4C4}",l.appendChild(a),l.appendChild(B("span","dv-file-name",o)),i.appendChild(l)}if(n.length===0)return i.appendChild(B("div","dv-empty","(no changes)")),i;for(let l of n)i.appendChild(Zs(l,r));return i}var rn=/bash|delete|remove|overwrite|rm |drop/i;function $(t,e,n){let s=document.createElement(t);return e&&(s.className=e),n!==void 0&&(s.textContent=n),s}function Js(t){if(!t)return"";let e=Math.floor((Date.now()-new Date(t).getTime())/6e4);return e>=1?`waiting ${e}m`:""}function Te(t,e,n){t.textContent="",t.classList.toggle("has-pending",e.length>0);for(let s of e){let r=s.request??{},i=r.title??r.message??"The agent is waiting for a response.",o=rn.test(i)||rn.test(r.serverName??""),l=$("div",o?"approval-card approval-card--destructive":"approval-card"),a=$("div","approval-head");a.appendChild($("span","approval-badge",r.origin==="agent"?"question":"approval")),r.serverName&&a.appendChild($("span","approval-source",r.serverName));let c=Js(s.createdAt);c&&a.appendChild($("span","approval-time",c)),l.appendChild(a),l.appendChild($("div","approval-title",i)),r.description&&l.appendChild($("div","approval-desc",r.description));let d=$("div","approval-actions");if(r.type==="choice"&&Array.isArray(r.choices)&&r.choices.length>0)for(let p of r.choices){let m=$("button","approval-btn",p);m.addEventListener("click",()=>n(s.id,{action:"accept",content:{value:p}})),d.appendChild(m)}else if(r.type==="multi_choice"&&Array.isArray(r.choices)&&r.choices.length>0){let p=$("div","approval-checkboxes"),m=[];for(let g of r.choices){let R=$("label","approval-checkbox-row"),C=document.createElement("input");C.type="checkbox",C.value=g,m.push(C),R.appendChild(C),R.appendChild($("span",void 0,g)),p.appendChild(R)}l.appendChild(p);let h=$("button","approval-btn approval-primary","Submit");h.addEventListener("click",()=>n(s.id,{action:"accept",content:{value:m.filter(g=>g.checked).map(g=>g.value)}})),d.appendChild(h)}else if(r.type==="text"||r.type==="number"){let p=document.createElement("input");p.className="approval-input",p.type=r.type==="number"?"number":"text",r.questionDefault!==void 0&&(p.value=String(r.questionDefault));let m=()=>n(s.id,{action:"accept",content:{value:r.type==="number"?Number(p.value):p.value}});p.addEventListener("keydown",g=>{g.key==="Enter"&&m()}),l.appendChild(p);let h=$("button","approval-btn approval-primary","Submit");h.addEventListener("click",m),d.appendChild(h)}else{let p=$("button","approval-btn approval-primary","Approve");p.addEventListener("click",()=>n(s.id,{action:"accept",content:{value:!0}})),d.appendChild(p)}let u=$("button","approval-btn approval-danger","Deny");u.addEventListener("click",()=>n(s.id,{action:"decline"})),d.appendChild(u),l.appendChild(d),t.appendChild(l)}}var on=2e3,an=2e3;function f(t,e,n){let s=document.createElement(t);return e&&(s.className=e),n!==void 0&&(s.textContent=n),s}function Qs(t){if(!t)return;let e=t.replace(/[/\\]+$/,"").split(/[/\\]/).pop()??"";return e&&e!=="."?e:void 0}function Xs(t){return(t.title??"").replace(/^\s*\[[^\]]{0,80}\]\s*/,"").trim()||t.title||t.id.slice(0,8)}function tt(t,e,n,s){t.textContent="";let r=[...e.filter(i=>i.alive===!0||i.mode==="live"),...e.filter(i=>!(i.alive===!0||i.mode==="live"))];for(let i of r){let o=f("button","session-row");i.id===n&&o.classList.add("is-active");let l=f("span","session-title",Xs(i));o.appendChild(l);let a=f("span","session-meta"),c=Qs(i.cwd);if(c){let u=f("span","session-cwd",c);u.title=i.cwd??c,a.appendChild(u)}let d=f("span",i.mode==="live"?"badge badge-live":"badge badge-readonly");d.textContent=i.mode==="live"?"live":"read-only",a.appendChild(d),i.alive===!0&&i.mode==="live"?a.appendChild(Ye("needs-input")):a.appendChild(Ye(tn(i))),i.alive&&a.appendChild(f("span","badge badge-alive","running")),i.model&&a.appendChild($t(i.model)),i.updatedAt&&a.appendChild(f("span","session-time",ir(i.updatedAt))),o.appendChild(a),o.addEventListener("click",()=>s(i.id)),t.appendChild(o)}e.length===0&&t.appendChild(f("div","empty","No sessions found."))}function nt(t,e){Yt(t,e,Ys)}function Ys(t){switch(t.kind){case"user":{let e=f("div","msg msg-user");return e.appendChild(f("div","msg-role","you")),e.appendChild(f("div","msg-body",t.text)),e}case"assistant":{let e=f("div","msg msg-assistant");e.appendChild(f("div","msg-role","agent"));let n=f("div","msg-body md-body");return n.appendChild(Qt(t.text)),e.appendChild(n),e}case"thinking":return en(t);case"error":{let e=f("div","msg msg-error");return e.appendChild(f("div","msg-role","error")),e.appendChild(f("div","msg-body",t.message)),e}case"notice":return f("div","notice",t.text);case"tool":return er(t);case"subagent":return nr(t);case"bg_job":return sr(t)}}function er(t){let e=f("details",`tool tool-${t.status}`),n=f("summary","tool-summary");n.appendChild(f("span",`tool-dot tool-dot-${t.status}`,"")),n.appendChild(f("span","tool-name",t.name)),t.inputPreview&&n.appendChild(f("span","tool-target",rr(t.name,t.inputPreview))),e.appendChild(n);let s=f("div","tool-body");if(t.inputPreview){s.appendChild(f("div","tool-label","input"));let r=ve(t.inputPreview);if(r.length>an){let i=f("pre","tool-pre",r.slice(0,an));s.appendChild(i);let o=f("button","tool-more",`Show full input (${r.length.toLocaleString()} chars)`);o.addEventListener("click",()=>{i.textContent=r,o.remove()}),s.appendChild(o)}else s.appendChild(f("pre","tool-pre",r))}if(t.outputUnavailable===!0)s.appendChild(f("div","tool-unavailable","Result not available after refresh \u2014 successful tool output is not persisted to the session ledger."));else if(t.output!==void 0&&t.output!==""){s.appendChild(f("div","tool-label","output"));let r=ve(t.output);if(r.length>on){let i=f("pre","tool-pre",r.slice(0,on));s.appendChild(i);let o=f("button","tool-more",`Show full output (${r.length.toLocaleString()} chars)`);o.addEventListener("click",()=>{i.textContent=r,o.remove()}),s.appendChild(o)}else s.appendChild(f("pre","tool-pre",r))}return t.diff!==void 0&&(s.appendChild(f("div","tool-label","diff")),s.appendChild(sn(ve(String(t.diff))))),e.appendChild(s),e}function tr(t){let e=t/1e3;return e<60?`${e.toFixed(1)}s`:`${Math.floor(e/60)}m ${Math.round(e%60)}s`}var ln={started:"\u25B6",succeeded:"\u2713",failed:"\u2717",cancelled:"\u25FC",completed:"\u2713"};function nr(t){let e=t.status,n=f("div",`sa-card sa-card--${e}`),s=f("span","sa-icon",ln[e]??"\u25CF"),r=f("div","sa-header");return r.appendChild(s),r.appendChild(f("span","sa-label",t.label)),t.model&&r.appendChild(f("span","sa-model",t.model)),t.durationMs!==void 0&&r.appendChild(f("span","sa-dur",tr(t.durationMs))),n.appendChild(r),t.promptHead&&n.appendChild(f("div","sa-prompt",t.promptHead)),n}function sr(t){let e=f("div",`sa-card sa-card--${t.status}`),n=f("span","sa-icon",ln[t.status]??"\u25CF"),s=f("div","sa-header");return s.appendChild(n),s.appendChild(f("span","sa-label",`bg: ${t.label}`)),e.appendChild(s),e}function et(t,e){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}function rr(t,e){try{let n=JSON.parse(e);if((t==="bash"||t==="shell")&&typeof n.command=="string")return et(n.command,80);if((t==="edit_file"||t==="write_file"||t==="read_file")&&typeof n.file_path=="string")return n.file_path;if(t==="agent"&&typeof n.prompt=="string")return et(n.prompt,60);if((t==="grep"||t==="glob")&&typeof n.pattern=="string")return n.pattern}catch{}return et(e,90)}function ir(t){let e=Date.parse(t);if(Number.isNaN(e))return"";let n=Math.max(0,(Date.now()-e)/1e3);return n<60?"just now":n<3600?`${Math.floor(n/60)}m ago`:n<86400?`${Math.floor(n/3600)}h ago`:`${Math.floor(n/86400)}d ago`}function or(t){let e=t.trim();return e?e.startsWith("/")||e.startsWith("./")||e.startsWith("~/")||/^[\w.]/.test(e):!1}function ar(t,e){let n=t.selectionStart??t.value.length,s=t.selectionEnd??n,r=t.value.slice(0,n),i=t.value.slice(s),o=r.length>0&&!/\s$/.test(r)?" ":"";t.value=r+o+e+" "+i;let l=n+o.length+e.length+1;t.setSelectionRange(l,l),t.dispatchEvent(new Event("input",{bubbles:!0})),t.focus()}function dn(t){let{input:e,container:n}=t,s=document.createElement("button");s.type="button",s.className="atf-btn",s.title="Insert @file reference",s.setAttribute("aria-label","Insert file reference"),s.textContent="@";let r=document.createElement("div");r.className="atf-popover",r.setAttribute("role","dialog"),r.setAttribute("aria-label","Insert file path"),r.hidden=!0;let i=document.createElement("p");i.className="atf-hint",i.textContent="Type a file path. @~/file.ts or @src/file.ts";let o=document.createElement("div");o.className="atf-input-row";let l=document.createElement("input");l.type="text",l.className="atf-path-input",l.placeholder="src/foo.ts or ~/file.ts",l.setAttribute("autocomplete","off"),l.setAttribute("spellcheck","false");let a=document.createElement("button");a.type="button",a.className="atf-add-btn",a.textContent="Add";let c=document.createElement("p");c.className="atf-error",c.hidden=!0,c.textContent="Enter a valid file path.",o.appendChild(l),o.appendChild(a),r.appendChild(i),r.appendChild(o),r.appendChild(c);function d(){r.hidden=!1,c.hidden=!0,l.value="",s.classList.add("atf-btn--active"),s.setAttribute("aria-expanded","true"),l.focus()}function u(){r.hidden=!0,s.classList.remove("atf-btn--active"),s.setAttribute("aria-expanded","false")}function p(){let C=l.value.trim();if(!or(C)){c.hidden=!1,l.focus();return}ar(e,`@${C}`),u()}let m=()=>{r.hidden?d():u()},h=()=>{p()},g=C=>{C.key==="Enter"&&(C.preventDefault(),p()),C.key==="Escape"&&u()},R=C=>{!r.hidden&&!n.contains(C.target)&&u()};return s.addEventListener("click",m),a.addEventListener("click",h),l.addEventListener("keydown",g),document.addEventListener("click",R,{capture:!0}),n.appendChild(r),n.appendChild(s),()=>{s.removeEventListener("click",m),a.removeEventListener("click",h),l.removeEventListener("keydown",g),document.removeEventListener("click",R,{capture:!0}),r.remove(),s.remove()}}var st=0;function M(t){return st+=1,`${t}_${st}`}function cn(){st=0}function S(t){return typeof t=="string"?t:void 0}function K(t){return typeof t=="number"?t:void 0}function pn(t,e,n){let s=t;if(typeof s.kind=="string")switch(s.kind){case"user":return{kind:"user",id:M("u"),text:S(s.text)??""};case"assistant":return{kind:"assistant",id:M("a"),text:S(s.text)??""};case"thinking":return{kind:"thinking",id:M("th"),text:S(s.text)??""};case"tool":{let r=S(s.input)??"";if(r.trim()==="\u2026")return;let i={kind:"tool",id:M("t"),name:S(s.toolName)??"tool",inputPreview:r,status:"ok",outputUnavailable:!0};return e&&S(s.toolUseId)&&e.set(S(s.toolUseId),i),i}case"tool_result":{let r=S(s.toolUseId),i=S(s.content)??"",o=K(s.durationMs);if(e&&r){let l=e.get(r);if(l){l.output=i,l.outputUnavailable=!1,o!==void 0&&(l.durationMs=o);return}}return{kind:"notice",id:M("n"),text:`tool result: ${i.slice(0,80)}`}}case"tool_error":{let r=S(s.content)??"",i=r.split(`
65
+ `,1)[0]??"";return{kind:"tool",id:M("t"),name:S(s.toolName)??"error",inputPreview:i,status:"error",output:r}}case"error":return{kind:"error",id:M("e"),message:S(s.message)??"error"};case"done":{let r=s.costUsd,i=s.durationMs,o=[];typeof r=="number"&&o.push(`$${r.toFixed(4)}`),typeof i=="number"&&o.push(`${(i/1e3).toFixed(1)}s`);let l=K(s.inputTokens),a=K(s.outputTokens),c=K(s.cacheReadTokens);if(l!==void 0||a!==void 0){let d=[];l!==void 0&&d.push(`${l}in`),a!==void 0&&d.push(`${a}out`),c!==void 0&&d.push(`${c}cache`),o.push(d.join("/"))}return{kind:"notice",id:M("n"),text:o.length?`turn complete \xB7 ${o.join(" \xB7 ")}`:"turn complete"}}case"paused":return{kind:"notice",id:M("n"),text:"paused \u2014 usage limit"};case"resumed":return{kind:"notice",id:M("n"),text:"resumed"};case"tool_activity":{let r=K(s.activeCount)??0;if(r===0)return{kind:"notice",id:M("n"),text:"tool wave complete"};let i=r===1?"tool":"tools";return{kind:"notice",id:M("n"),text:`Running ${r} ${i} in parallel`}}case"rate_limit":{let r=K(s.retryAfterMs),i=r!==void 0?` (retrying in ${Math.ceil(r/1e3)}s)`:"";return{kind:"notice",id:M("n"),text:`Rate limited${i}`}}case"progress":return{kind:"notice",id:M("n"),text:S(s.message)??"progress"};case"subagent_lifecycle":{let r=S(s.subagentId)??"subagent",i=S(s.status)??"unknown",o=S(s.agentType),l=o?`${o} (${r.slice(0,8)})`:r.slice(0,12);if(n){let c=n.get(r);if(c){c.status=i,K(s.durationMs)!==void 0&&(c.durationMs=K(s.durationMs));return}}let a={kind:"subagent",id:M("sa"),subagentId:r,status:i,label:l,model:S(s.model),durationMs:K(s.durationMs),promptHead:S(s.promptHead)};return n?.set(r,a),a}case"background_job":{let r=S(s.jobId)??"job",i=S(s.status)??"unknown",o=S(s.label)??r.slice(0,12);return{kind:"bg_job",id:M("bj"),jobId:r,status:i,label:o}}case"plan_mode":{let r=S(s.mode)??"default";return{kind:"notice",id:M("n"),text:`Switched to ${r} mode`}}default:return}}function un(t,e){let n=e;if(n.kind!=="done")return t;let s=n.costUsd,r=n.durationMs,i=n.inputTokens,o=n.outputTokens,l=n.cacheReadTokens;return{costUsd:t.costUsd+(typeof s=="number"?s:0),durationMs:t.durationMs+(typeof r=="number"?r:0),turns:t.turns+1,inputTokens:(t.inputTokens??0)+(typeof i=="number"?i:0),outputTokens:(t.outputTokens??0)+(typeof o=="number"?o:0),cacheReadTokens:(t.cacheReadTokens??0)+(typeof l=="number"?l:0)}}function Le(t,e){return Number.isInteger(e)&&e>=0&&e<t.length}function hn(t,e){if(!Le(t,e)||e===0)return t.slice();let n=t.slice(),s=n[e-1],r=n[e];return s===void 0||r===void 0?t.slice():(n[e-1]=r,n[e]=s,n)}function mn(t,e){if(!Le(t,e)||e===t.length-1)return t.slice();let n=t.slice(),s=n[e+1],r=n[e];return s===void 0||r===void 0?t.slice():(n[e+1]=r,n[e]=s,n)}function fn(t,e){if(!Le(t,e))return t.slice();let n=t.slice();return n.splice(e,1),n}function gn(t,e,n){if(!Le(t,e))return t.slice();let s=t.slice();return s[e]=n,s}var Me=class{constructor(e){this.deps=e}deps;queue=[];flushing=!1;entries(){return[...this.queue]}clear(){this.queue=[],this.render()}wire(){let e=()=>{let n=this.deps.input.value.trim();n&&(this.queue=[...this.queue,n],this.deps.input.value="",be(this.deps.input),this.render(),this.flush())};this.deps.send.addEventListener("click",e),this.deps.input.addEventListener("keydown",n=>{n.key==="Enter"&&(n.metaKey||n.ctrlKey)&&e()})}render(){let e=this.deps.container;e.textContent="",this.queue.forEach((n,s)=>{let r=document.createElement("div");r.className="queue-row";let i=document.createElement("span");i.className="queue-text",i.textContent=n,r.appendChild(i);let o=document.createElement("button");o.className="queue-btn",o.textContent="\u270E",o.title="Edit",o.addEventListener("click",()=>{let l=document.createElement("input");l.className="queue-text queue-edit-input",l.value=n,r.replaceChild(l,i),l.focus();let a=!1,c=()=>{a||(a=!0,this.queue=gn(this.queue,s,l.value),this.render())};l.addEventListener("keydown",d=>{d.key==="Enter"&&c(),d.key==="Escape"&&(d.preventDefault(),a=!0,r.replaceChild(i,l))}),l.addEventListener("blur",c)}),r.appendChild(o);for(let[l,a]of[["\u2191",()=>{this.queue=hn(this.queue,s)}],["\u2193",()=>{this.queue=mn(this.queue,s)}],["\u2715",()=>{this.queue=fn(this.queue,s)}]]){let c=document.createElement("button");c.className="queue-btn",c.textContent=l,c.addEventListener("click",()=>{a(),this.render()}),r.appendChild(c)}e.appendChild(r)})}async flush(){if(this.flushing||!this.deps.isLive()||this.deps.isTurnActive())return;let e=this.queue[0];if(e!==void 0){this.flushing=!0;try{await this.deps.submit(e),this.queue=this.queue.slice(1),this.render(),this.deps.onAccepted()}catch(n){this.deps.onError(n instanceof Error?n.message:"send failed")}finally{this.flushing=!1}}}};function bn(t,e=80){return t.scrollHeight-t.scrollTop-t.clientHeight<=e}function kn(t,e){let n=[];function s(i,o){n=n.filter(l=>l.id!==i),Te(e,n,s),t("/api/approve",{method:"POST",body:JSON.stringify({requestId:i,response:o})}).catch(l=>{T(l instanceof Error?l.message:"approval failed")})}async function r(){let i=await t("/api/pending"),o=i.pending.length!==n.length||i.pending.some((l,a)=>l.id!==n[a]?.id);n=i.pending,o&&Te(e,n,s),document.title=n.length>0?`(${n.length}) afk web`:"afk web"}return{pollPending:r,answerApproval:s}}function b(t,e,n){let s=document.createElement(t);return e&&(s.className=e),n!==void 0&&(s.textContent=n),s}function lr(t){let e=t.trim().split(/\s+/);if(e.length<5)return t;let[n,s,r,i,o]=e;return r==="*"&&i==="*"&&o==="*"&&s.startsWith("*/")?`Every ${s.slice(2)} hours`:r==="*"&&i==="*"&&o==="*"&&s!=="*"&&n!=="*"?`Daily at ${s.padStart(2,"0")}:${n.padStart(2,"0")}`:r==="*"&&i==="*"&&o!=="*"&&s!=="*"?`${["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][Number(o)]??o} at ${s.padStart(2,"0")}:${n.padStart(2,"0")}`:r==="*"&&i==="*"&&o==="*"&&s==="*"&&n!=="*"?`Every hour at :${n.padStart(2,"0")}`:r==="*"&&i==="*"&&o==="*"&&s==="*"&&n==="*"?"Every minute":t}function dr(t){let e=Date.now()-new Date(t).getTime(),n=Math.floor(e/1e3);if(n<60)return"just now";let s=Math.floor(n/60);if(s<60)return`${s}m ago`;let r=Math.floor(s/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}var Ae=class{container;api;onEdit;onShowHistory;schedules=[];daemonStatus={running:!1};constructor(e){this.container=e.container,this.api=e.api,this.onEdit=e.onEdit,this.onShowHistory=e.onShowHistory}async load(){try{let[e,n]=await Promise.all([this.api("/api/schedules"),this.api("/api/daemon/status")]);this.schedules=e.schedules,this.daemonStatus=n}catch(e){T(e instanceof Error?e.message:"failed to load schedules")}this.render()}render(){this.container.textContent="";let e=b("div","sched-header"),n=b("div","sched-title-row");n.appendChild(b("h2","sched-title","Schedules"));let s=b("button","sched-add-btn","+ New Schedule");s.addEventListener("click",()=>this.onEdit({id:"",name:"",command:"",cron:"",enabled:!0,createdAt:"",updatedAt:""})),n.appendChild(s),e.appendChild(n);let r=b("div","sched-daemon-status"),i=b("span",this.daemonStatus.running?"sched-dot-ok":"sched-dot-off");if(r.appendChild(i),r.appendChild(b("span","sched-daemon-text",this.daemonStatus.running?`Daemon running (${this.daemonStatus.tasks??0} tasks)`:"Daemon not running")),e.appendChild(r),this.container.appendChild(e),this.schedules.length===0){let l=b("div","sched-empty");l.appendChild(b("div","sched-empty-icon","\u23F0")),l.appendChild(b("div","sched-empty-title","No schedules yet")),l.appendChild(b("div","sched-empty-sub","Create a schedule to run tasks on a cron timer.")),this.container.appendChild(l);return}let o=b("div","sched-list");for(let l of this.schedules)o.appendChild(this.renderCard(l));this.container.appendChild(o)}renderCard(e){let n=b("div",`sched-card${e.enabled?"":" sched-card-disabled"}`),s=b("div","sched-card-top"),r=b("span","sched-card-name",e.name);s.appendChild(r);let i=b("button",`sched-toggle${e.enabled?" is-on":""}`),o=b("span","sched-toggle-dot");i.appendChild(o),i.title=e.enabled?"Disable":"Enable",i.addEventListener("click",()=>{this.toggleSchedule(e.id,i)}),s.appendChild(i),n.appendChild(s);let l=b("div","sched-card-details"),a=b("div","sched-detail-row");a.appendChild(b("span","sched-detail-label","Schedule"));let c=b("span","sched-detail-value");c.appendChild(b("span",void 0,lr(e.cron))),c.appendChild(b("span","sched-cron-raw",e.cron)),a.appendChild(c),l.appendChild(a);let d=b("div","sched-detail-row");if(d.appendChild(b("span","sched-detail-label","Command")),d.appendChild(b("code","sched-detail-code",e.command)),l.appendChild(d),e.trigger&&e.trigger!=="cron"){let R=b("div","sched-detail-row");R.appendChild(b("span","sched-detail-label","Trigger")),R.appendChild(b("span","sched-detail-value",e.trigger)),l.appendChild(R)}let u=b("div","sched-card-meta");u.appendChild(b("span","sched-card-id",e.id)),e.updatedAt&&u.appendChild(b("span","sched-card-time",dr(e.updatedAt))),l.appendChild(u),n.appendChild(l);let p=b("div","sched-card-actions"),m=b("button","sched-action-btn","History");m.addEventListener("click",()=>this.onShowHistory(e.id)),p.appendChild(m);let h=b("button","sched-action-btn","Edit");h.addEventListener("click",()=>this.onEdit(e)),p.appendChild(h);let g=b("button","sched-action-btn sched-action-danger","Delete");return g.addEventListener("click",()=>{this.deleteSchedule(e.id,e.name,g)}),p.appendChild(g),n.appendChild(p),n}inflight=!1;async toggleSchedule(e,n){if(!this.inflight){this.inflight=!0,n.disabled=!0;try{await this.api(`/api/schedules/${encodeURIComponent(e)}/toggle`,{method:"POST"}),await this.load()}catch(s){T(s instanceof Error?s.message:"toggle failed"),n.disabled=!1}finally{this.inflight=!1}}}async deleteSchedule(e,n,s){if(!this.inflight&&confirm(`Delete schedule "${n}"? This cannot be undone.`)){this.inflight=!0,s.disabled=!0;try{await this.api(`/api/schedules/${encodeURIComponent(e)}`,{method:"DELETE"}),await this.load()}catch(r){T(r instanceof Error?r.message:"delete failed"),s.disabled=!1}finally{this.inflight=!1}}}};function A(t,e,n){let s=document.createElement(t);return e&&(s.className=e),n!==void 0&&(s.textContent=n),s}var rt=[{label:"Every hour",value:"0 * * * *"},{label:"Daily at 2:00 AM",value:"0 2 * * *"},{label:"Daily at 9:00 AM",value:"0 9 * * *"},{label:"Every 6 hours",value:"0 */6 * * *"},{label:"Weekly (Monday 9 AM)",value:"0 9 * * 1"},{label:"Custom...",value:""}];function cr(t){let e=t.trim().split(/\s+/);if(e.length<5)return"";let[n,s,r,i,o]=e;return r==="*"&&i==="*"&&o==="*"&&s.startsWith("*/")?`Runs every ${s.slice(2)} hours`:r==="*"&&i==="*"&&o==="*"&&s!=="*"&&n!=="*"?`Runs daily at ${s.padStart(2,"0")}:${n.padStart(2,"0")}`:r==="*"&&i==="*"&&o!=="*"&&s!=="*"?`Runs every ${["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][Number(o)]??o} at ${s.padStart(2,"0")}:${n.padStart(2,"0")}`:r==="*"&&i==="*"&&o==="*"&&s==="*"?n==="*"?"Runs every minute":`Runs every hour at :${n.padStart(2,"0")}`:`Cron: ${t}`}function vn(t,e){let n=t!==null&&t.id!=="";document.getElementById("sched-form-overlay")?.remove();let s=A("div","sched-overlay");s.id="sched-form-overlay";let r=A("div","sched-modal");r.setAttribute("role","dialog"),r.setAttribute("aria-modal","true"),r.setAttribute("aria-labelledby","sched-form-title");let i=A("h3","sched-modal-title",n?"Edit Schedule":"New Schedule");i.id="sched-form-title",r.appendChild(i);let o=A("div","sched-field"),l=A("label","sched-label","Name");l.htmlFor="sf-name",o.appendChild(l);let a=document.createElement("input");a.id="sf-name",a.type="text",a.className="sched-input",a.placeholder="e.g. Nightly forge",a.value=t?.name??"",o.appendChild(a),r.appendChild(o);let c=A("div","sched-field"),d=A("label","sched-label","Command");d.htmlFor="sf-command",c.appendChild(d);let u=document.createElement("input");u.id="sf-command",u.type="text",u.className="sched-input sched-input-mono",u.placeholder="e.g. /forge-friction --auto",u.value=t?.command??"",c.appendChild(u),r.appendChild(c);let p=A("div","sched-field"),m=A("label","sched-label","Schedule");m.htmlFor="sf-cron-select",p.appendChild(m);let h=document.createElement("select");h.id="sf-cron-select",h.className="sched-select";for(let w of rt){let I=document.createElement("option");I.value=w.value,I.textContent=w.label,h.appendChild(I)}let g=document.createElement("input");g.id="sf-cron",g.type="text",g.className="sched-input sched-input-mono",g.placeholder="0 2 * * *",g.value=t?.cron??"";let R=A("div","sched-cron-preview"),C=!1,ne=t?.cron??"",se=rt.find(w=>w.value===ne);se&&se.value!==""?(h.value=se.value,g.hidden=!0,C=!1):ne?(h.value="",g.hidden=!1,C=!0):(h.value=rt[0]?.value??"",g.hidden=!0,g.value=h.value,C=!1);let re=()=>{let w=C?g.value:h.value;R.textContent=w?cr(w):""};h.addEventListener("change",()=>{h.value===""?(g.hidden=!1,C=!0,g.focus()):(g.hidden=!0,C=!1,g.value=h.value),re()}),g.addEventListener("input",re),re(),p.appendChild(h),p.appendChild(g),p.appendChild(R),r.appendChild(p);let W=A("div","sched-field"),U=A("label","sched-label","Trigger");U.htmlFor="sf-trigger",W.appendChild(U);let ie=document.createElement("select");ie.id="sf-trigger",ie.className="sched-select";for(let[w,I]of[["cron","Cron schedule only"],["sessionstart","On daemon start"],["both","Both (cron + daemon start)"]]){let H=document.createElement("option");H.value=w,H.textContent=I,w===(t?.trigger??"cron")&&(H.selected=!0),ie.appendChild(H)}W.appendChild(ie),r.appendChild(W);let Pe=A("div","sched-field"),ut=A("label","sched-label","Notifications");ut.htmlFor="sf-notify",Pe.appendChild(ut);let oe=document.createElement("select");oe.id="sf-notify",oe.className="sched-select";for(let[w,I]of[["failure","On failure only"],["always","On every run"],["never","Never"]]){let H=document.createElement("option");H.value=w,H.textContent=I,w===(t?.notifyOn??"failure")&&(H.selected=!0),oe.appendChild(H)}Pe.appendChild(oe),r.appendChild(Pe);let _e=A("div","sched-btn-row"),Be=A("button","sched-cancel-btn","Cancel");Be.type="button",Be.addEventListener("click",()=>s.remove());let V=A("button","sched-save-btn",n?"Save Changes":"Create Schedule");V.type="button",V.addEventListener("click",()=>{Ln()}),_e.appendChild(Be),_e.appendChild(V),r.appendChild(_e);let De=()=>{s.remove(),document.removeEventListener("keydown",ht)};s.appendChild(r),document.body.appendChild(s),a.focus();let Tn="input:not([disabled]), select:not([disabled]), button:not([disabled]), textarea:not([disabled])";r.addEventListener("keydown",w=>{if(w.key!=="Tab")return;let I=Array.from(r.querySelectorAll(Tn));if(I.length===0)return;let H=I[0],G=I[I.length-1];w.shiftKey?document.activeElement===H&&(w.preventDefault(),G.focus()):document.activeElement===G&&(w.preventDefault(),H.focus())}),s.addEventListener("click",w=>{w.target===s&&De()});let ht=w=>{w.key==="Escape"&&De()};document.addEventListener("keydown",ht);async function Ln(){let w=a.value.trim(),I=u.value.trim(),H=C?g.value.trim():h.value;if(!w||!I||!H){T("Name, command, and schedule are required");return}V.disabled=!0,V.textContent="Saving...";try{let G={name:w,command:I,cron:H,trigger:ie.value,notifyOn:oe.value,enabled:t?.enabled??!0};n?await e.api(`/api/schedules/${encodeURIComponent(t.id)}`,{method:"PATCH",body:JSON.stringify(G)}):await e.api("/api/schedules",{method:"POST",body:JSON.stringify(G)}),De(),e.onSaved()}catch(G){T(G instanceof Error?G.message:"save failed"),V.disabled=!1,V.textContent=n?"Save Changes":"Create Schedule"}}}function L(t,e,n){let s=document.createElement(t);return e&&(s.className=e),n!==void 0&&(s.textContent=n),s}function pr(t){if(t<1e3)return`${t}ms`;let e=t/1e3;if(e<60)return`${e.toFixed(1)}s`;let n=Math.floor(e/60),s=Math.floor(e%60);return`${n}m ${s}s`}function ur(t){try{return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return t}}function yn(t,e){document.getElementById("sched-history-overlay")?.remove();let n=L("div","sched-overlay");n.id="sched-history-overlay";let s=L("div","sched-modal sched-modal-wide");s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-labelledby","sched-history-title");let r=L("h3","sched-modal-title",`History: ${t}`);r.id="sched-history-title",s.appendChild(r);let i=L("div","sched-history-body");i.appendChild(L("div","sched-history-loading","Loading...")),s.appendChild(i);let o=()=>{n.remove(),document.removeEventListener("keydown",c)},l=L("button","sched-cancel-btn","Close");l.type="button",l.addEventListener("click",o),s.appendChild(l),n.appendChild(s),document.body.appendChild(n),l.focus();let a="input:not([disabled]), select:not([disabled]), button:not([disabled]), textarea:not([disabled])";s.addEventListener("keydown",d=>{if(d.key!=="Tab")return;let u=Array.from(s.querySelectorAll(a));if(u.length===0)return;let p=u[0],m=u[u.length-1];d.shiftKey?document.activeElement===p&&(d.preventDefault(),m.focus()):document.activeElement===m&&(d.preventDefault(),p.focus())}),n.addEventListener("click",d=>{d.target===n&&o()});let c=d=>{d.key==="Escape"&&o()};document.addEventListener("keydown",c),hr(t,e,i)}async function hr(t,e,n){try{let s=await e(`/api/schedules/${encodeURIComponent(t)}/history`);if(n.textContent="",s.history.length===0){n.appendChild(L("div","sched-empty","No executions recorded yet."));return}let r=[...s.history].reverse();for(let i of r)n.appendChild(mr(i))}catch(s){T(s instanceof Error?s.message:"failed to load history"),n.textContent="",n.appendChild(L("div","sched-empty","Failed to load history."))}}function mr(t){let e=L("div",`sched-hist-row sched-hist-${t.status}`),n=L("div","sched-hist-header"),s=L("span",`sched-hist-dot sched-hist-dot-${t.status}`);if(n.appendChild(s),n.appendChild(L("span","sched-hist-status",t.status)),n.appendChild(L("span","sched-hist-time",ur(t.triggeredAt))),n.appendChild(L("span","sched-hist-duration",pr(t.durationMs))),t.trigger&&n.appendChild(L("span","sched-hist-trigger",t.trigger)),e.appendChild(n),t.status==="error"&&t.errorMessage){let r=L("div","sched-hist-error",t.errorMessage);e.appendChild(r)}if(t.status==="skipped"&&t.skipReason&&e.appendChild(L("div","sched-hist-skip",`Skipped: ${t.skipReason}`)),t.responseExcerpt){let r=L("div","sched-hist-excerpt",t.responseExcerpt);e.appendChild(r)}return e}function z(t,e,n){let s=document.createElement(t);return e&&(s.className=e),n!==void 0&&(s.textContent=n),s}function fr(t){switch(t){case"running":return"running";case"completed":return"done";case"failed":return"failed";case"cancelled":return"cancelled"}}function gr(t){switch(t){case"running":return"bgjob-badge bgjob-badge--running";case"completed":return"bgjob-badge bgjob-badge--completed";case"failed":return"bgjob-badge bgjob-badge--failed";case"cancelled":return"bgjob-badge bgjob-badge--cancelled"}}function br(t,e){if(e===void 0)return"";let n=e-t;if(n<1e3)return`${n}ms`;let s=Math.round(n/1e3);if(s<60)return`${s}s`;let r=Math.floor(s/60),i=s%60;return i===0?`${r}m`:`${r}m ${i}s`}function kr(t){let e=t.lastIndexOf("/");return e!==-1?t.slice(e+1):t}function vr(t){let e=z("div","bgjob-row"),n=z("span",gr(t.status),fr(t.status));if(e.appendChild(n),t.status==="running"){let a=z("span","bgjob-pulse");e.appendChild(a)}let s=z("div","bgjob-body"),r=z("div","bgjob-label",t.label||"(no label)");s.appendChild(r);let i=z("div","bgjob-meta"),o=z("span","bgjob-model",kr(t.model));i.appendChild(o);let l=br(t.startedAt,t.endedAt);if(l){let a=z("span","bgjob-duration",l);i.appendChild(a)}return s.appendChild(i),e.appendChild(s),e}function xn(t,e){t.textContent="";let n=z("div","bgjobs-panel");if(n.appendChild(z("h2","bgjobs-title","Background Jobs")),e.length===0){n.appendChild(z("div","bgjobs-empty","No background jobs")),t.appendChild(n);return}for(let s of e)n.appendChild(vr(s));t.appendChild(n)}function k(t,e,n){let s=document.createElement(t);return e&&(s.className=e),n!==void 0&&(s.textContent=n),s}function yr(t){if(!t)return"";let e=Date.now()-new Date(t).getTime(),n=Math.floor(Math.abs(e)/1e3);if(n<60)return"just now";let s=Math.floor(n/60);if(s<60)return`${s}m ago`;let r=Math.floor(s/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function xr(){let t=k("div","mem-hot"),e=k("div","mem-hot-header"),n=k("span","mem-hot-title","Hot Memory"),s=k("div","mem-hot-meta"),r=k("span","mem-hot-pct",""),i=k("span","mem-hot-truncated","truncated");i.hidden=!0,s.appendChild(r),s.appendChild(i),e.appendChild(n),e.appendChild(s);let o=k("div","mem-usage-bar"),l=k("div","mem-usage-fill");o.appendChild(l);let a=k("pre","mem-hot-pre"),c=k("p","mem-hot-empty","No hot memory \u2014 HOT.md is empty or not yet created.");t.appendChild(e),t.appendChild(o),t.appendChild(a),t.appendChild(c);function d(u){let{content:p,usage:m}=u;r.textContent=`${m.pct}% of ~${m.maxTokens} token cap`,i.hidden=!m.truncated,l.style.width=`${m.pct}%`,l.className="mem-usage-fill",m.pct>=100?l.classList.add("is-full"):m.pct>=80&&l.classList.add("is-warn"),p?(a.textContent=p,a.hidden=!1,c.hidden=!0):(a.hidden=!0,c.hidden=!1)}return{root:t,update:d}}function wr(t){let e=k("div","mem-card"),n=k("div","mem-card-top"),s=k("span",`mem-badge-type mem-badge-${t.type}`,t.type);if(n.appendChild(s),t.category){let l=k("span",`mem-badge-cat mem-badge-${t.category}`,t.category);n.appendChild(l)}let r=k("span","mem-card-date",yr(t.created_at));r.title=t.created_at,n.appendChild(r),e.appendChild(n);let i=t.content.length>200?`${t.content.slice(0,200)}\u2026`:t.content,o=k("p","mem-card-content",i);return e.appendChild(o),e}var Cr=["","preference","convention","decision","learning"];function Er(t){let e=k("div"),n=k("div","mem-search-row"),s=k("input","mem-search-input");s.type="text",s.placeholder="Search your cross-session memory\u2026",s.setAttribute("autocomplete","off");let r=k("select","mem-cat-select");for(let a of Cr){let c=k("option");c.value=a,c.textContent=a===""?"All categories":a,r.appendChild(c)}let i=k("button","mem-search-btn","Search");n.appendChild(s),n.appendChild(r),n.appendChild(i),e.appendChild(n);let o=k("div","mem-results");Sr(o),e.appendChild(o);async function l(){let a=s.value.trim();if(!a)return;i.setAttribute("disabled",""),Tr(o);let c=new URLSearchParams({q:a}),d=r.value;d&&c.set("category",d);try{let u=await t(`/api/memory/search?${c.toString()}`);Mr(o,u.results)}catch(u){Lr(o,u instanceof Error?u.message:"Search failed")}finally{i.removeAttribute("disabled")}}return i.addEventListener("click",()=>{l()}),s.addEventListener("keydown",a=>{a.key==="Enter"&&l()}),{root:e,resultsArea:o}}function Sr(t){t.textContent="";let e=k("div","mem-empty");e.appendChild(k("div","mem-empty-icon","\u{1F9E0}")),e.appendChild(k("div","mem-empty-title","Search your cross-session memory")),e.appendChild(k("div","mem-empty-sub","Type a query above to find facts and procedures.")),t.appendChild(e)}function Tr(t){t.textContent="",t.appendChild(k("div","mem-loading","Searching\u2026"))}function Lr(t,e){t.textContent="",t.appendChild(k("div","mem-error",`Error: ${e}`))}function Mr(t,e){if(t.textContent="",e.length===0){let n=k("div","mem-empty");n.appendChild(k("div","mem-empty-icon","\u{1F50D}")),n.appendChild(k("div","mem-empty-title","No results found")),n.appendChild(k("div","mem-empty-sub","Try a different query or category.")),t.appendChild(n);return}for(let n of e)t.appendChild(wr(n))}function wn(t){let{api:e}=t,n=k("div","mem-panel"),s=k("div","mem-inner");s.appendChild(k("h2","mem-title","Memory"));let{root:r,update:i}=xr();s.appendChild(r);let{root:o}=Er(e);s.appendChild(o),n.appendChild(s);let l=()=>{(async()=>{try{let a=await e("/api/memory/hot");i(a)}catch{}})()};return l(),n.refresh=l,n}var Re,$e,it,Ar=["nav-sessions","nav-schedules","nav-bg-jobs","nav-memory"],Rr=["transcript","approvals","composer"],$r=["schedules-view","bg-jobs-view","memory-view"],Ir={schedules:"schedules-view","bg-jobs":"bg-jobs-view",memory:"memory-view"};function he(t,e){let n=document.getElementById(t);n&&(n.hidden=e)}function me(t,e){let n=t==="sessions";for(let s of Ar){let r=document.getElementById(s),i=r?.getAttribute("data-view")??"";r?.classList.toggle("is-active",i===t)}for(let s of Rr)he(s,!n);he("sidebar-head",!n),he("sessions",!n);for(let s of $r)he(s,!0);if(n||he(Ir[t],!1),t==="schedules"){let s=document.getElementById("schedules-view");!Re&&s&&(Re=new Ae({container:s,api:e,onEdit:r=>vn(r.id?r:null,{api:e,onSaved:()=>{Re?.load()}}),onShowHistory:r=>yn(r,e)})),Re?.load()}if(t==="bg-jobs"){let s=document.getElementById("bg-jobs-view");if(s){it?.abort(),it=new AbortController;let{signal:r}=it;(async()=>{try{let i=await e("/api/bg-jobs",{signal:r});xn(s,i.jobs)}catch(i){if(i instanceof Error&&i.name==="AbortError")return;T(i instanceof Error?i.message:"Failed to load background jobs")}})()}}if(t==="memory"){let s=document.getElementById("memory-view");s&&!$e?($e=wn({api:e}),s.appendChild($e)):$e?.refresh()}}var En=gt(),ee=[],P,Ie=[],j={costUsd:0,durationMs:0,turns:0},ot,at,te=!1,fe=!1,lt;function dt(){return lt||(lt=new Me({container:E("queue"),input:E("prompt"),send:E("send"),submit:async t=>{if(P===void 0)throw new Error("no active session");await F(`/api/sessions/${encodeURIComponent(P)}/prompt`,{method:"POST",body:JSON.stringify({text:t})})},isLive:pt,isTurnActive:()=>te,onAccepted:()=>{te=!0,He()},onError:t=>{T(t)}})),lt}async function F(t,e){let n=await fetch(t,{...e,headers:{authorization:`Bearer ${En}`,"content-type":"application/json",...e?.headers??{}}});if(n.status===401){let s="Session credential missing \u2014 reopen the URL printed by `afk web`. A new tab does not inherit the credential from the first one.";try{let r=document.getElementById("status");r&&(r.textContent=s)}catch{}throw new Error(s)}if(!n.ok){let s=await n.text(),r=`${n.status} ${s}`;try{let i=JSON.parse(s);typeof i.message=="string"&&(r=i.message)}catch{}throw new Error(r)}return await n.json()}function Hr(t){t.scrollTop=t.scrollHeight}function Nr(){return ee.find(t=>t.id===P)}function pt(){return Nr()?.mode==="live"}async function ct(){if(ee=(await F("/api/sessions")).sessions,P===void 0&&ee.length>0){let e=ee[0];e&&Ne(e.id)}tt(E("sessions"),ee,P,Ne)}function Ne(t){P=t;let e=t;Ie=[],cn(),Xt();let n=new Map,s=new Map;dt().clear(),j={costUsd:0,durationMs:0,turns:0},ot?.stop(),te=!1,fe=!1,tt(E("sessions"),ee,P,Ne),nt(E("transcript"),Ie),Cn(),He(),ot=new ge(t,En,{onEvent:r=>{if(P!==e)return;let i=r;if(i.error){T(`Stream error: ${i.error}`);return}let o=i.record;if(!o)return;(o.kind==="done"||o.kind==="error")&&(te=!1,He(),dt().flush());let l=pn(o,n,s);if(j=un(j,o),l){Ie.push(l);let a=E("transcript"),c=!a.hidden&&bn(a);nt(a,Ie),c&&Hr(a)}Sn()},onStatus:r=>{if(P!==e)return;let i=E("status");i.textContent=r==="ended"?"session ended":r,i.className=`status status-${r}`,r==="ended"&&(te=!1),fe=r==="reconnecting"||r==="connecting",Cn(),He()}}),ot.start()}function Pr(t){return t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function Sn(){let t=[`${j.turns} turns`];j.costUsd>0&&t.push(`$${j.costUsd.toFixed(4)}`);let e=(j.inputTokens??0)+(j.outputTokens??0);e>0&&t.push(`${Pr(e)} tokens`),j.durationMs>0&&t.push(`${(j.durationMs/1e3).toFixed(1)}s`),E("meter").textContent=t.join(" \xB7 ")}function Cn(){let t=pt(),e=E("prompt"),n=E("send"),s=!t||fe;e.disabled=s,n.disabled=s,e.placeholder=t?fe?"Reconnecting\u2026":"Message the agent\u2026 (queues while it works)":"Read-only \u2014 this session runs in another process",E("composer").classList.toggle("is-readonly",!t),E("composer").classList.toggle("is-reconnecting",t&&fe)}function He(){E("stop").hidden=!(te&&pt())}async function _r(t,e){let n=E("new-session");n.disabled=!0,n.textContent="starting\u2026";let s=P;try{let r={model:t};e&&(r.cwd=e);let{session:i}=await F("/api/sessions",{method:"POST",body:JSON.stringify(r)});if(await ct(),P!==s&&P!==i.id)return;Ne(i.id)}catch(r){T(r instanceof Error?r.message:"could not start session")}finally{n.disabled=!1,n.textContent="+ New"}}async function Br(){if(P===void 0)return;let t=E("stop");t.disabled=!0,t.textContent="Stopping\u2026";try{await F(`/api/sessions/${encodeURIComponent(P)}/interrupt`,{method:"POST",body:JSON.stringify({})})}catch(e){throw t.disabled=!1,t.textContent="Stop",e}}async function Dr(){Mt({input:E("prompt"),loadCommands:async()=>(await F("/api/commands")).commands}),dt().wire();let t=document.querySelector(".composer-row");t instanceof HTMLElement&&dn({input:E("prompt"),container:t}),E("new-session").addEventListener("click",()=>Ht((n,s)=>{_r(n,s)})),document.getElementById("nav-sessions")?.addEventListener("click",()=>me("sessions",F)),document.getElementById("nav-schedules")?.addEventListener("click",()=>me("schedules",F)),document.getElementById("nav-bg-jobs")?.addEventListener("click",()=>me("bg-jobs",F)),document.getElementById("nav-memory")?.addEventListener("click",()=>me("memory",F)),It(),E("stop").addEventListener("click",()=>{Br().catch(n=>{T(n instanceof Error?n.message:"stop failed")})}),Sn(),await ct(),setInterval(()=>{ct().catch(()=>{})},1e4);let e=kn(F,E("approvals"));at=setInterval(()=>{e.pollPending().catch(()=>{})},1e3),e.pollPending().catch(()=>{}),window.addEventListener("beforeunload",()=>{at&&clearInterval(at)})}Dr().catch(t=>{T(t instanceof Error?t.message:String(t))});