@plurnk/plurnk-web 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +337 -2
- package/SPEC.md +869 -0
- package/ai.plurnk/.env.defaults +38 -0
- package/ai.plurnk/assets.json +193 -0
- package/ai.plurnk/creations.js +65 -0
- package/ai.plurnk/diagram-compiler.js +15 -0
- package/ai.plurnk/diagrams.js +130 -0
- package/ai.plurnk/directory-addresses.js +35 -0
- package/ai.plurnk/dist/assets/Temml-CCjoacWt.woff2 +0 -0
- package/ai.plurnk/dist/assets/index-DQK23MMn.js +2 -0
- package/ai.plurnk/dist/assets/index-DQK23MMn.js.br +0 -0
- package/ai.plurnk/dist/assets/index-DQK23MMn.js.gz +0 -0
- package/ai.plurnk/dist/assets/index-DgGvOprn.css +1 -0
- package/ai.plurnk/dist/assets/index-DgGvOprn.css.br +0 -0
- package/ai.plurnk/dist/assets/index-DgGvOprn.css.gz +0 -0
- package/ai.plurnk/dist/assets/math-renderer-CZ_XtOMq.css +1 -0
- package/ai.plurnk/dist/assets/math-renderer-CZ_XtOMq.css.br +0 -0
- package/ai.plurnk/dist/assets/math-renderer-CZ_XtOMq.css.gz +0 -0
- package/ai.plurnk/dist/assets/math-renderer-CnlgS6FH.js +96 -0
- package/ai.plurnk/dist/assets/math-renderer-CnlgS6FH.js.br +0 -0
- package/ai.plurnk/dist/assets/math-renderer-CnlgS6FH.js.gz +0 -0
- package/ai.plurnk/dist/assets/overview-IkhWTlh2.js +1 -0
- package/ai.plurnk/dist/assets/overview-IkhWTlh2.js.br +0 -0
- package/ai.plurnk/dist/assets/overview-IkhWTlh2.js.gz +0 -0
- package/ai.plurnk/dist/assets/preload-helper-BjS5LQBu.js +1 -0
- package/ai.plurnk/dist/assets/preload-helper-BjS5LQBu.js.br +0 -0
- package/ai.plurnk/dist/assets/preload-helper-BjS5LQBu.js.gz +0 -0
- package/ai.plurnk/dist/assets/session-BgePzPYk.js +4 -0
- package/ai.plurnk/dist/assets/session-BgePzPYk.js.br +0 -0
- package/ai.plurnk/dist/assets/session-BgePzPYk.js.gz +0 -0
- package/ai.plurnk/dist/assets/session-agent-DWERfauE.js +111 -0
- package/ai.plurnk/dist/assets/session-agent-DWERfauE.js.br +0 -0
- package/ai.plurnk/dist/assets/session-agent-DWERfauE.js.gz +0 -0
- package/ai.plurnk/dist/assets/src-BdHyjaXT.js +1 -0
- package/ai.plurnk/dist/assets/src-BdHyjaXT.js.br +0 -0
- package/ai.plurnk/dist/assets/src-Vt7-ppeC.js +6 -0
- package/ai.plurnk/dist/assets/src-Vt7-ppeC.js.br +0 -0
- package/ai.plurnk/dist/assets/src-Vt7-ppeC.js.gz +0 -0
- package/ai.plurnk/dist/icons/APACHE-2.0.txt +202 -0
- package/ai.plurnk/dist/icons/APACHE-2.0.txt.br +0 -0
- package/ai.plurnk/dist/icons/APACHE-2.0.txt.gz +0 -0
- package/ai.plurnk/dist/icons/NOTO-NOTICE.txt +10 -0
- package/ai.plurnk/dist/icons/NOTO-NOTICE.txt.br +0 -0
- package/ai.plurnk/dist/icons/NOTO-NOTICE.txt.gz +0 -0
- package/ai.plurnk/dist/icons/plurnk-maskable.svg +64 -0
- package/ai.plurnk/dist/icons/plurnk-maskable.svg.br +0 -0
- package/ai.plurnk/dist/icons/plurnk-maskable.svg.gz +0 -0
- package/ai.plurnk/dist/icons/plurnk.svg +63 -0
- package/ai.plurnk/dist/icons/plurnk.svg.br +0 -0
- package/ai.plurnk/dist/icons/plurnk.svg.gz +0 -0
- package/ai.plurnk/dist/index.html +421 -0
- package/ai.plurnk/dist/manifest.webmanifest +27 -0
- package/ai.plurnk/dist/manifest.webmanifest.br +0 -0
- package/ai.plurnk/dist/manifest.webmanifest.gz +0 -0
- package/ai.plurnk/dist/vendor/CFWORKER-JSON-SCHEMA-LICENSE.txt +25 -0
- package/ai.plurnk/dist/vendor/CFWORKER-JSON-SCHEMA-LICENSE.txt.br +0 -0
- package/ai.plurnk/dist/vendor/CFWORKER-JSON-SCHEMA-LICENSE.txt.gz +0 -0
- package/ai.plurnk/dist/vendor/DEPENDENCIES-LICENSE.txt +571 -0
- package/ai.plurnk/dist/vendor/DEPENDENCIES-LICENSE.txt.br +0 -0
- package/ai.plurnk/dist/vendor/DEPENDENCIES-LICENSE.txt.gz +0 -0
- package/ai.plurnk/dist/vendor/MARKED-FOOTNOTE-LICENSE.txt +25 -0
- package/ai.plurnk/dist/vendor/MARKED-FOOTNOTE-LICENSE.txt.br +0 -0
- package/ai.plurnk/dist/vendor/MARKED-FOOTNOTE-LICENSE.txt.gz +0 -0
- package/ai.plurnk/dist/vendor/OTM-LICENSE.txt +21 -0
- package/ai.plurnk/dist/vendor/OTM-LICENSE.txt.br +0 -0
- package/ai.plurnk/dist/vendor/OTM-LICENSE.txt.gz +0 -0
- package/ai.plurnk/dist/vendor/PICO-LICENSE.txt +21 -0
- package/ai.plurnk/dist/vendor/PICO-LICENSE.txt.br +0 -0
- package/ai.plurnk/dist/vendor/PICO-LICENSE.txt.gz +0 -0
- package/ai.plurnk/documents.js +483 -0
- package/ai.plurnk/http.js +69 -0
- package/ai.plurnk/index-document.js +5 -0
- package/ai.plurnk/module.js +326 -0
- package/ai.plurnk/session.js +319 -0
- package/ai.plurnk/static-assets.js +40 -0
- package/package.json +92 -5
- package/plugin.json +13 -0
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/math-renderer-CnlgS6FH.js","assets/math-renderer-CZ_XtOMq.css","assets/src-BdHyjaXT.js","assets/src-Vt7-ppeC.js","assets/session-BgePzPYk.js","assets/preload-helper-BjS5LQBu.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{a as e,i as t,n,r,t as i}from"./preload-helper-BjS5LQBu.js";import"./src-Vt7-ppeC.js";function a(e){if(e.kind===`daemon`)return`/~/`;let{workspace:t}=e;if(!t||!t.isWellFormed()||t.split(`/`).some(e=>e===`.`||e===`..`))return null;let n=`/~/${t.split(`/`).map(encodeURIComponent).join(`/`)}`;return e.kind===`workspace`?`${n}/`:!e.session||!e.session.isWellFormed()?null:`${n}@${encodeURIComponent(e.session)}/`}async function o(e,t){if(e===`none`)return{};let n=await fetch(`/auth/token`,{method:`POST`,signal:t});if(!n.ok)throw Object.assign(Error(`Access credential request failed (${n.status}).`),{status:n.status});let r;try{r=await n.json()}catch(e){throw Error(`Access credential response is not valid JSON.`,{cause:e})}if(!r||r.token_type!==`Bearer`||typeof r.access_token!=`string`||!r.access_token)throw Error(`Invalid access credential response.`);return{Authorization:`Bearer ${r.access_token}`}}function s(e,t,r=!0){let i=n(e,`:scope > article`);if(!i)throw Error(`Card has no article.`);let a=n(i,`:scope > details`),o=n(i,`:scope > header`)??(a?n(a,`:scope > summary`):null),s=!1;if(r&&t&&!a){if(a=n.clone(i,`#card-disclosure`,{position:`afterbegin`}),!(a instanceof HTMLDetailsElement))throw Error(`Card disclosure must be details.`);let e=n(a,`summary`);if(!e)throw Error(`Card disclosure has no summary.`);o&&(e.append(...o.childNodes),o.remove()),o=e}else if((!r||!t)&&a){let e=n.clone(i,`#card-header`,{position:`afterbegin`});o&&e.append(...o.childNodes),a.remove(),a=null,o=e,s=!0}return o??=n.clone(i,`#card-header`,{position:`afterbegin`}),{header:o,body:r?a:i,removedDisclosure:s}}function c(e){e.tagName===`SUMMARY`&&(e.ariaLabel=[e.closest(`article`)?.ariaLabel,...Array.from(e.children,e=>e.textContent)].filter(Boolean).join(` · `))}function l(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var u=l();function d(e){u=e}var f={exec:()=>null};function p(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function m(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(g.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var h=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),g={codeRemoveIndent:/^(?: {0,3}\t| {1,4})/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,endingSpaceTabChar:/[ \t]$/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,leadingSpaceTab:/^[ \t]+/,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,numericCharacterReference:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/,numericCharacterReferenceOrAmpersand:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,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:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:p(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:p(e=>RegExp(`^ {0,${e}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:p(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:p(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:p(e=>RegExp(`^ {0,${e}}(?:</?(?:${me})(?: +|$|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`,`i`)),blockquoteBeginRegex:p(e=>RegExp(`^ {0,${e}}>`))},ee=/^(?:[ \t]*(?:\n|$))+/,te=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,ne=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,re=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ie=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,ae=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,oe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |fences|blockquote|heading|hr|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,se=m(oe).replace(/bull/g,ae).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}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),ce=m(oe).replace(/bull/g,ae).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}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),le=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,ue=/^[^\n]+/,de=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,fe=m(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,de).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),pe=m(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,ae).getRegex(),me=`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`,he=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,ge=m(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!(?:script|pre|style|textarea)(?![a-z0-9-]))([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</[a-z][a-z0-9-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,he).replace(`tag`,me).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),_e=e=>m(le).replace(`hr`,re).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,e).replace(`html`,` {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`).replace(`tag`,me).getRegex(),ve=_e(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),ye=_e(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),be={blockquote:m(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,ye).getRegex(),code:te,def:fe,fences:ne,heading:ie,hr:re,html:ge,lheading:se,list:pe,newline:ee,paragraph:ve,table:f,text:ue},xe=m(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,re).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,` {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`).replace(`tag`,me).getRegex(),Se={...be,lheading:ce,table:xe,paragraph:m(le).replace(`hr`,re).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,xe).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]`).replace(`html`,` {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`).replace(`tag`,me).getRegex()},Ce={...be,html:m(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,he).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:f,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:m(le).replace(`hr`,re).replace(`heading`,` *#{1,6} *[^
|
|
3
|
+
]`).replace(`lheading`,se).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},we=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,_=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Te=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,Ee=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,De=/[\p{P}\p{S}]/u,Oe=/[\s\p{P}\p{S}]/u,ke=/[^\s\p{P}\p{S}]/u,Ae=m(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,Oe).getRegex(),je=/[\p{Pi}\p{Ps}"']/u,Me=/(?!~)[\p{P}\p{S}]/u,Ne=/(?!~)[\s\p{P}\p{S}]/u,v=/(?:[^\s\p{P}\p{S}]|~)/u,Pe=m(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,h?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),y=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Fe=m(y,`u`).replace(/punct/g,De).getRegex(),Ie=m(y,`u`).replace(/punct/g,Me).getRegex(),Le=m(/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,`u`).replace(/openQuote/g,je).replace(/punct/g,De).getRegex(),Re=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,ze=m(Re,`gu`).replace(/notPunctSpace/g,ke).replace(/punctSpace/g,Oe).replace(/punct/g,De).getRegex(),Be=m(Re,`gu`).replace(/notPunctSpace/g,v).replace(/punctSpace/g,Ne).replace(/punct/g,Me).getRegex(),Ve=m(`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,ke).replace(/punctSpace/g,Oe).replace(/punct/g,De).getRegex(),He=m(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,ke).replace(/punctSpace/g,Oe).replace(/punct/g,De).getRegex(),Ue=m(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,ke).replace(/punctSpace/g,Oe).replace(/punct/g,De).getRegex(),We=m(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,De).getRegex(),Ge=m(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,ke).replace(/punctSpace/g,Oe).replace(/punct/g,De).getRegex(),Ke=m(/\\(punct)/,`gu`).replace(/punct/g,De).getRegex(),qe=m(/(`+)(?:[^`]|[^`][\s\S]*?[^`])\1(?!`)|`+|\\(punct)/,`gu`).replace(/punct/g,De).getRegex(),Je=m(/^<(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(),Ye=m(he).replace(`(?:-->|$)`,`-->`).getRegex(),Xe=m(`^comment|^</[a-zA-Z][a-zA-Z0-9-]*\\s*>|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>`).replace(`comment`,Ye).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Ze=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,Qe=m(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace(`brackets`,Ze).getRegex(),$e=m(/^!?\[(label)\]\([ \t\n]*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?[ \t\n]*\)/).replace(`label`,Qe).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),et=m(/^!?\[(label)\]\[(ref)\]/).replace(`label`,Qe).replace(`ref`,de).getRegex(),tt=m(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,de).getRegex(),nt=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,rt=m(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).replace(`brackets`,Ze).getRegex(),it=m(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,m(/^!?\[(label)\]\[(ref)\]/).replace(`label`,rt).replace(`ref`,nt).getRegex()).replace(`nolink`,m(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,nt).getRegex()).getRegex(),at=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,ot=m(/(?:mailto:email|xmpp:email(?:\/[A-Za-z0-9@.]+)?)/).replace(/email/g,/[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),st={_backpedal:f,anyPunctuation:Ke,anyPunctuationOutsideCode:qe,autolink:Je,blockSkip:Pe,br:Te,code:_,del:f,delLDelim:f,delRDelim:f,emStrongLDelim:Fe,emStrongRDelimAst:ze,emStrongRDelimUnd:He,escape:we,link:$e,nolink:tt,punctuation:Ae,reflink:et,reflinkSearch:it,tag:Xe,text:Ee,url:f},ct={...st,emStrongLDelim:Le,emStrongRDelimAst:Ve,emStrongRDelimUnd:Ue,link:m(/^!?\[(label)\]\((.*?)\)/).replace(`label`,Qe).getRegex(),reflink:m(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,Qe).getRegex()},lt={...st,emStrongRDelimAst:Be,emStrongLDelim:Ie,delLDelim:We,delRDelim:Ge,url:m(/^emailProtocol|^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`emailProtocol`,ot).replace(`protocol`,at).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:m(/^(?:[^a-zA-Z0-9](?=emailProtocol)|(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9](?=emailProtocol)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))))/).replace(`protocol`,at).replace(/emailProtocol/g,/(?:mailto|xmpp):/).getRegex()},ut={...lt,br:m(Te).replace(`{2,}`,`*`).getRegex(),text:m(lt.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},dt={normal:be,gfm:Se,pedantic:Ce},ft={normal:st,gfm:lt,breaks:ut,pedantic:ct},pt={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},mt=e=>pt[e];function b(e,t){if(t){if(g.escapeTest.test(e))return e.replace(g.escapeReplace,mt)}else if(g.escapeTestNoEncode.test(e))return e.replace(g.escapeReplaceNoEncode,mt);return e}function ht(e){return g.numericCharacterReference.test(e)?e.replace(g.numericCharacterReferenceOrAmpersand,(e,t,n)=>{if(t===void 0&&n===void 0)return`&`;let r=t===void 0?Number.parseInt(n,16):Number.parseInt(t,10);return r===0||r>1114111||r>=55296&&r<=57343?`�`:r===38?`&`:String.fromCodePoint(r)}):e}function gt(e){try{e=encodeURI(e).replace(g.percentDecode,`%`)}catch{return null}return e}function _t(e,t){let n=e.replace(g.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(g.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t){if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``)}for(;r<n.length;r++)n[r]=n[r].trim().replace(g.slashPipe,`|`);return n}function vt(e,t,n){let r=e.length;if(r===0)return``;let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function yt(e){let t=e.split(`
|
|
4
|
+
`),n=t.length-1;for(;n>=0&&g.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
|
|
5
|
+
`)}function bt(e){return e.trim().toLowerCase().toUpperCase().toLowerCase()}function xt(e,t){if(e.indexOf(t[0])===-1&&e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]===`\\`)r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function St(e,t=0){let n=t,r=``;for(let t of e)if(t===` `){let e=4-n%4;r+=` `.repeat(e),n+=e}else r+=t,n++;return r}function Ct(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`),c=e[0].charAt(0)===`!`,l=r.state.inLink,u=r.state.linkEmitted,d=r.state.inRawBlock;r.state.inLink=!0,r.state.linkEmitted=!1;let f=r.inlineTokens(s),p=r.state.linkEmitted;if(r.state.linkEmitted=u,r.state.inLink=l,!c){if(p){r.state.inRawBlock=d;return}r.state.linkEmitted=!0}return{type:c?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:f}}function wt(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
|
|
6
|
+
`).map(e=>{let t=e.match(n.other.beginningSpace);if(t===null)return e;let[r]=t;return e.slice(Math.min(r.length,i.length))}).join(`
|
|
7
|
+
`)}function Tt(e,t,n,r){if(!t.includes(`<`))return!1;for(let i=0;i<t.length;i++){if(t[i]===`\\`){i++;continue}if(t[i]==="`"){let e=r.inline.code.exec(t.slice(i));if(e){i+=e[0].length-1;continue}}if(t[i]!==`<`)continue;let a=e.slice(n+i),o=r.inline.tag.exec(a)||r.inline.autolink.exec(a);if(o){if(o[0].length>t.length-i)return!0;i+=o[0].length-1}}return!1}var x=class{options;rules;lexer;constructor(e){this.options=e||u}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:`space`,raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let e=this.options.pedantic?t[0]:yt(t[0]);return{type:`code`,raw:e,codeBlockStyle:`indented`,text:e.replace(this.rules.other.codeRemoveIndent,``)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let e=t[0],n=wt(e,t[3]||``,this.rules);return{type:`code`,raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,`$1`):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){let t=vt(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceTabChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:vt(t[0],`
|
|
8
|
+
`),depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:`hr`,raw:vt(t[0],`
|
|
9
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=vt(t[0],`
|
|
10
|
+
`).split(`
|
|
11
|
+
`),n=``,r=``,i=[];for(;e.length>0;){let t=!1,a=[],o=0;for(;o<e.length;o++)if(this.rules.other.blockquoteStart.test(e[o]))a.push(e[o]),t=!0;else if(!t)a.push(e[o]);else break;e=e.slice(o);let s=a.join(`
|
|
12
|
+
`),c=s.replace(this.rules.other.blockquoteSetextReplace,`
|
|
13
|
+
$1`).replace(this.rules.other.blockquoteSetextReplace2,``);n=n?`${n}
|
|
14
|
+
${s}`:s,r=r?`${r}
|
|
15
|
+
${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(c,i,!0),this.lexer.state.top=l,e.length===0)break;let u=i.at(-1);if(u?.type===`code`||u?.type===`heading`||u?.type===`hr`||u?.type===`html`)break;if(u?.type===`blockquote`){let t=u,a=e.join(`
|
|
16
|
+
`),o=t.raw+`
|
|
17
|
+
`+a.replace(this.rules.other.blockquoteSetextReplace2,``),s=this.blockquote(o);i[i.length-1]=s;let c=o.substring(s.raw.length).replace(/^\n/,``),l=c?c.split(`
|
|
18
|
+
`).length:0,d=l?e.slice(0,-l):e;d.length>0&&(n=`${n}
|
|
19
|
+
${d.join(`
|
|
20
|
+
`)}`),r=r.substring(0,r.length-t.text.length)+s.text;break}if(u?.type===`list`){let t=u,a=t.raw+`
|
|
21
|
+
`+e.join(`
|
|
22
|
+
`),o=this.list(a);i[i.length-1]=o,n=n.substring(0,n.length-u.raw.length)+o.raw,r=r.substring(0,r.length-t.raw.length)+o.raw,e=a.substring(i.at(-1).raw.length).split(`
|
|
23
|
+
`)}}return{type:`blockquote`,raw:n,tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=e,r=()=>n.length-e.length,i=t[1].trim(),a=i.length>1,o={type:`list`,raw:``,ordered:a,start:a?+i.slice(0,-1):``,loose:!1,items:[]};i=a?`\\d{1,9}\\${i.slice(-1)}`:`\\${i}`,this.options.pedantic&&(i=a?i:`[*+-]`);let s=this.rules.other.listItemRegex(i),c=!1;for(;e;){let i=!1,a=``;if(!(t=s.exec(e))||this.rules.block.hr.test(e))break;let l=r();e=e.substring(t[0].length);let u=t[2].split(`
|
|
24
|
+
`,1)[0],d=t[1].length,f=this.options.pedantic?St(u,d):u.replace(this.rules.other.leadingSpaceTab,e=>St(e,d)),p=e.split(`
|
|
25
|
+
`,1)[0],m=!f.trim(),h=0;if(this.options.pedantic?(h=2,a=f.trimStart()):m?h=d+1:(h=f.search(this.rules.other.nonSpaceChar),h=h>4?1:h,a=f.slice(h),h+=d),m&&this.rules.other.blankLine.test(p)&&(e=e.substring(p.length+1),i=!0),!i){let t=this.rules.other.nextBulletRegex(h),n=this.rules.other.hrRegex(h),r=this.rules.other.fencesBeginRegex(h),i=this.rules.other.headingBeginRegex(h),o=this.rules.other.htmlBeginRegex(h),s=this.rules.other.blockquoteBeginRegex(h);for(;e;){let c=e.split(`
|
|
26
|
+
`,1)[0],l;if(p=c,this.options.pedantic?(p=p.replace(this.rules.other.listReplaceNesting,` `),l=p):l=p.replace(this.rules.other.leadingSpaceTab,e=>St(e)),r.test(p)||i.test(p)||o.test(p)||s.test(p)||t.test(p)||n.test(p))break;if(l.search(this.rules.other.nonSpaceChar)>=h||!p.trim())a+=`
|
|
27
|
+
`+l.slice(h);else{if(m||f.replace(this.rules.other.tabCharGlobal,` `).search(this.rules.other.nonSpaceChar)>=4||r.test(f)||i.test(f)||n.test(f))break;a+=`
|
|
28
|
+
`+p}m=!p.trim(),e=e.substring(c.length+1),f=l.slice(h)}}let g=n.slice(l,r());o.loose||(c?o.loose=!0:this.rules.other.doubleBlankLine.test(g)&&(c=!0)),o.items.push({type:`list_item`,raw:g,task:!!this.options.gfm&&this.rules.other.listIsTask.test(a),loose:!1,text:a,tokens:[]})}let l=o.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;o.raw=n.slice(0,r()).trimEnd();for(let e of o.items)if(this.lexer.state.top=!1,e.tokens=this.lexer.blockTokens(e.text,[]),!o.loose){let t=e.tokens.filter(e=>e.type===`space`);o.loose=t.length>0&&t.some(e=>this.rules.other.anyLine.test(e.raw))}for(let e of o.items){let t=e.tokens[0];if(e.task&&(t?.type===`text`||t?.type===`paragraph`)){e.text=e.text.replace(this.rules.other.listReplaceTask,``),t.raw=t.raw.replace(this.rules.other.listReplaceTask,``),t.text=t.text.replace(this.rules.other.listReplaceTask,``);for(let e=this.lexer.inlineQueue.length-1;e>=0;e--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[e].src)){this.lexer.inlineQueue[e].src=this.lexer.inlineQueue[e].src.replace(this.rules.other.listReplaceTask,``);break}let n=this.rules.other.listTaskCheckbox.exec(e.raw);if(n){let t={type:`checkbox`,raw:n[0]+` `,checked:n[0]!==`[ ]`};e.checked=t.checked,o.loose?e.tokens[0]&&[`paragraph`,`text`].includes(e.tokens[0].type)&&`tokens`in e.tokens[0]&&e.tokens[0].tokens?(e.tokens[0].raw=t.raw+e.tokens[0].raw,e.tokens[0].text=t.raw+e.tokens[0].text,e.tokens[0].tokens.unshift(t)):e.tokens.unshift({type:`paragraph`,raw:t.raw,text:t.raw,tokens:[t]}):e.tokens.unshift(t)}}else e.task&&=!1}if(o.loose)for(let e of o.items){e.loose=!0;for(let t of e.tokens)t.type===`text`&&(t.type=`paragraph`)}return o}}html(e){let t=this.rules.block.html.exec(e);if(t){let e=yt(t[0]);return{type:`html`,block:!0,raw:e,pre:t[1]===`pre`||t[1]===`script`||t[1]===`style`,text:e}}}def(e){let t=this.rules.block.def.exec(e);if(t){if(!this.rules.other.startAngleBracket.test(t[2])&&xt(t[2],`()`)!==-1)return;let e=bt(t[1]).replace(this.rules.other.multipleSpaceGlobal,` `),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,`$1`).replace(this.rules.inline.anyPunctuation,`$1`):``,r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,`$1`):t[3];return{type:`def`,tag:e,raw:vt(t[0],`
|
|
29
|
+
`),href:n,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=_t(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(`
|
|
30
|
+
`):[],a={type:`table`,raw:vt(t[0],`
|
|
31
|
+
`),header:[],align:[],rows:[]};if(n.length===r.length){for(let e of r)this.rules.other.tableAlignRight.test(e)?a.align.push(`right`):this.rules.other.tableAlignCenter.test(e)?a.align.push(`center`):this.rules.other.tableAlignLeft.test(e)?a.align.push(`left`):a.align.push(null);for(let e=0;e<n.length;e++)a.header.push({text:n[e],tokens:this.lexer.inline(n[e]),header:!0,align:a.align[e]});for(let e of i)a.rows.push(_t(e,a.header.length).map((e,t)=>({text:e,tokens:this.lexer.inline(e),header:!1,align:a.align[t]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let e=t[1].trim();return{type:`heading`,raw:vt(t[0],`
|
|
32
|
+
`),depth:t[2].charAt(0)===`=`?1:2,text:e,tokens:this.lexer.inline(e)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let e=t[1].charAt(t[1].length-1)===`
|
|
33
|
+
`?t[1].slice(0,-1):t[1];return{type:`paragraph`,raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:`text`,raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:`escape`,raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:`html`,raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){if(this.lexer.state.linkParenPossible===!1)return;let t=this.rules.inline.link.exec(e);if(t){let n=t[0].charAt(0)===`!`?2:1;if(!this.options.pedantic&&Tt(e,t[1],n,this.rules))return;let r=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let e=vt(r.slice(0,-1),`\\`);if((r.length-e.length)%2==0)return}else{let e=xt(t[2],`()`);if(e===-2)return;if(e>-1){let n=(t[0].indexOf(`!`)===0?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=``}}let i=t[2],a=``;if(this.options.pedantic){let e=this.rules.other.pedanticHrefTitle.exec(i);e&&(i=e[1],a=e[3])}else a=t[3]?t[3].slice(1,-1):``;return i=i.trim(),this.rules.other.startAngleBracket.test(i)&&(i=this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?i.slice(1):i.slice(1,-1)),Ct(t,{href:i&&i.replace(this.rules.inline.anyPunctuation,`$1`),title:a&&a.replace(this.rules.inline.anyPunctuation,`$1`)},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let r=n[0].charAt(0)===`!`?2:1;if(!this.options.pedantic&&Tt(e,n[1],r,this.rules))return;let i=t[bt((n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,` `))];if(!i){let e=n[0].charAt(0);return{type:`text`,raw:e,text:e}}return Ct(n,i,n[0],this.lexer,this.rules)}}emStrong(e,t,n=``){let r=this.rules.inline.emStrongLDelim.exec(e);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 i=[...r[0]].length-1,a,o,s=i,c=0,l=r[0][0],u=n===l,d=l===`*`?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+i);(r=d.exec(t))!==null;){if(a=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!a)continue;if(o=[...a].length,r[3]||r[4]){s+=o;continue}if(r[5]||r[6]){if(i%3&&!((i+o)%3)){c+=o;continue}if(u)break}if(s-=o,s>0)continue;o=Math.min(o,o+s+c);let t=[...r[0]][0].length,n=e.slice(0,i+r.index+t+o);if(Math.min(i,o)%2){let e=n.slice(1,-1);return{type:`em`,raw:n,text:e,tokens:this.lexer.inlineTokens(e)}}let l=n.slice(2,-2);return{type:`strong`,raw:n,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal,` `),n=this.rules.other.nonSpaceChar.test(e),r=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&r&&(e=e.substring(1,e.length-1)),{type:`codespan`,raw:t[0],text:e}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:`br`,raw:t[0]}}del(e,t,n=``){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=this.rules.inline.delRDelim;for(s.lastIndex=0,t=t.slice(-1*e.length+n);(r=s.exec(t))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(a=[...i].length,a!==n))continue;if(r[3]||r[4]){o+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o);let t=[...r[0]][0].length,s=e.slice(0,n+r.index+t+a),c=s.slice(n,-n);return{type:`del`,raw:s,text:c,tokens:this.lexer.inlineTokens(c)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let e,n;return t[2]===`@`?(e=t[1],n=`mailto:`+e):(e=t[1],n=e),{type:`link`,raw:t[0],text:e,href:n,autolink:!0,tokens:[{type:`text`,raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if(t[2]===`@`)e=t[0],n=`mailto:`+e;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??``;while(r!==t[0]);e=t[0],n=t[1]===`www.`?`http://`+t[0]:t[0]}return{type:`link`,raw:t[0],text:e,href:n,autolink:!0,tokens:[{type:`text`,raw:e,text:e}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let e=this.lexer.state.inRawBlock;return{type:`text`,raw:t[0],text:e?t[0]:ht(t[0]),escaped:e}}}},Et=class e{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 x,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,linkParenPossible:!0,top:!0};let t={other:g,block:dt.normal,inline:ft.normal};this.options.pedantic?(t.block=dt.pedantic,t.inline=ft.pedantic):this.options.gfm&&(t.block=dt.gfm,t.inline=this.options.breaks?ft.breaks:ft.gfm),this.tokenizer.rules=t}static get rules(){return{block:dt,inline:ft}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(e){e=e.replace(g.carriageReturn,`
|
|
34
|
+
`),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){let t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(g.tabCharGlobal,` `).replace(g.spaceLine,``));let r=1/0;for(;e;){if(e.length<r)r=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let i;if(this.options.extensions?.block?.some(n=>(i=n.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let n=t.at(-1);i.raw.length===1&&n!==void 0?n.raw+=`
|
|
35
|
+
`:t.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(`
|
|
36
|
+
`)?``:`
|
|
37
|
+
`)+i.raw,n.text+=`
|
|
38
|
+
`+i.text,this.inlineQueue.at(-1).src=n.text):t.push(i);continue}if((i=this.tokenizer.fences(e))||(i=this.tokenizer.heading(e))||(i=this.tokenizer.hr(e))||(i=this.tokenizer.blockquote(e))||(i=this.tokenizer.list(e))||(i=this.tokenizer.html(e))){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.def(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(`
|
|
39
|
+
`)?``:`
|
|
40
|
+
`)+i.raw,n.text+=`
|
|
41
|
+
`+i.raw,this.inlineQueue.at(-1).src=n.text):this.tokens.links[i.tag]||(this.tokens.links[i.tag]={href:i.href,title:i.title},t.push(i));continue}if((i=this.tokenizer.table(e))||(i=this.tokenizer.lheading(e))){e=e.substring(i.raw.length),t.push(i);continue}let a=e;if(this.options.extensions?.startBlock){let t=1/0,n=e.slice(1),r;this.options.extensions.startBlock.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(a=e.substring(0,t+1))}if(this.state.top&&(i=this.tokenizer.paragraph(a))){let r=t.at(-1);n&&r?.type===`paragraph`?(r.raw+=(r.raw.endsWith(`
|
|
42
|
+
`)?``:`
|
|
43
|
+
`)+i.raw,r.text+=`
|
|
44
|
+
`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=r.text):t.push(i),n=a.length!==e.length,e=e.substring(i.raw.length)}else if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`text`?(n.raw+=(n.raw.endsWith(`
|
|
45
|
+
`)?``:`
|
|
46
|
+
`)+i.raw,n.text+=`
|
|
47
|
+
`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(i)}else if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}linkInText(e){if(!e.includes(`[`))return!1;let t=this.tokenizer.rules.inline.link;for(let n of e.matchAll(this.tokenizer.rules.inline.blockSkip))if(t.test(n[0])&&e.charAt(n.index-1)!==`!`)return!0;for(let t of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let e=t[0],n=e.lastIndexOf(`[`);if(e.charAt(0)!==`!`&&Object.hasOwn(this.tokens.links,bt(e.slice(n+1,-1)))&&!(n>1&&this.linkInText(e.slice(1,n-1))))return!0}return!1}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=this.state.linkParenPossible;this.state.linkParenPossible=n&&e.includes(`)`);try{return this.#e(e,t)}finally{this.state.linkParenPossible=n}}#e(e,t){let n=e;if(this.tokens.links&&e.includes(`[`)){let e=this.tokenizer.rules.inline.reflinkSearch,t=n=>{let r=n.lastIndexOf(`[`);if(!Object.hasOwn(this.tokens.links,bt(n.slice(r+1,-1))))return n;if(r>1&&n.charAt(0)!==`!`){let i=n.slice(1,r-1);if(this.linkInText(i))return`[`+i.replace(e,t)+`][`+`a`.repeat(n.length-r-2)+`]`}return`[`+`a`.repeat(n.length-2)+`]`};n=n.replace(e,t)}n=n.replace(this.tokenizer.rules.inline.anyPunctuationOutsideCode,(e,t,n)=>n?`+`.repeat(e.length):t?t+e.slice(t.length,-t.length).replace(/`/g,`+`)+t:e),n=n.replace(this.tokenizer.rules.inline.blockSkip,(e,t,n)=>{let r=n?n.length:0;return e.slice(0,r)+`[`+`a`.repeat(e.length-r-2)+`]`}),n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let r=!1,i=``,a=1/0;for(;e;){if(e.length<a)a=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}r||(i=``),r=!1;let o;if(this.options.extensions?.inline?.some(n=>(o=n.call({lexer:this},e,t))?(e=e.substring(o.raw.length),t.push(o),!0):!1))continue;if((o=this.tokenizer.escape(e))||(o=this.tokenizer.tag(e))||(o=this.tokenizer.link(e))){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(o.raw.length);let n=t.at(-1);o.type===`text`&&n?.type===`text`?(n.raw+=o.raw,n.text+=o.text):t.push(o);continue}if((o=this.tokenizer.emStrong(e,n,i))||(o=this.tokenizer.codespan(e))||(o=this.tokenizer.br(e))||(o=this.tokenizer.del(e,n,i))||(o=this.tokenizer.autolink(e))||!this.state.inLink&&(o=this.tokenizer.url(e))){e=e.substring(o.raw.length),t.push(o);continue}let s=e;if(this.options.extensions?.startInline){let t=1/0,n=e.slice(1),r;this.options.extensions.startInline.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(s=e.substring(0,t+1))}if(o=this.tokenizer.inlineText(s)){e=e.substring(o.raw.length),o.raw.slice(-1)!==`_`&&(i=o.raw.slice(-1)),r=!0;let n=t.at(-1);n?.type===`text`?(n.raw+=o.raw,n.text+=o.text):t.push(o)}else if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t=`Infinite loop on byte: `+e;if(this.options.silent)console.error(t);else throw Error(t)}},Dt=class{options;parser;constructor(e){this.options=e||u}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(g.notSpaceStart)?.[0],i=e?e.replace(g.endingNewline,``)+`
|
|
48
|
+
`:``;return r?`<pre><code class="language-`+b(r)+`">`+(n?i:b(i,!0))+`</code></pre>
|
|
49
|
+
`:`<pre><code>`+(n?i:b(i,!0))+`</code></pre>
|
|
50
|
+
`}blockquote({tokens:e}){return`<blockquote>
|
|
51
|
+
${this.parser.parse(e)}</blockquote>
|
|
52
|
+
`}html({text:e}){return e}def(e){return``}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
53
|
+
`}hr(e){return`<hr>
|
|
54
|
+
`}list(e){let t=e.ordered,n=e.start,r=``;for(let t=0;t<e.items.length;t++){let n=e.items[t];r+=this.listitem(n)}let i=t?`ol`:`ul`,a=t&&n!==1?` start="`+n+`"`:``;return`<`+i+a+`>
|
|
55
|
+
`+r+`</`+i+`>
|
|
56
|
+
`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
|
|
57
|
+
`}checkbox({checked:e}){return`<input `+(e?`checked="" `:``)+`disabled="" type="checkbox"> `}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
|
|
58
|
+
`}table(e){let t=``,n=``;for(let t=0;t<e.header.length;t++)n+=this.tablecell(e.header[t]);t+=this.tablerow({text:n});let r=``;for(let t=0;t<e.rows.length;t++){let i=e.rows[t];n=``;for(let e=0;e<i.length;e++)n+=this.tablecell(i[e]);r+=this.tablerow({text:n})}return r&&=`<tbody>${r}</tbody>`,`<table>
|
|
59
|
+
<thead>
|
|
60
|
+
`+t+`</thead>
|
|
61
|
+
`+r+`</table>
|
|
62
|
+
`}tablerow({text:e}){return`<tr>
|
|
63
|
+
${e}</tr>
|
|
64
|
+
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
|
|
65
|
+
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${b(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,text:n,tokens:r,autolink:i}){let a=i?b(n,!0):this.parser.parseInline(r),o=gt(e);if(o===null)return a;e=b(o,i);let s=`<a href="`+e+`"`;return t&&(s+=` title="`+b(t)+`"`),s+=`>`+a+`</a>`,s}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=gt(e);if(i===null)return b(n);e=i;let a=`<img src="${b(e)}" alt="${b(n)}"`;return t&&(a+=` title="${b(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:b(e.text)}},Ot=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}checkbox({raw:e}){return e}},kt=class e{options;renderer;textRenderer;constructor(e){this.options=e||u,this.options.renderer=this.options.renderer||new Dt,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ot}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let e=r,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(n!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`checkbox`,`html`,`def`,`paragraph`,`text`].includes(e.type)){t+=n||``;continue}}let i=r;switch(i.type){case`space`:t+=this.renderer.space(i);break;case`hr`:t+=this.renderer.hr(i);break;case`heading`:t+=this.renderer.heading(i);break;case`code`:t+=this.renderer.code(i);break;case`table`:t+=this.renderer.table(i);break;case`blockquote`:t+=this.renderer.blockquote(i);break;case`list`:t+=this.renderer.list(i);break;case`checkbox`:t+=this.renderer.checkbox(i);break;case`html`:t+=this.renderer.html(i);break;case`def`:t+=this.renderer.def(i);break;case`paragraph`:t+=this.renderer.paragraph(i);break;case`text`:t+=this.renderer.text(i);break;default:{let e=`Token with "`+i.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`checkbox`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`checkbox`:n+=t.checkbox(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},At=class{options;block;constructor(e){this.options=e||u}static passThroughHooks=new Set([`preprocess`,`postprocess`,`processAllTokens`,`emStrongMask`]);static passThroughHooksRespectAsync=new Set([`preprocess`,`postprocess`,`processAllTokens`]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?Et.lex:Et.lexInline}provideParser(e=this.block){return e?kt.parse:kt.parseInline}};function jt(e,t){if(Array.isArray(t))for(let n=0;n<t.length;n++)e.push(t[n]);else e.push(t)}var Mt=class{defaults=l();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=kt;Renderer=Dt;TextRenderer=Ot;Lexer=Et;Tokenizer=x;Hooks=At;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(jt(n,t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)jt(n,this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)jt(n,this.walkTokens(e.tokens,t));break}case`list`:{let e=r;jt(n,this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);jt(n,this.walkTokens(i,t))}):e.tokens&&jt(n,this.walkTokens(e.tokens,t))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new Dt(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new x(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new At;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];t[r]=At.passThroughHooks.has(n)?e=>{if(this.defaults.async&&At.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&jt(n,t.call(this,e)),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Et.lex(e,t??this.defaults)}parser(e,t){return kt.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(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 t>`u`||t===null)return a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer(e):e?Et.lex:Et.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser(e):e?kt.parse:kt.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer(e):e?Et.lex:Et.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser(e):e?kt.parse:kt.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`
|
|
66
|
+
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+b(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}},Nt=new Mt;function S(e,t){return Nt.parse(e,t)}S.options=S.setOptions=function(e){return Nt.setOptions(e),S.defaults=Nt.defaults,d(S.defaults),S},S.getDefaults=l,S.defaults=u;function Pt(...e){return Nt.use(...e),S.defaults=Nt.defaults,d(S.defaults),S}S.use=Pt,S.walkTokens=function(e,t){return Nt.walkTokens(e,t)},S.parseInline=Nt.parseInline,S.Parser=kt,S.parser=kt.parse,S.Renderer=Dt,S.TextRenderer=Ot,S.Lexer=Et,S.lexer=Et.lex,S.Tokenizer=x,S.Hooks=At,S.parse=S,S.options,S.setOptions,S.walkTokens,S.parseInline,kt.parse,Et.lex;function Ft(e,t){let n={type:`footnotes`,raw:t,rawItems:[],items:[]};return{name:`footnote`,level:`block`,childTokens:[`content`],tokenizer(t){e.hasFootnotes||(this.lexer.tokens.push(n),e.tokens=this.lexer.tokens,e.hasFootnotes=!0,n.rawItems=[],n.items=[]);let r=/^\[\^([^\]\n]+)\]:(?:[ \t]+|[\n]*?|$)([^\n]*?(?:\n|$)(?:\n*?[ ]{4,}[^\n]*)*)/.exec(t);if(r){let[e,t,i=``]=r,a=i.split(`
|
|
67
|
+
`).reduce((e,t)=>e+`
|
|
68
|
+
`+t.replace(/^(?:[ ]{4}|[\t])/,``),``),o=a.trimEnd().split(`
|
|
69
|
+
`).pop();a+=o&&/^[ \t]*?[>\-*][ ]|[`]{3,}$|^[ \t]*?[|].+[|]$/.test(o)?`
|
|
70
|
+
|
|
71
|
+
`:``;let s={type:`footnote`,raw:e,label:t,refs:[],content:this.lexer.blockTokens(a)};return n.rawItems.push(s),s}},renderer(){return``}}}function It(e){return e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}function Lt(e,t=!1,n=!1){let r=0;return{name:`footnoteRef`,level:`inline`,tokenizer(e){let t=/^\[\^([^\]\n]+)\]/.exec(e);if(t){let[e,n]=t,i=this.lexer.tokens[0],a=i.rawItems.filter(e=>e.label===n);if(!a.length)return;let o=a[0],s=i.items.filter(e=>e.label===n)[0],c={type:`footnoteRef`,raw:e,index:o.refs.length,id:``,label:n};return s?(c.id=s.refs[0].id,s.refs.push(c)):(r++,c.id=String(r),o.refs.push(c),i.items.push(o)),c}},renderer({index:i,id:a,label:o}){r=0;let s=encodeURIComponent(o),c=n?It(o):a;return`<sup><a id="${e}ref-${s}${i>0?`-${i+1}`:``}" href="#${e+s}" data-${e}ref aria-describedby="${e}label">${t?`[${c}]`:c}</a></sup>`}}}function Rt(e,t,n,r,i,a){return{name:`footnotes`,renderer({raw:o,items:s=[]}){if(s.length===0)return``;let c=s.reduce((t,{label:n,content:r,refs:i})=>{let o=encodeURIComponent(n),s=this.parser.parse(r).trimEnd(),c=s.endsWith(`</p>`),l=`<li id="${e+o}">
|
|
72
|
+
`;return l+=c?s.replace(/<\/p>$/,``):s,i.forEach((t,r)=>{let i=a.replace(`{0}`,n),s,c;if(r>0){let e=r+1;s=`↩<sup>${e}</sup>`,c=`-${e}`}else s=`↩`,c=``;l+=` <a href="#${e}ref-${o}${c}" data-${e}backref aria-label="${i}">${s}</a>`}),l+=c?`</p>
|
|
73
|
+
`:`
|
|
74
|
+
`,l+=`</li>
|
|
75
|
+
`,t+l},``),l=``;n&&(l+=`<hr data-${t}footnotes>
|
|
76
|
+
`);let u=``;r&&(u=` class="${r}"`);let d=``;return i&&(d=` class="${i}"`),l+=`<section${u} data-${t}footnotes>
|
|
77
|
+
`,l+=`<h2 id="${e}label"${d}>${o.trimEnd()}</h2>
|
|
78
|
+
`,l+=`<ol>
|
|
79
|
+
${c}</ol>
|
|
80
|
+
`,l+=`</section>
|
|
81
|
+
`,l}}}function zt(e={}){let{prefixId:t=`footnote-`,prefixData:n=``,description:r=`Footnotes`,refMarkers:i=!1,footnoteDivider:a=!1,keepLabels:o=!1,sectionClass:s=`footnotes`,headingClass:c=`sr-only`,backRefLabel:l=`Back to reference {0}`}=e,u={hasFootnotes:!1,tokens:[]};return{extensions:[Ft(u,r),Lt(t,i,o),Rt(t,n,a,s,c,l)],walkTokens(e){e.type===`footnotes`&&u.tokens.indexOf(e)===0&&e.items.length&&(u.tokens[0]={type:`space`,raw:``},u.tokens.push(e)),u.hasFootnotes&&=!1}}}function Bt(e,t){this.v=e,this.k=t}function Vt(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Ht(e){if(Array.isArray(e))return e}function Ut(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function Wt(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
82
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Gt(e,t){return Ht(e)||Ut(e,t)||Kt(e,t)||Wt()}function Kt(e,t){if(e){if(typeof e==`string`)return Vt(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Vt(e,t):void 0}}function qt(e){var t,n;function r(t,n){try{var a=e[t](n),o=a.value,s=o instanceof Bt;Promise.resolve(s?o.v:o).then(function(n){if(s){var c=t===`return`&&o.k?t:`next`;if(!o.k||n.done)return r(c,n);n=e[c](n).value}i(!!a.done,n)},function(e){r(`throw`,e)})}catch(e){i(2,e)}}function i(e,i){e===2?t.reject(i):t.resolve({value:i,done:e}),(t=t.next)?r(t.key,t.arg):n=null}this._invoke=function(e,i){return new Promise(function(a,o){var s={key:e,arg:i,resolve:a,reject:o,next:null};n?n=n.next=s:(t=n=s,r(e,i))})},typeof e.return!=`function`&&(this.return=void 0)}qt.prototype[typeof Symbol==`function`&&Symbol.asyncIterator||`@@asyncIterator`]=function(){return this},qt.prototype.next=function(e){return this._invoke(`next`,e)},qt.prototype.throw=function(e){return this._invoke(`throw`,e)},qt.prototype.return=function(e){return this._invoke(`return`,e)};var Jt=Object.entries,Yt=Object.setPrototypeOf,Xt=Object.isFrozen,Zt=Object.getPrototypeOf,Qt=Object.getOwnPropertyDescriptor,$t=Object.freeze,en=Object.seal,tn=Object.create,nn=typeof Reflect<`u`&&Reflect,rn=nn.apply,an=nn.construct;$t||=function(e){return e},en||=function(e){return e},rn||=function(e,t){var n=[...arguments].slice(2);return e.apply(t,n)},an||=function(e){return new e(...[...arguments].slice(1))};var on=C(Array.prototype.forEach);Array.prototype.indexOf;var sn=C(Array.prototype.lastIndexOf),cn=C(Array.prototype.pop),ln=C(Array.prototype.push),un=C(Array.prototype.slice),dn=C(Array.prototype.splice),fn=Array.isArray,pn=An(Set),mn=C(Set.prototype.add),hn=C(Set.prototype.has),gn=C(String.prototype.toLowerCase),_n=C(String.prototype.toString),vn=C(String.prototype.match),yn=C(String.prototype.replace),bn=C(String.prototype.indexOf),xn=C(String.prototype.trim),Sn=C(Number.prototype.toString),Cn=C(Boolean.prototype.toString),wn=typeof BigInt>`u`?null:C(BigInt.prototype.toString),Tn=typeof Symbol>`u`?null:C(Symbol.prototype.toString),En=C(Object.prototype.hasOwnProperty),Dn=C(Object.prototype.toString),On=C(RegExp.prototype.test),kn=An(TypeError);function C(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return rn(e,t,n)}}function An(e){return function(){return an(e,[...arguments])}}function w(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:gn;if(Yt&&Yt(e,null),!fn(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(Xt(t)||(t[r]=e),i=e)}e[i]=!0}return e}function jn(e){for(let t=0;t<e.length;t++)En(e,t)||(e[t]=null);return e}function Mn(e){let t=tn(null);for(let r of Jt(e)){var n=Gt(r,2);let i=n[0],a=n[1];En(e,i)&&(t[i]=fn(a)?jn(a):a&&typeof a==`object`&&a.constructor===Object?Mn(a):a)}return t}function Nn(e){switch(typeof e){case`string`:return e;case`number`:return Sn(e);case`boolean`:return Cn(e);case`bigint`:return wn?wn(e):`0`;case`symbol`:return Tn?Tn(e):`Symbol()`;case`undefined`:return Dn(e);case`function`:case`object`:{if(e===null)return Dn(e);let t=e,n=Pn(t,`toString`);if(typeof n==`function`){let e=n(t);return typeof e==`string`?e:Dn(e)}return Dn(e)}default:return Dn(e)}}function Pn(e,t){for(;e!==null;){let n=Qt(e,t);if(n){if(n.get)return C(n.get);if(typeof n.value==`function`)return C(n.value)}e=Zt(e)}function n(){return null}return n}function Fn(e,t){for(;e!==null;){let n=Qt(e,t);if(n)return n.get?C(n.get):null;e=Zt(e)}return null}function In(e){try{return On(e,``),!0}catch{return!1}}var Ln=$t(`a.abbr.acronym.address.area.article.aside.audio.b.bdi.bdo.big.blink.blockquote.body.br.button.canvas.caption.center.cite.code.col.colgroup.content.data.datalist.dd.decorator.del.details.dfn.dialog.dir.div.dl.dt.element.em.fieldset.figcaption.figure.font.footer.form.h1.h2.h3.h4.h5.h6.head.header.hgroup.hr.html.i.img.input.ins.kbd.label.legend.li.main.map.mark.marquee.menu.menuitem.meter.nav.nobr.ol.optgroup.option.output.p.picture.pre.progress.q.rp.rt.ruby.s.samp.search.section.select.shadow.slot.small.source.spacer.span.strike.strong.style.sub.summary.sup.table.tbody.td.template.textarea.tfoot.th.thead.time.tr.track.tt.u.ul.var.video.wbr`.split(`.`)),Rn=$t(`svg.a.altglyph.altglyphdef.altglyphitem.animatecolor.animatemotion.animatetransform.circle.clippath.defs.desc.ellipse.enterkeyhint.exportparts.filter.font.g.glyph.glyphref.hkern.image.inputmode.line.lineargradient.marker.mask.metadata.mpath.part.path.pattern.polygon.polyline.radialgradient.rect.stop.style.switch.symbol.text.textpath.title.tref.tspan.view.vkern`.split(`.`)),zn=$t([`feBlend`,`feColorMatrix`,`feComponentTransfer`,`feComposite`,`feConvolveMatrix`,`feDiffuseLighting`,`feDisplacementMap`,`feDistantLight`,`feDropShadow`,`feFlood`,`feFuncA`,`feFuncB`,`feFuncG`,`feFuncR`,`feGaussianBlur`,`feImage`,`feMerge`,`feMergeNode`,`feMorphology`,`feOffset`,`fePointLight`,`feSpecularLighting`,`feSpotLight`,`feTile`,`feTurbulence`]),Bn=$t([`animate`,`color-profile`,`cursor`,`discard`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`foreignobject`,`hatch`,`hatchpath`,`mesh`,`meshgradient`,`meshpatch`,`meshrow`,`missing-glyph`,`script`,`set`,`solidcolor`,`unknown`,`use`]),Vn=$t(`math.menclose.merror.mfenced.mfrac.mglyph.mi.mlabeledtr.mmultiscripts.mn.mo.mover.mpadded.mphantom.mroot.mrow.ms.mspace.msqrt.mstyle.msub.msup.msubsup.mtable.mtd.mtext.mtr.munder.munderover.mprescripts`.split(`.`)),Hn=$t([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),Un=$t([`#text`]),Wn=$t(`accept.action.align.alt.autocapitalize.autocomplete.autopictureinpicture.autoplay.background.bgcolor.border.capture.cellpadding.cellspacing.checked.cite.class.clear.color.cols.colspan.command.commandfor.controls.controlslist.coords.crossorigin.datetime.decoding.default.dir.disabled.disablepictureinpicture.disableremoteplayback.download.draggable.enctype.enterkeyhint.exportparts.face.for.headers.height.hidden.high.href.hreflang.id.inert.inputmode.integrity.ismap.kind.label.lang.list.loading.loop.low.max.maxlength.media.method.min.minlength.multiple.muted.name.nonce.noshade.novalidate.nowrap.open.optimum.part.pattern.placeholder.playsinline.popover.popovertarget.popovertargetaction.poster.preload.pubdate.radiogroup.readonly.rel.required.rev.reversed.role.rows.rowspan.spellcheck.scope.selected.shape.size.sizes.slot.span.srclang.start.src.srcset.step.style.summary.tabindex.title.translate.type.usemap.valign.value.width.wrap.xmlns`.split(`.`)),Gn=$t(`accent-height.accumulate.additive.alignment-baseline.amplitude.ascent.attributename.attributetype.azimuth.basefrequency.baseline-shift.begin.bias.by.class.clip.clippathunits.clip-path.clip-rule.color.color-interpolation.color-interpolation-filters.color-profile.color-rendering.cx.cy.d.dx.dy.diffuseconstant.direction.display.divisor.dominant-baseline.dur.edgemode.elevation.end.exponent.fill.fill-opacity.fill-rule.filter.filterunits.flood-color.flood-opacity.font-family.font-size.font-size-adjust.font-stretch.font-style.font-variant.font-weight.fx.fy.g1.g2.glyph-name.glyphref.gradientunits.gradienttransform.height.href.id.image-rendering.in.in2.intercept.k.k1.k2.k3.k4.kerning.keypoints.keysplines.keytimes.lang.lengthadjust.letter-spacing.kernelmatrix.kernelunitlength.lighting-color.local.marker-end.marker-mid.marker-start.markerheight.markerunits.markerwidth.maskcontentunits.maskunits.max.mask.mask-type.media.method.mode.min.name.numoctaves.offset.operator.opacity.order.orient.orientation.origin.overflow.paint-order.path.pathlength.patterncontentunits.patterntransform.patternunits.pointer-events.points.preservealpha.preserveaspectratio.primitiveunits.r.rx.ry.radius.refx.refy.repeatcount.repeatdur.restart.result.rotate.scale.seed.shape-rendering.slope.specularconstant.specularexponent.spreadmethod.startoffset.stddeviation.stitchtiles.stop-color.stop-opacity.stroke-dasharray.stroke-dashoffset.stroke-linecap.stroke-linejoin.stroke-miterlimit.stroke-opacity.stroke.stroke-width.style.surfacescale.systemlanguage.tabindex.tablevalues.targetx.targety.transform.transform-origin.text-anchor.text-decoration.text-orientation.text-rendering.textlength.type.u1.u2.unicode.values.vector-effect.viewbox.visibility.version.vert-adv-y.vert-origin-x.vert-origin-y.width.word-spacing.wrap.writing-mode.xchannelselector.ychannelselector.x.x1.x2.xmlns.y.y1.y2.z.zoomandpan`.split(`.`)),Kn=$t(`accent.accentunder.align.bevelled.close.columnalign.columnlines.columnspacing.columnspan.denomalign.depth.dir.display.displaystyle.encoding.fence.frame.height.href.id.largeop.length.linethickness.lquote.lspace.mathbackground.mathcolor.mathsize.mathvariant.maxsize.minsize.movablelimits.notation.numalign.open.rowalign.rowlines.rowspacing.rowspan.rspace.rquote.scriptlevel.scriptminsize.scriptsizemultiplier.selection.separator.separators.stretchy.subscriptshift.supscriptshift.symmetric.voffset.width.xmlns`.split(`.`)),qn=$t([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),Jn=en(/{{[\w\W]*|^[\w\W]*}}/g),Yn=en(/<%[\w\W]*|^[\w\W]*%>/g),Xn=en(/\${[\w\W]*/g),Zn=en(/^data-[\-\w.\u00B7-\uFFFF]+$/),Qn=en(/^aria-[\-\w]+$/),$n=en(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),er=en(/^(?:\w+script|data):/i),tr=en(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),nr=en(/^html$/i),rr=en(/^[a-z][.\w]*(-[.\w]+)+$/i),ir=en(/<[/\w!]/g),ar=en(/<[/\w]/g),or=en(/<\/no(script|embed|frames)/i),sr=en(/\/>/i),T={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},cr=$t(w({},[`style`,`script`,`xmp`,`iframe`,`noembed`,`noframes`,`plaintext`,`noscript`])),lr=function(){return typeof window>`u`?null:window},ur=function(e,t){if(typeof e!=`object`||typeof e.createPolicy!=`function`)return null;let n=null,r=`data-tt-policy-suffix`;t&&t.hasAttribute(r)&&(n=t.getAttribute(r));let i=`dompurify`+(n?`#`+n:``);try{return e.createPolicy(i,{createHTML(e){return e},createScriptURL(e){return e}})}catch{return console.warn(`TrustedTypes policy `+i+` could not be created.`),null}},dr=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},fr=function(e,t,n,r){return En(e,t)&&fn(e[t])?w(r.base?Mn(r.base):{},e[t],r.transform):n},pr=function(e,t,n){let r=En(e,t)?e[t]:void 0;return r&&typeof r==`object`?Mn(r):n()};function mr(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:lr(),t=e=>mr(e);if(t.version=`3.4.17`,t.removed=[],!e||!e.document||e.document.nodeType!==T.document||!e.Element)return t.isSupported=!1,t;let n=e.document,r=n,i=r.currentScript;e.DocumentFragment;let a=e.HTMLTemplateElement,o=e.Node,s=e.Element,c=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;let l=e.DOMParser,u=e.trustedTypes,d=s.prototype,f=Pn(d,`cloneNode`),p=Pn(d,`remove`),m=Pn(d,`removeAttributeNode`),h=Pn(d,`nextSibling`),g=Pn(d,`childNodes`),ee=Pn(d,`parentNode`),te=Pn(d,`shadowRoot`),ne=Pn(d,`attributes`),re=o&&o.prototype?Pn(o.prototype,`nodeType`):null,ie=o&&o.prototype?Pn(o.prototype,`nodeName`):null,ae=o&&o.prototype?Pn(o.prototype,`ownerDocument`):null,oe=function(e){return re?re(e):e.nodeType},se=function(e){return ie?ie(e):e.nodeName},ce=Fn(d,`namespaceURI`),le=function(e){return ce?ce(e):e.namespaceURI};if(typeof a==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let ue,de=``,fe,pe=!1,me=0,he=function(){if(me>0)throw kn(`A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.`)},ge=function(e){he(),me++;try{return ue.createHTML(e)}finally{me--}},_e=function(e){he(),me++;try{return ue.createScriptURL(e)}finally{me--}},ve=function(){return pe||=(fe=ur(u,i),!0),fe},ye=n,be=ye.implementation,xe=ye.createNodeIterator,Se=ye.createDocumentFragment,Ce=ye.getElementsByTagName,we=r.importNode,_=dr();t.isSupported=typeof Jt==`function`&&typeof ee==`function`&&be&&be.createHTMLDocument!==void 0;let Te=Jn,Ee=Yn,De=Xn,Oe=Zn,ke=Qn,Ae=er,je=tr,Me=rr,Ne=$n,v=null,Pe=w({},[...Ln,...Rn,...zn,...Vn,...Un]),y=null,Fe=w({},[...Wn,...Gn,...Kn,...qn]),Ie=Object.seal(tn(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Le=null,Re=null,ze=Object.seal(tn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),Be=!0,Ve=!0,He=!1,Ue=!0,We=!1,Ge=!0,Ke=!1,qe=!1,Je=null,Ye=null,Xe=!1,Ze=!1,Qe=!1,$e=!1,et=!0,tt=!1,nt=`user-content-`,rt=!0,it=!1,at=null,ot={},st=null,ct=w({},`annotation-xml.audio.colgroup.desc.foreignobject.head.iframe.math.mi.mn.mo.ms.mtext.noembed.noframes.noscript.plaintext.script.selectedcontent.style.svg.template.thead.title.video.xmp`.split(`.`)),lt=null,ut=w({},[`audio`,`video`,`img`,`source`,`image`,`track`]),dt=null,ft=w({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),pt=`http://www.w3.org/1998/Math/MathML`,mt=`http://www.w3.org/2000/svg`,b=`http://www.w3.org/1999/xhtml`,ht=b,gt=!1,_t=null,vt=w({},[pt,mt,b],_n),yt=$t([`mi`,`mo`,`mn`,`ms`,`mtext`]),bt=w({},yt),xt=$t([`annotation-xml`]),St=w({},xt),Ct=w({},[`title`,`style`,`font`,`a`,`script`]),wt=null,Tt=[`application/xhtml+xml`,`text/html`],x=null,Et=null,Dt=n.createElement(`form`),Ot=function(e){return e instanceof RegExp||e instanceof Function},kt=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Et&&Et===e)return;(!e||typeof e!=`object`)&&(e={}),e=Mn(e),wt=Tt.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,x=wt===`application/xhtml+xml`?_n:gn,v=fr(e,`ALLOWED_TAGS`,Pe,{transform:x}),y=fr(e,`ALLOWED_ATTR`,Fe,{transform:x}),_t=fr(e,`ALLOWED_NAMESPACES`,vt,{transform:_n}),dt=fr(e,`ADD_URI_SAFE_ATTR`,ft,{transform:x,base:ft}),lt=fr(e,`ADD_DATA_URI_TAGS`,ut,{transform:x,base:ut}),st=fr(e,`FORBID_CONTENTS`,ct,{transform:x}),Le=fr(e,`FORBID_TAGS`,Mn({}),{transform:x}),Re=fr(e,`FORBID_ATTR`,Mn({}),{transform:x}),ot=En(e,`USE_PROFILES`)?e.USE_PROFILES&&typeof e.USE_PROFILES==`object`?Mn(e.USE_PROFILES):e.USE_PROFILES:!1,Be=e.ALLOW_ARIA_ATTR!==!1,Ve=e.ALLOW_DATA_ATTR!==!1,He=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Ue=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,We=e.SAFE_FOR_TEMPLATES||!1,Ge=e.SAFE_FOR_XML!==!1,Ke=e.WHOLE_DOCUMENT||!1,Ze=e.RETURN_DOM||!1,Qe=e.RETURN_DOM_FRAGMENT||!1,$e=e.RETURN_TRUSTED_TYPE||!1,Xe=e.FORCE_BODY||!1,et=e.SANITIZE_DOM!==!1,tt=e.SANITIZE_NAMED_PROPS||!1,rt=e.KEEP_CONTENT!==!1,it=e.IN_PLACE||!1,Ne=In(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:$n,ht=typeof e.NAMESPACE==`string`?e.NAMESPACE:b,bt=pr(e,`MATHML_TEXT_INTEGRATION_POINTS`,()=>w({},yt)),St=pr(e,`HTML_INTEGRATION_POINTS`,()=>w({},xt));let t=pr(e,`CUSTOM_ELEMENT_HANDLING`,()=>tn(null));if(Ie=tn(null),En(t,`tagNameCheck`)&&Ot(t.tagNameCheck)&&(Ie.tagNameCheck=t.tagNameCheck),En(t,`attributeNameCheck`)&&Ot(t.attributeNameCheck)&&(Ie.attributeNameCheck=t.attributeNameCheck),En(t,`allowCustomizedBuiltInElements`)&&typeof t.allowCustomizedBuiltInElements==`boolean`&&(Ie.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),en(Ie),We&&(Ve=!1),Qe&&(Ze=!0),ot&&(v=w({},Un),y=tn(null),ot.html===!0&&(w(v,Ln),w(y,Wn)),ot.svg===!0&&(w(v,Rn),w(y,Gn),w(y,qn)),ot.svgFilters===!0&&(w(v,zn),w(y,Gn),w(y,qn)),ot.mathMl===!0&&(w(v,Vn),w(y,Kn),w(y,qn))),ze.tagCheck=null,ze.attributeCheck=null,En(e,`ADD_TAGS`)&&(typeof e.ADD_TAGS==`function`?ze.tagCheck=e.ADD_TAGS:fn(e.ADD_TAGS)&&(v===Pe&&(v=Mn(v)),w(v,e.ADD_TAGS,x))),En(e,`ADD_ATTR`)&&(typeof e.ADD_ATTR==`function`?ze.attributeCheck=e.ADD_ATTR:fn(e.ADD_ATTR)&&(y===Fe&&(y=Mn(y)),w(y,e.ADD_ATTR,x))),En(e,`ADD_FORBID_CONTENTS`)&&fn(e.ADD_FORBID_CONTENTS)&&(st===ct&&(st=Mn(st)),w(st,e.ADD_FORBID_CONTENTS,x)),rt&&(v[`#text`]=!0),Ke&&w(v,[`html`,`head`,`body`]),v.table&&(w(v,[`tbody`]),delete Le.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw kn(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw kn(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);let t=ue;ue=e.TRUSTED_TYPES_POLICY;try{de=ge(``)}catch(e){throw ue=t,e}}else e.TRUSTED_TYPES_POLICY===null?(ue=void 0,de=``):(ue===void 0&&(ue=ve()),ue&&typeof de==`string`&&(de=ge(``)));$t&&$t(e),Et=e},At=w({},[...Rn,...zn,...Bn]),jt=w({},[...Vn,...Hn]),Mt=function(e,t,n){return t.namespaceURI===b?e===`svg`:t.namespaceURI===pt?e===`svg`&&(n===`annotation-xml`||bt[n]):!!At[e]},Nt=function(e,t,n){return t.namespaceURI===b?e===`math`:t.namespaceURI===mt?e===`math`&&St[n]:!!jt[e]},S=function(e,t,n){return t.namespaceURI===mt&&!St[n]||t.namespaceURI===pt&&!bt[n]?!1:!jt[e]&&(Ct[e]||!At[e])},Pt=function(e){let t=le(e),n=gn(se(e)),r=ee(e),i,a;return r&&oe(r)===T.element?(i={namespaceURI:le(r)},a=gn(se(r))):(i={namespaceURI:ht},a=`template`),_t[t]?t===mt?Mt(n,i,a):t===pt?Nt(n,i,a):t===b?S(n,i,a):!!(wt===`application/xhtml+xml`&&_t[t]):!1},Ft=function(e){ln(t.removed,{element:e});try{ee(e).removeChild(e)}catch{if(p(e),!ee(e))throw kn(`a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place`)}},It=function(e,t,n){try{m(e,t)}catch{try{e.removeAttribute(n)}catch{}}},Lt=function(e){Vt(e);let t=g(e);t&&on(un(t),e=>{try{p(e)}catch{}});let n=oe(e)===T.element?ne(e):null;if(n)for(let t=n.length-1;t>=0;--t){let r=n[t],i=r&&r.name;typeof i==`string`&&It(e,r,i)}},Rt=function(e,n,r){if(!r)try{r=n.getAttributeNode(e)}catch{r=null}ln(t.removed,{attribute:r||null,from:n});try{r?m(n,r):n.removeAttribute(e)}catch{try{n.removeAttribute(e)}catch{}}if(e===`is`){if(Ze||Qe)try{Ft(n)}catch{}else try{n.setAttribute(e,``)}catch{}}},zt=function(e){let t=ne(e);if(t)for(let n=t.length-1;n>=0;--n){let r=t[n],i=r&&r.name;typeof i!=`string`||y[x(i)]||It(e,r,i)}},Bt=function(e,t){let n=arguments.length>2&&arguments[2]!==void 0&&arguments[2],r=[e];for(;r.length>0;){let e=r.pop();if(t(e)===!1)continue;if(n&&oe(e)===T.element){let t=te(e);Cn(t)&&r.push(t)}let i=g(e);if(i)for(let e=i.length-1;e>=0;--e)r.push(i[e])}},Vt=function(e){Bt(e,e=>{oe(e)===T.element&&zt(e)})},Ht=function(e){let t=[];return Bt(e,e=>{t.push(e)},!0),t},Ut=function(e,t){let n=pn();on(Ht(e),e=>{oe(e)===T.element&&mn(n,e)}),on(t,e=>{oe(e)===T.element&&!hn(n,e)&&zt(e)})},Wt=function(e,n){let r=!1;return on(t.removed,t=>{t.element&&(r||=t.element===e,Vt(t.element))}),Ut(e,n),r},Gt=function(e,t){let n=at,r=null,i=()=>(r||(r=pn(),on(t,e=>{mn(r,e)})),r);for(let t=0;;t++){let r=Ht(e),a=[e],o=!1;if(on(r,e=>{oe(e)===T.documentFragment?ln(a,e):!o&&!hn(n,e)&&(o=hn(i(),e))}),!o)return;if(t>=8)throw kn(`the tree kept changing during in-place sanitization; refusing to return it`);on(a,(t,n)=>{Kt(t,n>0,e,i())})}},Kt=function(e,t,n,r){let i=Qt(e),a;for(;a=i.nextNode();)hn(r,a)&&!hn(at,a)&&(t&&Tn(_.uponSanitizeShadowNode,a,null),gr(a,n),Cr(a,n),Cn(a.content)&&wr(a.content))},qt=function(e){at&&mn(at,e)},Yt=function(e,t){return Ge?e===`patchsrc`||e===`for`&&t!==`label`&&t!==`output`:!1},Xt=function(e){Ge&&Bt(e,e=>{let t=oe(e);if(t===T.processingInstruction||t===T.comment&&On(ar,e.data)){try{p(e)}catch{}return!1}if(t===T.element){let t=e,n=x(se(e));try{t.hasAttribute&&t.hasAttribute(`patchsrc`)&&t.removeAttribute(`patchsrc`),t.hasAttribute&&t.hasAttribute(`for`)&&Yt(`for`,n)&&t.removeAttribute(`for`)}catch{}}return!0})},Zt=function(e){let t=null,r=null;if(Xe)e=`<remove></remove>`+e;else{let t=vn(e,/^[\r\n\t ]+/);r=t&&t[0]}wt===`application/xhtml+xml`&&ht===b&&(e=`<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>`+e+`</body></html>`);let i=ue?ge(e):e;if(ht===b)try{t=new l().parseFromString(i,wt)}catch{}if(!t||!t.documentElement){t=be.createDocument(ht,`template`,null);try{t.documentElement.innerHTML=gt?de:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),ht===b?Ce.call(t,Ke?`html`:`body`)[0]:Ke?t.documentElement:a},Qt=function(e){let t=ae?ae(e):e.ownerDocument;return xe.call(t||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},nn=function(e){return e=yn(e,Te,` `),e=yn(e,Ee,` `),e=yn(e,De,` `),e},rn=function(e){an(e);let t=e.querySelectorAll?.call(e,`template`);t&&on(t,e=>{Cn(e.content)&&rn(e.content)})},an=function(e){e.normalize();let t=ae?ae(e):e.ownerDocument,n=xe.call(t||e,e,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null),r=n.nextNode();for(;r;)r.data=nn(r.data),r=n.nextNode()},Sn=function(e){let t=ie?ie(e):null;return typeof t!=`string`||x(t)!==`form`?!1:typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||e.attributes!==ne(e)||typeof e.removeAttribute!=`function`||typeof e.removeAttributeNode!=`function`||typeof e.getAttributeNode!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`||e.nodeType!==re(e)||e.childNodes!==g(e)},Cn=function(e){if(!re||typeof e!=`object`||!e)return!1;try{return re(e)===T.documentFragment}catch{return!1}},wn=function(e){if(!re||typeof e!=`object`||!e)return!1;try{return typeof re(e)==`number`}catch{return!1}};function Tn(e,n,r){e.length!==0&&on(e,e=>{e.call(t,n,r,Et)})}let Dn=function(e,t){return!!(Ge&&e.hasChildNodes()&&!wn(e.firstElementChild)&&On(ir,e.textContent)&&On(ir,e.innerHTML)||Ge&&cr[t]&&oe(e)===T.element&&le(e)===b&&(wn(e.firstElementChild)||typeof e.textContent==`string`&&On(ir,e.textContent))||e.nodeType===T.processingInstruction||Ge&&e.nodeType===T.comment&&On(ar,e.data))},C=function(e,t){return e instanceof RegExp?On(e,t):e instanceof Function&&!!e(t,...[...arguments].slice(2))},An=function(e,t,n){if(!Le[t]&&yr(t)&&C(Ie.tagNameCheck,t))return!1;if(rt&&!st[t]&&!st[gn(t)]){let t=ee(e),r=g(e);if(r&&t){let i=r.length;for(let a=i-1;a>=0;--a){let i=e===n?f(r[a],!0):r[a];t.insertBefore(i,h(e))}}}return Ft(e),!0},jn=function(e,t,n,r){return e.length===0?t:t===n||t===r?Mn(t):t},hr=function(e,t){return e===t||ee(e)!==null?!1:(it&&Vt(e),!0)},gr=function(e,n){if(qt(e),Tn(_.beforeSanitizeElements,e,null),hr(e,n))return!0;if(Sn(e))return Ft(e),!0;let r=x(se(e));if(v=jn(_.uponSanitizeElement,v,Pe,Je),Tn(_.uponSanitizeElement,e,{tagName:r,allowedTags:v}),hr(e,n))return!0;if(Dn(e,r))return Ft(e),!0;if(Le[r]||!(ze.tagCheck instanceof Function&&ze.tagCheck(r))&&!v[r]){let t=An(e,r,n);return t===!1&&(Tn(_.afterSanitizeElements,e,null),hr(e,n))?!0:t}if(oe(e)===T.element&&!Pt(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&On(or,e.innerHTML))return Ft(e),!0;if(We&&e.nodeType===T.text){let n=nn(e.textContent);e.textContent!==n&&(ln(t.removed,{element:e.cloneNode()}),e.textContent=n)}return Tn(_.afterSanitizeElements,e,null),hr(e,n)},_r=function(e,t,r){if(Re[t]||Yt(t,e)||et&&(t===`id`||t===`name`)&&(r in n||r in Dt))return!1;let i=y[t]||ze.attributeCheck instanceof Function&&ze.attributeCheck(t,e);return Ve&&On(Oe,t)||Be&&On(ke,t)?!0:i?dt[t]||On(Ne,yn(r,je,``))||(t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&bn(r,`data:`)===0&<[e]||He&&!On(Ae,yn(r,je,``))?!0:!r:yr(e)&&C(Ie.tagNameCheck,e)&&C(Ie.attributeNameCheck,t,e)||t===`is`&&Ie.allowCustomizedBuiltInElements&&C(Ie.tagNameCheck,r)},vr=w({},[`annotation-xml`,`color-profile`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`missing-glyph`]),yr=function(e){return!vr[gn(e)]&&On(Me,e)},br=function(e,t,n,r){if(ue&&typeof u==`object`&&typeof u.getAttributeType==`function`&&!n)switch(u.getAttributeType(e,t)){case`TrustedHTML`:return ge(r);case`TrustedScriptURL`:return _e(r)}return r},xr=function(e,t,n,r){try{return n?e.setAttributeNS(n,t,r):e.setAttribute(t,r),!Sn(e)||(Ft(e),!1)}catch{return Rt(t,e),!1}},Sr=function(e,t){return Ge&&On(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,t)?!0:gn(e)===`attributename`&&vn(t,`href`)!==null},Cr=function(e,n){if(Tn(_.beforeSanitizeAttributes,e,null),hr(e,n))return;let r=e.attributes;if(!r||Sn(e))return;y=jn(_.uponSanitizeAttribute,y,Fe,Ye);let i={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:y,forceKeepAttr:void 0},a=r.length,o=x(e.nodeName);for(;a--;){let n=r[a],s=n.name,c=n.namespaceURI,l=n.value,u=x(s),d=l,f=s===`value`?d:xn(d),p=!1;i.attrName=u,i.attrValue=f,i.keepAttr=!0,i.forceKeepAttr=void 0,Tn(_.uponSanitizeAttribute,e,i),f=i.attrValue,tt&&(u===`id`||u===`name`)&&bn(f,nt)!==0&&(Rt(s,e,n),f=nt+f,p=!0),Sr(s,f)?Rt(s,e,n):i.forceKeepAttr||(i.keepAttr?!Ue&&On(sr,f)?Rt(s,e,n):(We&&(f=nn(f)),_r(o,u,f)?(f=br(o,u,c,f),f!==d&&xr(e,s,c,f)&&p&&cn(t.removed)):Rt(s,e,n)):Rt(s,e,n))}Tn(_.afterSanitizeAttributes,e,null),hr(e,n)},wr=function(e){let t=null,n=Qt(e);for(Tn(_.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if(Tn(_.uponSanitizeShadowNode,t,null),gr(t,e),Cr(t,e),Cn(t.content)&&wr(t.content),oe(t)===T.element){let e=te(t);Cn(e)&&(Tr(e),wr(e))}We&&an(e),Tn(_.afterSanitizeShadowDOM,e,null)},Tr=function(e){let t=[{node:e,shadow:null}];for(;t.length>0;){let e=t.pop();if(e.shadow){wr(e.shadow);continue}let n=e.node,r=oe(n)===T.element,i=g(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){let e=ie?ie(n):null;if(typeof e==`string`&&x(e)===`template`){let e=n.content;Cn(e)&&t.push({node:e,shadow:null})}}if(r){let e=te(n);Cn(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return t.sanitize=function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=null,a=null,o=null,s=null;if(gt=!e,gt&&(e=`<!-->`),typeof e!=`string`&&!wn(e)&&(e=Nn(e),typeof e!=`string`))throw kn(`dirty is not a string, aborting`);if(!t.isSupported)return e;qe?(v=Je,y=Ye):kt(n),(_.uponSanitizeElement.length>0||_.uponSanitizeAttribute.length>0)&&(v=Mn(v)),_.uponSanitizeAttribute.length>0&&(y=Mn(y)),t.removed=[];let c=it&&typeof e!=`string`&&wn(e),l=[],u=at;if(c){Xt(e);let t=se(e);if(typeof t==`string`){let n=x(t);if(!v[n]||Le[n])throw Lt(e),kn(`root node is forbidden and cannot be sanitized in-place`)}if(Sn(e))throw Lt(e),kn(`root node is clobbered and cannot be sanitized in-place`);l=Ht(e),at=pn()}else if(wn(e))i=Zt(`<!---->`),a=i.ownerDocument.importNode(e,!0),a.nodeType===T.element&&a.nodeName===`BODY`||a.nodeName===`HTML`?i=a:i.appendChild(a),Tr(i);else{if(!Ze&&!We&&!Ke&&e.indexOf(`<`)===-1)return ue&&$e?ge(e):e;if(i=Zt(e),!i)return Ze?null:$e?de:``}i&&Xe&&Ft(i.firstChild);let d=c?e:i;try{c&&Tr(e);let t=Qt(d);for(;o=t.nextNode();)gr(o,d),Cr(o,d),Cn(o.content)&&wr(o.content);c&&Gt(e,l)}catch(t){throw c&&(Lt(e),Wt(e,l)),t}finally{at=u}if(c){if(Wt(e,l))throw kn(`a node selected for removal could not be safely returned; refusing to sanitize in place`);return We&&rn(e),e}if(Ze){if(We&&rn(i),Qe)for(s=Se.call(i.ownerDocument);i.firstChild;)s.appendChild(i.firstChild);else s=i;return(y.shadowroot||y.shadowrootmode)&&(s=we.call(r,s,!0)),s}let f=Ke?i.outerHTML:i.innerHTML;return Ke&&v[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&On(nr,i.ownerDocument.doctype.name)&&(f=`<!DOCTYPE `+i.ownerDocument.doctype.name+`>
|
|
83
|
+
`+f),We&&(f=nn(f)),ue&&$e?ge(f):f},t.setConfig=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};kt(e),qe=!0,Je=v,Ye=y},t.clearConfig=function(){Et=null,qe=!1,Je=null,Ye=null,ue=fe,de=``},t.isValidAttribute=function(e,t,n){Et||kt({});let r=x(e),i=x(t);return typeof n==`string`&&(Sr(t,n)||!Ue&&On(sr,n))?!1:_r(r,i,n)},t.addHook=function(e,t){typeof t==`function`&&En(_,e)&&ln(_[e],t)},t.removeHook=function(e,t){if(En(_,e)){if(t!==void 0){let n=sn(_[e],t);return n===-1?void 0:dn(_[e],n,1)[0]}return cn(_[e])}},t.removeHooks=function(e){En(_,e)&&(_[e]=[])},t.removeAllHooks=function(){_=dr()},t}var hr=mr();function gr(e,t){return`${e}-${new TextEncoder().encode(JSON.stringify(t)).toBase64({alphabet:`base64url`,omitPadding:!0})}`}function _r(e){let t=gr(`footnote`,e);return{extensions:[{name:`footnoteRef`,renderer(e){let{id:n,index:r}=e;return`<sup><a id="${`${t}-ref-${n}-${r}`}" href="#${`${t}-note-${n}`}" aria-label="Footnote ${n}">${n}</a></sup>`}},{name:`footnotes`,renderer(e){let{items:n}=e;return n.length?`<section aria-label="Footnotes"><ol>${n.map(({refs:e,content:n})=>{let r=e.map(({id:e,index:n})=>`<a href="#${`${t}-ref-${e}-${n}`}" aria-label="Back to reference ${e}.${n+1}">↩${n?`<sup>${n+1}</sup>`:``}</a>`).join(` `);return`<li id="${t}-note-${e[0].id}" tabindex="-1">${this.parser.parse(n)}<p>${r}</p></li>`}).join(`
|
|
84
|
+
`)}</ol></section>`:``}}]}}function vr(e){let t=/^(\$\$|\\\[|\\\(|\$)/u.exec(e)?.[0];if(!t)return;let n=t===`\\[`?`\\]`:t===`\\(`?`\\)`:t;if(t===`$`&&/\s/u.test(e[1]??``))return;let r=0;for(let i=t.length;i<e.length;i++){if(t===`$`&&e[i]===`
|
|
85
|
+
`)return;if(r===0&&e.startsWith(n,i)){if(t===`$`&&(/\s/u.test(e[i-1])||/\d/u.test(e[i+1]??``)))return;let r=e.slice(t.length,i).trim();return r?{raw:e.slice(0,i+n.length),text:r,display:t===`$$`||t===`\\[`}:void 0}e[i]===`\\`?i++:e[i]===`{`?r++:e[i]===`}`&&(r=Math.max(0,r-1))}}var yr=e=>e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`),br={extensions:[`block`,`inline`].map(e=>({name:`math-${e}`,level:e,start:t=>e===`block`?t.match(/(?:^|\n) {0,3}(?:\$\$|\\\[)/u)?.index:t.search(/\$|\\[[(]/u),tokenizer(t){let n=e===`block`?/^( {0,3})(?=\$\$|\\\[)/u.exec(t)?.[0]:``;if(n===void 0)return;let r=vr(t.slice(n.length));if(r&&(e!==`block`||/^\s*(?:\n|$)/u.test(t.slice(n.length+r.raw.length))))return{type:`math-${e}`,...r,raw:n+r.raw}},renderer:e=>`<span data-math="${e.display?`block`:`inline`}"><code>${yr(e.raw)}</code></span>`}))},xr;async function Sr(t){let n=r(t,`[data-math]`);if(!n.length)return;let a;try{({default:a}=await(xr??=i(()=>import(`./math-renderer-CnlgS6FH.js`),__vite__mapDeps([0,1]))))}catch(t){for(let t of n)e(t,`mathError`,`Math unavailable`);throw t}for(let t of n){if(!t.isConnected)continue;let n=vr(t.textContent.trimStart());if(!n)throw Error(`Math outlet lost its delimited source.`);let r=t.cloneNode(!1);try{a.render(n.text,r,{displayMode:n.display,annotate:!0,trust:!1,throwOnError:!0,macros:{}})}catch(n){if(!(n instanceof a.ParseError))throw n;e(t,`mathError`,`Invalid or unsupported math`),t.setAttribute(`title`,String(n));continue}hr.sanitize(r,{IN_PLACE:!0,USE_PROFILES:{mathMl:!0},ADD_TAGS:[`span`,`semantics`,`annotation`,`none`],ADD_ATTR:[`class`,`style`],FORBID_ATTR:[`id`,`href`,`xlink:href`],ALLOW_DATA_ATTR:!1,ALLOW_ARIA_ATTR:!1}),t.replaceChildren(...r.childNodes)}}var Cr=Promise.resolve(),wr=class extends Error{};function Tr(e){let t=Cr.then(async()=>{let t;try{t=await fetch(`/render/mermaid`,{method:`POST`,credentials:`same-origin`,mode:`same-origin`,headers:{"content-type":`application/json`,accept:`image/svg+xml`},body:JSON.stringify({source:e})})}catch(e){throw new wr(`The diagram request did not complete.`,{cause:e})}if(!t.ok){let e=await t.json(),n=e.detail??e.title??`Diagram request failed (${t.status}).`;throw[408,429,503].includes(t.status)?new wr(n):Error(n)}if(t.headers.get(`content-type`)!==`image/svg+xml`)throw Error(`Diagram service did not return an SVG image.`);return t.text()});return Cr=t.then(()=>void 0,()=>void 0),t}function Er(t,r){e(t,`diagramError`,`Diagram failed to render`),t.setAttribute(`title`,String(r)),r instanceof wr&&t.nextElementSibling?.hasAttribute(`data-diagram-retry`)!==!0&&n.clone(t,`#diagram-retry`,{position:`afterend`})}async function Dr(e){let t=n(e,`code`);if(!t)throw Error(`Diagram outlet lost its source.`);let r;try{r=await Tr(t.textContent??``)}catch(t){e.isConnected&&Er(e,t);return}if(!e.isConnected)return;let i=n.clone(e,`#conversation-diagram`,{position:`beforebegin`}),a=n(i,`img`),o=n(i,`[data-diagram-source]`);if(!(a instanceof HTMLImageElement)||!(i instanceof HTMLElement)||!o)throw Error(`Diagram template is incomplete.`);o.textContent=t.textContent,a.setAttribute(`src`,`data:image/svg+xml;charset=utf-8,${encodeURIComponent(r)}`);try{await a.decode()}catch(t){i.remove(),Er(e,t);return}e.isConnected?(e.replaceWith(i),i.hidden=!1):i.remove()}t(document,`click`,`[data-diagram-retry]`,t=>{let n=t.target instanceof Element?t.target.closest(`[data-diagram-retry]`):null,r=n?.previousElementSibling;n&&r?.hasAttribute(`data-mermaid`)&&(n.remove(),e(r,`diagramError`,null),r.removeAttribute(`title`),Dr(r).catch(reportError))});async function Or(e){let t=r(e,`[data-mermaid]`);if(t.length){await Promise.resolve();for(let e of t)e.isConnected&&await Dr(e)}}var kr={renderer:{html:({text:e})=>e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`),image(e){return this.link({...e,type:`link`})},table(e){return`<figure>${Dt.prototype.table.call(this,e)}</figure>`},code(e){let t=Dt.prototype.code.call(this,e);return/^mermaid(?:\s|$)/iu.test(e.lang?.trim()??``)?`<figure data-mermaid>${t}</figure>`:t}}};function Ar(e,t){let n=new Mt(br,zt(),_r(t),kr),r=hr.sanitize(n.parse(e,{async:!1}),{RETURN_DOM_FRAGMENT:!0,ALLOWED_TAGS:`p.br.hr.h1.h2.h3.h4.h5.h6.blockquote.ul.ol.li.pre.code.em.strong.del.a.table.thead.tbody.tr.th.td.input.figure.span.section.sup`.split(`.`),ALLOWED_ATTR:[`href`,`title`,`start`,`align`,`type`,`checked`,`disabled`,`data-math`,`data-mermaid`,`id`,`aria-label`,`tabindex`],ALLOW_DATA_ATTR:!1,ALLOW_ARIA_ATTR:!1});return Sr(r).catch(reportError),Or(r).catch(reportError),r}async function jr(e){if(e.ok||e.headers.get(`content-type`)?.split(`;`)[0]?.trim()!==`application/problem+json`)return null;let{Validator:t}=await i(async()=>{let{Validator:e}=await import(`./src-BdHyjaXT.js`);return{Validator:e}},__vite__mapDeps([2,3,4,5])),n=t.assertProblemDetails(await e.json());return Object.assign(Error(n.detail??n.title,{cause:n}),{status:n.status})}async function Mr(e,t,n){if(!e.trim())throw Error(`Read address is empty.`);let r=new URL(e,location.href);if(![`http:`,`https:`].includes(r.protocol)||r.origin!==location.origin||r.username||r.password)throw Error(`Read address must be on this daemon's origin.`);let i=await o(t,n);n.throwIfAborted();let a=await fetch(r,{headers:i,signal:n,redirect:`error`,cache:`no-store`}),s=await jr(a);if(s)throw s;if(!a.ok)throw Error(`Read request failed (${a.status}).`);return a}async function Nr(e,t,n){return(await Mr(e,t,n)).text()}var Pr=Object.freeze({status:`aborted`});function E(e,t,n){function r(n,r){var i;Object.defineProperty(n,"_zod",{value:n._zod??{},enumerable:!1}),(i=n._zod).traits??(i.traits=new Set),n._zod.traits.add(e),t(n,r);for(let e in o.prototype)e in n||Object.defineProperty(n,e,{value:o.prototype[e].bind(n)});n._zod.constr=o,n._zod.def=r}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var Fr=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Ir={};function Lr(e){return e&&Object.assign(Ir,e),Ir}function Rr(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function zr(e,t){return typeof t==`bigint`?t.toString():t}function Br(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Vr(e){return e==null}function Hr(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Ur(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}function D(e,t,n){Object.defineProperty(e,t,{get(){{let r=n();return e[t]=r,r}},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Wr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Gr(e){return JSON.stringify(e)}var Kr=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function qr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Jr=Br(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function Yr(e){if(qr(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return qr(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}var Xr=new Set([`string`,`number`,`symbol`]);function Zr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Qr(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function O(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function $r(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}var ei={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function ti(e,t){let n={},r=e._zod.def;for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&(n[e]=r.shape[e])}return Qr(e,{...e._zod.def,shape:n,checks:[]})}function ni(e,t){let n={...e._zod.def.shape},r=e._zod.def;for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete n[e]}return Qr(e,{...e._zod.def,shape:n,checks:[]})}function ri(e,t){if(!Yr(t))throw Error(`Invalid input to extend: expected a plain object`);return Qr(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return Wr(this,`shape`,n),n},checks:[]})}function ii(e,t){return Qr(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Wr(this,`shape`,n),n},catchall:t._zod.def.catchall,checks:[]})}function ai(e,t,n){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return Qr(t,{...t._zod.def,shape:i,checks:[]})}function oi(e,t,n){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return Qr(t,{...t._zod.def,shape:i,checks:[]})}function si(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function ci(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function li(e){return typeof e==`string`?e:e?.message}function ui(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=li(e.inst?._zod.def?.error?.(e))??li(t?.error?.(e))??li(n.customError?.(e))??li(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function di(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function fi(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var pi=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,zr,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},mi=E(`$ZodError`,pi),hi=E(`$ZodError`,pi,{Parent:Error});function gi(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function _i(e,t){let n=t||function(e){return e.message},r={_errors:[]},i=e=>{for(let t of e.issues)if(t.code===`invalid_union`&&t.errors.length)t.errors.map(e=>i({issues:e}));else if(t.code===`invalid_key`)i({issues:t.issues});else if(t.code===`invalid_element`)i({issues:t.issues});else if(t.path.length===0)r._errors.push(n(t));else{let e=r,i=0;for(;i<t.path.length;){let r=t.path[i];i===t.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(n(t))):e[r]=e[r]||{_errors:[]},e=e[r],i++}}};return i(e),r}var vi=e=>(t,n,r,i)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Fr;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>ui(e,a,Lr())));throw Kr(t,i?.callee),t}return o.value},yi=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>ui(e,a,Lr())));throw Kr(t,i?.callee),t}return o.value},bi=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Fr;return a.issues.length?{success:!1,error:new(e??mi)(a.issues.map(e=>ui(e,i,Lr())))}:{success:!0,data:a.value}},xi=bi(hi),Si=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>ui(e,i,Lr())))}:{success:!0,data:a.value}},Ci=Si(hi),wi=/^[cC][^\s-]{8,}$/,Ti=/^[0-9a-z]+$/,Ei=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Di=/^[0-9a-vA-V]{20}$/,Oi=/^[A-Za-z0-9]{27}$/,ki=/^[a-zA-Z0-9_-]{21}$/,Ai=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ji=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Mi=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,Ni=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Pi=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function Fi(){return new RegExp(Pi,`u`)}var Ii=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Li=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Ri=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,zi=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Bi=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Vi=/^[A-Za-z0-9_-]*$/,Hi=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Ui=/^\+(?:[0-9]){6,14}[0-9]$/,Wi=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,Gi=RegExp(`^${Wi}$`);function Ki(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function qi(e){return RegExp(`^${Ki(e)}$`)}function Ji(e){let t=Ki({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-]\\d{2}:\\d{2})`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${Wi}T(?:${r})$`)}var Yi=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Xi=/^\d+$/,Zi=/^-?\d+(?:\.\d+)?/i,Qi=/true|false/i,$i=/null/i,ea=/^[^A-Z]*$/,ta=/^[^a-z]*$/,na=E(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),ra={number:`number`,bigint:`bigint`,object:`date`},ia=E(`$ZodCheckLessThan`,(e,t)=>{na.init(e,t);let n=ra[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),aa=E(`$ZodCheckGreaterThan`,(e,t)=>{na.init(e,t);let n=ra[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),oa=E(`$ZodCheckMultipleOf`,(e,t)=>{na.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):Ur(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),sa=E(`$ZodCheckNumberFormat`,(e,t)=>{na.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=ei[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=Xi)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inst:e})}}),ca=E(`$ZodCheckMaxLength`,(e,t)=>{var n;na.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Vr(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=di(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),la=E(`$ZodCheckMinLength`,(e,t)=>{var n;na.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Vr(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=di(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),ua=E(`$ZodCheckLengthEquals`,(e,t)=>{var n;na.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Vr(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=di(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),da=E(`$ZodCheckStringFormat`,(e,t)=>{var n,r;na.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),fa=E(`$ZodCheckRegex`,(e,t)=>{da.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),pa=E(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=ea,da.init(e,t)}),ma=E(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=ta,da.init(e,t)}),ha=E(`$ZodCheckIncludes`,(e,t)=>{na.init(e,t);let n=Zr(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),ga=E(`$ZodCheckStartsWith`,(e,t)=>{na.init(e,t);let n=RegExp(`^${Zr(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),_a=E(`$ZodCheckEndsWith`,(e,t)=>{na.init(e,t);let n=RegExp(`.*${Zr(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),va=E(`$ZodCheckOverwrite`,(e,t)=>{na.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),ya=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
86
|
+
`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(`
|
|
87
|
+
`))}},ba={major:4,minor:0,patch:0},k=E(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ba;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=si(e),i;for(let a of t){if(a._zod.def.when){if(!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new Fr;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=si(e,t))});else{if(e.issues.length===t)continue;r||=si(e,t)}}return i?i.then(()=>e):e};e._zod.run=(n,i)=>{let a=e._zod.parse(n,i);if(a instanceof Promise){if(i.async===!1)throw new Fr;return a.then(e=>t(e,r,i))}return t(a,r,i)}}e[`~standard`]={validate:t=>{try{let n=xi(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return Ci(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}}),xa=E(`$ZodString`,(e,t)=>{k.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Yi(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),A=E(`$ZodStringFormat`,(e,t)=>{da.init(e,t),xa.init(e,t)}),Sa=E(`$ZodGUID`,(e,t)=>{t.pattern??=ji,A.init(e,t)}),Ca=E(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=Mi(e)}else t.pattern??=Mi();A.init(e,t)}),wa=E(`$ZodEmail`,(e,t)=>{t.pattern??=Ni,A.init(e,t)}),Ta=E(`$ZodURL`,(e,t)=>{A.init(e,t),e._zod.check=n=>{try{let r=n.value,i=new URL(r),a=i.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:Hi.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),n.value=!r.endsWith(`/`)&&a.endsWith(`/`)?a.slice(0,-1):a;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Ea=E(`$ZodEmoji`,(e,t)=>{t.pattern??=Fi(),A.init(e,t)}),Da=E(`$ZodNanoID`,(e,t)=>{t.pattern??=ki,A.init(e,t)}),Oa=E(`$ZodCUID`,(e,t)=>{t.pattern??=wi,A.init(e,t)}),ka=E(`$ZodCUID2`,(e,t)=>{t.pattern??=Ti,A.init(e,t)}),Aa=E(`$ZodULID`,(e,t)=>{t.pattern??=Ei,A.init(e,t)}),ja=E(`$ZodXID`,(e,t)=>{t.pattern??=Di,A.init(e,t)}),Ma=E(`$ZodKSUID`,(e,t)=>{t.pattern??=Oi,A.init(e,t)}),Na=E(`$ZodISODateTime`,(e,t)=>{t.pattern??=Ji(t),A.init(e,t)}),Pa=E(`$ZodISODate`,(e,t)=>{t.pattern??=Gi,A.init(e,t)}),Fa=E(`$ZodISOTime`,(e,t)=>{t.pattern??=qi(t),A.init(e,t)}),Ia=E(`$ZodISODuration`,(e,t)=>{t.pattern??=Ai,A.init(e,t)}),La=E(`$ZodIPv4`,(e,t)=>{t.pattern??=Ii,A.init(e,t),e._zod.onattach.push(e=>{let t=e._zod.bag;t.format=`ipv4`})}),Ra=E(`$ZodIPv6`,(e,t)=>{t.pattern??=Li,A.init(e,t),e._zod.onattach.push(e=>{let t=e._zod.bag;t.format=`ipv6`}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),za=E(`$ZodCIDRv4`,(e,t)=>{t.pattern??=Ri,A.init(e,t)}),Ba=E(`$ZodCIDRv6`,(e,t)=>{t.pattern??=zi,A.init(e,t),e._zod.check=n=>{let[r,i]=n.value.split(`/`);try{if(!i)throw Error();let e=Number(i);if(`${e}`!==i||e<0||e>128)throw Error();new URL(`http://[${r}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function Va(e){if(e===``)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var Ha=E(`$ZodBase64`,(e,t)=>{t.pattern??=Bi,A.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding=`base64`}),e._zod.check=n=>{Va(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function Ua(e){if(!Vi.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Va(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var Wa=E(`$ZodBase64URL`,(e,t)=>{t.pattern??=Vi,A.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding=`base64url`}),e._zod.check=n=>{Ua(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Ga=E(`$ZodE164`,(e,t)=>{t.pattern??=Ui,A.init(e,t)});function Ka(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var qa=E(`$ZodJWT`,(e,t)=>{A.init(e,t),e._zod.check=n=>{Ka(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Ja=E(`$ZodNumber`,(e,t)=>{k.init(e,t),e._zod.pattern=e._zod.bag.pattern??Zi,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Ya=E(`$ZodNumber`,(e,t)=>{sa.init(e,t),Ja.init(e,t)}),Xa=E(`$ZodBoolean`,(e,t)=>{k.init(e,t),e._zod.pattern=Qi,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Za=E(`$ZodNull`,(e,t)=>{k.init(e,t),e._zod.pattern=$i,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),Qa=E(`$ZodUnknown`,(e,t)=>{k.init(e,t),e._zod.parse=e=>e}),$a=E(`$ZodNever`,(e,t)=>{k.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function eo(e,t,n){e.issues.length&&t.issues.push(...ci(n,e.issues)),t.value[n]=e.value}var to=E(`$ZodArray`,(e,t)=>{k.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>eo(t,n,e))):eo(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function no(e,t,n){e.issues.length&&t.issues.push(...ci(n,e.issues)),t.value[n]=e.value}function ro(e,t,n,r){e.issues.length?r[n]===void 0?n in r?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...ci(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}var io=E(`$ZodObject`,(e,t)=>{k.init(e,t);let n=Br(()=>{let e=Object.keys(t.shape);for(let n of e)if(!(t.shape[n]instanceof k))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=$r(t.shape);return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}});D(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=e=>{let t=new ya([`shape`,`payload`,`ctx`]),r=n.value,i=e=>{let t=Gr(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of r.keys)a[e]=`key_${o++}`;t.write(`const newResult = {}`);for(let e of r.keys)if(r.optionalKeys.has(e)){let n=a[e];t.write(`const ${n} = ${i(e)};`);let r=Gr(e);t.write(`
|
|
88
|
+
if (${n}.issues.length) {
|
|
89
|
+
if (input[${r}] === undefined) {
|
|
90
|
+
if (${r} in input) {
|
|
91
|
+
newResult[${r}] = undefined;
|
|
92
|
+
}
|
|
93
|
+
} else {
|
|
94
|
+
payload.issues = payload.issues.concat(
|
|
95
|
+
${n}.issues.map((iss) => ({
|
|
96
|
+
...iss,
|
|
97
|
+
path: iss.path ? [${r}, ...iss.path] : [${r}],
|
|
98
|
+
}))
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
} else if (${n}.value === undefined) {
|
|
102
|
+
if (${r} in input) newResult[${r}] = undefined;
|
|
103
|
+
} else {
|
|
104
|
+
newResult[${r}] = ${n}.value;
|
|
105
|
+
}
|
|
106
|
+
`)}else{let n=a[e];t.write(`const ${n} = ${i(e)};`),t.write(`
|
|
107
|
+
if (${n}.issues.length) payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
|
|
108
|
+
...iss,
|
|
109
|
+
path: iss.path ? [${Gr(e)}, ...iss.path] : [${Gr(e)}]
|
|
110
|
+
})));`),t.write(`newResult[${Gr(e)}] = ${n}.value`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},i,a=qr,o=!Ir.jitless,s=o&&Jr.value,c=t.catchall,l;e._zod.parse=(u,d)=>{l??=n.value;let f=u.value;if(!a(f))return u.issues.push({expected:`object`,code:`invalid_type`,input:f,inst:e}),u;let p=[];if(o&&s&&d?.async===!1&&d.jitless!==!0)i||=r(t.shape),u=i(u,d);else{u.value={};let e=l.shape;for(let t of l.keys){let n=e[t],r=n._zod.run({value:f[t],issues:[]},d),i=n._zod.optin===`optional`&&n._zod.optout===`optional`;r instanceof Promise?p.push(r.then(e=>i?ro(e,u,t,f):no(e,u,t))):i?ro(r,u,t,f):no(r,u,t)}}if(!c)return p.length?Promise.all(p).then(()=>u):u;let m=[],h=l.keySet,g=c._zod,ee=g.def.type;for(let e of Object.keys(f)){if(h.has(e))continue;if(ee===`never`){m.push(e);continue}let t=g.run({value:f[e],issues:[]},d);t instanceof Promise?p.push(t.then(t=>no(t,u,e))):no(t,u,e)}return m.length&&u.issues.push({code:`unrecognized_keys`,keys:m,input:f,inst:e}),p.length?Promise.all(p).then(()=>u):u}});function ao(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;return t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>ui(e,r,Lr())))}),t}var oo=E(`$ZodUnion`,(e,t)=>{k.init(e,t),D(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),D(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),D(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),D(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>Hr(e.source)).join(`|`)})$`)}}),e._zod.parse=(n,r)=>{let i=!1,a=[];for(let e of t.options){let t=e._zod.run({value:n.value,issues:[]},r);if(t instanceof Promise)a.push(t),i=!0;else{if(t.issues.length===0)return t;a.push(t)}}return i?Promise.all(a).then(t=>ao(t,n,e,r)):ao(a,n,e,r)}}),so=E(`$ZodIntersection`,(e,t)=>{k.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>lo(e,t,n)):lo(e,i,a)}});function co(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Yr(e)&&Yr(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=co(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=co(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function lo(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),si(e))return e;let r=co(t.value,n.value);if(!r.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}var uo=E(`$ZodRecord`,(e,t)=>{k.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Yr(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[];if(t.keyType._zod.values){let o=t.keyType._zod.values;n.value={};for(let e of o)if(typeof e==`string`||typeof e==`number`||typeof e==`symbol`){let o=t.valueType._zod.run({value:i[e],issues:[]},r);o instanceof Promise?a.push(o.then(t=>{t.issues.length&&n.issues.push(...ci(e,t.issues)),n.value[e]=t.value})):(o.issues.length&&n.issues.push(...ci(e,o.issues)),n.value[e]=o.value)}let s;for(let e in i)o.has(e)||(s??=[],s.push(e));s&&s.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:s})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`)continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){n.issues.push({origin:`record`,code:`invalid_key`,issues:s.issues.map(e=>ui(e,r,Lr())),input:o,path:[o],inst:e}),n.value[s.value]=s.value;continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...ci(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...ci(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),fo=E(`$ZodEnum`,(e,t)=>{k.init(e,t);let n=Rr(t.entries);e._zod.values=new Set(n),e._zod.pattern=RegExp(`^(${n.filter(e=>Xr.has(typeof e)).map(e=>typeof e==`string`?Zr(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,r)=>{let i=t.value;return e._zod.values.has(i)||t.issues.push({code:`invalid_value`,values:n,input:i,inst:e}),t}}),po=E(`$ZodLiteral`,(e,t)=>{k.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?Zr(e):e?e.toString():String(e)).join(`|`)})$`),e._zod.parse=(n,r)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:`invalid_value`,values:t.values,input:i,inst:e}),n}}),mo=E(`$ZodTransform`,(e,t)=>{k.init(e,t),e._zod.parse=(e,n)=>{let r=t.transform(e.value,e);if(n.async)return(r instanceof Promise?r:Promise.resolve(r)).then(t=>(e.value=t,e));if(r instanceof Promise)throw new Fr;return e.value=r,e}}),ho=E(`$ZodOptional`,(e,t)=>{k.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,D(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),D(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Hr(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>t.innerType._zod.optin===`optional`?t.innerType._zod.run(e,n):e.value===void 0?e:t.innerType._zod.run(e,n)}),go=E(`$ZodNullable`,(e,t)=>{k.init(e,t),D(e._zod,`optin`,()=>t.innerType._zod.optin),D(e._zod,`optout`,()=>t.innerType._zod.optout),D(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Hr(e.source)}|null)$`):void 0}),D(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),_o=E(`$ZodDefault`,(e,t)=>{k.init(e,t),e._zod.optin=`optional`,D(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>vo(e,t)):vo(r,t)}});function vo(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var yo=E(`$ZodPrefault`,(e,t)=>{k.init(e,t),e._zod.optin=`optional`,D(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),bo=E(`$ZodNonOptional`,(e,t)=>{k.init(e,t),D(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>xo(t,e)):xo(i,e)}});function xo(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var So=E(`$ZodCatch`,(e,t)=>{k.init(e,t),e._zod.optin=`optional`,D(e._zod,`optout`,()=>t.innerType._zod.optout),D(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>ui(e,n,Lr()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>ui(e,n,Lr()))},input:e.value}),e.issues=[]),e)}}),Co=E(`$ZodPipe`,(e,t)=>{k.init(e,t),D(e._zod,`values`,()=>t.in._zod.values),D(e._zod,`optin`,()=>t.in._zod.optin),D(e._zod,`optout`,()=>t.out._zod.optout),e._zod.parse=(e,n)=>{let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>wo(e,t,n)):wo(r,t,n)}});function wo(e,t,n){return si(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}var To=E(`$ZodReadonly`,(e,t)=>{k.init(e,t),D(e._zod,`propValues`,()=>t.innerType._zod.propValues),D(e._zod,`values`,()=>t.innerType._zod.values),D(e._zod,`optin`,()=>t.innerType._zod.optin),D(e._zod,`optout`,()=>t.innerType._zod.optout),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Eo):Eo(r)}});function Eo(e){return e.value=Object.freeze(e.value),e}var Do=E(`$ZodCustom`,(e,t)=>{na.init(e,t),k.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Oo(t,n,r,e));Oo(i,n,r,e)}});function Oo(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(fi(e))}}var ko=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==`object`&&`id`in n){if(this._idmap.has(n.id))throw Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function Ao(){return new ko}var jo=Ao();function Mo(e,t){return new e({type:`string`,...O(t)})}function No(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...O(t)})}function Po(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...O(t)})}function Fo(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...O(t)})}function Io(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...O(t)})}function Lo(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...O(t)})}function Ro(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...O(t)})}function zo(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...O(t)})}function Bo(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...O(t)})}function Vo(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...O(t)})}function Ho(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...O(t)})}function Uo(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...O(t)})}function Wo(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...O(t)})}function Go(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...O(t)})}function Ko(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...O(t)})}function qo(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...O(t)})}function Jo(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...O(t)})}function Yo(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...O(t)})}function Xo(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...O(t)})}function Zo(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...O(t)})}function Qo(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...O(t)})}function $o(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...O(t)})}function es(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...O(t)})}function ts(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...O(t)})}function ns(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...O(t)})}function rs(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...O(t)})}function is(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...O(t)})}function as(e,t){return new e({type:`number`,checks:[],...O(t)})}function os(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...O(t)})}function ss(e,t){return new e({type:`boolean`,...O(t)})}function cs(e,t){return new e({type:`null`,...O(t)})}function ls(e){return new e({type:`unknown`})}function us(e,t){return new e({type:`never`,...O(t)})}function ds(e,t){return new ia({check:`less_than`,...O(t),value:e,inclusive:!1})}function fs(e,t){return new ia({check:`less_than`,...O(t),value:e,inclusive:!0})}function ps(e,t){return new aa({check:`greater_than`,...O(t),value:e,inclusive:!1})}function ms(e,t){return new aa({check:`greater_than`,...O(t),value:e,inclusive:!0})}function hs(e,t){return new oa({check:`multiple_of`,...O(t),value:e})}function gs(e,t){return new ca({check:`max_length`,...O(t),maximum:e})}function _s(e,t){return new la({check:`min_length`,...O(t),minimum:e})}function vs(e,t){return new ua({check:`length_equals`,...O(t),length:e})}function ys(e,t){return new fa({check:`string_format`,format:`regex`,...O(t),pattern:e})}function bs(e){return new pa({check:`string_format`,format:`lowercase`,...O(e)})}function xs(e){return new ma({check:`string_format`,format:`uppercase`,...O(e)})}function Ss(e,t){return new ha({check:`string_format`,format:`includes`,...O(t),includes:e})}function Cs(e,t){return new ga({check:`string_format`,format:`starts_with`,...O(t),prefix:e})}function ws(e,t){return new _a({check:`string_format`,format:`ends_with`,...O(t),suffix:e})}function Ts(e){return new va({check:`overwrite`,tx:e})}function Es(e){return Ts(t=>t.normalize(e))}function Ds(){return Ts(e=>e.trim())}function Os(){return Ts(e=>e.toLowerCase())}function ks(){return Ts(e=>e.toUpperCase())}function As(e,t,n){return new e({type:`array`,element:t,...O(n)})}function js(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...O(n)})}Lr({jitless:!0});var j={initialize:`initialize`,auth_login:`auth/login`,providers_list:`providers/list`,providers_set:`providers/set`,providers_disable:`providers/disable`,session_new:`session/new`,session_set_config_option:`session/set_config_option`,session_prompt:`session/prompt`,session_cancel:`session/cancel`,mcp_message:`mcp/message`,session_list:`session/list`,session_delete:`session/delete`,session_fork:`session/fork`,session_archive:`session/archive`,session_unarchive:`session/unarchive`,session_status:`session/status`,session_set_title:`session/set_title`,session_resume:`session/resume`,session_close:`session/close`,tool_call_cancel:`tool_call/cancel`,terminal_cancel:`terminal/cancel`,auth_logout:`auth/logout`,auth_status:`auth/status`},Ms={session_request_permission:`session/request_permission`,session_update:`session/update`,mcp_message:`mcp/message`,elicitation_create:`elicitation/create`,elicitation_complete:`elicitation/complete`,auth_status_update:`auth/status_update`},Ns={cancel_request:`$/cancel_request`},Ps=E(`ZodISODateTime`,(e,t)=>{Na.init(e,t),P.init(e,t)});function Fs(e){return ts(Ps,e)}var Is=E(`ZodISODate`,(e,t)=>{Pa.init(e,t),P.init(e,t)});function Ls(e){return ns(Is,e)}var Rs=E(`ZodISOTime`,(e,t)=>{Fa.init(e,t),P.init(e,t)});function zs(e){return rs(Rs,e)}var Bs=E(`ZodISODuration`,(e,t)=>{Ia.init(e,t),P.init(e,t)});function Vs(e){return is(Bs,e)}var Hs=(e,t)=>{mi.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>_i(e,t)},flatten:{value:t=>gi(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get(){return e.issues.length===0}}})};E(`ZodError`,Hs);var Us=E(`ZodError`,Hs,{Parent:Error}),Ws=vi(Us),Gs=yi(Us),Ks=bi(Us),qs=Si(Us),M=E(`ZodType`,(e,t)=>(k.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),e.clone=(t,n)=>Qr(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>Ws(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Ks(e,t,n),e.parseAsync=async(t,n)=>Gs(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>qs(e,t,n),e.spa=e.safeParseAsync,e.refine=(t,n)=>e.check(nl(t,n)),e.superRefine=t=>e.check(rl(t)),e.overwrite=t=>e.check(Ts(t)),e.optional=()=>zc(e),e.nullable=()=>Vc(e),e.nullish=()=>zc(Vc(e)),e.nonoptional=t=>qc(e,t),e.array=()=>L(e),e.or=t=>z([e,t]),e.and=t=>jc(e,t),e.transform=t=>Zc(e,Lc(t)),e.default=t=>Uc(e,t),e.prefault=t=>Gc(e,t),e.catch=t=>Yc(e,t),e.pipe=t=>Zc(e,t),e.readonly=()=>$c(e),e.describe=t=>{let n=e.clone();return jo.add(n,{description:t}),n},Object.defineProperty(e,"description",{get(){return jo.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return jo.get(e);let n=e.clone();return jo.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Js=E(`_ZodString`,(e,t)=>{xa.init(e,t),M.init(e,t);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(ys(...t)),e.includes=(...t)=>e.check(Ss(...t)),e.startsWith=(...t)=>e.check(Cs(...t)),e.endsWith=(...t)=>e.check(ws(...t)),e.min=(...t)=>e.check(_s(...t)),e.max=(...t)=>e.check(gs(...t)),e.length=(...t)=>e.check(vs(...t)),e.nonempty=(...t)=>e.check(_s(1,...t)),e.lowercase=t=>e.check(bs(t)),e.uppercase=t=>e.check(xs(t)),e.trim=()=>e.check(Ds()),e.normalize=(...t)=>e.check(Es(...t)),e.toLowerCase=()=>e.check(Os()),e.toUpperCase=()=>e.check(ks())}),Ys=E(`ZodString`,(e,t)=>{xa.init(e,t),Js.init(e,t),e.email=t=>e.check(No(Xs,t)),e.url=t=>e.check(zo($s,t)),e.jwt=t=>e.check(es(hc,t)),e.emoji=t=>e.check(Bo(tc,t)),e.guid=t=>e.check(Po(Zs,t)),e.uuid=t=>e.check(Fo(Qs,t)),e.uuidv4=t=>e.check(Io(Qs,t)),e.uuidv6=t=>e.check(Lo(Qs,t)),e.uuidv7=t=>e.check(Ro(Qs,t)),e.nanoid=t=>e.check(Vo(nc,t)),e.guid=t=>e.check(Po(Zs,t)),e.cuid=t=>e.check(Ho(rc,t)),e.cuid2=t=>e.check(Uo(ic,t)),e.ulid=t=>e.check(Wo(ac,t)),e.base64=t=>e.check(Zo(fc,t)),e.base64url=t=>e.check(Qo(pc,t)),e.xid=t=>e.check(Go(oc,t)),e.ksuid=t=>e.check(Ko(sc,t)),e.ipv4=t=>e.check(qo(cc,t)),e.ipv6=t=>e.check(Jo(lc,t)),e.cidrv4=t=>e.check(Yo(uc,t)),e.cidrv6=t=>e.check(Xo(dc,t)),e.e164=t=>e.check($o(mc,t)),e.datetime=t=>e.check(Fs(t)),e.date=t=>e.check(Ls(t)),e.time=t=>e.check(zs(t)),e.duration=t=>e.check(Vs(t))});function N(e){return Mo(Ys,e)}var P=E(`ZodStringFormat`,(e,t)=>{A.init(e,t),Js.init(e,t)}),Xs=E(`ZodEmail`,(e,t)=>{wa.init(e,t),P.init(e,t)}),Zs=E(`ZodGUID`,(e,t)=>{Sa.init(e,t),P.init(e,t)}),Qs=E(`ZodUUID`,(e,t)=>{Ca.init(e,t),P.init(e,t)}),$s=E(`ZodURL`,(e,t)=>{Ta.init(e,t),P.init(e,t)});function ec(e){return zo($s,e)}var tc=E(`ZodEmoji`,(e,t)=>{Ea.init(e,t),P.init(e,t)}),nc=E(`ZodNanoID`,(e,t)=>{Da.init(e,t),P.init(e,t)}),rc=E(`ZodCUID`,(e,t)=>{Oa.init(e,t),P.init(e,t)}),ic=E(`ZodCUID2`,(e,t)=>{ka.init(e,t),P.init(e,t)}),ac=E(`ZodULID`,(e,t)=>{Aa.init(e,t),P.init(e,t)}),oc=E(`ZodXID`,(e,t)=>{ja.init(e,t),P.init(e,t)}),sc=E(`ZodKSUID`,(e,t)=>{Ma.init(e,t),P.init(e,t)}),cc=E(`ZodIPv4`,(e,t)=>{La.init(e,t),P.init(e,t)}),lc=E(`ZodIPv6`,(e,t)=>{Ra.init(e,t),P.init(e,t)}),uc=E(`ZodCIDRv4`,(e,t)=>{za.init(e,t),P.init(e,t)}),dc=E(`ZodCIDRv6`,(e,t)=>{Ba.init(e,t),P.init(e,t)}),fc=E(`ZodBase64`,(e,t)=>{Ha.init(e,t),P.init(e,t)}),pc=E(`ZodBase64URL`,(e,t)=>{Wa.init(e,t),P.init(e,t)}),mc=E(`ZodE164`,(e,t)=>{Ga.init(e,t),P.init(e,t)}),hc=E(`ZodJWT`,(e,t)=>{qa.init(e,t),P.init(e,t)}),gc=E(`ZodNumber`,(e,t)=>{Ja.init(e,t),M.init(e,t),e.gt=(t,n)=>e.check(ps(t,n)),e.gte=(t,n)=>e.check(ms(t,n)),e.min=(t,n)=>e.check(ms(t,n)),e.lt=(t,n)=>e.check(ds(t,n)),e.lte=(t,n)=>e.check(fs(t,n)),e.max=(t,n)=>e.check(fs(t,n)),e.int=t=>e.check(yc(t)),e.safe=t=>e.check(yc(t)),e.positive=t=>e.check(ps(0,t)),e.nonnegative=t=>e.check(ms(0,t)),e.negative=t=>e.check(ds(0,t)),e.nonpositive=t=>e.check(fs(0,t)),e.multipleOf=(t,n)=>e.check(hs(t,n)),e.step=(t,n)=>e.check(hs(t,n)),e.finite=()=>e;let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function _c(e){return as(gc,e)}var vc=E(`ZodNumberFormat`,(e,t)=>{Ya.init(e,t),gc.init(e,t)});function yc(e){return os(vc,e)}var bc=E(`ZodBoolean`,(e,t)=>{Xa.init(e,t),M.init(e,t)});function F(e){return ss(bc,e)}var xc=E(`ZodNull`,(e,t)=>{Za.init(e,t),M.init(e,t)});function Sc(e){return cs(xc,e)}var Cc=E(`ZodUnknown`,(e,t)=>{Qa.init(e,t),M.init(e,t)});function I(){return ls(Cc)}var wc=E(`ZodNever`,(e,t)=>{$a.init(e,t),M.init(e,t)});function Tc(e){return us(wc,e)}var Ec=E(`ZodArray`,(e,t)=>{to.init(e,t),M.init(e,t),e.element=t.element,e.min=(t,n)=>e.check(_s(t,n)),e.nonempty=t=>e.check(_s(1,t)),e.max=(t,n)=>e.check(gs(t,n)),e.length=(t,n)=>e.check(vs(t,n)),e.unwrap=()=>e.element});function L(e,t){return As(Ec,e,t)}var Dc=E(`ZodObject`,(e,t)=>{io.init(e,t),M.init(e,t),D(e,`shape`,()=>t.shape),e.keyof=()=>Pc(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:I()}),e.loose=()=>e.clone({...e._zod.def,catchall:I()}),e.strict=()=>e.clone({...e._zod.def,catchall:Tc()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>ri(e,t),e.merge=t=>ii(e,t),e.pick=t=>ti(e,t),e.omit=t=>ni(e,t),e.partial=(...t)=>ai(Rc,e,t[0]),e.required=(...t)=>oi(Kc,e,t[0])});function R(e,t){return new Dc({type:`object`,get shape(){return Wr(this,`shape`,{...e}),this.shape},...O(t)})}function Oc(e,t){return new Dc({type:`object`,get shape(){return Wr(this,`shape`,{...e}),this.shape},catchall:I(),...O(t)})}var kc=E(`ZodUnion`,(e,t)=>{oo.init(e,t),M.init(e,t),e.options=t.options});function z(e,t){return new kc({type:`union`,options:e,...O(t)})}var Ac=E(`ZodIntersection`,(e,t)=>{so.init(e,t),M.init(e,t)});function jc(e,t){return new Ac({type:`intersection`,left:e,right:t})}var Mc=E(`ZodRecord`,(e,t)=>{uo.init(e,t),M.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function B(e,t,n){return new Mc({type:`record`,keyType:e,valueType:t,...O(n)})}var Nc=E(`ZodEnum`,(e,t)=>{fo.init(e,t),M.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Nc({...t,checks:[],...O(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Nc({...t,checks:[],...O(r),entries:i})}});function Pc(e,t){return new Nc({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...O(t)})}var Fc=E(`ZodLiteral`,(e,t)=>{po.init(e,t),M.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function V(e,t){return new Fc({type:`literal`,values:Array.isArray(e)?e:[e],...O(t)})}var Ic=E(`ZodTransform`,(e,t)=>{mo.init(e,t),M.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=r=>{if(typeof r==`string`)n.issues.push(fi(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,t.continue??=!0,n.issues.push(fi(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Lc(e){return new Ic({type:`transform`,transform:e})}var Rc=E(`ZodOptional`,(e,t)=>{ho.init(e,t),M.init(e,t),e.unwrap=()=>e._zod.def.innerType});function zc(e){return new Rc({type:`optional`,innerType:e})}var Bc=E(`ZodNullable`,(e,t)=>{go.init(e,t),M.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Vc(e){return new Bc({type:`nullable`,innerType:e})}var Hc=E(`ZodDefault`,(e,t)=>{_o.init(e,t),M.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Uc(e,t){return new Hc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}var Wc=E(`ZodPrefault`,(e,t)=>{yo.init(e,t),M.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Gc(e,t){return new Wc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}var Kc=E(`ZodNonOptional`,(e,t)=>{bo.init(e,t),M.init(e,t),e.unwrap=()=>e._zod.def.innerType});function qc(e,t){return new Kc({type:`nonoptional`,innerType:e,...O(t)})}var Jc=E(`ZodCatch`,(e,t)=>{So.init(e,t),M.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Yc(e,t){return new Jc({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var Xc=E(`ZodPipe`,(e,t)=>{Co.init(e,t),M.init(e,t),e.in=t.in,e.out=t.out});function Zc(e,t){return new Xc({type:`pipe`,in:e,out:t})}var Qc=E(`ZodReadonly`,(e,t)=>{To.init(e,t),M.init(e,t)});function $c(e){return new Qc({type:`readonly`,innerType:e})}var el=E(`ZodCustom`,(e,t)=>{Do.init(e,t),M.init(e,t)});function tl(e){let t=new na({check:`custom`});return t._zod.check=e,t}function nl(e,t={}){return js(el,e,t)}function rl(e){let t=tl(n=>(n.addIssue=e=>{if(typeof e==`string`)n.issues.push(fi(e,n.value,t._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=n.value,r.inst??=t,r.continue??=!t._zod.def.abort,n.issues.push(fi(r))}},e(n.value,n)));return t}function il(e,t){return Zc(Lc(e),t)}var al=Symbol(`skippedItem`);function H(e,t){return e.catch(t)}function ol(e,t){let n=e.catch(t);return I().transform((e,t)=>e===void 0?(t.addIssue({code:`custom`,message:`Required value is missing`}),Pr):n.parse(e))}function sl(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e[t];return typeof n==`string`?n:void 0}function U(e,t,n){return e.superRefine((e,r)=>{let i=sl(e,t);i!==void 0&&n.includes(i)&&r.addIssue({code:`custom`,path:[t],message:`${t} ${JSON.stringify(i)} is reserved by a known variant, but the value does not match that variant's schema`})})}function W(e,t,n){return I().transform((r,i)=>{let a=e.safeParse(r);if(!a.success){for(let e of a.error.issues)i.addIssue({...e,input:r});return Pr}let o=a.data,s=sl(r,t);if(s!==void 0&&!n.includes(s)){let e=r;for(let[t,n]of Object.entries(e))t!==`__proto__`&&(Object.hasOwn(o,t)||(o[t]=n))}return o})}function cl(e,t){return il(e=>{if(typeof e!=`object`||!e||Array.isArray(e))return e;let n=e,r=n[t];if(r==null||typeof r==`string`)return e;let i={...n};return delete i[t],i},e)}function G(e){return L(e.catch(al)).transform(e=>e.filter(e=>e!==al))}function K(e,t){return il(e=>e===null?t():e,e)}function q(){return _c().refine(Number.isInteger,{error:`Invalid input: expected int, received number`})}function ll(e,t){if(e.length!==t.length)throw Error(`exactlyOneByRequiredKeys: options/keys length mismatch`);let n=t.map(e=>e.map(e=>`\`${e}\``).join(` + `)).join(` or `);return I().transform((r,i)=>{if(typeof r!=`object`||!r||Array.isArray(r))return i.addIssue({code:`invalid_type`,expected:`object`,input:r}),Pr;let a=r,o=t.flatMap((e,t)=>e.every(e=>Object.hasOwn(a,e)&&a[e]!==void 0)?[t]:[]);if(o.length!==1)return i.addIssue({code:`custom`,message:`Expected exactly one of ${n}, found ${o.length}`}),Pr;let s=e[o[0]].safeParse(r);if(!s.success){for(let e of s.error.issues)i.addIssue({...e,input:r});return Pr}return s.data})}var ul=z([q(),N()]),J=N(),dl=N(),fl=z([V(`read`),V(`edit`),V(`delete`),V(`move`),V(`search`),V(`execute`),V(`think`),V(`fetch`),V(`switch_mode`),V(`other`),N()]),pl=z([V(`pending`),V(`in_progress`),V(`paused`),V(`completed`),V(`failed`),V(`cancelled`),N()]),ml=R({audience:H(G(z([V(`assistant`),V(`user`),N()])).nullish(),()=>void 0),lastModified:H(N().nullish(),()=>void 0),priority:H(_c().gte(0).lte(1).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),hl=R({text:N(),annotations:H(ml.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),gl=N(),_l=R({data:N(),mimeType:gl,uri:H(ec().nullish(),()=>void 0),annotations:H(ml.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),vl=R({data:N(),mimeType:gl,annotations:H(ml.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),yl=z([V(`light`),V(`dark`),N()]),bl=R({src:ec(),mimeType:H(gl.nullish(),()=>void 0),sizes:H(G(N()).nullish(),()=>void 0),theme:H(yl.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),xl=R({name:N(),uri:ec(),title:H(N().nullish(),()=>void 0),description:H(N().nullish(),()=>void 0),icons:H(G(bl).nullish(),()=>void 0),mimeType:H(gl.nullish(),()=>void 0),size:H(q().gte(0).nullish(),()=>void 0),annotations:H(ml.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Sl=R({resource:z([R({text:N(),uri:ec(),mimeType:H(gl.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),R({blob:N(),uri:ec(),mimeType:H(gl.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)})]),annotations:H(ml.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Cl=W(z([hl.and(R({type:V(`text`)})),_l.and(R({type:V(`image`)})),vl.and(R({type:V(`audio`)})),xl.and(R({type:V(`resource_link`)})),Sl.and(R({type:V(`resource`)})),U(R({type:N()}),`type`,[`audio`,`image`,`resource`,`resource_link`,`text`])]),`type`,[`audio`,`image`,`resource`,`resource_link`,`text`]),wl=R({content:Cl,_meta:H(B(N(),I()).nullish(),()=>void 0)}),Tl=z([V(`text`),V(`binary`),V(`directory`),V(`symlink`),N()]),El=N(),Dl=R({path:El}),Ol=R({oldPath:El,path:El}),kl=W(jc(z([Dl.and(R({operation:V(`add`)})),Dl.and(R({operation:V(`delete`)})),Dl.and(R({operation:V(`modify`)})),Ol.and(R({operation:V(`move`)})),Ol.and(R({operation:V(`copy`)})),U(R({operation:N()}),`operation`,[`add`,`copy`,`delete`,`modify`,`move`])]),R({fileType:H(Tl.nullish(),()=>void 0),mimeType:H(gl.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)})),`operation`,[`add`,`copy`,`delete`,`modify`,`move`]),Al=R({format:z([V(`git_patch`),N()]),text:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),jl=R({changes:G(kl),patch:H(Al.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Ml=N(),Nl=R({terminalId:Ml,_meta:H(B(N(),I()).nullish(),()=>void 0)}),Pl=W(z([wl.and(R({type:V(`content`)})),jl.and(R({type:V(`diff`)})),Nl.and(R({type:V(`terminal`)})),U(R({type:N()}),`type`,[`content`,`diff`,`terminal`])]),`type`,[`content`,`diff`,`terminal`]),Fl=R({path:El,line:H(yc().gte(1).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Il=R({cancel:H(R({_meta:H(B(N(),I()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Ll=R({toolCallId:dl,name:H(N().nullish(),()=>void 0),title:H(N().nullish(),()=>void 0),kind:H(fl.nullish(),()=>void 0),status:H(pl.nullish(),()=>void 0),content:H(G(Pl).nullish(),()=>void 0),locations:H(G(Fl).nullish(),()=>void 0),rawInput:H(I().optional(),()=>void 0),rawOutput:H(I().optional(),()=>void 0),capabilities:H(Il.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Rl=R({toolCall:Ll,_meta:H(B(N(),I()).nullish(),()=>void 0)}),zl=R({command:N(),cwd:El,toolCallId:H(dl.nullish(),()=>void 0),terminalId:H(Ml.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Bl=W(z([Rl.and(R({type:V(`tool_call`)})),zl.and(R({type:V(`command`)})),U(R({type:N()}),`type`,[`command`,`tool_call`])]),`type`,[`command`,`tool_call`]),Vl=N(),Hl=z([V(`allow_once`),V(`allow_always`),V(`reject_once`),V(`reject_always`),N()]),Ul=R({optionId:Vl,name:N(),kind:Hl,_meta:H(B(N(),I()).nullish(),()=>void 0)}),Wl=R({sessionId:J,title:N(),description:H(N().nullish(),()=>void 0),subject:Bl.nullish(),options:L(Ul).min(1),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Gl=R({sessionId:J,toolCallId:H(dl.nullish(),()=>void 0)}),Kl=R({requestId:ul}),ql=V(`object`),Jl=z([V(`email`),V(`uri`),V(`date`),V(`date-time`),N()]),Yl=R({const:N(),title:N(),description:H(N().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Xl=R({title:H(N().nullish(),()=>void 0),description:H(N().nullish(),()=>void 0),minLength:yc().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),maxLength:yc().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),pattern:N().nullish(),format:Jl.nullish(),default:H(N().nullish(),()=>void 0),enum:L(N()).min(1).nullish(),oneOf:L(Yl).min(1).nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Zl=R({title:H(N().nullish(),()=>void 0),description:H(N().nullish(),()=>void 0),minimum:_c().nullish(),maximum:_c().nullish(),default:H(_c().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Ql=R({title:H(N().nullish(),()=>void 0),description:H(N().nullish(),()=>void 0),minimum:q().nullish(),maximum:q().nullish(),default:H(q().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),$l=R({title:H(N().nullish(),()=>void 0),description:H(N().nullish(),()=>void 0),default:H(F().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),eu=R({enum:L(N()).min(1),_meta:H(B(N(),I()).nullish(),()=>void 0)}),tu=R({anyOf:L(Yl).min(1),_meta:H(B(N(),I()).nullish(),()=>void 0)}),nu=W(z([eu.and(R({type:V(`string`)})),U(R({type:N()}),`type`,[`string`]),tu]),`type`,[`string`]),ru=R({title:H(N().nullish(),()=>void 0),description:H(N().nullish(),()=>void 0),minItems:q().gte(0).nullish(),maxItems:q().gte(0).nullish(),items:nu,default:H(G(N()).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),iu=W(z([Xl.and(R({type:V(`string`)})),Zl.and(R({type:V(`number`)})),Ql.and(R({type:V(`integer`)})),$l.and(R({type:V(`boolean`)})),ru.and(R({type:V(`array`)})),U(R({type:N()}),`type`,[`array`,`boolean`,`integer`,`number`,`string`])]),`type`,[`array`,`boolean`,`integer`,`number`,`string`]),au=R({type:ql,title:H(N().nullish(),()=>void 0),properties:B(N(),iu),required:L(N()).nullish(),description:H(N().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),ou=jc(ll([Gl,Kl],[[`sessionId`],[`requestId`]]),R({requestedSchema:au})),su=N(),cu=jc(ll([Gl,Kl],[[`sessionId`],[`requestId`]]),R({elicitationId:su,url:ec()})),lu=W(jc(z([ou.and(R({mode:V(`form`)})),cu.and(R({mode:V(`url`)})),U(jc(ll([Gl,Kl],[[`sessionId`],[`requestId`]]),R({mode:N()})),`mode`,[`form`,`url`])]),R({message:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)})),`mode`,[`form`,`url`]),uu=N(),du=N(),fu=R({serverId:uu,requestId:du,method:N(),params:B(N(),I()).nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),pu=I();R({id:ul,method:N(),params:z([Wl,lu,fu,pu]).nullish()});var mu=yc().gte(0).lte(65535),hu=R({name:N(),title:H(N().nullish(),()=>void 0),version:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),gu=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),_u=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),vu=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),yu=R({image:H(gu.nullish(),()=>void 0),audio:H(_u.nullish(),()=>void 0),embeddedContext:H(vu.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),bu=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),xu=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Su=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Cu=R({stdio:H(bu.nullish(),()=>void 0),http:H(xu.nullish(),()=>void 0),acp:H(Su.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),wu=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Tu=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Eu=R({mode:H(R({override:H(R({_meta:H(B(N(),I()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Du=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Ou=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),ku=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Au=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),ju=R({prompt:H(yu.nullish(),()=>void 0),mcp:H(Cu.nullish(),()=>void 0),delete:H(wu.nullish(),()=>void 0),additionalDirectories:H(Tu.nullish(),()=>void 0),systemPrompt:H(Eu.nullish(),()=>void 0),fork:H(Du.nullish(),()=>void 0),archive:H(Ou.nullish(),()=>void 0),status:H(ku.nullish(),()=>void 0),title:H(Au.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Mu=R({status:H(R({_meta:H(B(N(),I()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Nu=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Pu=R({session:H(ju.nullish(),()=>void 0),auth:H(Mu.nullish(),()=>void 0),providers:H(Nu.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Fu=N(),Iu=R({name:N(),value:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Lu=R({methodId:Fu,name:N(),description:H(N().nullish(),()=>void 0),args:K(L(N()),()=>[]).optional(),env:K(L(Iu),()=>[]).optional(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Ru=R({methodId:Fu,name:N(),description:H(N().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),zu=W(z([Lu.and(R({type:V(`terminal`)})),Ru.and(R({type:V(`agent`)})),U(R({type:N(),methodId:Fu,name:N()}),`type`,[`agent`,`terminal`])]),`type`,[`agent`,`terminal`]),Bu=R({protocolVersion:mu,info:hu,capabilities:H(Pu.optional().default({}),()=>({})),authMethods:H(G(zu).optional(),()=>[]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Vu=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Hu=N(),Uu=z([V(`anthropic`),V(`openai`),V(`azure`),V(`vertex`),V(`bedrock`),N()]),Wu=R({apiType:Uu,baseUrl:ec(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Gu=R({providers:L(R({providerId:Hu,supported:ol(G(Uu),()=>[]),required:F(),current:Wu.nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)})),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Ku=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),qu=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Ju=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Yu=z([V(`authenticated`),V(`unauthenticated`),V(`not_required`),V(`unknown`),N()]),Xu=R({label:N(),active:H(F().nullish(),()=>void 0),name:H(N().nullish(),()=>void 0),email:H(N().nullish(),()=>void 0),organization:H(N().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Zu=R({state:Yu,accounts:H(G(Xu).optional(),()=>[]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Qu=N(),$u=z([V(`mode`),V(`model`),V(`model_config`),V(`thought_level`),N()]),ed=N(),td=R({value:ed,name:N(),description:H(N().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),nd=R({groupId:N(),name:N(),options:ol(G(td),()=>[]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),rd=R({currentValue:ed,options:z([L(td).min(1),L(nd).min(1)])}),id=R({currentValue:F()}),ad=W(jc(z([rd.and(R({type:V(`select`)})),id.and(R({type:V(`boolean`)})),U(R({type:N()}),`type`,[`boolean`,`select`])]),R({configId:Qu,name:N(),description:H(N().nullish(),()=>void 0),category:H($u.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)})),`type`,[`boolean`,`select`]),od=R({hint:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),sd=W(z([od.and(R({type:V(`text`)})),U(R({type:N()}),`type`,[`text`])]),`type`,[`text`]),cd=R({name:N(),description:N(),input:H(sd.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),ld=W(z([cd.and(R({type:V(`command`)})),U(R({type:N(),name:N(),description:N()}),`type`,[`command`])]),`type`,[`command`]),ud=R({sessionId:J,configOptions:H(G(ad).optional(),()=>[]),availableCommands:H(G(ld).optional(),()=>[]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),dd=R({sessionId:J,cwd:El,additionalDirectories:K(L(El),()=>[]).optional(),title:H(N().nullish(),()=>void 0),updatedAt:H(Fs({offset:!0}).nullish(),()=>void 0),archived:H(F().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),fd=N(),pd=R({sessions:ol(G(dd),()=>[]),nextCursor:fd.nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),md=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),hd=R({sessionId:J,configOptions:H(G(ad).optional(),()=>[]),availableCommands:H(G(ld).optional(),()=>[]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),gd=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),_d=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),vd=z([V(`open`),V(`saved`),N()]),yd=R({terminalId:Ml,_meta:H(B(N(),I()).nullish(),()=>void 0)}),bd=R({toolCallId:dl,_meta:H(B(N(),I()).nullish(),()=>void 0)}),xd=R({sessionId:J,_meta:H(B(N(),I()).nullish(),()=>void 0)}),Sd=W(z([yd.and(R({type:V(`terminal`)})),bd.and(R({type:V(`tool_call`)})),xd.and(R({type:V(`subagent`)})),U(R({type:N()}),`type`,[`subagent`,`terminal`,`tool_call`])]),`type`,[`subagent`,`terminal`,`tool_call`]),Cd=R({background:H(L(Sd).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),wd=z([V(-32700),V(-32600),V(-32601),V(-32602),V(-32603),V(-32800),V(-32e3),V(-32002),V(-32022),yc().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`})]),Td=z([R({requested:mu,supported:L(mu),_meta:H(B(N(),I()).nullish(),()=>void 0)}),R({sessionId:J,_meta:H(B(N(),I()).nullish(),()=>void 0)}),I()]),Ed=R({code:wd,message:N(),data:H(Td.nullish(),()=>void 0)}),Dd=R({error:H(Ed.nullish(),()=>void 0)}),Od=R({totalTokens:q().gte(0),inputTokens:q().gte(0),outputTokens:q().gte(0),thoughtTokens:H(q().gte(0).nullish(),()=>void 0),cachedReadTokens:H(q().gte(0).nullish(),()=>void 0),cachedWriteTokens:H(q().gte(0).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),kd=cl(W(jc(z([R({stopReason:V(`end_turn`)}),R({stopReason:V(`max_tokens`)}),R({stopReason:V(`max_turn_requests`)}),R({stopReason:V(`refusal`)}),R({stopReason:V(`cancelled`)}),Dd.and(R({stopReason:V(`error`)})),U(R({stopReason:N()}),`stopReason`,[`cancelled`,`end_turn`,`error`,`max_tokens`,`max_turn_requests`,`refusal`]),R({stopReason:Sc().optional()})]),R({usage:H(Od.nullish(),()=>void 0),background:H(L(Sd).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0),stopReason:H(N().nullish(),()=>void 0)})),`stopReason`,[`cancelled`,`end_turn`,`error`,`max_tokens`,`max_turn_requests`,`refusal`]),`stopReason`),Ad=R({background:H(L(Sd).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),jd=R({background:H(L(Sd).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Md=W(z([Cd.and(R({state:V(`running`)})),kd.and(R({state:V(`idle`)})),Ad.and(R({state:V(`requires_action`)})),jd.and(R({state:V(`unknown`)})),U(R({state:N()}),`state`,[`idle`,`requires_action`,`running`,`unknown`])]),`state`,[`idle`,`requires_action`,`running`,`unknown`]),Nd=R({status:vd,state:H(Md.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Pd=R({title:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Fd=R({configOptions:H(G(ad).optional(),()=>[]),availableCommands:H(G(ld).optional(),()=>[]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Id=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Ld=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Rd=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),zd=R({configOptions:G(ad),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Bd=N(),Vd=R({messageId:Bd,_meta:H(B(N(),I()).nullish(),()=>void 0)}),Hd=I();z([R({id:ul,result:z([Bu,Vu,Gu,Ku,qu,Ju,Zu,ud,pd,md,hd,gd,_d,Nd,Pd,Fd,Id,Ld,Rd,zd,Vd,Hd])}),R({id:z([q(),N()]).nullable(),error:Ed})]);var Ud=R({messageId:Bd,content:Cl,_meta:H(B(N(),I()).nullish(),()=>void 0)}),Wd=R({messageId:Bd,content:H(G(Cl).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Gd=R({messageId:Bd,content:H(G(Cl).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Kd=R({messageId:Bd,content:H(G(Cl).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),qd=R({toolCallId:dl,content:Pl,_meta:H(B(N(),I()).nullish(),()=>void 0)}),Jd=R({data:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Yd=R({exitCode:H(q().nullish(),()=>void 0),signal:H(N().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Xd=R({cols:yc().gte(1).lte(65535),rows:yc().gte(1).lte(65535),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Zd=R({cancel:H(R({_meta:H(B(N(),I()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Qd=R({terminalId:Ml,command:H(N().nullish(),()=>void 0),cwd:H(El.nullish(),()=>void 0),output:H(Jd.nullish(),()=>void 0),exitStatus:H(Yd.nullish(),()=>void 0),size:H(Xd.nullish(),()=>void 0),capabilities:H(Zd.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),$d=R({terminalId:Ml,data:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),ef=N(),tf=z([V(`high`),V(`medium`),V(`low`),N()]),nf=z([V(`pending`),V(`in_progress`),V(`completed`),V(`cancelled`),N()]),rf=R({planId:ef,entries:G(R({content:N(),priority:tf,status:nf,_meta:H(B(N(),I()).nullish(),()=>void 0)})),_meta:H(B(N(),I()).nullish(),()=>void 0)}),af=R({planId:ef,uri:ec(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),of=R({planId:ef,content:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),sf=R({plan:W(z([rf.and(R({type:V(`items`)})),af.and(R({type:V(`file`)})),of.and(R({type:V(`markdown`)})),U(R({type:N(),planId:ef}),`type`,[`file`,`items`,`markdown`])]),`type`,[`file`,`items`,`markdown`]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),cf=R({planId:ef,_meta:H(B(N(),I()).nullish(),()=>void 0)}),lf=R({availableCommands:G(ld),_meta:H(B(N(),I()).nullish(),()=>void 0)}),uf=R({configOptions:G(ad),_meta:H(B(N(),I()).nullish(),()=>void 0)}),df=R({title:H(N().nullish(),()=>void 0),updatedAt:H(Fs({offset:!0}).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),ff=R({amount:_c(),currency:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),pf=R({used:q().gte(0),size:q().gte(0),cost:H(ff.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),mf=R({severity:z([V(`info`),V(`warning`),V(`error`),N()]),title:N().min(1),description:H(N().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),hf=N(),gf=R({compactionId:hf,status:z([V(`in_progress`),V(`completed`),V(`failed`),V(`cancelled`),N()]),summary:H(G(Cl).nullish(),()=>void 0),error:H(N().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),_f=R({compactionId:hf,content:Cl,_meta:H(B(N(),I()).nullish(),()=>void 0)}),vf=R({cancel:H(R({_meta:H(B(N(),I()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),yf=R({sessionId:J,title:H(N().nullish(),()=>void 0),description:H(N().nullish(),()=>void 0),capabilities:H(vf.nullish(),()=>void 0),state:H(Md.nullish(),()=>void 0),cwd:El.nullish(),additionalDirectories:L(El).nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),bf=R({messageId:Bd,senderSessionId:H(J.nullish(),()=>void 0),recipientSessionId:H(J.nullish(),()=>void 0),senderMessageId:H(Bd.nullish(),()=>void 0),recipientMessageId:H(Bd.nullish(),()=>void 0),content:H(G(Cl).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),xf=R({messageId:Bd,content:Cl,_meta:H(B(N(),I()).nullish(),()=>void 0)}),Sf=R({sessionId:J,update:W(z([Ud.and(R({sessionUpdate:V(`user_message_chunk`)})),Wd.and(R({sessionUpdate:V(`user_message`)})),Ud.and(R({sessionUpdate:V(`agent_message_chunk`)})),Gd.and(R({sessionUpdate:V(`agent_message`)})),Ud.and(R({sessionUpdate:V(`agent_thought_chunk`)})),Kd.and(R({sessionUpdate:V(`agent_thought`)})),Md.and(R({sessionUpdate:V(`state_update`)})),qd.and(R({sessionUpdate:V(`tool_call_content_chunk`)})),Ll.and(R({sessionUpdate:V(`tool_call_update`)})),Qd.and(R({sessionUpdate:V(`terminal_update`)})),$d.and(R({sessionUpdate:V(`terminal_output_chunk`)})),sf.and(R({sessionUpdate:V(`plan_update`)})),cf.and(R({sessionUpdate:V(`plan_removed`)})),lf.and(R({sessionUpdate:V(`available_commands_update`)})),uf.and(R({sessionUpdate:V(`config_option_update`)})),df.and(R({sessionUpdate:V(`session_info_update`)})),pf.and(R({sessionUpdate:V(`usage_update`)})),mf.and(R({sessionUpdate:V(`notice`)})),gf.and(R({sessionUpdate:V(`compaction_update`)})),_f.and(R({sessionUpdate:V(`compaction_summary_chunk`)})),yf.and(R({sessionUpdate:V(`subagent_update`)})),bf.and(R({sessionUpdate:V(`session_message`)})),xf.and(R({sessionUpdate:V(`session_message_chunk`)})),U(R({sessionUpdate:N()}),`sessionUpdate`,[`agent_message`,`agent_message_chunk`,`agent_thought`,`agent_thought_chunk`,`available_commands_update`,`compaction_summary_chunk`,`compaction_update`,`config_option_update`,`notice`,`plan_removed`,`plan_update`,`session_info_update`,`session_message`,`session_message_chunk`,`state_update`,`subagent_update`,`terminal_output_chunk`,`terminal_update`,`tool_call_content_chunk`,`tool_call_update`,`usage_update`,`user_message`,`user_message_chunk`])]),`sessionUpdate`,[`agent_message`,`agent_message_chunk`,`agent_thought`,`agent_thought_chunk`,`available_commands_update`,`compaction_summary_chunk`,`compaction_update`,`config_option_update`,`notice`,`plan_removed`,`plan_update`,`session_info_update`,`session_message`,`session_message_chunk`,`state_update`,`subagent_update`,`terminal_output_chunk`,`terminal_update`,`tool_call_content_chunk`,`tool_call_update`,`usage_update`,`user_message`,`user_message_chunk`]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Cf=R({elicitationId:su,_meta:H(B(N(),I()).nullish(),()=>void 0)}),wf=R({state:Yu,accounts:H(G(Xu).optional(),()=>[]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Tf=I();R({method:N(),params:z([Sf,Cf,wf,Tf]).nullish()});var Ef=R({terminal:H(R({_meta:H(B(N(),I()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Df=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Of=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),kf=R({form:H(Df.nullish(),()=>void 0),url:H(Of.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Af=R({protocolVersion:mu,info:hu,capabilities:H(R({auth:H(Ef.nullish(),()=>void 0),elicitation:H(kf.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}).optional().default({}),()=>({})),_meta:H(B(N(),I()).nullish(),()=>void 0)}),jf=R({methodId:Fu,_meta:H(B(N(),I()).nullish(),()=>void 0)}),Mf=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Nf=R({providerId:Hu,apiType:Uu,baseUrl:ec(),headers:B(N(),N()).optional(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Pf=R({providerId:Hu,_meta:H(B(N(),I()).nullish(),()=>void 0)}),Ff=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),If=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Lf=R({name:N(),value:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Rf=R({name:N(),url:ec(),headers:K(L(Lf),()=>[]).optional(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),zf=R({name:N(),serverId:uu,_meta:H(B(N(),I()).nullish(),()=>void 0)}),Bf=R({name:N(),command:El,args:K(L(N()),()=>[]).optional(),env:K(L(Iu),()=>[]).optional(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Vf=W(z([Rf.and(R({type:V(`http`)})),zf.and(R({type:V(`acp`)})),Bf.and(R({type:V(`stdio`)})),U(R({type:N()}),`type`,[`acp`,`http`,`stdio`])]),`type`,[`acp`,`http`,`stdio`]),Hf=R({mode:z([V(`append`),V(`override`),N()]),content:L(Cl),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Uf=R({cwd:El,additionalDirectories:K(L(El),()=>[]).optional(),mcpServers:K(L(Vf),()=>[]).optional(),systemPrompt:Hf.nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Wf=z([V(`exclude`),V(`include`),V(`only`),N()]),Gf=R({cwd:El.nullish(),cursor:fd.nullish(),archived:Wf.nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Kf=R({sessionId:J,_meta:H(B(N(),I()).nullish(),()=>void 0)}),qf=R({sessionId:J,cwd:El,additionalDirectories:K(L(El),()=>[]).optional(),mcpServers:K(L(Vf),()=>[]).optional(),systemPrompt:Hf.nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Jf=R({sessionId:J,_meta:H(B(N(),I()).nullish(),()=>void 0)}),Yf=R({sessionId:J,_meta:H(B(N(),I()).nullish(),()=>void 0)}),Xf=R({sessionId:J,_meta:H(B(N(),I()).nullish(),()=>void 0)}),Zf=R({sessionId:J,title:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Qf=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),$f=W(z([Qf.and(R({type:V(`start`)})),U(R({type:N()}),`type`,[`start`])]),`type`,[`start`]),ep=R({sessionId:J,cwd:El,additionalDirectories:K(L(El),()=>[]).optional(),mcpServers:K(L(Vf),()=>[]).optional(),replayFrom:$f.nullish(),systemPrompt:Hf.nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),tp=R({sessionId:J,_meta:H(B(N(),I()).nullish(),()=>void 0)}),np=R({sessionId:J,toolCallId:dl,_meta:H(B(N(),I()).nullish(),()=>void 0)}),rp=R({sessionId:J,terminalId:Ml,_meta:H(B(N(),I()).nullish(),()=>void 0)}),ip=W(jc(z([R({type:V(`id`),value:ed}),R({type:V(`boolean`),value:F()}),U(R({type:N(),value:I()}),`type`,[`boolean`,`id`])]),R({sessionId:J,configId:Qu,_meta:H(B(N(),I()).nullish(),()=>void 0)})),`type`,[`boolean`,`id`]),ap=R({sessionId:J,prompt:L(Cl).min(1),_meta:H(B(N(),I()).nullish(),()=>void 0)});R({id:ul,method:N(),params:z([Af,jf,Mf,Nf,Pf,Ff,If,Uf,Gf,Kf,qf,Jf,Yf,Xf,Zf,ep,tp,np,rp,ip,ap,pu]).nullish()});var op=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),sp=R({optionId:Vl,_meta:H(B(N(),I()).nullish(),()=>void 0)}),cp=R({outcome:W(z([op.and(R({outcome:V(`cancelled`)})),sp.and(R({outcome:V(`selected`)})),U(R({outcome:N()}),`outcome`,[`cancelled`,`selected`])]),`outcome`,[`cancelled`,`selected`]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),lp=z([N(),q(),_c(),F(),L(N()),I()]),up=R({content:B(N(),lp).nullish()}),dp=W(jc(z([up.and(R({action:V(`accept`)})),R({action:V(`decline`)}),R({action:V(`cancel`)}),U(R({action:N()}),`action`,[`accept`,`cancel`,`decline`])]),R({_meta:H(B(N(),I()).nullish(),()=>void 0)})),`action`,[`accept`,`cancel`,`decline`]),fp=Oc({code:yc().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`}),message:N(),data:I().optional()}),pp=z([R({result:I(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),R({error:fp,_meta:H(B(N(),I()).nullish(),()=>void 0)})]);z([R({id:ul,result:z([cp,dp,pp,Hd])}),R({id:z([q(),N()]).nullable(),error:Ed})]);var mp=R({sessionId:J,_meta:H(B(N(),I()).nullish(),()=>void 0)}),hp=R({serverId:uu,requestId:du,method:N(),params:B(N(),I()).nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)});R({method:N(),params:z([mp,hp,Tf]).nullish()}),R({requestId:ul,_meta:H(B(N(),I()).nullish(),()=>void 0)});var gp=Af,_p=R({method:N(),params:I().optional(),_meta:H(B(N(),I()).nullish(),()=>void 0)});R({id:ul,method:N(),params:z([gp,_p]).nullish()}),z([R({id:ul,result:z([Bu,I()])}),R({id:z([q(),N()]).nullable(),error:Ed})]);var vp=R({method:N(),params:I().optional(),_meta:H(B(N(),I()).nullish(),()=>void 0)});R({method:N(),params:vp.nullish()});function Y(e,t){return typeof e==`object`&&e?e[t]:void 0}var yp=Rl.and(R({type:V(`tool_call`)})),bp=zl.and(R({toolCallId:dl.nullish(),terminalId:Ml.nullish()})).and(R({type:V(`command`)}));wl.and(R({type:V(`content`)})),jl.and(R({patch:Al.nullish()})).and(R({type:V(`diff`)})),Nl.and(R({type:V(`terminal`)}));var xp=hl.and(R({annotations:ml.nullish()})).and(R({type:V(`text`)})),Sp=_l.and(R({annotations:ml.nullish()})).and(R({type:V(`image`)})),Cp=vl.and(R({annotations:ml.nullish()})).and(R({type:V(`audio`)})),wp=xl.and(R({mimeType:gl.nullish(),annotations:ml.nullish()})).and(R({type:V(`resource_link`)})),Tp=Sl.and(R({annotations:ml.nullish()})).and(R({type:V(`resource`)}));Dl.and(R({operation:V(`add`)})),Dl.and(R({operation:V(`delete`)})),Dl.and(R({operation:V(`modify`)})),Ol.and(R({operation:V(`move`)})),Ol.and(R({operation:V(`copy`)})),ou.and(R({mode:V(`form`)})).and(R({message:N()})),cu.and(R({mode:V(`url`)})).and(R({message:N()})),ll([Gl,Kl],[[`sessionId`],[`requestId`]]).and(R({message:N()})),Xl.and(R({type:V(`string`)})),Zl.and(R({type:V(`number`)})),Ql.and(R({type:V(`integer`)})),$l.and(R({type:V(`boolean`)})),ru.and(R({type:V(`array`)})),eu.and(R({type:V(`string`)})),Lu.and(R({type:V(`terminal`)})),Ru.and(R({type:V(`agent`)})),R({methodId:Fu,name:N()}),rd.and(R({type:V(`select`)})).and(R({configId:Qu,name:N()})),id.and(R({type:V(`boolean`)})).and(R({configId:Qu,name:N()})),R({configId:Qu,name:N()}),cd.and(R({input:sd.nullish()})).and(R({type:V(`command`)})),R({name:N(),description:N()}),od.and(R({type:V(`text`)}));var Ep=Cd.and(R({state:V(`running`)})),Dp=kd.and(R({usage:Od.nullish()})).and(R({state:V(`idle`)})),Op=Ad.and(R({state:V(`requires_action`)})),kp=jd.and(R({state:V(`unknown`)})),Ap=yd.and(R({type:V(`terminal`)})),jp=bd.and(R({type:V(`tool_call`)})),Mp=xd.and(R({type:V(`subagent`)}));R({stopReason:V(`end_turn`)}),R({stopReason:V(`max_tokens`)}),R({stopReason:V(`max_turn_requests`)}),R({stopReason:V(`refusal`)}),R({stopReason:V(`cancelled`)}),Dd.and(R({error:Ed.nullish()})).and(R({stopReason:V(`error`)})),R({stopReason:Sc().optional()});var Np=Ud.and(R({sessionUpdate:V(`user_message_chunk`)})),Pp=Wd.and(R({sessionUpdate:V(`user_message`)})),Fp=Ud.and(R({sessionUpdate:V(`agent_message_chunk`)})),Ip=Gd.and(R({sessionUpdate:V(`agent_message`)})),Lp=Ud.and(R({sessionUpdate:V(`agent_thought_chunk`)})),Rp=Kd.and(R({sessionUpdate:V(`agent_thought`)})),zp=Md.and(R({sessionUpdate:V(`state_update`)})),Bp=qd.and(R({sessionUpdate:V(`tool_call_content_chunk`)})),Vp=Ll.and(R({kind:fl.nullish(),status:pl.nullish(),capabilities:Il.nullish()})).and(R({sessionUpdate:V(`tool_call_update`)})),Hp=Qd.and(R({cwd:El.nullish(),output:Jd.nullish(),exitStatus:Yd.nullish(),size:Xd.nullish(),capabilities:Zd.nullish()})).and(R({sessionUpdate:V(`terminal_update`)})),Up=$d.and(R({sessionUpdate:V(`terminal_output_chunk`)})),Wp=sf.and(R({sessionUpdate:V(`plan_update`)})),Gp=cf.and(R({sessionUpdate:V(`plan_removed`)})),Kp=lf.and(R({sessionUpdate:V(`available_commands_update`)})),qp=uf.and(R({sessionUpdate:V(`config_option_update`)})),Jp=df.and(R({sessionUpdate:V(`session_info_update`)})),Yp=pf.and(R({cost:ff.nullish()})).and(R({sessionUpdate:V(`usage_update`)})),Xp=mf.and(R({sessionUpdate:V(`notice`)})),Zp=gf.and(R({sessionUpdate:V(`compaction_update`)})),Qp=_f.and(R({sessionUpdate:V(`compaction_summary_chunk`)})),$p=yf.and(R({capabilities:vf.nullish(),state:Md.nullish()})).and(R({sessionUpdate:V(`subagent_update`)})),em=bf.and(R({senderSessionId:J.nullish(),recipientSessionId:J.nullish(),senderMessageId:Bd.nullish(),recipientMessageId:Bd.nullish()})).and(R({sessionUpdate:V(`session_message`)})),tm=xf.and(R({sessionUpdate:V(`session_message_chunk`)}));rf.and(R({type:V(`items`)})),af.and(R({type:V(`file`)})),of.and(R({type:V(`markdown`)})),R({planId:ef}),Rf.and(R({type:V(`http`)})),zf.and(R({type:V(`acp`)})),Bf.and(R({type:V(`stdio`)})),Qf.and(R({type:V(`start`)})),R({type:V(`id`)}).and(R({value:ed})).and(R({sessionId:J,configId:Qu})),R({type:V(`boolean`)}).and(R({value:F()})).and(R({sessionId:J,configId:Qu})),R({value:I()}).and(R({sessionId:J,configId:Qu})),op.and(R({outcome:V(`cancelled`)})),sp.and(R({outcome:V(`selected`)})),up.and(R({action:V(`accept`)})),R({action:V(`decline`)}),R({action:V(`cancel`)});var nm={isToolCall(e){return Y(e,`type`)===`tool_call`&&yp.safeParse(e).success},isCommand(e){return Y(e,`type`)===`command`&&bp.safeParse(e).success},isCustom(e){let t=Y(e,`type`);return typeof t==`string`&&![`command`,`tool_call`].includes(t)}},rm={isText(e){return Y(e,`type`)===`text`&&xp.safeParse(e).success},isImage(e){return Y(e,`type`)===`image`&&Sp.safeParse(e).success},isAudio(e){return Y(e,`type`)===`audio`&&Cp.safeParse(e).success},isResourceLink(e){return Y(e,`type`)===`resource_link`&&wp.safeParse(e).success},isResource(e){return Y(e,`type`)===`resource`&&Tp.safeParse(e).success},isCustom(e){let t=Y(e,`type`);return typeof t==`string`&&![`audio`,`image`,`resource`,`resource_link`,`text`].includes(t)}},im={isRunning(e){return Y(e,`state`)===`running`&&Ep.safeParse(e).success},isIdle(e){return Y(e,`state`)===`idle`&&Dp.safeParse(e).success},isRequiresAction(e){return Y(e,`state`)===`requires_action`&&Op.safeParse(e).success},isUnknown(e){return Y(e,`state`)===`unknown`&&kp.safeParse(e).success},isCustom(e){let t=Y(e,`state`);return typeof t==`string`&&![`idle`,`requires_action`,`running`,`unknown`].includes(t)}},am={isTerminal(e){return Y(e,`type`)===`terminal`&&Ap.safeParse(e).success},isToolCall(e){return Y(e,`type`)===`tool_call`&&jp.safeParse(e).success},isSubagent(e){return Y(e,`type`)===`subagent`&&Mp.safeParse(e).success},isCustom(e){let t=Y(e,`type`);return typeof t==`string`&&![`subagent`,`terminal`,`tool_call`].includes(t)}},om={isUserMessageChunk(e){return Y(e,`sessionUpdate`)===`user_message_chunk`&&Np.safeParse(e).success},isUserMessage(e){return Y(e,`sessionUpdate`)===`user_message`&&Pp.safeParse(e).success},isAgentMessageChunk(e){return Y(e,`sessionUpdate`)===`agent_message_chunk`&&Fp.safeParse(e).success},isAgentMessage(e){return Y(e,`sessionUpdate`)===`agent_message`&&Ip.safeParse(e).success},isAgentThoughtChunk(e){return Y(e,`sessionUpdate`)===`agent_thought_chunk`&&Lp.safeParse(e).success},isAgentThought(e){return Y(e,`sessionUpdate`)===`agent_thought`&&Rp.safeParse(e).success},isStateUpdate(e){return Y(e,`sessionUpdate`)===`state_update`&&zp.safeParse(e).success},isToolCallContentChunk(e){return Y(e,`sessionUpdate`)===`tool_call_content_chunk`&&Bp.safeParse(e).success},isToolCallUpdate(e){return Y(e,`sessionUpdate`)===`tool_call_update`&&Vp.safeParse(e).success},isTerminalUpdate(e){return Y(e,`sessionUpdate`)===`terminal_update`&&Hp.safeParse(e).success},isTerminalOutputChunk(e){return Y(e,`sessionUpdate`)===`terminal_output_chunk`&&Up.safeParse(e).success},isPlanUpdate(e){return Y(e,`sessionUpdate`)===`plan_update`&&Wp.safeParse(e).success},isPlanRemoved(e){return Y(e,`sessionUpdate`)===`plan_removed`&&Gp.safeParse(e).success},isAvailableCommandsUpdate(e){return Y(e,`sessionUpdate`)===`available_commands_update`&&Kp.safeParse(e).success},isConfigOptionUpdate(e){return Y(e,`sessionUpdate`)===`config_option_update`&&qp.safeParse(e).success},isSessionInfoUpdate(e){return Y(e,`sessionUpdate`)===`session_info_update`&&Jp.safeParse(e).success},isUsageUpdate(e){return Y(e,`sessionUpdate`)===`usage_update`&&Yp.safeParse(e).success},isNotice(e){return Y(e,`sessionUpdate`)===`notice`&&Xp.safeParse(e).success},isCompactionUpdate(e){return Y(e,`sessionUpdate`)===`compaction_update`&&Zp.safeParse(e).success},isCompactionSummaryChunk(e){return Y(e,`sessionUpdate`)===`compaction_summary_chunk`&&Qp.safeParse(e).success},isSubagentUpdate(e){return Y(e,`sessionUpdate`)===`subagent_update`&&$p.safeParse(e).success},isSessionMessage(e){return Y(e,`sessionUpdate`)===`session_message`&&em.safeParse(e).success},isSessionMessageChunk(e){return Y(e,`sessionUpdate`)===`session_message_chunk`&&tm.safeParse(e).success},isCustom(e){let t=Y(e,`sessionUpdate`);return typeof t==`string`&&![`agent_message`,`agent_message_chunk`,`agent_thought`,`agent_thought_chunk`,`available_commands_update`,`compaction_summary_chunk`,`compaction_update`,`config_option_update`,`notice`,`plan_removed`,`plan_update`,`session_info_update`,`session_message`,`session_message_chunk`,`state_update`,`subagent_update`,`terminal_output_chunk`,`terminal_update`,`tool_call_content_chunk`,`tool_call_update`,`usage_update`,`user_message`,`user_message_chunk`].includes(t)}},sm=`$/cancel_request`;function cm(e,t,n){return e!==`session/close`&&e!==`session/delete`?t:t.catch(e=>{if(e instanceof X&&e.code===-32002)return n();throw e})}function lm(e){return pm(e)&&`id`in e&&typeof e.method==`string`&&mm(e.id)}function um(e){if(!pm(e)||`method`in e||!(`id`in e)||!mm(e.id))return!1;let t=Object.hasOwn(e,`result`),n=Object.hasOwn(e,`error`);return t===n?!1:!n||_m(e.error)}function dm(e){return pm(e)&&!(`id`in e)&&typeof e.method==`string`}function fm(e){return typeof e==`object`&&!!e}function pm(e){return fm(e)&&e.jsonrpc===`2.0`}function mm(e){return e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e)}function hm(e){return fm(e)&&!(`method`in e)&&(`id`in e||`result`in e||`error`in e)}function gm(e){if(fm(e)&&mm(e.requestId))return e.requestId}function _m(e){return fm(e)&&typeof e.code==`number`&&Number.isInteger(e.code)&&typeof e.message==`string`}var vm={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};function ym(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function bm(e){if(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)return e.message}function xm(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`ZodError`&&`issues`in e&&Array.isArray(e.issues)&&`format`in e&&typeof e.format==`function`}function Sm(e){return Array.isArray(e)?{type:`array`}:fm(e)?{type:`object`,keys:Object.keys(e)}:{type:e===null?`null`:typeof e}}function Cm(e){if(e instanceof X)return e.toResult();if(xm(e))return X.invalidParams(e.format()).toResult();let t=bm(e);try{return X.internalError(t?JSON.parse(t):{}).toResult()}catch{return X.internalError({details:t}).toResult()}}function wm(e){return e instanceof X&&e.code===-32800?e:X.requestCancelled(e)}function Tm(e,t){let n=Em(e,t);return n?n.toResult():Cm(e)}function Em(e,t){if(t.aborted&&Dm(e))return wm(t.reason)}function Dm(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.name===`AbortError`||t.code===`ABORT_ERR`}var Om=class{id;sendResult;signal;finishRequest;didRespond=!1;constructor(e,t,n=new AbortController().signal,r){this.id=e,this.sendResult=t,this.signal=n,this.finishRequest=r}get responded(){return this.didRespond}respond(e){return this.respondWithResult({result:e??null})}respondWithError(e){let t=e instanceof X?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?ym(Error(`JSON-RPC request already responded`)):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},km=new WeakSet;function Am(e){return typeof e==`string`||Number.isInteger(e)}function jm(e,t){return km.add(e),e.respondWithError(t)}var Mm=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},Nm=class{connection;constructor(e){this.connection=e}sendRequest(e,t,n,r){return this.connection.sendRequest(e,t,n,r)}sendNotification(e,t){return this.connection.sendNotification(e,t)}sendCancelRequest(e){return this.connection.sendCancelRequest(e)}addDynamicHandler(e){return this.connection.addDynamicHandler(e)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},Pm=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;fallbackHandlers=[];stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new Nm(this);receiveReader;constructor(e,t,n,r){if(typeof e==`function`){let i=e,a=t,o=n;this.initialize(o,[...r?.handlers??[],this.legacyHandler(i,a)],r);return}let i=e,a=t,o=n;this.initialize(i,[...o?.handlers??[],...a],o)}static builder(){return new Fm}runUntil(e){let t=!1,n=Promise.resolve().then(()=>e(this.context)).finally(()=>{t=!0}),r=this.closed.then(()=>{if(t)return new Promise(()=>{});throw this.closedReason()});return Promise.race([n,r]).finally(()=>{t=!0,this.close()})}addDynamicHandler(e){if(this.dynamicHandlers.add(e),this.retryQueue.length>0)for(let e of this.retryQueue.splice(0))this.processIncomingMessage(e).catch(e=>this.close(e));return new Mm(()=>{this.dynamicHandlers.delete(e)})}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}getContext(){return this.context}sendRequest(e,t,n,r={}){if(this.abortController.signal.aborted)return ym(this.closedReason());let i=this.prepareRequest(e,t,n,r);return this.sendMessage(i.message).catch(()=>{}),r.cancellationSignal?.aborted&&i.cancel(),i.response}sendCancelRequest(e){return this.sendNotification(sm,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?ym(this.closedReason()):this.sendMessage({jsonrpc:`2.0`,method:e,params:t})}prepareRequest(e,t,n,r={}){let i=this.nextRequestId++,a=()=>{},o=new Promise((e,t)=>{let o={resolve:r=>{try{e(n?n(r):r)}catch(e){t(e)}},reject:t};a=()=>{o.cancellationSent||(o.cancellationSent=!0,o.cleanup?.(),this.sendCancelRequest(i).catch(()=>{}),r.stopWaitingOnCancel&&(o.abandoned=!0,t(wm(r.cancellationSignal?.reason))))},r.cancellationSignal?.addEventListener(`abort`,a,{once:!0}),o.cleanup=()=>{r.cancellationSignal?.removeEventListener(`abort`,a)},this.pendingResponses.set(i,o)});return o.catch(()=>{}),{message:{jsonrpc:`2.0`,id:i,method:e,params:t},response:o,cancel:()=>a()}}close(e){if(this.abortController.signal.aborted)return;let t=e??Error(`ACP connection closed`);this.abortController.abort(t);for(let e of this.pendingResponses.values())e.cleanup?.(),e.reject(t);this.pendingResponses.clear();for(let e of this.incomingRequests.values())e.abort(t);this.incomingRequests.clear(),this.receiveReader?.cancel(t).catch(()=>{})}initialize(e,t,n){this.stream=e,this.staticHandlers=t,this.fallbackHandlers=[...n?.fallbackHandlers??[]],this.closedPromise=new Promise(e=>{this.abortController.signal.addEventListener(`abort`,()=>e())}),this.receive()}legacyHandler(e,t){return{handleMessage:async(n,r)=>{if(n.kind===`request`){let t=await e(n.method,n.params,r);await n.responder.respond(t)}else await t(n.method,n.params,r);return vm.yes()}}}async receive(){let e;try{let e=this.stream.readable.getReader();this.receiveReader=e;try{for(;!this.abortController.signal.aborted;){let{value:t,done:n}=await e.read();if(this.abortController.signal.aborted||n)break;this.receiveUnvalidatedMessage(t)}}finally{this.receiveReader===e&&(this.receiveReader=void 0),e.releaseLock()}}catch(t){e=t}finally{this.close(e)}}receiveUnvalidatedMessage(e){Array.isArray(e)?this.sendMessage(Im(X.invalidRequest(void 0,`JSON-RPC batches are not supported`))).catch(()=>{}):!lm(e)&&!dm(e)&&!hm(e)?this.sendMessage(Im(X.invalidRequest(e))).catch(()=>{}):this.receiveMessage(e)}receiveMessage(e){return this.abortController.signal.aborted?Promise.resolve():fm(e)?`method`in e?(`id`in e||this.handleProtocolNotification(e),this.processIncomingMessage(this.toIncomingMessage(e)).catch(e=>this.close(e))):(`id`in e?this.handleResponse(e):console.error(`Invalid message`,Sm(e)),Promise.resolve()):(console.error(`Invalid message`,Sm(e)),Promise.resolve())}async processIncomingMessage(e){if(this.abortController.signal.aborted)return;let t=e,n=!1;try{for(let e of[...this.staticHandlers,...this.dynamicHandlers.values(),...this.fallbackHandlers]){if(this.abortController.signal.aborted)return;let r=await e.handleMessage(t,this.context)??{handled:!0};if(r.handled)return;t=r.message??t,n||=!!r.retry}n?this.retryQueue.push(t):t.kind===`request`&&await t.responder.respondWithError(X.methodNotFound(t.method))}catch(n){if(this.abortController.signal.aborted)return;if(t.kind===`request`&&!t.responder.responded)await t.responder.respondWithResult(Tm(n,t.responder.signal));else{let t=Cm(n);`error`in t&&console.error(`Error handling notification`,{method:e.method,code:t.error.code,message:t.error.message})}}}toIncomingMessage(e){if(`id`in e){let t=new AbortController;this.incomingRequests.set(e.id,t);let n=new Om(e.id,t=>{let r={jsonrpc:`2.0`,id:km.has(n)?null:e.id,...t};return this.sendMessage(r)},t.signal,()=>{this.incomingRequests.get(e.id)===t&&this.incomingRequests.delete(e.id)});return{kind:`request`,method:e.method,params:e.params,raw:e,signal:t.signal,responder:n}}return{kind:`notification`,method:e.method,params:e.params,raw:e}}handleResponse(e){let t=this.pendingResponses.get(e.id);if(t){if(this.pendingResponses.delete(e.id),t.cleanup?.(),t.abandoned)return;if(!um(e))t.reject(X.invalidRequest(e));else if(`result`in e)t.resolve(e.result);else{let{code:n,message:r,data:i}=e.error;t.reject(new X(n,r,i))}}else console.error(`Got response to unknown request`,e.id)}handleProtocolNotification(e){if(e.method!==sm)return;let t=gm(e.params);if(t===void 0)return;let n=this.incomingRequests.get(t);n&&!n.signal.aborted&&n.abort(X.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??Error(`ACP connection closed`)}async sendMessage(e){return this.abortController.signal.aborted?ym(this.closedReason()):(this.writeQueue=this.writeQueue.then(async()=>{if(this.abortController.signal.aborted)throw this.closedReason();let t=this.stream.writable.getWriter();try{await t.write(e)}finally{t.releaseLock()}}).catch(e=>{throw this.close(e),e}),this.writeQueue)}},Fm=class{handlers=[];fallbackHandlers=[];connectionName;name(e){return this.connectionName=e,this}withHandler(e){return this.handlers.push(e),this}withFallbackHandler(e){return this.fallbackHandlers.push(e),this}onReceiveMessage(e){return this.withHandler({handleMessage:async(t,n)=>await e(t,n)??vm.no(t),describe:()=>this.connectionName??`onReceiveMessage`})}onReceiveRequest(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`request`||r.method!==e?vm.no(r):await n(t(r.params),r.responder,i)??vm.yes(),describe:()=>`${this.connectionName??`request`}:${e}`})}onReceiveNotification(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`notification`||r.method!==e?vm.no(r):await n(t(r.params),i)??vm.yes(),describe:()=>`${this.connectionName??`notification`}:${e}`})}connect(e,t){return new Pm(e,this.handlers,{...t,fallbackHandlers:[...t?.fallbackHandlers??[],...this.fallbackHandlers]})}connectWith(e,t,n){return this.connect(e,n).runUntil(t)}},X=class e extends Error{code;data;constructor(e,t,n){super(t),this.code=e,this.name=`RequestError`,this.data=n}static parseError(t,n){return new e(-32700,`Parse error${n?`: ${n}`:``}`,t)}static invalidRequest(t,n){return new e(-32600,`Invalid request${n?`: ${n}`:``}`,t)}static methodNotFound(t){return new e(-32601,`"Method not found": ${t}`,{method:t})}static invalidParams(t,n){return new e(-32602,`Invalid params${n?`: ${n}`:``}`,t)}static internalError(t,n){return new e(-32603,`Internal error${n?`: ${n}`:``}`,t)}static requestCancelled(t,n){return new e(-32800,`Request cancelled${n?`: ${n}`:``}`,t)}static authRequired(t,n){return new e(-32e3,`Authentication required${n?`: ${n}`:``}`,t)}static resourceNotFound(t){return new e(-32002,`Resource not found${t?`: ${t}`:``}`,t&&{uri:t})}static sessionNotFound(t){return new e(-32002,`Resource not found`,{sessionId:t})}static unsupportedProtocolVersion(t,n){return new e(-32022,`Unsupported protocol version`,{requested:t,supported:[...n]})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}};function Im(e){return{jsonrpc:`2.0`,id:null,error:e.toErrorResponse()}}var Lm=33554432,Rm=class extends Error{maxMessageBytes;constructor(e){super(`Incoming ACP data exceeds the configured ${e} byte limit`),this.maxMessageBytes=e,this.name=`MessageTooLargeError`}};function zm(e){let t=e??33554432;if(!Number.isSafeInteger(t)||t<=0)throw RangeError(`maxMessageBytes must be a positive safe integer`);return t}var Bm=class{#e=new Uint8Array;#t=0;#n;constructor(e){this.#n=zm(e)}get byteLength(){return this.#t}get lastByte(){return this.#e[this.#t-1]}#r(e){if(e>this.#n-this.#t)throw this.clear(),new Rm(this.#n)}append(e){this.#r(e.byteLength);let t=this.#t+e.byteLength;if(t>this.#e.byteLength){let e=Math.min(this.#n,Math.max(t,this.#e.byteLength*2,1024)),n=new Uint8Array(e);n.set(this.#e.subarray(0,this.#t)),this.#e=n}this.#e.set(e,this.#t),this.#t=t}take(){let e=this.#e.subarray(0,this.#t);return this.clear(),e}clear(){this.#e=new Uint8Array,this.#t=0}},Vm=10,Hm=13,Um=class{#e;#t;#n;#r=!1;constructor(e,{splitOnCarriageReturn:t=!1}={}){this.#t=zm(e),this.#e=new Bm(Math.min(2**53-1,this.#t+1)),this.#n=t}*push(e){let t=0;this.#r&&e.byteLength>0&&(this.#r=!1,e[0]===Vm&&(t=1));let n=e.indexOf(Vm,t),r=this.#n?e.indexOf(Hm,t):-1;for(;n!==-1||r!==-1;)r===-1||n!==-1&&n<r?(yield this.#i(e.subarray(t,n)),t=n+1,n=e.indexOf(Vm,t)):(yield this.#i(e.subarray(t,r)),t=r+1,t===e.byteLength?this.#r=!0:e[t]===Vm&&(t++,n=e.indexOf(Vm,t)),r=e.indexOf(Hm,t));if(t<e.byteLength){let n=e.subarray(t);this.#a(n),this.#e.append(n)}}flush(){if(this.#r=!1,this.#e.byteLength!==0)return Wm(this.#e.take())}clear(){this.#r=!1,this.#e.clear()}#i(e){return this.#a(e),this.#e.byteLength===0?Wm(e):(this.#e.append(e),Wm(this.#e.take()))}#a(e){let t=e.byteLength>0?e[e.byteLength-1]:this.#e.lastByte;if(this.#e.byteLength+e.byteLength-+(t===Hm)>this.#t)throw this.clear(),new Rm(this.#t)}};function Wm(e){return e[e.byteLength-1]===Hm?e.subarray(0,-1):e}function Gm(e,t){return e?typeof e==`function`?e(t):e.parse(t):t}function Km(e,t,n,r,i,a){let o=async(e,t,o,s)=>{try{let c=await r(n(e,o,t.signal,t.id,s)),l=i?i(c):c;a?.beforeResponse(e,l,o),await t.respond(l)}catch(e){throw a?.onError(o,e),e}};t.method===`*`?e.withFallbackHandler({handleMessage:async(e,t)=>e.kind===`request`?(await o(e.params,e.responder,t,e.method),vm.yes()):vm.no(e)}):e.onReceiveRequest(t.method,e=>Gm(t.params,e),(e,n,r)=>o(e,n,r,t.method))}function qm(e,t,n,r){t.method===`*`?e.withFallbackHandler({handleMessage:async(e,t)=>e.kind===`notification`?(await r(n(e.params,t,t.signal,e.method)),vm.yes()):vm.no(e)}):e.onReceiveNotification(t.method,e=>Gm(t.params,e),(e,i)=>r(n(e,i,i.signal,t.method)))}var Jm=z([q(),N()]).nullable(),Z=N(),Ym=R({sessionId:Z,path:N(),content:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Xm=R({sessionId:Z,path:N(),line:yc().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),limit:yc().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Zm=N(),Qm=z([V(`read`),V(`edit`),V(`delete`),V(`move`),V(`search`),V(`execute`),V(`think`),V(`fetch`),V(`switch_mode`),V(`other`)]),$m=z([V(`pending`),V(`in_progress`),V(`completed`),V(`failed`)]),eh=R({audience:H(G(z([V(`assistant`),V(`user`)])).nullish(),()=>void 0),lastModified:H(N().nullish(),()=>void 0),priority:H(_c().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),th=R({annotations:H(eh.nullish(),()=>void 0),text:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),nh=R({annotations:H(eh.nullish(),()=>void 0),data:N(),mimeType:N(),uri:H(N().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),rh=R({annotations:H(eh.nullish(),()=>void 0),data:N(),mimeType:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),ih=R({annotations:H(eh.nullish(),()=>void 0),description:H(N().nullish(),()=>void 0),mimeType:H(N().nullish(),()=>void 0),name:N(),size:H(q().nullish(),()=>void 0),title:H(N().nullish(),()=>void 0),uri:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),ah=z([R({mimeType:H(N().nullish(),()=>void 0),text:N(),uri:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),R({blob:N(),mimeType:H(N().nullish(),()=>void 0),uri:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)})]),oh=R({annotations:H(eh.nullish(),()=>void 0),resource:ah,_meta:H(B(N(),I()).nullish(),()=>void 0)}),sh=z([th.and(R({type:V(`text`)})),nh.and(R({type:V(`image`)})),rh.and(R({type:V(`audio`)})),ih.and(R({type:V(`resource_link`)})),oh.and(R({type:V(`resource`)}))]),ch=R({content:sh,_meta:H(B(N(),I()).nullish(),()=>void 0)}),lh=R({path:N(),oldText:H(N().nullish(),()=>void 0),newText:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),uh=N(),dh=R({terminalId:uh,_meta:H(B(N(),I()).nullish(),()=>void 0)}),fh=z([ch.and(R({type:V(`content`)})),lh.and(R({type:V(`diff`)})),dh.and(R({type:V(`terminal`)}))]),ph=R({path:N(),line:H(yc().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),mh=R({toolCallId:Zm,kind:H(Qm.nullish(),()=>void 0),status:H($m.nullish(),()=>void 0),title:H(N().nullish(),()=>void 0),name:H(N().nullish(),()=>void 0),content:H(G(fh).nullish(),()=>void 0),locations:H(G(ph).nullish(),()=>void 0),rawInput:H(I().optional(),()=>void 0),rawOutput:H(I().optional(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),hh=N(),gh=z([V(`allow_once`),V(`allow_always`),V(`reject_once`),V(`reject_always`)]),_h=R({sessionId:Z,toolCall:mh,options:L(R({optionId:hh,name:N(),kind:gh,_meta:H(B(N(),I()).nullish(),()=>void 0)})),_meta:H(B(N(),I()).nullish(),()=>void 0)}),vh=R({name:N(),value:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),yh=R({sessionId:Z,command:N(),args:K(L(N()),()=>[]).optional(),env:K(L(vh),()=>[]).optional(),cwd:N().nullish(),outputByteLimit:q().gte(0).nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),bh=R({sessionId:Z,terminalId:uh,_meta:H(B(N(),I()).nullish(),()=>void 0)}),xh=R({sessionId:Z,terminalId:uh,_meta:H(B(N(),I()).nullish(),()=>void 0)}),Sh=R({sessionId:Z,terminalId:uh,_meta:H(B(N(),I()).nullish(),()=>void 0)}),Ch=R({sessionId:Z,terminalId:uh,_meta:H(B(N(),I()).nullish(),()=>void 0)}),wh=R({sessionId:Z,toolCallId:H(Zm.nullish(),()=>void 0)}),Th=R({requestId:Jm}),Eh=V(`object`),Dh=z([V(`email`),V(`uri`),V(`date`),V(`date-time`)]),Oh=R({const:N(),title:N(),description:H(N().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),kh=R({title:H(N().nullish(),()=>void 0),description:H(N().nullish(),()=>void 0),minLength:yc().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),maxLength:yc().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),pattern:N().nullish(),format:Dh.nullish(),default:H(N().nullish(),()=>void 0),enum:L(N()).nullish(),oneOf:L(Oh).nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Ah=R({title:H(N().nullish(),()=>void 0),description:H(N().nullish(),()=>void 0),minimum:_c().nullish(),maximum:_c().nullish(),default:H(_c().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),jh=R({title:H(N().nullish(),()=>void 0),description:H(N().nullish(),()=>void 0),minimum:q().nullish(),maximum:q().nullish(),default:H(q().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Mh=R({title:H(N().nullish(),()=>void 0),description:H(N().nullish(),()=>void 0),default:H(F().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Nh=R({enum:L(N()),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Ph=R({anyOf:L(Oh),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Fh=W(z([Nh.and(R({type:V(`string`)})),U(R({type:N()}),`type`,[`string`]),Ph]),`type`,[`string`]),Ih=R({title:H(N().nullish(),()=>void 0),description:H(N().nullish(),()=>void 0),minItems:q().gte(0).nullish(),maxItems:q().gte(0).nullish(),items:Fh,default:H(G(N()).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Lh=W(z([kh.and(R({type:V(`string`)})),Ah.and(R({type:V(`number`)})),jh.and(R({type:V(`integer`)})),Mh.and(R({type:V(`boolean`)})),Ih.and(R({type:V(`array`)})),U(R({type:N()}),`type`,[`array`,`boolean`,`integer`,`number`,`string`])]),`type`,[`array`,`boolean`,`integer`,`number`,`string`]),Rh=R({type:H(Eh.optional().default(`object`),()=>`object`),title:H(N().nullish(),()=>void 0),properties:B(N(),Lh).optional().default({}),required:L(N()).nullish(),description:H(N().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),zh=jc(z([wh,Th]),R({requestedSchema:Rh})),Bh=N(),Vh=jc(z([wh,Th]),R({elicitationId:Bh,url:ec()})),Hh=W(jc(z([zh.and(R({mode:V(`form`)})),Vh.and(R({mode:V(`url`)})),U(jc(z([wh,Th]),R({mode:N()})),`mode`,[`form`,`url`])]),R({message:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)})),`mode`,[`form`,`url`]),Uh=N(),Wh=N(),Gh=R({serverId:Uh,requestId:Wh,method:N(),params:B(N(),I()).nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Kh=I();R({id:Jm,method:N(),params:z([Ym,Xm,_h,yh,bh,xh,Sh,Ch,Hh,Gh,Kh]).nullish()});var qh=yc().gte(0).lte(65535),Jh=R({image:H(F().optional().default(!1),()=>!1),audio:H(F().optional().default(!1),()=>!1),embeddedContext:H(F().optional().default(!1),()=>!1),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Yh=R({http:H(F().optional().default(!1),()=>!1),sse:H(F().optional().default(!1),()=>!1),acp:H(F().optional().default(!1),()=>!1),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Xh=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Zh=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Qh=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),$h=R({mode:H(R({override:H(R({_meta:H(B(N(),I()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),eg=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),tg=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),ng=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),rg=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),ig=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),ag=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),og=R({list:H(Xh.nullish(),()=>void 0),delete:H(Zh.nullish(),()=>void 0),additionalDirectories:H(Qh.nullish(),()=>void 0),systemPrompt:H($h.nullish(),()=>void 0),fork:H(eg.nullish(),()=>void 0),archive:H(tg.nullish(),()=>void 0),status:H(ng.nullish(),()=>void 0),title:H(rg.nullish(),()=>void 0),resume:H(ig.nullish(),()=>void 0),close:H(ag.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),sg=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),cg=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),lg=R({status:H(sg.nullish(),()=>void 0),logout:H(cg.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),ug=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),dg=R({loadSession:H(F().optional().default(!1),()=>!1),promptCapabilities:H(Jh.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:H(Yh.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:H(og.optional().default({}),()=>({})),auth:H(lg.optional().default({}),()=>({})),providers:H(ug.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),fg=N(),pg=R({id:fg,name:N(),description:H(N().nullish(),()=>void 0),args:K(L(N()),()=>[]).optional(),env:K(B(N(),N()),()=>({})).optional(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),mg=R({id:fg,name:N(),description:H(N().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),hg=z([pg.and(R({type:V(`terminal`)})),mg]),gg=R({name:N(),title:H(N().nullish(),()=>void 0),version:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),_g=R({protocolVersion:qh,agentCapabilities:H(dg.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:H(G(hg).optional().default([]),()=>[]),agentInfo:H(gg.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),vg=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),yg=N(),bg=z([V(`anthropic`),V(`openai`),V(`azure`),V(`vertex`),V(`bedrock`),N()]),xg=R({apiType:bg,baseUrl:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Sg=R({providers:L(R({providerId:yg,supported:ol(G(bg),()=>[]),required:F(),current:xg.nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)})),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Cg=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),wg=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Tg=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Eg=z([V(`authenticated`),V(`unauthenticated`),V(`not_required`),V(`unknown`),N()]),Dg=R({label:N(),active:H(F().nullish(),()=>void 0),name:H(N().nullish(),()=>void 0),email:H(N().nullish(),()=>void 0),organization:H(N().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Og=R({state:Eg,accounts:H(G(Dg).optional(),()=>[]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),kg=N(),Ag=R({currentModeId:kg,availableModes:ol(G(R({id:kg,name:N(),description:H(N().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)})),()=>[]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),jg=N(),Mg=z([V(`mode`),V(`model`),V(`model_config`),V(`thought_level`),N()]),Ng=N(),Pg=R({value:Ng,name:N(),description:H(N().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Fg=R({group:N(),name:N(),options:ol(G(Pg),()=>[]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Ig=R({currentValue:Ng,options:z([L(Pg),L(Fg)])}),Lg=R({currentValue:F()}),Rg=jc(z([Ig.and(R({type:V(`select`)})),Lg.and(R({type:V(`boolean`)}))]),R({id:jg,name:N(),description:H(N().nullish(),()=>void 0),category:H(Mg.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)})),zg=R({sessionId:Z,modes:H(Ag.nullish(),()=>void 0),configOptions:H(G(Rg).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Bg=R({modes:H(Ag.nullish(),()=>void 0),configOptions:H(G(Rg).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Vg=R({sessions:ol(G(R({sessionId:Z,cwd:N(),additionalDirectories:H(G(N()).optional(),()=>[]),title:H(N().nullish(),()=>void 0),updatedAt:H(N().nullish(),()=>void 0),archived:H(F().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)})),()=>[]),nextCursor:H(N().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Hg=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Ug=R({sessionId:Z,modes:H(Ag.nullish(),()=>void 0),configOptions:H(G(Rg).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Wg=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Gg=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Kg=R({status:z([V(`open`),V(`saved`),N()]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),qg=R({title:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Jg=R({modes:H(Ag.nullish(),()=>void 0),configOptions:H(G(Rg).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Yg=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Xg=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Zg=R({configOptions:ol(G(Rg),()=>[]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Qg=z([V(`end_turn`),V(`max_tokens`),V(`max_turn_requests`),V(`refusal`),V(`cancelled`)]),$g=R({totalTokens:q().gte(0),inputTokens:q().gte(0),outputTokens:q().gte(0),thoughtTokens:H(q().gte(0).nullish(),()=>void 0),cachedReadTokens:H(q().gte(0).nullish(),()=>void 0),cachedWriteTokens:H(q().gte(0).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),e_=R({stopReason:Qg,usage:H($g.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),t_=I(),n_=R({code:z([V(-32700),V(-32600),V(-32601),V(-32602),V(-32603),V(-32800),V(-32e3),V(-32002),yc().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`})]),message:N(),data:H(I().optional(),()=>void 0)});z([R({id:Jm,result:z([_g,vg,Sg,Cg,wg,Tg,Og,zg,Bg,Vg,Hg,Ug,Wg,Gg,Kg,qg,Jg,Yg,Xg,Zg,e_,t_])}),R({id:Jm,error:n_})]);var r_=N(),i_=R({content:sh,messageId:H(r_.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),a_=R({toolCallId:Zm,title:N(),name:H(N().nullish(),()=>void 0),kind:H(Qm.optional(),()=>void 0),status:H($m.optional(),()=>void 0),content:H(G(fh).optional(),()=>[]),locations:H(G(ph).optional(),()=>[]),rawInput:H(I().optional(),()=>void 0),rawOutput:H(I().optional(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),o_=z([V(`high`),V(`medium`),V(`low`)]),s_=z([V(`pending`),V(`in_progress`),V(`completed`)]),c_=R({content:N(),priority:o_,status:s_,_meta:H(B(N(),I()).nullish(),()=>void 0)}),l_=R({entries:ol(G(c_),()=>[]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),u_=N(),d_=R({planId:u_,entries:ol(G(c_),()=>[]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),f_=R({planId:u_,uri:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),p_=R({planId:u_,content:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),m_=R({plan:z([d_.and(R({type:V(`items`)})),f_.and(R({type:V(`file`)})),p_.and(R({type:V(`markdown`)}))]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),h_=R({planId:u_,_meta:H(B(N(),I()).nullish(),()=>void 0)}),g_=R({hint:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),__=R({availableCommands:ol(G(R({name:N(),description:N(),input:H(g_.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)})),()=>[]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),v_=R({currentModeId:kg,_meta:H(B(N(),I()).nullish(),()=>void 0)}),y_=R({configOptions:ol(G(Rg),()=>[]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),b_=R({title:H(N().nullish(),()=>void 0),updatedAt:H(N().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),x_=R({amount:_c(),currency:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),S_=R({used:q().gte(0),size:q().gte(0),cost:H(x_.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),C_=R({severity:z([V(`info`),V(`warning`),V(`error`),N()]),title:N().min(1),description:H(N().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),w_=N(),T_=R({compactionId:w_,status:z([V(`in_progress`),V(`completed`),V(`failed`),V(`cancelled`),N()]),summary:H(G(sh).nullish(),()=>void 0),error:H(N().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),E_=R({compactionId:w_,content:sh,_meta:H(B(N(),I()).nullish(),()=>void 0)}),D_=R({cancel:H(R({_meta:H(B(N(),I()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),O_=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),k_=R({error:H(n_.nullish(),()=>void 0)}),A_=cl(W(jc(z([R({stopReason:V(`end_turn`)}),R({stopReason:V(`max_tokens`)}),R({stopReason:V(`max_turn_requests`)}),R({stopReason:V(`refusal`)}),R({stopReason:V(`cancelled`)}),k_.and(R({stopReason:V(`error`)})),U(R({stopReason:N()}),`stopReason`,[`cancelled`,`end_turn`,`error`,`max_tokens`,`max_turn_requests`,`refusal`]),R({stopReason:Sc().optional()})]),R({usage:H($g.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0),stopReason:H(N().nullish(),()=>void 0)})),`stopReason`,[`cancelled`,`end_turn`,`error`,`max_tokens`,`max_turn_requests`,`refusal`]),`stopReason`),j_=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),M_=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),N_=W(z([O_.and(R({state:V(`running`)})),A_.and(R({state:V(`idle`)})),j_.and(R({state:V(`requires_action`)})),M_.and(R({state:V(`unknown`)})),U(R({state:N()}),`state`,[`idle`,`requires_action`,`running`,`unknown`])]),`state`,[`idle`,`requires_action`,`running`,`unknown`]),P_=R({sessionId:Z,title:H(N().nullish(),()=>void 0),description:H(N().nullish(),()=>void 0),capabilities:H(D_.nullish(),()=>void 0),state:H(N_.nullish(),()=>void 0),cwd:N().nullish(),additionalDirectories:L(N()).nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),F_=R({messageId:r_,senderSessionId:H(Z.nullish(),()=>void 0),recipientSessionId:H(Z.nullish(),()=>void 0),senderMessageId:H(r_.nullish(),()=>void 0),recipientMessageId:H(r_.nullish(),()=>void 0),content:H(G(sh).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),I_=R({messageId:r_,content:sh,_meta:H(B(N(),I()).nullish(),()=>void 0)}),L_=R({sessionId:Z,update:z([i_.and(R({sessionUpdate:V(`user_message_chunk`)})),i_.and(R({sessionUpdate:V(`agent_message_chunk`)})),i_.and(R({sessionUpdate:V(`agent_thought_chunk`)})),a_.and(R({sessionUpdate:V(`tool_call`)})),mh.and(R({sessionUpdate:V(`tool_call_update`)})),l_.and(R({sessionUpdate:V(`plan`)})),m_.and(R({sessionUpdate:V(`plan_update`)})),h_.and(R({sessionUpdate:V(`plan_removed`)})),__.and(R({sessionUpdate:V(`available_commands_update`)})),v_.and(R({sessionUpdate:V(`current_mode_update`)})),y_.and(R({sessionUpdate:V(`config_option_update`)})),b_.and(R({sessionUpdate:V(`session_info_update`)})),S_.and(R({sessionUpdate:V(`usage_update`)})),C_.and(R({sessionUpdate:V(`notice`)})),T_.and(R({sessionUpdate:V(`compaction_update`)})),E_.and(R({sessionUpdate:V(`compaction_summary_chunk`)})),P_.and(R({sessionUpdate:V(`subagent_update`)})),F_.and(R({sessionUpdate:V(`session_message`)})),I_.and(R({sessionUpdate:V(`session_message_chunk`)}))]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),R_=R({elicitationId:Bh,_meta:H(B(N(),I()).nullish(),()=>void 0)}),z_=R({state:Eg,accounts:H(G(Dg).optional(),()=>[]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),B_=I();R({method:N(),params:z([L_,R_,z_,B_]).nullish()});var V_=R({readTextFile:H(F().optional().default(!1),()=>!1),writeTextFile:H(F().optional().default(!1),()=>!1),_meta:H(B(N(),I()).nullish(),()=>void 0)}),H_=B(N(),I()),U_=R({boolean:H(R({_meta:H(B(N(),I()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),W_=B(N(),I()),G_=R({compaction:H(H_.nullish(),()=>void 0),configOptions:H(U_.nullish(),()=>void 0),notices:H(W_.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),K_=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),q_=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),J_=R({terminal:H(F().optional().default(!1),()=>!1),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Y_=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),X_=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Z_=R({form:H(Y_.nullish(),()=>void 0),url:H(X_.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Q_=R({protocolVersion:qh,clientCapabilities:H(R({fs:H(V_.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:H(F().optional().default(!1),()=>!1),session:H(G_.nullish(),()=>void 0),subagents:H(K_.nullish(),()=>void 0),plan:H(q_.nullish(),()=>void 0),auth:H(J_.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:H(Z_.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}).optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:H(gg.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),$_=R({methodId:fg,_meta:H(B(N(),I()).nullish(),()=>void 0)}),ev=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),tv=R({providerId:yg,apiType:bg,baseUrl:N(),headers:B(N(),N()).optional(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),nv=R({providerId:yg,_meta:H(B(N(),I()).nullish(),()=>void 0)}),rv=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),iv=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),av=R({name:N(),value:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),ov=R({name:N(),url:N(),headers:K(L(av),()=>[]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),sv=R({name:N(),url:N(),headers:K(L(av),()=>[]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),cv=R({name:N(),serverId:Uh,_meta:H(B(N(),I()).nullish(),()=>void 0)}),lv=R({name:N(),command:N(),args:K(L(N()),()=>[]),env:K(L(vh),()=>[]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),uv=z([ov.and(R({type:V(`http`)})),sv.and(R({type:V(`sse`)})),cv.and(R({type:V(`acp`)})),lv]),dv=R({mode:z([V(`append`),V(`override`),N()]),content:L(sh),_meta:H(B(N(),I()).nullish(),()=>void 0)}),fv=R({cwd:N(),additionalDirectories:K(L(N()),()=>[]).optional(),mcpServers:K(L(uv),()=>[]),systemPrompt:dv.nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),pv=R({mcpServers:K(L(uv),()=>[]),cwd:N(),additionalDirectories:K(L(N()),()=>[]).optional(),sessionId:Z,systemPrompt:dv.nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),mv=z([V(`exclude`),V(`include`),V(`only`),N()]),hv=R({cwd:N().nullish(),cursor:N().nullish(),archived:mv.nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),gv=R({sessionId:Z,_meta:H(B(N(),I()).nullish(),()=>void 0)}),_v=R({sessionId:Z,cwd:N(),additionalDirectories:K(L(N()),()=>[]).optional(),mcpServers:K(L(uv),()=>[]).optional(),systemPrompt:dv.nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),vv=R({sessionId:Z,_meta:H(B(N(),I()).nullish(),()=>void 0)}),yv=R({sessionId:Z,_meta:H(B(N(),I()).nullish(),()=>void 0)}),bv=R({sessionId:Z,_meta:H(B(N(),I()).nullish(),()=>void 0)}),xv=R({sessionId:Z,title:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Sv=R({sessionId:Z,cwd:N(),additionalDirectories:K(L(N()),()=>[]).optional(),mcpServers:K(L(uv),()=>[]).optional(),systemPrompt:dv.nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Cv=R({sessionId:Z,_meta:H(B(N(),I()).nullish(),()=>void 0)}),wv=R({sessionId:Z,modeId:kg,_meta:H(B(N(),I()).nullish(),()=>void 0)}),Tv=jc(z([R({type:V(`boolean`),value:F()}),R({value:Ng})]),R({sessionId:Z,configId:jg,_meta:H(B(N(),I()).nullish(),()=>void 0)})),Ev=R({sessionId:Z,prompt:L(sh),_meta:H(B(N(),I()).nullish(),()=>void 0)});R({id:Jm,method:N(),params:z([Q_,$_,ev,tv,nv,rv,iv,fv,pv,hv,gv,_v,vv,yv,bv,xv,Sv,Cv,wv,Tv,Ev,Kh]).nullish()});var Dv=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Ov=R({content:N(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),kv=R({optionId:hh,_meta:H(B(N(),I()).nullish(),()=>void 0)}),Av=R({outcome:z([R({outcome:V(`cancelled`)}),kv.and(R({outcome:V(`selected`)}))]),_meta:H(B(N(),I()).nullish(),()=>void 0)}),jv=R({terminalId:uh,_meta:H(B(N(),I()).nullish(),()=>void 0)}),Mv=R({exitCode:H(yc().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:H(N().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Nv=R({output:N(),truncated:F(),exitStatus:H(Mv.nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Pv=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Fv=R({exitCode:H(yc().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:H(N().nullish(),()=>void 0),_meta:H(B(N(),I()).nullish(),()=>void 0)}),Iv=R({_meta:H(B(N(),I()).nullish(),()=>void 0)}),Lv=z([N(),q(),_c(),F(),L(N())]),Rv=W(jc(z([R({content:B(N(),Lv).nullish()}).and(R({action:V(`accept`)})),R({action:V(`decline`)}),R({action:V(`cancel`)}),U(R({action:N()}),`action`,[`accept`,`cancel`,`decline`])]),R({_meta:H(B(N(),I()).nullish(),()=>void 0)})),`action`,[`accept`,`cancel`,`decline`]),zv=Oc({code:yc().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`}),message:N(),data:I().optional()});z([R({id:Jm,result:z([Dv,Ov,Av,jv,Nv,Pv,Fv,Iv,Rv,z([R({result:I(),_meta:H(B(N(),I()).nullish(),()=>void 0)}),R({error:zv,_meta:H(B(N(),I()).nullish(),()=>void 0)})]),t_])}),R({id:Jm,error:n_})]);var Bv=R({sessionId:Z,_meta:H(B(N(),I()).nullish(),()=>void 0)}),Vv=R({serverId:Uh,requestId:Wh,method:N(),params:B(N(),I()).nullish(),_meta:H(B(N(),I()).nullish(),()=>void 0)});R({method:N(),params:z([Bv,Vv,B_]).nullish()}),R({requestId:Jm,_meta:H(B(N(),I()).nullish(),()=>void 0)});var Hv=Q_,Uv=R({method:N(),params:I().optional(),_meta:H(B(N(),I()).nullish(),()=>void 0)});R({id:Jm,method:N(),params:z([Hv,Uv]).nullish()}),z([R({id:Jm,result:z([_g,I()])}),R({id:Jm,error:n_})]);var Wv=R({method:N(),params:I().optional(),_meta:H(B(N(),I()).nullish(),()=>void 0)});R({method:N(),params:Wv.nullish()});var Gv=Symbol(`connectionContextOf`);function Kv(e){return e??{}}var qv=new Set([...Object.values(j),...Object.values(Ms),...Object.values(Ns)]);function Jv(e,t,n,r=!1){if(!(Object.hasOwn(t,e)||r&&e===Ns.cancel_request)&&qv.has(e))throw TypeError(`ACP v2 ${n} method '${e}' is not valid in this direction`)}function Yv(e,t){if(qv.has(e))throw TypeError(`Cannot replace the built-in ACP v2 ${t} parser for '${e}'`)}var Xv={name:`unknown`,version:`unknown`};function Zv(e){return Ny(mu).parse($v(e)?e.protocolVersion:void 0)}function Qv(e){let t=Zv(e);if(t<2)throw X.unsupportedProtocolVersion(t,[2]);let n=t>2&&$v(e),r=Ny(Af).parse(n&&!hu.safeParse(e.info).success?{...e,info:Xv}:e);return structuredClone({...r,protocolVersion:2})}function $v(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ey(e){let t={...typeof e==`object`&&e&&!Array.isArray(e)?e:{},protocolVersion:2},n=Qv(t);return{wire:structuredClone(t),parsed:n}}function ty(e){let t=Ny(Bu).parse(e);if(t.protocolVersion!==2)throw X.invalidRequest({expectedProtocolVersion:2,receivedProtocolVersion:t.protocolVersion},`The v2 API only supports protocol version 2`);return structuredClone(t)}function ny(e){return ty(e),structuredClone(e)}function ry(e){return structuredClone(e)}function iy(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}var ay=class{phase=`uninitialized`;request;snapshot;otherRequestSeen=!1;attempt=iy();barrier=iy();constructor(){this.barrier.promise.catch(()=>{}),this.attempt.resolve()}get status(){return this.phase}get initialized(){return this.barrier.promise.then(()=>this.attempt.promise).then(()=>ry(this.snapshot))}beginError(){if(this.phase===`initializing`)return X.invalidRequest(`ACP v2 initialize is already in progress`);if(this.phase===`failed`)return X.invalidRequest(`ACP v2 connection initialization failed`);if(this.phase===`initialized`&&this.otherRequestSeen)return X.invalidRequest(`ACP v2 initialize must not be repeated after other requests`)}begin(e){let t=this.beginError();if(t)throw t;let n=structuredClone(e);this.request=n,this.phase=`initializing`,this.attempt=iy()}complete(e){if(this.phase!==`initializing`||!this.request)throw X.invalidRequest(`ACP v2 initialization is not in progress`);let t={request:structuredClone(this.request),response:structuredClone(e)};this.snapshot=t,this.request=void 0,this.phase=`initialized`,this.barrier.resolve(t),this.attempt.resolve()}get hasInitialized(){return this.snapshot!==void 0&&this.phase!==`failed`}failAttempt(){this.phase===`initializing`&&(this.phase=this.snapshot?`initialized`:`uninitialized`,this.request=void 0,this.attempt.resolve())}fail(e){this.phase===`initializing`&&this.snapshot?this.failAttempt():(this.phase===`uninitialized`||this.phase===`initializing`)&&(this.phase=`failed`,this.request=void 0,this.barrier.reject(e??X.invalidRequest(`ACP v2 connection initialization failed`)),this.attempt.resolve())}noteRequest(){(this.phase===`initializing`||this.phase===`initialized`)&&(this.otherRequestSeen=!0)}waitUntilInitialized(e){return this.phase===`initialized`?Promise.resolve():this.phase===`initializing`?this.attempt.promise.then(()=>this.waitUntilInitialized(e)):this.phase===`failed`?this.barrier.promise.then(()=>{}):Promise.reject(cy(e))}},oy=new WeakMap;function sy(e){let t=oy.get(e);return t||(t=new ay,oy.set(e,t),e.signal.aborted?t.fail(e.signal.reason):e.signal.addEventListener(`abort`,()=>t?.fail(e.signal.reason),{once:!0})),t}function cy(e){return X.invalidRequest(`ACP v2 connection must be initialized before '${e}'`)}async function ly(e){return uy(e,cy(e.method))}async function uy(e,t){return e.kind===`request`&&await e.responder.respondWithError(t),vm.yes()}async function dy(e){if(!(e.kind!==`request`||Am(e.raw.id)))return await jm(e.responder,X.invalidRequest(void 0,`ACP v2 request IDs must be strings or integers`)),vm.yes()}async function fy(e,t){if(t.status===`initialized`)return vm.no(e);if(t.status===`initializing`){try{await t.waitUntilInitialized(e.method)}catch{return ly(e)}return vm.no(e)}return ly(e)}function py(){return{async handleMessage(e,t){let n=await dy(e);if(n)return n;let r=sy(t);return e.kind===`notification`&&e.method===Ns.cancel_request?vm.yes():fy(e,r)},describe:()=>`client-initialization`}}function my(e,t){return Gm(e.response,t)}function hy(e){return typeof e==`object`&&!!e&&`readable`in e&&`writable`in e}function gy(){let e=new TransformStream,t=new TransformStream;return[{readable:t.readable,writable:e.writable},{readable:e.readable,writable:t.writable}]}Object.keys(Cu.shape).filter(e=>e!==`_meta`);var _y={agent:{initialize:j.initialize,auth:{login:j.auth_login,logout:j.auth_logout,status:j.auth_status},providers:{list:j.providers_list,set:j.providers_set,disable:j.providers_disable},session:{new:j.session_new,list:j.session_list,delete:j.session_delete,fork:j.session_fork,archive:j.session_archive,unarchive:j.session_unarchive,status:j.session_status,setTitle:j.session_set_title,resume:j.session_resume,close:j.session_close,setConfigOption:j.session_set_config_option,prompt:j.session_prompt,cancel:j.session_cancel},toolCall:{cancel:j.tool_call_cancel},terminal:{cancel:j.terminal_cancel},mcp:{message:j.mcp_message}},client:{session:{requestPermission:Ms.session_request_permission,update:Ms.session_update},mcp:{message:Ms.mcp_message},elicitation:{create:Ms.elicitation_create,complete:Ms.elicitation_complete},auth:{statusUpdate:Ms.auth_status_update}},protocol:{cancelRequest:Ns.cancel_request}},vy=Symbol(`startActiveSession`),yy=Symbol(`routeActiveSessionUpdate`),by=class{cx;currentRequestId;constructor(e,t){this.cx=e,this.currentRequestId=t}get initialized(){return sy(this.cx).initialized}get initializationLifecycle(){return sy(this.cx)}get requestId(){return this.currentRequestId}get connectionContext(){return this.cx}[Gv](){return this.cx}sendRequest(e,t,n,r){return this.cx.sendRequest(e,t,n,r)}sendNotification(e,t){return this.cx.sendNotification(e,t)}addDynamicHandler(e){return this.cx.addDynamicHandler(e)}},xy=class e extends by{constructor(e,t){super(e,t)}static create(t,n){return new e(t,n)}request(e,t,n){Jv(e,Hy,`request`);let r=Hy[e];return this.initializationLifecycle.waitUntilInitialized(e).then(()=>this.sendRequest(e,t,r?e=>my(r,e):void 0,n))}notify(e,t){return Jv(e,Uy,`notification`,!0),this.initializationLifecycle.waitUntilInitialized(e).then(()=>this.sendNotification(e,t))}},Sy=class e extends by{closeOnInitializationFailure;constructor(e,t,n){super(e,t),this.closeOnInitializationFailure=n}static create(t,n,r){return new e(t,n,r)}[vy](e,t){return this.request(j.session_new,e,t).then(e=>this.attachSession(e))}buildSession(e){return typeof e==`string`?jy.create(this,{cwd:e,mcpServers:[]}):jy.create(this,e)}attachSession(e){let t=new Oy,n=this.connectionContext.signal,r=()=>{t.fail(n.reason??Error(`ACP connection closed`))};n.aborted?r():n.addEventListener(`abort`,r);let i=[],a=My.create(this,e,t,i);return i.push(Jy(this.connectionContext).attach(e,{enqueue:e=>a[yy](e)}),new Mm(()=>{n.removeEventListener(`abort`,r)})),a}request(e,t,n){Jv(e,By,`request`);let r=By[e],i=this.initializationLifecycle;if(e===j.initialize){let{wire:a,parsed:o}=ey(t);i.begin(o);let s,c=!1;try{s=this.sendRequest(e,a,e=>{try{let t=my(r,e);return i.complete(t),t}catch(e){throw c=!0,e}},n)}catch(e){throw this.failInitialization(e),e}return s.catch(e=>{i.status===`initializing`&&(c?this.failInitialization(e):i.failAttempt())}),s}i.noteRequest();let a=r?e=>my(r,e):void 0;return i.waitUntilInitialized(e).then(()=>cm(e,this.sendRequest(e,t,a,n),()=>a?a({}):{}))}failInitialization(e){let t=this.initializationLifecycle;t.fail(e),t.status===`failed`&&this.closeOnInitializationFailure?.(e)}notify(e,t){return Jv(e,Vy,`notification`,!0),this.initializationLifecycle.waitUntilInitialized(e).then(()=>this.sendNotification(e,t))}},Cy=class{connection;constructor(e){this.connection=e}get initialized(){return sy(this.connection.getContext()).initialized}get signal(){return this.connection.signal}get closed(){return this.connection.closed}close(e){this.connection.close(e)}},wy=class extends Cy{connectHandlers;client;didStartConnectHandlers=!1;constructor(e,t=[]){super(e),this.connectHandlers=t,this.client=xy.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Yy(this,this.connectHandlers))}},Ty=class extends Cy{connectHandlers;agent;didStartConnectHandlers=!1;constructor(e,t=[]){super(e),this.connectHandlers=t,this.agent=Sy.create(e.getContext(),void 0,t=>e.close(t))}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Yy(this,this.connectHandlers))}};function Ey(e,t=[]){return new wy(e,t)}function Dy(e,t=[]){return new Ty(e,t)}var Oy=class{values=[];waiters=[];failed=!1;failure;enqueue(e){if(this.failed)return;let t=this.waiters.shift();t?t.resolve(e):this.values.push(e)}fail(e){if(!this.failed){this.failed=!0,this.failure=e;for(let t of this.waiters.splice(0))t.reject(e)}}next(e){return e?.aborted?Promise.reject(e.reason):this.values.length>0?Promise.resolve(this.values.shift()):this.failed?Promise.reject(this.failure):new Promise((t,n)=>{let r=()=>{e?.removeEventListener(`abort`,a)},i={resolve:e=>{r(),t(e)},reject:e=>{r(),n(e)}},a=()=>{let t=this.waiters.indexOf(i);t>=0&&this.waiters.splice(t,1),i.reject(e?.reason)};this.waiters.push(i),e?.addEventListener(`abort`,a,{once:!0}),e?.aborted&&a()})}};function ky(e,t,n){n!==void 0&&(n?.cancel==null?e.delete(t):e.add(t))}function Ay(e){return structuredClone(e)}var jy=class e{cx;request;constructor(e,t){this.cx=e,this.request=Ay(t)}static create(t,n){return new e(t,n)}toRequest(){return Ay(this.request)}withAdditionalDirectories(e){return this.request={...this.request,additionalDirectories:[...e]},this}withMcpServer(e){return this.request={...this.request,mcpServers:[...this.request.mcpServers??[],structuredClone(e)]},this}async start(e){return this.cx[vy](this.toRequest(),e)}async withSession(e){let t=await this.start();try{return await e(t)}finally{t.dispose()}}},My=class e{cx;sessionResponse;updates;registrations;currentConfigOptions;latestBackground;cancellableToolCalls=new Set;cancellableTerminals=new Set;constructor(e,t,n,r){this.cx=e,this.sessionResponse=t,this.updates=n,this.registrations=r,this.currentConfigOptions=t.configOptions??void 0}static create(t,n,r,i){return new e(t,n,r,i)}get sessionId(){return this.sessionResponse.sessionId}get configOptions(){return this.currentConfigOptions}get meta(){return this.sessionResponse._meta}get background(){return this.latestBackground}isForBackgroundWork(e){let t=this.latestBackground,n=e.subject;if(!t||!n)return!1;let r,i;return nm.isToolCall(n)?r=n.toolCall.toolCallId:nm.isCommand(n)&&(r=n.toolCallId,i=n.terminalId),t.some(e=>r!=null&&am.isToolCall(e)&&e.toolCallId===r||i!=null&&am.isTerminal(e)&&e.terminalId===i)}canCancelToolCall(e){return this.cancellableToolCalls.has(e)}canCancelTerminal(e){return this.cancellableTerminals.has(e)}cancelToolCall(e,t){return this.canCancelToolCall(e)?this.cx.request(j.tool_call_cancel,{sessionId:this.sessionId,toolCallId:e},t):Promise.reject(TypeError(`Tool call ${JSON.stringify(e)} does not advertise cancel`))}cancelTerminal(e,t){return this.canCancelTerminal(e)?this.cx.request(j.terminal_cancel,{sessionId:this.sessionId,terminalId:e},t):Promise.reject(TypeError(`Terminal ${JSON.stringify(e)} does not advertise cancel`))}get newSessionResponse(){return this.sessionResponse}prompt(e,t){let n=this.promptBlocks(e);return n.length===0?Promise.reject(TypeError(`A prompt must contain at least one content block`)):this.cx.request(j.session_prompt,{sessionId:this.sessionId,prompt:n},t)}async setConfigOption(e,t){let n=await this.cx.request(j.session_set_config_option,{...e,sessionId:this.sessionId},t);return this.currentConfigOptions=n.configOptions,n}nextUpdate(e){return this.updates.next(e)}async readTextUntilIdle(e){let t=[],n=new Map,r=e=>{let r=n.get(e);return r||(r=[],t.push(e),n.set(e,r)),r};for(;;){let i=await this.nextUpdate(e);if(i.kind===`stop`)return t.flatMap(e=>n.get(e)??[]).filter(rm.isText).map(e=>e.text).join(``);let{update:a}=i;om.isAgentMessage(a)?(r(a.messageId),a.content!==void 0&&n.set(a.messageId,a.content??[])):om.isAgentMessageChunk(a)&&r(a.messageId).push(a.content)}}[yy](e){let{update:t}=e;om.isConfigOptionUpdate(t)?this.currentConfigOptions=t.configOptions:om.isStateUpdate(t)?this.latestBackground=!im.isCustom(t)&&Array.isArray(t.background)?t.background:void 0:om.isToolCallUpdate(t)?ky(this.cancellableToolCalls,t.toolCallId,t.capabilities):om.isTerminalUpdate(t)&&ky(this.cancellableTerminals,t.terminalId,t.capabilities),this.updates.enqueue(e)}dispose(){for(let e of this.registrations.splice(0))e.dispose();this.updates.fail(Error(`Active session disposed`))}[Symbol.dispose](){this.dispose()}promptBlocks(e){return typeof e==`string`?[{type:`text`,text:e}]:Array.isArray(e)?e:[e]}};function Ny(e){return e}function Q(e,t,n,r){return{method:e,params:e=>Gm(t,e??{}),response:n,serializeResponse:r}}function Py(e,t){return{method:e,params:t}}function Fy(e){let t=Object.create(null);for(let n of Object.values(e))t[n.method]=n;return t}var Iy={initialize:Q(j.initialize,Qv,ty,ny),loginAuth:Q(j.auth_login,jf,Vu,Kv),unstable_listProviders:Q(j.providers_list,Mf,Gu),unstable_setProvider:Q(j.providers_set,Nf,Ku,Kv),unstable_disableProvider:Q(j.providers_disable,Pf,qu,Kv),newSession:Q(j.session_new,Ny(Uf),Ny(ud)),setSessionConfigOption:Q(j.session_set_config_option,Ny(ip),Ny(zd)),prompt:Q(j.session_prompt,Ny(ap),Ny(Vd)),listSessions:Q(j.session_list,Gf,pd),deleteSession:Q(j.session_delete,Kf,md,Kv),unstable_forkSession:Q(j.session_fork,Ny(qf),Ny(hd)),unstable_archiveSession:Q(j.session_archive,Jf,gd,Kv),unstable_unarchiveSession:Q(j.session_unarchive,Yf,_d,Kv),unstable_sessionStatus:Q(j.session_status,Xf,Ny(Nd)),unstable_setSessionTitle:Q(j.session_set_title,Zf,Pd),resumeSession:Q(j.session_resume,Ny(ep),Ny(Fd)),closeSession:Q(j.session_close,tp,Id,Kv),cancelToolCall:Q(j.tool_call_cancel,np,Ld,Kv),cancelTerminal:Q(j.terminal_cancel,rp,Rd,Kv),logoutAuth:Q(j.auth_logout,Ff,Ju,Kv),unstable_authStatus:Q(j.auth_status,If,Zu)},Ly={cancelSession:Py(j.session_cancel,mp),unstable_messageMcp:Py(j.mcp_message,hp)},Ry={requestPermission:Q(Ms.session_request_permission,Ny(Wl),Ny(cp)),unstable_messageMcp:Q(Ms.mcp_message,fu,pp),createElicitation:Q(Ms.elicitation_create,Ny(lu),Ny(dp))},zy={sessionUpdate:Py(Ms.session_update,Ny(Sf)),completeElicitation:Py(Ms.elicitation_complete,Cf),unstable_authStatusUpdate:Py(Ms.auth_status_update,wf)},By=Fy(Iy),Vy=Fy(Ly),Hy=Fy(Ry),Uy=Fy(zy);function Wy(e,t,n,r,i){return{method:i,params:e,requestId:r,signal:n,agent:t}}function Gy(e,t,n,r){return{method:r,params:e,signal:n,agent:t}}var Ky=class{activeSessions=new Map;handleMessage(e){if(e.kind!==`notification`||e.method!==Ms.session_update)return vm.no(e);let t=Ny(Sf).parse(e.params),{update:n}=t,r=om.isStateUpdate(n)&&im.isIdle(n),i=this.activeSessions.get(t.sessionId);if(i&&i.size>0)for(let e of i)r?e.enqueue({kind:`stop`,notification:t,update:n,stopReason:n.stopReason}):e.enqueue({kind:`session_update`,notification:t,update:n});return vm.no(e)}attach(e,t){let n=this.activeSessions.get(e.sessionId)??new Set;return n.add(t),this.activeSessions.set(e.sessionId,n),new Mm(()=>{n.delete(t),n.size===0&&this.activeSessions.delete(e.sessionId)})}},qy=new WeakMap;function Jy(e){let t=qy.get(e);return t||(t=new Ky,qy.set(e,t)),t}function Yy(e,t){for(let n of t){let t;try{t=n(e)}catch(t){throw e.close(t),t}Promise.resolve(t).catch(t=>{e.close(t)})}}var Xy=Symbol(`appBuilder`),Zy=Symbol(`runAgentConnectHandlers`),Qy=Symbol(`runClientConnectHandlers`);function $y(e,t){e.closed.then(async()=>{sy(e.getContext()).status===`initialized`&&await t.initialized.catch(()=>{}),t.close(e.signal.reason)})}function eb(e){return new tb(e)}var tb=class{builder=Pm.builder();connectHandlers=[];fallbackKinds=new Set;constructor(e={}){e.name&&this.builder.name(e.name),this.builder.withHandler(py()),this.builder.withHandler({handleMessage:(e,t)=>Jy(t).handleMessage(e),describe:()=>`client-session-update-router`})}[Xy](){return this.builder}[Qy](e){Yy(e,this.connectHandlers)}connect(e){return this.connectConnection(e).connection}connectWith(e,t){let{rawConnection:n,connection:r}=this.connectConnection(e);return n.runUntil(()=>t(r.agent))}onConnect(e){return this.connectHandlers.push(e),this}onRequest(e,t,n){if(e===`*`){if(n)throw Error(`Wildcard handlers receive raw params; omit the parser.`);if(this.fallbackKinds.has(`request`))throw Error(`A request fallback is already registered.`);return this.fallbackKinds.add(`request`),this.request({method:e},t)}if(n)return Yv(e,`request`),this.request({method:e,params:t},n);let r=Hy[e];if(!r)throw Error(`Unknown ACP request method '${e}'. Pass a params parser for custom methods.`);return this.request(r,t)}onNotification(e,t,n){if(e===`*`){if(n)throw Error(`Wildcard handlers receive raw params; omit the parser.`);if(this.fallbackKinds.has(`notification`))throw Error(`A notification fallback is already registered.`);return this.fallbackKinds.add(`notification`),this.notification({method:e},t)}if(n)return Yv(e,`notification`),this.notification({method:e,params:t},n);let r=Uy[e];if(!r)throw Error(`Unknown ACP notification method '${e}'. Pass a params parser for custom methods.`);return this.notification(r,t)}request(e,t){return Km(this.builder,e,(e,t,n,r,i)=>Wy(e,Sy.create(t,r),n,r,i),t,e.serializeResponse),this}notification(e,t){return qm(this.builder,e,(e,t,n,r)=>Gy(e,Sy.create(t),n,r),t),this}connectConnection(e){if(hy(e)){let t=this.openStreamConnection(e);return this[Qy](t.connection),t}let[t,n]=gy(),r=e[Xy]().connect(n),i=Ey(r),a=this.openStreamConnection(t);$y(a.rawConnection,i),$y(r,a.connection);try{e[Zy](i),this[Qy](a.connection)}catch(e){throw i.close(e),a.connection.close(e),e}return a}openStreamConnection(e){let t=this.builder.connect(e);return{rawConnection:t,connection:Dy(t,this.connectHandlers)}}},nb={initialize:`initialize`,authenticate:`authenticate`,providers_list:`providers/list`,providers_set:`providers/set`,providers_disable:`providers/disable`,session_new:`session/new`,session_load:`session/load`,session_set_mode:`session/set_mode`,session_set_config_option:`session/set_config_option`,session_prompt:`session/prompt`,session_cancel:`session/cancel`,mcp_message:`mcp/message`,session_list:`session/list`,session_delete:`session/delete`,session_fork:`session/fork`,session_archive:`session/archive`,session_unarchive:`session/unarchive`,session_status:`session/status`,session_set_title:`session/set_title`,session_resume:`session/resume`,session_close:`session/close`,logout:`logout`,auth_status:`auth/status`},rb=`Acp-Connection-Id`,ib=`Acp-Session-Id`,ab=`text/event-stream`,ob=`application/json`;nb.session_cancel,nb.session_close,nb.session_delete,nb.session_fork,nb.session_load,nb.session_prompt,nb.session_resume,nb.session_set_config_option,nb.session_set_mode;function sb(e){if(!fm(e))return;let t=e.sessionId;return typeof t==`string`?t:void 0}function cb(e){return`method`in e?sb(e.params):void 0}function lb(e){if(!um(e)||!(`result`in e)||!fm(e.result))return;let t=e.result.sessionId;return typeof t==`string`?t:void 0}function ub(e){return e.jsonrpc===`2.0`&&`id`in e&&`method`in e&&e.method===nb.initialize}function db(e){if(typeof e==`string`)return`string:${e}`;if(typeof e==`number`)return`number:${e}`;if(e===null)return`null`}var fb=class{cookies=new Map;store(e){for(let t of pb(e)){let e=hb(t);e&&this.cookies.set(e.name,e.value)}}apply(e){let t=gb(this.cookieHeader(),e.get(`Cookie`));t&&e.set(`Cookie`,t)}clear(){this.cookies.clear()}cookieHeader(){return this.cookies.size===0?void 0:Array.from(this.cookies).map(([e,t])=>`${e}=${t}`).join(`; `)}};function pb(e){let t=e.getSetCookie;if(typeof t==`function`)return t.call(e).flatMap(mb);let n=e.get(`Set-Cookie`);return n?mb(n):[]}function mb(e){return e.split(/,(?=\s*[^;,\s]+=)/).map(e=>e.trim()).filter(e=>e.length>0)}function hb(e){let t=e.split(`;`,1)[0],n=t.indexOf(`=`);if(n<=0)return;let r=t.slice(0,n).trim();if(r)return{name:r,value:t.slice(n+1).trim()}}function gb(e,t){let n=new Map;for(let t of _b(e))n.set(t.name,t.value);for(let e of _b(t??void 0))n.set(e.name,e.value);return n.size===0?void 0:Array.from(n).map(([e,t])=>`${e}=${t}`).join(`; `)}function _b(e){return e?e.split(`;`).map(vb).filter(e=>e!==void 0):[]}function vb(e){let t=e.indexOf(`=`);if(t<=0)return;let n=e.slice(0,t).trim();if(n)return{name:n,value:e.slice(t+1).trim()}}var yb=new TextEncoder().encode(`data:`),bb=new Uint8Array([10]),xb=9;async function*Sb(e,t=Lm){let n=new TextDecoder(`utf-8`,{ignoreBOM:!0}),r=new Bm(t),i=new Um(Math.min(2**53-1,t+xb),{splitOnCarriageReturn:!0}),a=e.getReader(),o=!1,s=!1,c,l=()=>{if(o)return o=!1,Cb(n.decode(r.take()))},u=e=>{if(e[0]===239&&e[1]===187&&e[2]===191&&(e=e.subarray(3)),e.byteLength===0)return l();if(!yb.every((t,n)=>e[n]===t))return;let t=e.subarray(yb.byteLength+ +(e[yb.byteLength]===32));o&&r.append(bb),r.append(t),o=!0};try{for(;;){let e=await a.read();if(e.done){s=!0;break}for(let t of i.push(e.value)){let e=u(t);e&&(yield e)}}let e=i.flush();if(e){let t=u(e);t&&(yield t)}let t=l();t&&(yield t)}catch(e){throw c=e instanceof Rm&&e.maxMessageBytes!==t?new Rm(t):e,c}finally{i.clear(),r.clear(),s||a.cancel(c).catch(()=>{}),a.releaseLock()}}function Cb(e){if(e.trim())try{let t=JSON.parse(e);if(fm(t)&&!Array.isArray(t))return t;console.warn(`Skipping SSE payload that is not a JSON object`);return}catch{console.warn(`Failed to parse SSE JSON payload (${e.length} characters)`);return}}var wb=new Set([nb.session_load,nb.session_resume]),Tb=new Set([401,403,404,410]),Eb=8192;function Db(e,t={}){return new Ob(e,t).stream}var Ob=class{serverUrl;stream;fetchImpl;headers;maxMessageBytes;cookiePolicy;cookieStore;ownsCookieStore;abortController=new AbortController;knownSessions=new Set;sessionSse=new Map;pendingResponseSessions=new Map;pendingSessionRequests=new Map;sessionErrors=new Map;readableController;connectionId;isClosed=!1;writeChain=Promise.resolve();constructor(e,t){this.serverUrl=e,this.maxMessageBytes=zm(t.maxMessageBytes),this.fetchImpl=kb(t.fetch),this.headers=t.headers??{},this.cookiePolicy=t.cookies??`include`,this.cookieStore=t.cookieStore??new fb,this.ownsCookieStore=t.cookieStore===void 0,this.stream={readable:new ReadableStream({start:e=>{this.readableController=e},cancel:()=>this.close()}),writable:new WritableStream({write:e=>(this.writeChain=this.writeChain.then(()=>this.writeMessage(e)),this.writeChain),close:()=>this.close(),abort:()=>this.close()})}}async writeMessage(e){if(this.isClosed)throw Error(`ACP HTTP stream is closed`);this.connectionId?await this.postConnectedMessage(e):await this.postInitialize(e)}async postInitialize(e){let t;try{if(!ub(e))throw Error(`ACP HTTP stream first message must be initialize`);let n=await this.fetchRequest({method:`POST`,headers:{"Content-Type":ob},body:JSON.stringify(e),signal:this.abortController.signal});if(!n.ok)throw await Pb(`ACP initialize failed`,n,this.maxMessageBytes);let r=n.headers.get(rb);if(!r)throw Error(`ACP initialize response missing Acp-Connection-Id`);t=r,this.throwIfClosedDuringInitialize();let i=JSON.parse(await Ab(n,this.maxMessageBytes));if(this.throwIfClosedDuringInitialize(),!um(i))throw Error(`ACP initialize response was not a JSON-RPC response`);if(db(i.id)!==(`id`in e?db(e.id):void 0))throw Error(`ACP initialize response id did not match initialize request`);this.connectionId=r,this.openConnectionSse(),this.enqueue(i)}catch(e){throw this.isClosed&&t?(await this.deleteConnection(t).catch(()=>void 0),this.clearOwnedCookieStore()):this.errorReadable(e,t),e}}throwIfClosedDuringInitialize(){if(this.isClosed)throw Error(`ACP HTTP stream is closed`)}async postConnectedMessage(e){let t=this.connectionId;if(!t)throw Error(`ACP HTTP stream is not initialized`);let n=this.sessionIdForOutboundMessage(e);if(n){`method`in e&&wb.has(e.method)&&this.sessionErrors.delete(n);try{await this.openSessionSse(n)}catch(t){if(!jb(t))throw t;this.dropSessionMessage(e,t);return}}let r=n&&`method`in e&&`id`in e?db(e.id):void 0;n&&r&&`id`in e&&this.pendingSessionRequests.set(r,{sessionId:n,id:e.id});try{let r=await this.fetchRequest({method:`POST`,headers:{"Content-Type":ob,[rb]:t,...n?{[ib]:n}:{}},body:JSON.stringify(e),signal:this.abortController.signal});if(!r.ok)throw await Pb(`ACP POST failed`,r,Math.min(this.maxMessageBytes,Eb),{truncate:!0});if(r.body?.cancel().catch(()=>{}),!(`method`in e)&&`id`in e){let t=db(e.id);t&&this.pendingResponseSessions.delete(t)}}catch(t){let i=!r||this.pendingSessionRequests.delete(r);if(n&&jb(t)){this.failSession(n,t),this.dropSessionMessage(e,t);return}if(t instanceof Nb&&!Tb.has(t.status)&&`method`in e&&`id`in e){i&&this.enqueueRequestError(e.id,t);return}throw this.errorReadable(t),t}}sessionIdForOutboundMessage(e){let t=cb(e);if(t)return t;if(!(`id`in e)||`method`in e)return;let n=db(e.id);return n?this.pendingResponseSessions.get(n):void 0}openConnectionSse(){let e=this.connectionId;e&&this.openSse({[rb]:e},this.abortController.signal)}openSessionSse(e){let t=this.sessionErrors.get(e);if(t)return Promise.reject(t);let n=this.sessionSse.get(e);if(n)return n.ready;if(this.knownSessions.has(e))return Promise.resolve();let r=this.connectionId;if(!r)return Promise.resolve();let i=!1,a=()=>{},o=()=>{},s=new Promise((e,t)=>{a=e,o=t}),c=e=>{i||(i=!0,e())};s.catch(()=>void 0);let l=new AbortController,u=()=>l.abort();this.abortController.signal.addEventListener(`abort`,u,{once:!0});let d={ready:s,abortController:l};return this.knownSessions.add(e),this.sessionSse.set(e,d),this.openSse({[rb]:r,[ib]:e},l.signal,{onOpen:()=>{c(a)},onError:e=>{c(()=>{o(e)})},onClose:()=>{this.abortController.signal.removeEventListener(`abort`,u),this.sessionSse.get(e)===d&&this.sessionSse.delete(e),c(()=>{o(Error(`ACP session SSE stream closed before opening`))})}}),s}async openSse(e,t,n={}){let r=e[ib];try{let i=await this.fetchRequest({method:`GET`,headers:{Accept:ab,...e},signal:t});if(!i.ok)throw await Pb(`ACP SSE connection failed`,i,this.maxMessageBytes);if(!i.body)throw Error(`ACP SSE response missing body`);n.onOpen?.();for await(let n of Sb(i.body,this.maxMessageBytes)){if(this.isClosed||t.aborted)return;let r=lb(n);r&&this.openSessionSse(r).catch(()=>{}),this.trackServerRequestRoute(n,e[ib]),this.trackInboundResponse(n),this.enqueue(n)}t.aborted||this.handleSseEof(r)}catch(e){if(this.isClosed||t.aborted)return;n.onError?.(e),r&&jb(e)?this.failSession(r,e):this.errorReadable(e)}finally{n.onClose?.()}}handleSseEof(e){this.isClosed||this.abortController.signal.aborted||(e?(this.knownSessions.delete(e),this.rejectPendingSessionRequests(e,Error(`ACP session SSE stream closed`))):this.errorReadable(Error(`ACP connection SSE stream closed`)))}trackServerRequestRoute(e,t){if(!t||!(`method`in e)||!(`id`in e))return;let n=db(e.id);n&&this.pendingResponseSessions.set(n,t)}trackInboundResponse(e){if(!um(e))return;let t=db(e.id);t&&this.pendingSessionRequests.delete(t)}failSession(e,t){this.sessionErrors.set(e,t),this.knownSessions.delete(e);let n=this.sessionSse.get(e);n&&(this.sessionSse.delete(e),n.abortController.abort()),this.rejectPendingSessionRequests(e,t)}rejectPendingSessionRequests(e,t){for(let[n,r]of this.pendingSessionRequests)r.sessionId===e&&(this.pendingSessionRequests.delete(n),this.enqueueRequestError(r.id,t))}dropSessionMessage(e,t){if(!(`id`in e))return;if(`method`in e){this.enqueueRequestError(e.id,t);return}let n=db(e.id);n&&this.pendingResponseSessions.delete(n)}enqueueRequestError(e,t){this.enqueue({jsonrpc:`2.0`,id:e,error:{code:-32603,message:t.message,...t instanceof Nb?{data:{status:t.status,body:Mb(t.body)}}:{}}})}async fetchRequest(e){let t=await this.fetchImpl(this.serverUrl,{...e,credentials:this.cookiePolicy,headers:this.createRequestHeaders(e.headers)});return this.cookiePolicy===`include`&&this.cookieStore.store(t.headers),t}createRequestHeaders(e){let t=new Headers(this.headers);return new Headers(e).forEach((e,n)=>{t.set(n,e)}),this.cookiePolicy===`include`&&this.cookieStore.apply(t),t}async close(){if(!this.isClosed){this.isClosed=!0,this.abortController.abort();try{await this.deleteConnection()}finally{this.clearOwnedCookieStore(),this.closeReadable()}}}async deleteConnection(e=this.connectionId){if(!e)return;let t=await this.fetchRequest({method:`DELETE`,headers:{[rb]:e}});if(!t.ok)throw await Pb(`ACP DELETE failed`,t,this.maxMessageBytes);t.body?.cancel().catch(()=>{})}clearOwnedCookieStore(){this.ownsCookieStore&&this.cookieStore.clear()}enqueue(e){try{this.readableController?.enqueue(e)}catch(e){this.errorReadable(e)}}errorReadable(e,t=this.connectionId){if(!this.isClosed){this.isClosed=!0,this.abortController.abort(),this.deleteConnection(t).catch(()=>void 0).finally(()=>{this.clearOwnedCookieStore()});try{this.readableController?.error(e)}catch{}}}closeReadable(){try{this.readableController?.close()}catch{}}};function kb(e){if(e)return e;if(typeof globalThis.fetch==`function`)return(e,t)=>globalThis.fetch(e,t);throw Error(`createHttpStream requires globalThis.fetch or options.fetch`)}async function Ab(e,t,{truncate:n=!1}={}){if(!e.body)return``;let r=new Bm(t),i=e.body.getReader();try{for(;;){let{value:e,done:a}=await i.read();if(a)return new TextDecoder().decode(r.take());if(n&&e.byteLength>=t-r.byteLength)return r.append(e.subarray(0,t-r.byteLength)),i.cancel().catch(()=>{}),new TextDecoder().decode(r.take(),{stream:!0});r.append(e)}}catch(e){throw i.cancel(e).catch(()=>{}),e}finally{r.clear(),i.releaseLock()}}function jb(e){return e instanceof Nb&&e.status===409}function Mb(e){try{return JSON.parse(e)}catch{return e}}var Nb=class extends Error{status;body;constructor(e,t,n){super(e),this.status=t,this.body=n}};async function Pb(e,t,n,r={}){let i=``;try{i=await Ab(t,n,r)}catch(e){if(e instanceof Rm)throw e}return i?new Nb(`${e}: ${t.status} ${t.statusText}: ${i}`,t.status,i):new Nb(`${e}: ${t.status} ${t.statusText}`,t.status,i)}var $=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Fb(e,t){return $(e)?e.type===`resource_link`&&typeof e.uri==`string`?[{type:`resource_link`,uri:e.uri,...typeof e.name==`string`?{name:e.name}:{},mimeType:typeof e.mimeType==`string`?e.mimeType:t}]:e.type===`text`&&typeof e.text==`string`?e.text:``:``}function Ib(e,t){if(Array.isArray(e)&&e.some(e=>$(e)&&e.type===`content`&&$(e.content)&&e.content.type===`resource_link`)){let n=[];for(let t of e){if(!$(t)||t.type!==`content`||!$(t.content))continue;let e=t.content;e.type===`text`&&typeof e.text==`string`?n.push({type:`text`,text:e.text}):e.type===`resource_link`&&typeof e.uri==`string`&&n.push({type:`resource_link`,uri:e.uri,...typeof e.name==`string`?{name:e.name}:{},mimeType:typeof e.mimeType==`string`?e.mimeType:`text/plain`})}return!n.some(e=>e.type===`text`)&&t!==void 0&&n.unshift({type:`text`,text:typeof t==`string`?t:JSON.stringify(t)}),n}if(t!==void 0)return typeof t==`string`?t:JSON.stringify(t);if(Array.isArray(e)){let t=[];for(let n of e)$(n)&&n.type===`content`&&$(n.content)&&n.content.type===`text`&&typeof n.content.text==`string`&&t.push(n.content.text);return t.join(`
|
|
111
|
+
`)}return``}function Lb(e){let t=e._meta?.plurnk;if(typeof t?.loopId==`number`)return t.loopId;if(e.role===`assistant`&&Array.isArray(e.toolCalls)&&e.toolCalls.length>0){let t=e.toolCalls[0]._meta?.plurnk;if(typeof t?.loopId==`number`)return t.loopId}}function Rb(e,t){if(t.role===`user`&&t._meta?.plurnk?.published===!1){let n=Lb(t);if(n!==void 0){let r=e.findIndex(e=>{let t=Lb(e);return t!==void 0&&t>n});if(r!==-1){e.splice(r,0,t);return}}e.push(t);return}let n=Lb(t);if(n===void 0&&t.role===`tool`){let r=e.find(e=>e.role===`assistant`&&e.toolCalls?.some(e=>e.toolCallId===t.toolCallId));r&&(n=Lb(r))}let r=e.findIndex(e=>{if(e.role!==`user`||e._meta?.plurnk?.published!==!1)return!1;let t=Lb(e);if(n!==void 0&&t!==void 0)return t>=n;if(n===void 0){let t=e._meta?.plurnk?.lifecycle;return t===`running`||t===`queued`||t===`parked`}return!1});r===-1?e.push(t):e.splice(r,0,t)}var zb=class e{static#e=new Set;static projectMessages(t,n=[]){let r=[...n],i=new Set,a=e=>{let t=r[e];if(!i.has(t)){let n=structuredClone(t);return i.add(n),r[e]=n,n}return t};for(let n of t){if(!$(n)||typeof n.sessionUpdate!=`string`)continue;let t=n.sessionUpdate,o=$(n._meta)&&$(n._meta.plurnk)?n._meta.plurnk:void 0,s=typeof n.subagentRunId==`string`?n.subagentRunId:typeof o?.subagentRunId==`string`?o.subagentRunId:void 0;if(t===`user_message_chunk`){let e=typeof n.messageId==`string`&&n.messageId.length>0?n.messageId:typeof o?.messageId==`string`&&o.messageId.length>0?o.messageId:typeof o?.coordinate==`string`?o.coordinate:`user-${r.length+1}`,t=Fb(n.content,`text/plain`),c=r.findIndex(t=>t.id===e&&t.role===`user`);if(c!==-1){let e=a(c),n=e._meta?.plurnk?.published===!1,i=o!==void 0&&o.published!==!1&&(o.id!==void 0||o.coordinate!==void 0);if(Array.isArray(t)?e.content=t:typeof e.content==`string`?o?.id!==void 0&&e._meta?.plurnk?.id===o.id||e.content===t||e._meta?.plurnk===void 0?e.content=t:e.content+=t:e.content=t,s&&(e.subagentRunId=s),o){let t={...$(e._meta?.plurnk)?e._meta.plurnk:{},...structuredClone(o)};i&&delete t.published,e._meta={...e._meta,plurnk:t}}if(n&&i){let t=r.indexOf(e);t!==-1&&(r.splice(t,1),Rb(r,e))}}else{let n={id:e,role:`user`,content:t,...s?{subagentRunId:s}:{},...o?{_meta:{plurnk:structuredClone(o)}}:{}};i.add(n),Rb(r,n)}}else if(t===`agent_message_chunk`){let e=typeof n.messageId==`string`&&n.messageId.length>0?n.messageId:typeof o?.coordinate==`string`?o.coordinate:`assistant-${r.length+1}`,t=Fb(n.content,`text/markdown`),c=r.findIndex(t=>t.id===e&&t.role===`assistant`);if(c!==-1){let e=a(c);Array.isArray(t)?e.content=t:typeof e.content==`string`?o?.id!==void 0&&e._meta?.plurnk?.id===o.id?e.content=t:e.content+=t:e.content=t,s&&(e.subagentRunId=s),o&&(e._meta={...e._meta,plurnk:{...$(e._meta?.plurnk)?e._meta.plurnk:{},...structuredClone(o)}})}else{let n={id:e,role:`assistant`,content:t,...s?{subagentRunId:s}:{},...o?{_meta:{plurnk:structuredClone(o)}}:{}};i.add(n),Rb(r,n)}}else if(t===`agent_thought_chunk`){let e=typeof n.messageId==`string`&&n.messageId.length>0?n.messageId:typeof o?.coordinate==`string`?`${o.coordinate}/reasoning`:`reasoning-${r.length+1}`,t=$(n.content)?n.content:void 0,c=t?.type===`resource_link`&&typeof t.uri==`string`?{url:t.uri,mimeType:typeof t.mimeType==`string`?t.mimeType:`text/plain`}:void 0,l=o||c?{...o?structuredClone(o):{},...c&&!$(o?.body)?{body:c}:{}}:void 0,u=r.findIndex(t=>t.id===e&&t.role===`reasoning`);if(u!==-1){let e=a(u);s&&(e.subagentRunId=s),l&&(e._meta={...e._meta,plurnk:{...$(e._meta?.plurnk)?e._meta.plurnk:{},...l}})}else{let t={id:e,role:`reasoning`,content:``,...s?{subagentRunId:s}:{},...l?{_meta:{plurnk:l}}:{}};i.add(t),Rb(r,t)}}else if(t===`tool_call`||t===`tool_call_update`){let c=typeof n.toolCallId==`string`&&n.toolCallId.length>0?n.toolCallId:typeof o?.coordinate==`string`?o.coordinate:``;if(!c||c.startsWith(`int:`)||$(o?.interaction))continue;if(typeof o?.coordinate==`string`&&o.coordinate===c&&(o.origin===`model`?e.#e.delete(c):typeof o.origin==`string`&&e.#e.add(c)),typeof o?.coordinate==`string`&&o.coordinate!==c){if(e.#e.has(c))continue;let t=o.coordinate,l=o.op===`SEND`||o.op===`DONE`||o.op===`FAIL`?(()=>{if(Array.isArray(n.content)){let e=n.content[0];if($(e)&&e.type===`content`&&$(e.content))return Fb(e.content,`text/markdown`)}return Ib(n.content,n.rawOutput)})():Ib(n.content,n.rawOutput),u=r.findIndex(e=>e.id===t);if(u!==-1){let e=a(u);e.content=l,e.role===`tool`&&n.rawOutput!==void 0&&(e.rawOutput=structuredClone(n.rawOutput)),e._meta={plurnk:structuredClone(o)}}else{let e={id:t,role:`tool`,toolCallId:c,content:l,...n.rawOutput===void 0?{}:{rawOutput:structuredClone(n.rawOutput)},...s?{subagentRunId:s}:{},_meta:{plurnk:structuredClone(o)}};i.add(e),Rb(r,e)}continue}if(typeof o?.origin==`string`&&o.origin!==`model`||o?.op===null||$(o?.attrs)&&o.attrs.kind===`emissionAttempt`||o?.op===`NOTE`&&$(o?.attrs)&&typeof o.attrs.distilled==`string`&&o.attrs.distilled.trim().length>0)continue;let l=r.findIndex(e=>e.role===`assistant`&&e.toolCalls?.some(e=>e.toolCallId===c)),u=l===-1?void 0:(()=>{let e=a(l);return e.role===`assistant`?e.toolCalls?.find(e=>e.toolCallId===c):void 0})(),d=t===`tool_call`||typeof n.name==`string`||typeof o?.op==`string`||n.rawInput!==void 0;if(u){if(typeof n.name==`string`&&n.name.length>0?u.name=n.name:typeof o?.op==`string`&&o.op.length>0&&(u.name=o.op),typeof n.title==`string`&&(u.title=n.title),typeof n.kind==`string`&&(u.kind=n.kind),typeof n.status==`string`&&(u.status=n.status),n.rawInput!==void 0&&(u.rawInput=structuredClone(n.rawInput)),n.rawOutput!==void 0&&(u.rawOutput=structuredClone(n.rawOutput)),Array.isArray(n.locations)&&(u.locations=structuredClone(n.locations)),Array.isArray(n.content)&&(u.content=structuredClone(n.content)),o){let e=$(u._meta?.plurnk)?{...u._meta.plurnk}:{};(n.status===`completed`||n.status===`failed`)&&o.proposal===void 0&&delete e.proposal,u._meta={...u._meta,plurnk:{...e,...structuredClone(o)}}}}else if(d){let e=typeof n.name==`string`&&n.name.length>0?n.name:typeof o?.op==`string`&&o.op.length>0?o.op:typeof n.title==`string`&&n.title.length>0?n.title:`tool`,t=o?structuredClone(o):{},a={id:typeof n.messageId==`string`&&n.messageId.length>0?n.messageId:`call:${c}`,role:`assistant`,content:``,...s?{subagentRunId:s}:{},toolCalls:[{toolCallId:c,name:e,...typeof n.title==`string`?{title:n.title}:{},...typeof n.kind==`string`?{kind:n.kind}:{},...typeof n.status==`string`?{status:n.status}:{},...n.rawInput===void 0?{}:{rawInput:structuredClone(n.rawInput)},...n.rawOutput===void 0?{}:{rawOutput:structuredClone(n.rawOutput)},...Array.isArray(n.locations)?{locations:structuredClone(n.locations)}:{},...Array.isArray(n.content)?{content:structuredClone(n.content)}:{},...Object.keys(t).length>0?{_meta:{plurnk:t}}:{}}]};i.add(a),Rb(r,a)}if(n.status!==`pending`&&(n.rawOutput!==void 0||Array.isArray(n.content)&&n.content.some(e=>$(e)&&e.type===`content`))){let e=typeof o?.messageId==`string`&&o.messageId.length>0?o.messageId:`${c}:result`,t=Ib(n.content,n.rawOutput),s=r.findIndex(t=>t.id===e&&t.role===`tool`);if(s!==-1){let e=a(s);e.role===`tool`&&(e.content=t,n.rawOutput!==void 0&&(e.rawOutput=structuredClone(n.rawOutput)))}else{let a={id:e,role:`tool`,toolCallId:c,content:t,...n.rawOutput===void 0?{}:{rawOutput:structuredClone(n.rawOutput)}};i.add(a),Rb(r,a)}}}else if(t===`plan_update`&&$(n.plan)){if(typeof o?.origin==`string`&&o.origin!==`model`)continue;let e=structuredClone(n.plan),t=typeof o?.coordinate==`string`&&o.coordinate.length>0?o.coordinate:``,c=t?r.findIndex(e=>e.role===`assistant`&&e.toolCalls?.some(e=>e.toolCallId===t)):-1;if(c===-1&&(c=r.findLastIndex(e=>e.role===`assistant`&&e.toolCalls?.some(e=>e.name===`TODO`||$(e._meta?.plurnk)&&e._meta.plurnk.op===`TODO`))),c!==-1){let n=a(c),r=n.role===`assistant`?t?n.toolCalls?.find(e=>e.toolCallId===t):n.toolCalls?.findLast(e=>e.name===`TODO`||$(e._meta?.plurnk)&&e._meta.plurnk.op===`TODO`):void 0;if(r){let t=$(r._meta?.plurnk)?{...r._meta.plurnk}:{};delete t.planRemoved,r._meta={...r._meta,plurnk:{...t,...o?structuredClone(o):{},op:`TODO`,plan:e}}}}else{let n=t||`plan`,a={id:`call:${n}`,role:`assistant`,content:``,...s?{subagentRunId:s}:{},toolCalls:[{toolCallId:n,name:`TODO`,status:`completed`,_meta:{plurnk:{...o?structuredClone(o):{},op:`TODO`,plan:e}}}]};i.add(a),Rb(r,a)}}else if(t===`plan_removed`){let e=typeof o?.loopSeq==`number`?o.loopSeq:null;for(let t=0;t<r.length;t++){let n=r[t];if(n.role!==`assistant`||!n.toolCalls?.some(e=>e.name===`TODO`||$(e._meta?.plurnk)&&e._meta.plurnk.op===`TODO`))continue;let i=a(t);if(i.role===`assistant`&&i.toolCalls)for(let t of i.toolCalls){let n=$(t._meta?.plurnk)?t._meta.plurnk:void 0;if(t.name!==`TODO`&&n?.op!==`TODO`||e!==null&&typeof n?.loopSeq==`number`&&n.loopSeq!==e)continue;let r={...n??{},planRemoved:!0};delete r.plan,t._meta={...t._meta,plurnk:r}}}}}return r}};function Bb(){if(typeof globalThis.crypto?.randomUUID==`function`)return globalThis.crypto.randomUUID();let e=new Uint8Array(16);globalThis.crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var Vb=class{#e;#t=void 0;#n=void 0;#r=Promise.resolve();#i={};#a=!1;#o=[];#s=void 0;#c=new Map;#l=new Set;#u=new Set;#d=[];#f=void 0;#p=0;#m=Promise.resolve();#h=void 0;#g=void 0;#_=void 0;#v=void 0;#y=void 0;#b=void 0;#x=void 0;#S=!1;constructor(e={}){this.url=e.url??`/acp`,this.sessionId=e.sessionId??null,this.headers={...e.headers},this.state=$(e.state)?structuredClone(e.state):{},this.messages=Array.isArray(e.messages)?structuredClone(e.messages):[],this.pendingGates=[],this.abortController=void 0,this.isRunning=!1,this.#e=e.fetch??((e,t)=>globalThis.fetch(e,t))}abortRun(){this.#s?.abort(),this.abortController?.abort()}close(){this.#h!==void 0&&(clearTimeout(this.#h),this.#h=void 0),this.#g=void 0,this.#_=void 0,this.#v=void 0,this.#y=void 0,this.#x=void 0,this.#b=void 0,this.#f=void 0;for(let[,e]of this.#c)e.reject(new DOMException(`The operation was aborted.`,`AbortError`));this.#c.clear(),this.#d=[],this.pendingGates=[],this.#u.clear(),this.#l.clear(),this.#n?.abort(),this.#n=void 0;let e=this.#t;this.#t=void 0,e&&e.close()}#C(e){if(e.method===`session/request_permission`){let t=e._meta?.plurnk?.proposal;return typeof t?.session==`string`?t.session:typeof t?.sessionId==`number`?String(t.sessionId):``}let t=e._meta?.plurnk?.interaction;return typeof t?.sessionId==`number`?String(t.sessionId):``}#w(){let e=$(this.state.plurnk)?this.state.plurnk:void 0,t=$(e?.status)?e.status:void 0;if(!Array.isArray(t?.descendants))return!1;let n=!1,r=t.descendants.map(e=>{if(!$(e))return e;let t=[];for(let n of this.#d){let r=n.method===`session/request_permission`?n._meta?.plurnk?.proposal:void 0,i=n.method===`elicitation/create`?n._meta?.plurnk?.interaction:void 0,a=$(r)&&(typeof e.id==`number`&&r.sessionId===e.id||typeof e.name==`string`&&r.session===e.name),o=$(i)&&typeof e.id==`number`&&i.sessionId===e.id;a&&r!==void 0?t.push(structuredClone(r)):o&&i!==void 0&&t.push(structuredClone(i))}return(Array.isArray(e.gates)?e.gates.length:0)===t.length?e:(n=!0,{...e,gates:t})});return n&&(this.state={...this.state,plurnk:{...e,status:{...t,descendants:r}}}),n}#T(){if(this.#d.length===0)this.pendingGates=[];else if(this.#f!==void 0&&this.#f.length>0&&this.#f.every(e=>this.#d.some(t=>t.id===e)))this.pendingGates=this.#d.filter(e=>this.#f?.includes(e.id));else{let e=this.#C(this.#d[0]);this.pendingGates=this.#d.filter(t=>this.#C(t)===e)}return this.#w()}#E(e){this.#_===void 0?this.#v=e:this.#_(e)}#D(){this.#h!==void 0&&clearTimeout(this.#h),this.#h=setTimeout(()=>{this.#h=void 0,this.#r.then(async()=>{if(this.#n?.signal.aborted)return;this.#T(),this.#a||await this.#i.onStateChanged?.({state:this.state}),this.#g?.();let e=this.#f,t=this.pendingGates.map(({id:e})=>e);!(e!==void 0&&e.length===t.length&&t.every((t,n)=>t===e[n]))&&this.pendingGates.length>0&&this.#E({stopReason:`interrupt`})})})}#O(e){if(!(this.#c.has(e)||this.#d.some(t=>t.id===e)))return;this.#c.delete(e),this.#d=this.#d.filter(t=>t.id!==e);let t=this.#T();this.#u.has(e)&&this.#l.add(e),!this.#n?.signal.aborted&&setTimeout(()=>{this.#r.then(async()=>{if(!this.#n?.signal.aborted){if(t&&!this.#a&&await this.#i.onStateChanged?.({state:this.state}),this.pendingGates.length>0)this.#E({stopReason:`interrupt`});else if(this.#f!==void 0)this.#E({stopReason:`end_turn`});else if(this.#y===void 0){let e=$(this.state.plurnk)&&$(this.state.plurnk.status)?this.state.plurnk.status:void 0,t=typeof e?.lifecycle==`string`?e.lifecycle:`idle`;[`queued`,`running`,`parked`].includes(t)||this.#E({stopReason:`end_turn`})}}})})}#k(e){for(let t of[...this.#d]){let n=t.method===`session/request_permission`?t._meta?.plurnk?.proposal:void 0,r=t.method===`elicitation/create`?t._meta?.plurnk?.interaction:void 0,i=e.find(e=>$(e)?typeof e.id==`number`&&(n?.sessionId===e.id||r?.sessionId===e.id)||typeof e.name==`string`&&n?.session===e.name:!1);$(i)&&Array.isArray(i.gates)&&(i.gates.some(e=>$(e)?typeof n?.logEntryId==`number`&&e.logEntryId===n.logEntryId||typeof r?.interactionId==`number`&&e.interactionId===r.interactionId:!1)||this.#O(t.id))}}async#A(){await new Promise(e=>setTimeout(e)),await this.#r}async#j(e){if(this.#t!==void 0&&this.#n!==void 0&&!this.#n.signal.aborted)return this.#t;this.close();let t=new AbortController;this.#n=t,this.#b=void 0;let n=typeof globalThis.location?.origin==`string`&&globalThis.location.origin!==`null`?globalThis.location.origin:`http://127.0.0.1`,r=new URL(this.url,n).href,i=Db(r,{fetch:async(e,n)=>{if(n?.method===`DELETE`)return new Response(null,{status:204});let r=new Headers(n?.headers);for(let[e,t]of Object.entries(this.headers))r.set(e,t);if(this.sessionId&&!this.#S&&n?.method===`GET`&&!r.has(`acp-session-id`))return new Response(new ReadableStream({start(e){n.signal&&(n.signal.onabort=()=>{try{e.close()}catch{}})}}),{status:200,headers:{"Content-Type":`text/event-stream`}});let i=n?.signal?AbortSignal.any([n.signal,t.signal]):t.signal;if(n?.method===`GET`){let a=this.#e(e,{...n,headers:r,signal:i});a.catch(e=>{!t.signal.aborted&&!n.signal?.aborted&&this.#E({stopReason:`transport_error`,transportError:e instanceof Error?e:Error(String(e))})});let o=await a;if(!o.ok){if(this.#b===void 0){let e=await jr(o.clone());this.#b=e?{message:e.message,status:e.status,problem:$(e.cause)?e.cause:void 0}:{message:o.statusText||`HTTP ${o.status}`,status:o.status}}return o}if(!o.headers.get(`content-type`)?.toLowerCase().includes(`text/event-stream`)||!o.body)return o;let s=o.body.getReader(),c=()=>{i.aborted||this.#r.then(()=>{i.aborted||(this.#b===void 0?this.#E({stopReason:`eof`}):this.#E({stopReason:`error`,error:this.#b}))})},l=new ReadableStream({pull:async e=>{try{let{done:t,value:n}=await s.read();if(t){e.close(),c();return}e.enqueue(n)}catch(t){c(),e.error(t)}},cancel:e=>s.cancel(e)});return new Response(l,{status:o.status,statusText:o.statusText,headers:o.headers})}let a=n?.method===`POST`;a&&(this.#p+=1);let o;try{let t=this.#e(e,{...n,headers:r,signal:i});a&&(this.#m=this.#m.catch(()=>void 0).then(()=>t.then(()=>void 0,()=>void 0))),o=await t}catch(e){throw!t.signal.aborted&&!n?.signal?.aborted&&this.#E({stopReason:`transport_error`,transportError:e instanceof Error?e:Error(String(e))}),e}finally{a&&(this.#p=Math.max(0,this.#p-1))}if(!o.ok&&this.#b===void 0){let e=await jr(o.clone());this.#b=e?{message:e.message,status:e.status,problem:$(e.cause)?e.cause:void 0}:{message:o.statusText||`HTTP ${o.status}`,status:o.status}}return o},headers:this.headers,cookies:`omit`}),a=eb({name:`@plurnk/plurnk-web`});a.onNotification(_y.client.session.update,e=>{this.#r=this.#r.then(async()=>{if(t.signal.aborted)return;let n=typeof e.params.sessionId==`string`?e.params.sessionId:this.sessionId??``,r=e.params.update;if(!$(r))return;let i=$(r._meta)&&$(r._meta.plurnk)?r._meta.plurnk:void 0,a=typeof i?.subagentRunId==`string`&&r.subagentRunId===void 0?{...r,subagentRunId:i.subagentRunId}:r;await this.#V(n,a,this.#i)})}),a.onNotification(_y.client.elicitation.complete,e=>{let t=$(e.params)&&typeof e.params.elicitationId==`string`?e.params.elicitationId:``;if(t){for(let e of[...this.#d])if(e.method===`elicitation/create`&&e.elicitationId===t){let t=this.#c.get(e.id);this.#O(e.id),t?.resolve({action:`accept`})}}}),a.onRequest(_y.client.session.requestPermission,async e=>{await this.#r;let t=e.params,n=$(t._meta)&&$(t._meta.plurnk)?t._meta.plurnk:void 0,r=$(n?.proposal)?n.proposal:void 0,i=`proposal:${typeof r?.logEntryId==`number`?r.logEntryId:Bb()}:${Bb().slice(0,8)}`,a=r?.expiresAt,o=typeof a==`number`?new Date(a).toISOString():typeof a==`string`?a:void 0,s={id:i,method:`session/request_permission`,...typeof t.sessionId==`string`?{sessionId:t.sessionId}:{},...$(t.toolCall)?{toolCall:structuredClone(t.toolCall)}:{},...Array.isArray(t.options)?{options:structuredClone(t.options)}:{},...o===void 0?{}:{expiresAt:o},...r===void 0?{}:{_meta:{plurnk:{proposal:structuredClone(r)}}}};return this.#d.push(s),this.#T(),await new Promise((t,n)=>{this.#c.set(i,{method:`session/request_permission`,resolve:n=>{e.signal.removeEventListener(`abort`,r),t(n)},reject:t=>{e.signal.removeEventListener(`abort`,r),n(t)}});let r=()=>{this.#O(i),n(new DOMException(`The operation was aborted.`,`AbortError`))};e.signal.onabort=r,this.#D()})}),a.onRequest(_y.client.elicitation.create,async e=>{await this.#r;let t=e.params,n=$(t._meta)&&$(t._meta.plurnk)?t._meta.plurnk:void 0,r=$(n?.interaction)?n.interaction:void 0,i=`int:${typeof r?.interactionId==`number`?r.interactionId:Bb()}:${Bb().slice(0,8)}`,a=$(r?.request)?r.request:{},o=typeof t.message==`string`?t.message:typeof a.message==`string`?a.message:void 0,s=$(t.requestedSchema)?t.requestedSchema:$(a.requestedSchema)?a.requestedSchema:void 0,c=t.mode===`url`?`url`:`form`,l=r?.expiresAt,u=typeof l==`number`?new Date(l).toISOString():typeof l==`string`?l:void 0,d={id:i,method:`elicitation/create`,...typeof t.sessionId==`string`?{sessionId:t.sessionId}:{},mode:c,...o===void 0?{}:{message:o},...s===void 0?{}:{requestedSchema:structuredClone(s)},...typeof t.url==`string`?{url:t.url}:{},...typeof t.elicitationId==`string`?{elicitationId:t.elicitationId}:{},...u===void 0?{}:{expiresAt:u},...r===void 0?{}:{_meta:{plurnk:{interaction:structuredClone(r)}}}};return this.#d.push(d),this.#T(),await new Promise((t,n)=>{this.#c.set(i,{method:`elicitation/create`,resolve:n=>{e.signal.removeEventListener(`abort`,r),t(n)},reject:t=>{e.signal.removeEventListener(`abort`,r),n(t)}});let r=()=>{this.#O(i),n(new DOMException(`The operation was aborted.`,`AbortError`))};e.signal.onabort=r,this.#D()})});let o=a.connect(i);this.#t=o;try{await o.agent.request(_y.agent.initialize,{protocolVersion:2,info:{name:`@plurnk/plurnk-web`,version:`1.0.0`},capabilities:{}})}catch(t){let n=this.#b;throw this.close(),n!==void 0&&!e.aborted?Object.assign(Error(n.message,{cause:n.problem}),{status:n.status,problem:n.problem}):t}return o}async resume(e={},t={}){let n=e.abortController??this.abortController??new AbortController;this.#s=n,this.isRunning=!0,this.#i=t;let{signal:r}=n,i=Array.isArray(e.gates)?[...e.gates]:[];try{if(this.#f=i.length>0?i:void 0,i.length>0&&this.#t!==void 0){let e=this.pendingGates.map(({id:e})=>e);if(!(e.length===i.length&&e.every((e,t)=>e===i[t]))){let e=this.pendingGates.length>0?`interrupt`:`end_turn`;return await t.onSettled?.({stopReason:e,result:{}}),{result:{},stopReason:e}}let n=await this.#I(r);return n.error?(this.close(),await t.onError?.(n.error),{result:void 0,stopReason:`error`}):n.stopReason===`eof`?(this.close(),{result:{},stopReason:`end_turn`}):(await t.onSettled?.({stopReason:n.stopReason,meta:n.meta,result:{}}),{result:{},stopReason:n.stopReason,meta:n.meta})}this.#d=this.#d.filter(e=>this.#c.has(e.id)),this.#T(),this.#v=void 0,this.#x=void 0,this.#a=!0,this.#o=[],this.#S=!1;let n=await this.#j(r),a={sessionId:this.sessionId??``,cwd:`/`,replayFrom:{type:`start`},_meta:{plurnk:{control:!1,reasoning:`link`,...e.workspace?{workspace:e.workspace}:{},...e.projectRoot?{projectRoot:e.projectRoot}:{}}}},o=await n.agent.request(_y.agent.session.resume,a);await this.#A();let s=$(o)?o:{},c=$(s._meta)&&$(s._meta.plurnk)?s._meta.plurnk:void 0;if(this.#L(s,c),Object.keys(this.state).length>0&&await t.onStateChanged?.({state:this.state}),this.#a){this.#a=!1;let e=this.#o.splice(0),n=$(c?.history)?c.history:void 0;if(n!==void 0){this.messages=zb.projectMessages(e,[]);let r=typeof n.older==`string`?n.older:null;await t.onMessagesSnapshot?.({snapshot:{messages:this.messages,older:r,hasMore:typeof n.hasMore==`boolean`?n.hasMore:!!r,beforeLoopSeq:typeof n.beforeLoopSeq==`number`?n.beforeLoopSeq:null}}),await t.onMessagesChanged?.({messages:this.messages})}else for(let n of e)await this.#B(n,t)}if(this.#h!==void 0&&await new Promise(e=>{this.#g=()=>{this.#g=void 0,e(void 0)}}),this.pendingGates.length>0)return this.#v=void 0,await t.onSettled?.({stopReason:`interrupt`,meta:c,result:s}),{result:s,stopReason:`interrupt`,meta:c};let l=await this.#I(r);if(l.error)return this.close(),await t.onError?.(l.error),{result:void 0,stopReason:`error`,meta:l.meta};if(l.stopReason===`eof`)return this.close(),{result:s,stopReason:`end_turn`,meta:c};let u=l.stopReason;return await t.onSettled?.({stopReason:u,meta:l.meta??c,result:s}),{result:s,stopReason:u,meta:l.meta??c}}catch(e){return await this.#R(e,r,t)}finally{this.isRunning=!1,this.#s===n&&(this.#s=void 0)}}async send(e={},t={}){return e.action?await this.#M(e,t):Array.isArray(e.resolutions)&&e.resolutions.length>0?await this.#P(e.resolutions,e,t):e.message?await this.#N(e.message,e,t):await this.resume(e,t)}async#M(e,t){let n=e.abortController??this.abortController??new AbortController;this.#s=n,this.isRunning=!0,this.#i=t;let{signal:r}=n,{kind:i,params:a,...o}=e.action??{},s=$(a)?a:o,c=typeof i==`string`?i:``,l=!this.sessionId||c===`session/new`||c===`providers/list`||c===`session/list`;l&&!this.#S&&this.#t!==void 0&&this.close(),this.#S=l;let u=this.#t!==void 0&&this.#n!==void 0&&!this.#n.signal.aborted;try{let n=await this.#j(r),i;if(c===`session/new`)i=await n.agent.request(_y.agent.session.new,{cwd:`/`,_meta:{plurnk:{...this.sessionId?{session:this.sessionId}:{},...e.workspace?{workspace:e.workspace}:{},...e.projectRoot===void 0?{}:{projectRoot:e.projectRoot}}}});else if(c===`session/set_config_option`){let t=String(s.configId??``),r=String(s.value??``);i=await n.agent.request(_y.agent.session.setConfigOption,{sessionId:this.sessionId??`user`,type:`id`,configId:t,value:r,_meta:{plurnk:{...e.workspace?{workspace:e.workspace}:{},...e.projectRoot===void 0?{}:{projectRoot:e.projectRoot}}}})}else c===`session/resume`?i=await n.agent.request(_y.agent.session.resume,{sessionId:this.sessionId??`user`,cwd:`/`,...s.replayFrom===void 0?{}:{replayFrom:s.replayFrom},_meta:{plurnk:{control:!1,...e.workspace?{workspace:e.workspace}:{},...e.projectRoot===void 0?{}:{projectRoot:e.projectRoot}}}}):c===`session/fork`?i=await n.agent.request(_y.agent.session.fork,{sessionId:this.sessionId??`user`,cwd:`/`,...typeof s.name==`string`?{title:s.name}:{},_meta:{plurnk:{...typeof s.name==`string`?{name:s.name}:{},...e.workspace?{workspace:e.workspace}:{},...e.projectRoot===void 0?{}:{projectRoot:e.projectRoot}}}}):c===`session/cancel`?(await n.agent.notify(_y.agent.session.cancel,{sessionId:this.sessionId??`user`,...typeof s.reason==`string`?{_meta:{plurnk:{reason:s.reason}}}:{}}),i={cancelled:!0}):i=c===`session/list`?await n.agent.request(_y.agent.session.list,{cwd:typeof s.cwd==`string`?s.cwd:void 0,...$(s._meta)?{_meta:s._meta}:{}}):c===`session/delete`?await n.agent.request(_y.agent.session.delete,{sessionId:typeof s.sessionId==`string`?s.sessionId:this.sessionId??`user`}):c===`providers/list`?await n.agent.request(_y.agent.providers.list,{}):await n.agent.request(`_plurnk/action`,{kind:c,params:s,...this.sessionId?{sessionId:this.sessionId}:{},...e.workspace?{workspace:e.workspace}:{},...e.projectRoot===void 0?{}:{projectRoot:e.projectRoot}});await this.#A();let a=$(i)?i:{},o=$(a._meta)&&$(a._meta.plurnk)?a._meta.plurnk:void 0;this.#L(a,o),Object.keys(this.state).length>0&&await t.onStateChanged?.({state:this.state});let l=Object.hasOwn(a,`ok`)?a:{kind:c,ok:!0,result:i};return await t.onSettled?.({stopReason:`end_turn`,meta:o,result:l}),{result:l,stopReason:`end_turn`,meta:o}}catch(e){return await this.#R(e,r,t,c)}finally{this.isRunning=!1,this.#s===n&&(this.#s=void 0),u||this.close()}}async#N(e,t,n){let r=t.abortController??this.abortController??new AbortController;this.#s=r,this.isRunning=!0,this.#i=n,this.#a=!1,this.#o=[],this.#x=void 0,this.#v=void 0,this.#f=void 0,this.#d=this.#d.filter(e=>this.#c.has(e.id)),this.#T();let{signal:i}=r;try{this.#S=!1;let r=await this.#j(i),a={sessionId:this.sessionId??`user`,messageId:e.id,prompt:[{type:`text`,text:e.content}],_meta:{plurnk:{messageId:e.id,reasoning:`link`,...t.workspace?{workspace:t.workspace}:{},...t.projectRoot===void 0?{}:{projectRoot:t.projectRoot}}}},o=r.agent.request(_y.agent.session.prompt,a).then(e=>{let t=$(e)?e:{};return{result:t,meta:$(t._meta)&&$(t._meta.plurnk)?t._meta.plurnk:void 0}});return this.#y=o,o.then(()=>{this.#y===o&&(this.#y=void 0)},()=>{this.#y===o&&(this.#y=void 0)}),await this.#F(o,i,n)}catch(e){return await this.#R(e,i,n)}finally{this.isRunning=!1,this.#s===r&&(this.#s=void 0)}}async#P(e,t,n){let r=t.abortController??this.abortController??new AbortController;this.#s=r,this.isRunning=!0,this.#i=n,this.#a=!1,this.#o=[],this.#u.clear(),this.#l.clear(),this.#v=void 0,this.#f=void 0;let{signal:i}=r;try{this.#S=!1,await this.#j(i);let t=!1,r=$(this.state.plurnk)?this.state.plurnk:void 0,a=$(r?.status)?r.status:void 0,o=typeof this.sessionId==`string`?this.sessionId.split(`#`):[],s=typeof a?.name==`string`?a.name:o[1]||`user`,c=typeof a?.id==`number`?String(a.id):``,l=e.length>0;for(let t of e){let e=this.#d.find(e=>e.id===t.id);if(e){let t=this.#C(e);(!t||t===s||t===c)&&(l=!1)}else l=!1}for(let n of e){let e=this.#c.get(n.id);this.#d=this.#d.filter(e=>e.id!==n.id),e?(this.#c.delete(n.id),this.#u.add(n.id),e.resolve(n.response)):t=!0}let u=this.#T();if(t&&await n.onError?.({message:`Request is no longer pending.`,settled:!0}),this.pendingGates.length===0&&this.#y!==void 0)return await this.#F(this.#y,i,n);let d=typeof a?.lifecycle==`string`?a.lifecycle:`idle`;if(l&&![`queued`,`running`,`parked`].includes(d)||this.pendingGates.length>0){await new Promise(e=>setTimeout(e)),await this.#m,await this.#A(),u&&!this.#a&&await n.onStateChanged?.({state:this.state}),this.#l.size>0&&!t&&await n.onError?.({message:`Request is no longer pending.`,settled:!0});let e=this.pendingGates.length>0?`interrupt`:`end_turn`;return e===`interrupt`&&(this.#v=void 0),await n.onSettled?.({stopReason:e,result:{}}),{result:{},stopReason:e}}let f=await this.#I(i);if(await this.#m,await this.#A(),f.error)return this.close(),await n.onError?.(f.error),{result:void 0,stopReason:`error`,meta:f.meta};if(f.stopReason===`eof`)return this.close(),{result:{},stopReason:`end_turn`,meta:f.meta};this.#l.size>0&&!t&&await n.onError?.({message:`Request is no longer pending.`,settled:!0});let p=f.stopReason,m=f.meta,h=$(m?.terminal)&&$(m.terminal.result)?m.terminal.result:$(m?.result)?m.result:void 0;if(typeof h?.status==`number`&&h.status>=400&&h.status!==499||p===`error`||p===`refusal`){let e=$(h?.problem)?h.problem:h,t=typeof e?.detail==`string`?e.detail:typeof e?.title==`string`?e.title:`Session loop failed.`;await n.onError?.({message:t,status:typeof h?.status==`number`?h.status:void 0,problem:e,terminal:m?.terminal??h})}else await n.onSettled?.({stopReason:p,meta:f.meta,result:{}});return{result:{},stopReason:p,meta:f.meta}}catch(e){return await this.#R(e,i,n)}finally{this.isRunning=!1,this.#s===r&&(this.#s=void 0)}}async#F(e,t,n){let r=this.#I(t),i=await Promise.race([e.then(e=>({kind:`response`,...e})),r.then(e=>({kind:`outcome`,...e}))]);if(i.kind===`outcome`){if(e.catch(()=>void 0),this.#_=void 0,i.error)return this.close(),await n.onError?.(i.error),{result:void 0,stopReason:`error`,meta:i.meta};if(i.stopReason===`interrupt`)return this.#v?.stopReason===`interrupt`&&(this.#v=void 0),await n.onSettled?.({stopReason:`interrupt`,meta:i.meta,result:{}}),{result:{},stopReason:`interrupt`,meta:i.meta};if(i.stopReason===`eof`)return this.close(),{result:void 0,stopReason:`end_turn`,meta:i.meta}}let{result:a,meta:o}=i.kind===`response`?i:await e;await this.#A();let s=$(a)?a:{},c=o;this.#L(s,c),Object.keys(this.state).length>0&&await n.onStateChanged?.({state:this.state}),this.#h!==void 0&&await new Promise(e=>{this.#g=()=>{this.#g=void 0,e(void 0)}});let l=i.kind===`outcome`?i:void 0,u=typeof s.stopReason==`string`||typeof c?.stopReason==`string`||c?.terminal!==void 0||this.pendingGates.length>0;if(l===void 0&&!u&&(l=await r),this.#_=void 0,l!==void 0){if(l.error)return this.close(),await n.onError?.(l.error),{result:void 0,stopReason:`error`,meta:l.meta};l.meta&&(c=c?{...c,...l.meta}:l.meta,this.#L(s,c),Object.keys(this.state).length>0&&await n.onStateChanged?.({state:this.state}))}if(this.#l.size>0&&await n.onError?.({message:`Request is no longer pending.`,settled:!0}),l?.stopReason===`eof`&&!u)return this.close(),{result:s,stopReason:`end_turn`,meta:c};let d=this.pendingGates.length>0?`interrupt`:typeof l?.stopReason==`string`?l.stopReason:typeof c?.stopReason==`string`?c.stopReason:typeof s.stopReason==`string`?s.stopReason:`end_turn`,f=d===`eof`?`end_turn`:d;f===`interrupt`&&this.#v?.stopReason===`interrupt`&&(this.#v=void 0);let p=$(c?.terminal)&&$(c.terminal.result)?c.terminal.result:$(c?.result)?c.result:void 0;if(typeof p?.status==`number`&&p.status>=400&&p.status!==499||f===`error`||f===`refusal`){let e=$(p?.problem)?p.problem:p,t=typeof e?.detail==`string`?e.detail:typeof e?.title==`string`?e.title:`Session loop failed.`;await n.onError?.({message:t,status:typeof p?.status==`number`?p.status:void 0,problem:e,terminal:c?.terminal??p})}else await n.onSettled?.({stopReason:f,meta:c,result:s});return{result:s,stopReason:f,meta:c}}#I(e){if(this.#v!==void 0){let e=this.#v;return this.#v=void 0,e.transportError===void 0?Promise.resolve(e):Promise.reject(e.transportError)}return new Promise((t,n)=>{let r=()=>{this.#_===i&&(this.#_=void 0),n(e.reason instanceof Error?e.reason:new DOMException(`The operation was aborted.`,`AbortError`))},i=r=>{e.onabort=null,this.#_===i&&(this.#_=void 0),r.transportError===void 0?t(r):n(r.transportError)};this.#_=i,e.onabort=r,e.aborted&&r()})}#L(e,t){let n=$(this.state.plurnk)?{...this.state.plurnk}:{};if(Array.isArray(e.configOptions)&&(n.configOptions=structuredClone(e.configOptions)),Array.isArray(e.availableCommands)&&(n.availableCommands=structuredClone(e.availableCommands)),t){let{stopReason:e,terminal:r,result:i,history:a,action:o,proposal:s,interaction:c,budget:l,status:u,workspace:d,...f}=t;Object.assign(n,structuredClone(f)),$(u)&&(Array.isArray(u.descendants)&&this.#k(u.descendants),n.status={...$(n.status)?n.status:{},...structuredClone(u)}),$(d)&&(n.workspace={...$(n.workspace)?n.workspace:{},...structuredClone(d)}),this.state={...this.state,plurnk:n,...l===void 0?{}:{budget:structuredClone(l)}},this.#w()}else(Array.isArray(e.configOptions)||Array.isArray(e.availableCommands))&&(this.state={...this.state,plurnk:n})}async#R(e,t,n,r){if(t.aborted&&this.#b===void 0||(await this.#A(),t.aborted&&this.#b===void 0))throw t.reason instanceof Error?t.reason:new DOMException(`The operation was aborted.`,`AbortError`);if(this.#b===void 0&&e instanceof Error&&e.message===`ACP session SSE stream closed`)return this.close(),{result:void 0,stopReason:`end_turn`};if(this.#b!==void 0){let e=this.#b;if(this.#b=void 0,e.status===401)throw Object.assign(Error(e.message,{cause:e.problem}),{status:401,problem:e.problem});if(e.problem!==void 0)return await n.onError?.(e),{result:r===void 0?void 0:{kind:r,ok:!1,problem:e.problem},stopReason:`error`};throw Object.assign(Error(e.message),{status:e.status})}let i=$(e)&&$(e.data)?e.data:void 0,a=$(i?.body)?i.body:void 0,o=$(i?.plurnk)?i.plurnk:a??i,s=$(o?.problem)?o.problem:$(o)&&typeof o.type==`string`&&typeof o.status==`number`?o:void 0,c=o?.terminal,l=typeof s?.status==`number`?s.status:typeof i?.status==`number`?i.status:typeof Reflect.get(Object(e),`status`)==`number`?Reflect.get(Object(e),`status`):void 0,u=typeof s?.detail==`string`?s.detail:typeof s?.title==`string`?s.title:e instanceof Error?e.message:String(e);if(l===401)throw Object.assign(Error(u,{cause:s}),{status:401,problem:s});if(s!==void 0||c!==void 0)return await n.onError?.({message:u,status:l,problem:s,terminal:c}),{result:r!==void 0&&s!==void 0?{kind:r,ok:!1,problem:s}:void 0,stopReason:`error`};throw e}async#z(e){let t=this.#x;if(!t)return;this.#x=void 0;let n=this.messages.findIndex(e=>e.id===t.messageId&&e.role===`reasoning`),r=n===-1?void 0:this.messages[n];if(!r||$(r._meta?.plurnk)&&r._meta.plurnk.body!==void 0)return;let i={...r,_meta:{...r._meta,plurnk:{...$(r._meta?.plurnk)?r._meta.plurnk:{},body:t.body}}};this.messages=this.messages.with(n,i),await e.onMessagesChanged?.({messages:this.messages})}async#B(e,t){let n=e.sessionUpdate,r=$(e._meta)&&$(e._meta.plurnk)?e._meta.plurnk:void 0;n===`user_message_chunk`&&typeof e.messageId==`string`&&await t.onUserMessage?.({messageId:e.messageId});let i=e;if(n===`agent_thought_chunk`){let n=typeof e.messageId==`string`&&e.messageId.length>0?e.messageId:typeof r?.coordinate==`string`?`${r.coordinate}/reasoning`:``;if(this.#x&&this.#x.messageId!==n&&await this.#z(t),$(e.content)&&e.content.type===`resource_link`)this.#x=void 0;else if(n&&$(r?.body)){this.#x={messageId:n,body:structuredClone(r.body)};let{body:t,...a}=r;i={...e,_meta:{...$(e._meta)?e._meta:{},plurnk:a}}}$(e.content)&&e.content.type===`text`&&typeof e.content.text==`string`&&e.content.text.length>0&&await t.onThoughtChunk?.({update:e})}else(n===`agent_message_chunk`||n===`tool_call`||n===`tool_call_update`)&&await this.#z(t);this.messages=zb.projectMessages([i],this.messages),await t.onMessagesChanged?.({messages:this.messages})}async#V(e,t,n){let r=t.sessionUpdate;this.#a&&r===`agent_thought_chunk`||await n.onSessionUpdate?.({update:t,sessionId:e});let i=$(t._meta)&&$(t._meta.plurnk)?t._meta.plurnk:void 0;if(r===`config_option_update`){let e=$(this.state.plurnk)?{...this.state.plurnk}:{};if(Array.isArray(t.configOptions)&&(e.configOptions=structuredClone(t.configOptions)),i){let{budget:t,status:n,workspace:r,...a}=structuredClone(i);Object.assign(e,a),$(n)&&(e.status={...$(e.status)?e.status:{},...n}),$(r)&&(e.workspace={...$(e.workspace)?e.workspace:{},...r}),this.state={...this.state,plurnk:e,...t===void 0?{}:{budget:t}}}else this.state={...this.state,plurnk:e};this.#a||await n.onStateChanged?.({state:this.state})}else if(r===`available_commands_update`&&Array.isArray(t.availableCommands)){let e=$(this.state.plurnk)?{...this.state.plurnk}:{};e.availableCommands=structuredClone(t.availableCommands),this.state={...this.state,plurnk:e},this.#a||await n.onStateChanged?.({state:this.state})}else if(r===`usage_update`){let e=$(this.state.plurnk)?{...this.state.plurnk}:{},r=$(e.status)?{...e.status}:{};i&&($(i.status)&&Object.assign(r,structuredClone(i.status)),$(i.workspace)&&(e.workspace={...$(e.workspace)?e.workspace:{},...structuredClone(i.workspace)})),Object.keys(r).length>0&&(e.status=r);let a=$(i?.budget)?structuredClone(i.budget):typeof t.used==`number`&&typeof t.size==`number`?{...$(this.state.budget)?this.state.budget:{},contextTokens:t.used,contextCapacity:t.size}:void 0;this.state={...this.state,plurnk:e,...a===void 0?{}:{budget:a}},this.#a||await n.onStateChanged?.({state:this.state})}else if(r===`subagent_update`){let e=$(this.state.plurnk)?{...this.state.plurnk}:{},r=$(e.status)?{...e.status}:{},a=Array.isArray(r.descendants)?r.descendants.map(e=>structuredClone(e)):[],o=typeof i?.id==`number`?i.id:void 0,s=typeof i?.name==`string`?i.name:typeof t.title==`string`?t.title:void 0,c=$(t.state)?t.state:{},l=typeof i?.lifecycle==`string`?i.lifecycle:c.state===`running`||c.state===`requires_action`?`running`:c.stopReason===`cancelled`?`cancelled`:c.stopReason===`refusal`||c.stopReason===`error`?`failed`:`completed`;if(o!==void 0&&s!==void 0){if(c.state===`idle`)for(let e of[...this.#d]){let t=this.#C(e);(t===s||t===String(o))&&this.#O(e.id)}else if(c.state===`running`){let e=typeof i?.coordinate==`string`?i.coordinate.split(`#`)[1]:void 0;for(let t of[...this.#d]){let n=this.#C(t);if(n===s||n===String(o)){if(t.method===`session/request_permission`){let n=t._meta?.plurnk?.proposal;e!==void 0&&n?.coordinate===e&&this.#O(t.id)}else t.method===`elicitation/create`&&this.#O(t.id)}}}Array.isArray(i?.gates)&&this.#k([{id:o,name:s,gates:i.gates}]);let t=a.findIndex(e=>$(e)&&(e.id===o||e.name===s)),u={...t!==-1&&$(a[t])?a[t]:{},id:o,name:s,parentSessionId:typeof i?.parentSessionId==`number`?i.parentSessionId:null,kind:typeof i?.kind==`string`?i.kind:`session`,lifecycle:l,gates:Array.isArray(i?.gates)?structuredClone(i.gates):t!==-1&&$(a[t])&&Array.isArray(a[t].gates)?a[t].gates:[]};t===-1?a.push(u):a[t]=u,r.descendants=a,e.status=r,this.state={...this.state,plurnk:e},this.#w(),this.#a||await n.onStateChanged?.({state:this.state})}}else if(r===`state_update`){if(t.state===`running`||t.state===`idle`){if(this.#p>0&&this.#u.size>0)for(let e of this.#u)this.#l.add(e);if(this.#a)for(let e of[...this.#d])this.#O(e.id);else{let e=$(this.state.plurnk)?this.state.plurnk:void 0,t=$(e?.status)?e.status:void 0,n=typeof this.sessionId==`string`?this.sessionId.split(`#`):[],r=typeof t?.name==`string`?t.name:n[1]||`user`,i=typeof t?.id==`number`?String(t.id):``;for(let e of[...this.#d]){let t=this.#C(e);(!t||t===r||t===i)&&this.#O(e.id)}}}await this.#z(n);let e=$(this.state.plurnk)?{...this.state.plurnk}:{},r=$(e.status)?{...e.status}:{};if($(i?.status)&&Object.assign(r,structuredClone(i.status)),t.state===`running`&&r.lifecycle!==`queued`)r.lifecycle=`running`,r.waitUntil=null;else if(t.state===`idle`&&$(i?.terminal)){let e=typeof i.terminal.status==`number`?i.terminal.status:200;r.lifecycle=e===499?`cancelled`:e>=400?`failed`:`completed`,r.waitUntil=null}if(Object.keys(r).length>0&&(e.status=r,this.state={...this.state,plurnk:e},this.#a||await n.onStateChanged?.({state:this.state})),t.state===`idle`&&$(i?.terminal)){let e=typeof t.stopReason==`string`?t.stopReason:`end_turn`,n=$(i.terminal.result)?i.terminal.result:void 0,r=typeof n?.status==`number`?n.status:200;if(r>=400&&r!==499){let e=$(n?.problem)?n.problem:n,t=typeof e?.detail==`string`?e.detail:typeof e?.title==`string`?e.title:`Session loop failed.`;this.#E({stopReason:`error`,meta:i,error:{message:t,status:r,problem:e,terminal:i.terminal}})}else this.#E({stopReason:e,meta:i})}}else if(r===`notice`){let e=$(this.state.plurnk)?{...this.state.plurnk}:{},r=$(e.status)?{...e.status}:{},a=$(i?.notice)?i.notice:void 0;(a?.kind===`turn_generated`||typeof i?.id==`number`)&&await this.#z(n);let o=!1;if(a?.source===`engine:lifecycle`&&a.kind===`loop_status`){let t=typeof a.status==`number`?a.status:102;r.lifecycle=t===100?`queued`:t===202?`parked`:`running`,typeof a.loopSeq==`number`&&(r.loopSeq=a.loopSeq),typeof a.packetCount==`number`&&(r.packetCount=a.packetCount),(a.waitUntil===null||typeof a.waitUntil==`number`)&&(r.waitUntil=a.waitUntil),(a.claimedAt===null||typeof a.claimedAt==`number`)&&(r.claimedAt=a.claimedAt),r.terminatedAt=null,e.status=r,o=!0}if(a?.source===`engine:derivation`&&a.kind===`search_progress`){let t=$(e.workspace)?{...e.workspace}:{};t.activity=a.phase===`complete`?null:{kind:`derivation`,phase:a.phase,...typeof a.completed==`number`?{completed:a.completed}:{},...typeof a.total==`number`?{total:a.total}:{},...typeof a.percent==`number`?{percent:a.percent}:{},...typeof a.message==`string`?{message:a.message}:{}},e.workspace=t,o=!0}if($(i?.status)&&(Array.isArray(i.status.descendants)&&this.#k(i.status.descendants),Object.assign(r,structuredClone(i.status)),e.status=r,o=!0),$(i?.workspace)&&(e.workspace={...$(e.workspace)?e.workspace:{},...structuredClone(i.workspace)},o=!0),Array.isArray(i?.preparation)&&$(e.workspace)&&(e.workspace={...e.workspace,preparation:structuredClone(i.preparation)},o=!0),o&&(this.state={...this.state,plurnk:e},this.#w(),this.#a||await n.onStateChanged?.({state:this.state})),t.severity===`error`&&$(i?.problem)){let e=i.problem,t=typeof e.status==`number`?e.status:void 0,n=typeof e.detail==`string`?e.detail:typeof e.title==`string`?e.title:`Stream error.`;this.#a||(this.#b={message:n,status:t,problem:e}),(t===401||this.#u.size>0)&&(this.#b={message:n,status:t,problem:e},this.#E({stopReason:`error`,error:{message:n,status:t,problem:e}}))}}else if(r===`terminal_update`){let e=$(this.state.plurnk)?{...this.state.plurnk}:{},r=$(e.status)?{...e.status}:{},a=Array.isArray(r.streams)?r.streams.map(e=>structuredClone(e)):[],o=typeof i?.entryId==`number`?i.entryId:void 0,s=typeof i?.target==`string`?i.target:void 0;if(o!==void 0&&s!==void 0){if($(t.exitStatus))r.streams=a.filter(e=>!($(e)&&e.entryId===o));else{let e=a.findIndex(e=>$(e)&&e.entryId===o),t=typeof i?.channel==`string`?i.channel:`stdout`,n=typeof i?.state==`string`?i.state:`open`,c=typeof i?.mimetype==`string`?i.mimetype:`text/plain`;if(e===-1)a.push({entryId:o,sessionId:typeof i?.sessionId==`number`?i.sessionId:1,target:s,lifetime:`turn`,...typeof i?.loop_seq==`number`?{loop_seq:i.loop_seq}:{},...typeof i?.turn_seq==`number`?{turn_seq:i.turn_seq}:{},...typeof i?.sequence==`number`?{sequence:i.sequence}:{},channels:[{channel:t,state:n,mimetype:c}]});else if($(a[e])){let r=Array.isArray(a[e].channels)?[...a[e].channels]:[],i=r.findIndex(e=>$(e)&&e.channel===t),o={channel:t,state:n,mimetype:c};i===-1?r.push(o):r[i]=o,a[e]={...a[e],channels:r}}r.streams=a}e.status=r,this.state={...this.state,plurnk:e},this.#a||await n.onStateChanged?.({state:this.state})}}else if(r===`user_message_chunk`||r===`agent_message_chunk`||r===`agent_thought_chunk`||r===`tool_call`||r===`tool_call_update`||r===`plan_update`||r===`plan_removed`){if((r===`tool_call`||r===`tool_call_update`)&&typeof t.toolCallId==`string`&&typeof t.status==`string`&&t.status!==`pending`){for(let e of[...this.#d])if(e.method===`session/request_permission`)(e._meta?.plurnk?.proposal?.coordinate===t.toolCallId||$(e.toolCall)&&e.toolCall.toolCallId===t.toolCallId)&&this.#O(e.id);else if(e.method===`elicitation/create`&&(t.status===`completed`||t.status===`failed`)){let n=e._meta?.plurnk?.interaction;typeof n?.interactionId==`number`&&`int:${n.interactionId}`===t.toolCallId&&this.#O(e.id)}}if(this.#a){this.#o.push(t);return}r===`tool_call_update`&&(i?.proposal!==void 0||i?.interaction!==void 0)&&await n.onSettled?.({stopReason:`interrupt`,meta:i,result:{}}),await this.#B(t,n)}}};export{a as _,eb as a,R as c,Mr as d,jr as f,o as g,c as h,Db as i,N as l,s as m,zb as n,_y as o,Ar as p,Bb as r,L as s,Vb as t,Nr as u};
|