agent-afk 5.201.1 → 5.202.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/workspace/index.d.ts +1 -1
- package/dist/agent/workspace/workspace-tools.d.ts +2 -1
- package/dist/cli.mjs +689 -688
- package/dist/index.mjs +234 -234
- package/dist/telegram.mjs +292 -292
- package/dist/web-server/frontend/schedule-form.d.ts +7 -0
- package/dist/web-server/frontend/schedule-history.d.ts +1 -0
- package/dist/web-server/frontend/schedules-view.d.ts +32 -0
- package/dist/web-server/routes.schedules.d.ts +8 -0
- package/dist/web-ui-assets/app.js +30 -30
- package/dist/web-ui-assets/index.html +6 -0
- package/dist/web-ui-assets/schedules.css +202 -0
- package/package.json +1 -1
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ScheduleConfig } from './schedules-view.js';
|
|
2
|
+
interface ScheduleFormOptions {
|
|
3
|
+
api: <T>(path: string, init?: RequestInit) => Promise<T>;
|
|
4
|
+
onSaved: () => void;
|
|
5
|
+
}
|
|
6
|
+
export declare function openScheduleForm(schedule: ScheduleConfig | null, opts: ScheduleFormOptions): void;
|
|
7
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function openScheduleHistory(scheduleId: string, api: <T>(path: string, init?: RequestInit) => Promise<T>): void;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export interface ScheduleConfig {
|
|
2
|
+
id: string;
|
|
3
|
+
name: string;
|
|
4
|
+
command: string;
|
|
5
|
+
cron: string;
|
|
6
|
+
trigger?: 'cron' | 'sessionstart' | 'both';
|
|
7
|
+
enabled: boolean;
|
|
8
|
+
notifyOn?: 'failure' | 'always' | 'never';
|
|
9
|
+
createdAt: string;
|
|
10
|
+
updatedAt: string;
|
|
11
|
+
}
|
|
12
|
+
interface SchedulesViewOptions {
|
|
13
|
+
container: HTMLElement;
|
|
14
|
+
api: <T>(path: string, init?: RequestInit) => Promise<T>;
|
|
15
|
+
onEdit: (schedule: ScheduleConfig) => void;
|
|
16
|
+
onShowHistory: (id: string) => void;
|
|
17
|
+
}
|
|
18
|
+
export declare class SchedulesView {
|
|
19
|
+
private container;
|
|
20
|
+
private api;
|
|
21
|
+
private onEdit;
|
|
22
|
+
private onShowHistory;
|
|
23
|
+
private schedules;
|
|
24
|
+
private daemonStatus;
|
|
25
|
+
constructor(opts: SchedulesViewOptions);
|
|
26
|
+
load(): Promise<void>;
|
|
27
|
+
private render;
|
|
28
|
+
private renderCard;
|
|
29
|
+
private toggleSchedule;
|
|
30
|
+
private deleteSchedule;
|
|
31
|
+
}
|
|
32
|
+
export {};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ServerResponse } from 'node:http';
|
|
2
|
+
export declare function handleListSchedules(res: ServerResponse): Promise<void>;
|
|
3
|
+
export declare function handleCreateSchedule(res: ServerResponse, body: unknown): Promise<void>;
|
|
4
|
+
export declare function handleUpdateSchedule(res: ServerResponse, id: string, body: unknown): Promise<void>;
|
|
5
|
+
export declare function handleDeleteSchedule(res: ServerResponse, id: string): Promise<void>;
|
|
6
|
+
export declare function handleToggleSchedule(res: ServerResponse, id: string): Promise<void>;
|
|
7
|
+
export declare function handleScheduleHistory(res: ServerResponse, id: string): Promise<void>;
|
|
8
|
+
export declare function handleDaemonStatus(res: ServerResponse): Promise<void>;
|
|
@@ -1,49 +1,49 @@
|
|
|
1
|
-
var
|
|
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,`
|
|
2
2
|
`).split(`
|
|
3
3
|
|
|
4
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 Dt=15e3,Ot=500,W=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 p=i.status===401?"unauthorized":i.status===403?"forbidden":"not-found";this.handlers.onStatus?.("closed",p);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:p,value:c}=await o.read();if(p)break;a+=l.decode(c,{stream:!0});let{events:h,remainder:u}=De(a);a=u;for(let g of h){if(g.id!==void 0&&(this.lastEventId=g.id),g.data===void 0)continue;let m;try{m=JSON.parse(g.data)}catch{continue}if(Be(m)){e=!0,this.stopped=!0;break e}this.handlers.onEvent(m,{id:g.id})}}}catch{}if(this.stopped){e&&this.handlers.onStatus?.("ended");return}this.attempt+=1;let r=.75+Math.random()*.5,s=Math.min(Ot*2**(this.attempt-1),Dt)*r;setTimeout(()=>{this.connect()},s)}};var Oe=/(?:^|\s)(\/[A-Za-z][A-Za-z0-9_:-]*)/g,jt=Number.POSITIVE_INFINITY;function Fe(t){let e=new Map;for(let n=0;n<t.length;n++){let r=t[n];if(!r)continue;Oe.lastIndex=0;let s;for(;(s=Oe.exec(r))!==null;){let i=s[1]?.toLowerCase();i!==void 0&&!e.has(i)&&e.set(i,n)}}return e}function je(t,e){let n=t.startsWith("/")?t.toLowerCase():`/${t.toLowerCase()}`;return e.get(n)??jt}function Ue(t,e,n){let r=je(t,n),s=je(e,n);return r!==s?r-s:t.localeCompare(e)}var Ft=20;function Ut(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 Ze(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)&&Ut(r,c.key)),a=Fe(n),p=(c,h)=>Ue(c.cand.value,h.cand.value,a);return i.sort(p),l.sort(p),[...i,...l].map(c=>c.cand).slice(0,Ft)}function G(t){t.dispatchEvent(new Event("input"))}var Ke=new Set(["/clear","/compact","/editor","/exit","/fast","/font-size","/fork","/keys","/model","/reauth","/resume","/rewind","/sh","/theme","/thinking"]);function Qe(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),Ke.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 We=/^\/(?:[A-Za-z][\w:-]*)?$/,V=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(),G(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(!We.test(e)){this.close(!0);return}this.openIntent=!0;let n=++this.generation;if(await this.ensureCommands(),n!==this.generation||!this.openIntent||!this.focused||!We.test(this.deps.input.value)){n===this.generation&&this.close();return}let r=this.deps.input.value.slice(1);this.candidates=Ze(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 Qe(e,this.optionId(n),r,s=>{this.selected=this.candidates.indexOf(s),this.accept()})}};var Zt=/^\/[A-Za-z][\w:-]*$/;function Kt(t,e){return t===""?[]:t.split(/(\s+)/).filter(n=>n!=="").map(n=>Zt.test(n)?{text:n,kind:e(n)?"known":"slash"}:{text:n,kind:"plain"})}function Qt(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 de(t,e,n){Qt(e,Kt(t.value,n)),e.scrollTop=t.scrollTop,e.scrollLeft=t.scrollLeft}function Ge(t,e,n){let r=()=>{de(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 Wt="slash-menu",Gt="prompt-mirror";function Ve(t){let e=document.getElementById(Wt),n=document.getElementById(Gt);if(!e||!n)return;let r;return r=new V({input:t.input,menu:e,loadCommands:t.loadCommands,onCommandsLoaded:()=>de(t.input,n,s=>r.knows(s))}),r.wire(),Ge(t.input,n,s=>r.knows(s)),t.input.classList.add("slash-highlight-active"),r.preload(),r}function j(t){return document.getElementById(t)}function x(t){let e=document.getElementById(t);if(!e)throw new ReferenceError(`missing required element #${t}`);return e}function q(t,e=5e3){let n=j("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 Xe(){let t=j("sidebar-backdrop"),e=j("sidebar");t?.addEventListener("click",()=>{e?.classList.remove("is-open")}),document.addEventListener("keydown",n=>{n.key==="Escape"&&!n.defaultPrevented&&e?.classList.remove("is-open")})}function Je(t){let e=document.getElementById("new-session-form");if(e){e.remove();return}let n=j("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 p=document.createElement("option");p.value=a,p.textContent=a,a==="sonnet"&&(p.selected=!0),s.appendChild(p)}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 Vt=/\x1B\][^\x07\x1B\x9C]*(?:\x07|\x1B\\|\x9C)|\x1B[P^_X][^\x1B\x9C]*(?:\x1B\\|\x9C)|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[6-_]/g;function Ye(t){return t.replace(Vt,"")}function X(t){return Ye(t)}function me(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var M=me();function ot(t){M=t}var I={exec:()=>null};function f(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(v.caret,"$1"),n=n.replace(s,o),r},getRegex:()=>new RegExp(n,e)};return r}var Xt=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),v={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)}}>`)},Jt=/^(?:[ \t]*(?:\n|$))+/,Yt=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,en=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,K=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,tn=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,ge=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,at=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,lt=f(at).replace(/bull/g,ge).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(),nn=f(at).replace(/bull/g,ge).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(),ke=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,sn=/^[^\n]+/,be=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,rn=f(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",be).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),on=f(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,ge).getRegex(),ne="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",xe=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,an=f("^ {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",xe).replace("tag",ne).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),ct=f(ke).replace("hr",K).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",ne).getRegex(),ln=f(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",ct).getRegex(),we={blockquote:ln,code:Yt,def:rn,fences:en,heading:tn,hr:K,html:an,lheading:lt,list:on,newline:Jt,paragraph:ct,table:I,text:sn},et=f("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",K).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",ne).getRegex(),cn={...we,lheading:nn,table:et,paragraph:f(ke).replace("hr",K).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",et).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",ne).getRegex()},pn={...we,html:f(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",xe).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:I,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:f(ke).replace("hr",K).replace("heading",` *#{1,6} *[^
|
|
6
|
-
]`).replace("lheading",
|
|
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={"&":"&","<":"<",">":">",'"':""","'":"'"},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
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
|
|
9
|
-
`)}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let n=e[0],r=
|
|
10
|
-
`)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=
|
|
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],`
|
|
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
|
|
13
|
-
`),c=
|
|
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
14
|
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}
|
|
15
|
-
${
|
|
16
|
-
${c}`:c;let
|
|
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+`
|
|
17
17
|
`+n.join(`
|
|
18
|
-
`),
|
|
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+`
|
|
19
19
|
`+n.join(`
|
|
20
|
-
`),
|
|
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,
|
|
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
22
|
`,1)[0],e[1].length),u=t.split(`
|
|
23
|
-
`,1)[0],
|
|
24
|
-
`,t=t.substring(u.length+1),a=!0),!a){let
|
|
25
|
-
`,1)[0],
|
|
26
|
-
`+
|
|
27
|
-
`+u}
|
|
28
|
-
`,t=t.substring(
|
|
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(
|
|
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=
|
|
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(
|
|
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
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(`
|
|
33
33
|
`)?"":`
|
|
34
34
|
`)+s.raw,o.text+=`
|
|
35
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(`
|
|
36
36
|
`)?"":`
|
|
37
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(
|
|
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(`
|
|
39
39
|
`)?"":`
|
|
40
40
|
`)+s.raw,o.text+=`
|
|
41
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(`
|
|
42
42
|
`)?"":`
|
|
43
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
|
|
45
|
-
`;return r?'<pre><code class="language-'+
|
|
46
|
-
`:"<pre><code>"+(n?s:
|
|
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>
|
|
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}>
|
|
@@ -59,7 +59,7 @@ ${this.parser.parse(t)}</blockquote>
|
|
|
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>${
|
|
63
|
-
Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error occurred:</p><pre>"+
|
|
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
|
|
65
|
-
`,1)[0]??"";return{kind:"tool",id:R("t"),name:_(e.toolName)??"error",inputPreview:r,status:"error",output:n}}case"error":return{kind:"error",id:R("e"),message:_(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:R("n"),text:s.length?`turn complete \xB7 ${s.join(" \xB7 ")}`:"turn complete"}}case"paused":return{kind:"notice",id:R("n"),text:"paused \u2014 usage limit"};case"resumed":return{kind:"notice",id:R("n"),text:"resumed"};default:return}}function Tt(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 ie(t,e){return Number.isInteger(e)&&e>=0&&e<t.length}function St(t,e){if(!ie(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 Ct(t,e){if(!ie(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 Et(t,e){if(!ie(t,e))return t.slice();let n=t.slice();return n.splice(e,1),n}function Lt(t,e,n){if(!ie(t,e))return t.slice();let r=t.slice();return r[e]=n,r}var oe=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="",G(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,p=()=>{a||(a=!0,this.queue=Lt(this.queue,r,l.value),this.render())};l.addEventListener("keydown",c=>{c.key==="Enter"&&p(),c.key==="Escape"&&(c.preventDefault(),a=!0,s.replaceChild(i,l))}),l.addEventListener("blur",p)}),s.appendChild(o);for(let[l,a]of[["\u2191",()=>{this.queue=St(this.queue,r)}],["\u2193",()=>{this.queue=Ct(this.queue,r)}],["\u2715",()=>{this.queue=Et(this.queue,r)}]]){let p=document.createElement("button");p.className="queue-btn",p.textContent=l,p.addEventListener("click",()=>{a(),this.render()}),s.appendChild(p)}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 Rt(t,e=80){return t.scrollHeight-t.scrollTop-t.clientHeight<=e}var It=Ne(),B=[],y,ae=[],A={costUsd:0,durationMs:0,turns:0},Ae,L=[],$e,D=!1,Q=!1,Ie;function Pe(){return Ie||(Ie=new oe({container:x("queue"),input:x("prompt"),send:x("send"),submit:async t=>{if(y===void 0)throw new Error("no active session");await z(`/api/sessions/${encodeURIComponent(y)}/prompt`,{method:"POST",body:JSON.stringify({text:t})})},isLive:_e,isTurnActive:()=>D,onAccepted:()=>{D=!0,le()},onError:t=>{q(t)}})),Ie}async function z(t,e){let n=await fetch(t,{...e,headers:{authorization:`Bearer ${It}`,"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 Yn(t){t.scrollTop=t.scrollHeight}function es(){return B.find(t=>t.id===y)}function _e(){return es()?.mode==="live"}async function Me(){if(B=(await z("/api/sessions")).sessions,y===void 0&&B.length>0){let e=B[0];e&&ce(e.id)}Ee(x("sessions"),B,y,ce)}function ce(t){y=t;let e=t;ae=[],Pe().clear(),A={costUsd:0,durationMs:0,turns:0},Ae?.stop(),D=!1,Q=!1,Ee(x("sessions"),B,y,ce),Le(x("transcript"),ae),At(),le(),Ae=new W(t,It,{onEvent:n=>{if(y!==e)return;let s=n.record;if(!s)return;(s.kind==="done"||s.kind==="error")&&(D=!1,le(),Pe().flush());let i=yt(s);if(A=Tt(A,s),i){ae.push(i);let o=Rt(x("transcript"));Le(x("transcript"),ae),o&&Yn(x("transcript"))}Pt()},onStatus:n=>{if(y!==e)return;let r=x("status");r.textContent=n==="ended"?"session ended":n,r.className=`status status-${n}`,n==="ended"&&(D=!1),Q=n==="reconnecting"||n==="connecting",At(),le()}}),Ae.start()}function Pt(){let t=[`${A.turns} turns`];A.costUsd>0&&t.push(`$${A.costUsd.toFixed(4)}`),A.durationMs>0&&t.push(`${(A.durationMs/1e3).toFixed(1)}s`),x("meter").textContent=t.join(" \xB7 ")}function At(){let t=_e(),e=x("prompt"),n=x("send"),r=!t||Q;e.disabled=r,n.disabled=r,e.placeholder=t?Q?"Reconnecting\u2026":"Message the agent\u2026 (queues while it works)":"Read-only \u2014 this session runs in another process",x("composer").classList.toggle("is-readonly",!t),x("composer").classList.toggle("is-reconnecting",t&&Q)}function le(){x("stop").hidden=!(D&&_e())}async function ts(t,e){let n=x("new-session");n.disabled=!0,n.textContent="starting\u2026";let r=y;try{let s={model:t};e&&(s.cwd=e);let{session:i}=await z("/api/sessions",{method:"POST",body:JSON.stringify(s)});if(await Me(),y!==r&&y!==i.id)return;ce(i.id)}catch(s){q(s instanceof Error?s.message:"could not start session")}finally{n.disabled=!1,n.textContent="+ New"}}async function $t(){let t=await z("/api/pending"),e=t.pending.length!==L.length||t.pending.some((n,r)=>n.id!==L[r]?.id);L=t.pending,e&&Re(x("approvals"),L,Mt),document.title=L.length>0?`(${L.length}) afk web`:"afk web"}function Mt(t,e){L=L.filter(n=>n.id!==t),Re(x("approvals"),L,Mt),z("/api/approve",{method:"POST",body:JSON.stringify({requestId:t,response:e})}).catch(n=>{q(n instanceof Error?n.message:"approval failed")})}async function ns(){if(y===void 0)return;let t=x("stop");t.disabled=!0,t.textContent="Stopping\u2026";try{await z(`/api/sessions/${encodeURIComponent(y)}/interrupt`,{method:"POST",body:JSON.stringify({})})}catch(e){throw t.disabled=!1,t.textContent="Stop",e}}async function ss(){Ve({input:x("prompt"),loadCommands:async()=>(await z("/api/commands")).commands}),Pe().wire(),x("new-session").addEventListener("click",()=>Je((t,e)=>{ts(t,e)})),Xe(),x("stop").addEventListener("click",()=>{ns().catch(t=>{q(t instanceof Error?t.message:"stop failed")})}),Pt(),await Me(),setInterval(()=>{Me().catch(()=>{})},1e4),$e=setInterval(()=>{$t().catch(()=>{})},1e3),$t().catch(()=>{}),window.addEventListener("beforeunload",()=>{$e&&clearInterval($e)})}ss().catch(t=>{q(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>${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))});
|
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
/>
|
|
23
23
|
<link rel="stylesheet" href="/styles.css" />
|
|
24
24
|
<link rel="stylesheet" href="/approvals.css" />
|
|
25
|
+
<link rel="stylesheet" href="/schedules.css" />
|
|
25
26
|
</head>
|
|
26
27
|
<body>
|
|
27
28
|
<header class="topbar">
|
|
@@ -37,6 +38,10 @@
|
|
|
37
38
|
|
|
38
39
|
<main class="layout">
|
|
39
40
|
<aside id="sidebar" class="sidebar">
|
|
41
|
+
<nav class="sidebar-nav">
|
|
42
|
+
<button id="nav-sessions" class="sidebar-nav-btn is-active" data-view="sessions">Sessions</button>
|
|
43
|
+
<button id="nav-schedules" class="sidebar-nav-btn" data-view="schedules">Schedules</button>
|
|
44
|
+
</nav>
|
|
40
45
|
<div class="sidebar-head">
|
|
41
46
|
<span>Sessions</span>
|
|
42
47
|
<button id="new-session" class="new-session" title="Start a new session">+ New</button>
|
|
@@ -47,6 +52,7 @@
|
|
|
47
52
|
|
|
48
53
|
<section class="main">
|
|
49
54
|
<div id="transcript" class="transcript"></div>
|
|
55
|
+
<div id="schedules-view" class="sched-view"></div>
|
|
50
56
|
<div id="approvals" class="approvals"></div>
|
|
51
57
|
<div id="composer" class="composer">
|
|
52
58
|
<div id="slash-menu" class="slash-menu" hidden></div>
|