billion-context 0.1.210 → 0.1.211

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/agent/omp.js CHANGED
@@ -187,7 +187,7 @@ ${this.parser.parse(e)}</blockquote>
187
187
  ${e}</tr>
188
188
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
189
189
  `}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>${O(e,true)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let s3=this.parser.parseInline(n),r=V(e);if(r===null)return s3;e=r;let i='<a href="'+e+'"';return t&&(i+=' title="'+O(t)+'"'),i+=">"+s3+"</a>",i}image({href:e,title:t,text:n,tokens:s3}){s3&&(n=this.parser.parseInline(s3,this.parser.textRenderer));let r=V(e);if(r===null)return O(n);e=r;let i=`<img src="${e}" alt="${O(n)}"`;return t&&(i+=` title="${O(t)}"`),i+=">",i}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:O(e.text)}};var L=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}};var b=class l2{options;renderer;textRenderer;constructor(e){this.options=e||T,this.options.renderer=this.options.renderer||new y,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new L}static parse(e,t){return new l2(t).parse(e)}static parseInline(e,t){return new l2(t).parseInline(e)}parse(e){this.renderer.parser=this;let t="";for(let n=0;n<e.length;n++){let s3=e[n];if(this.options.extensions?.renderers?.[s3.type]){let i=s3,o=this.options.extensions.renderers[i.type].call({parser:this},i);if(o!==false||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(i.type)){t+=o||"";continue}}let r=s3;switch(r.type){case"space":{t+=this.renderer.space(r);break}case"hr":{t+=this.renderer.hr(r);break}case"heading":{t+=this.renderer.heading(r);break}case"code":{t+=this.renderer.code(r);break}case"table":{t+=this.renderer.table(r);break}case"blockquote":{t+=this.renderer.blockquote(r);break}case"list":{t+=this.renderer.list(r);break}case"checkbox":{t+=this.renderer.checkbox(r);break}case"html":{t+=this.renderer.html(r);break}case"def":{t+=this.renderer.def(r);break}case"paragraph":{t+=this.renderer.paragraph(r);break}case"text":{t+=this.renderer.text(r);break}default:{let i='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(i),"";throw new Error(i)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n="";for(let s3=0;s3<e.length;s3++){let r=e[s3];if(this.options.extensions?.renderers?.[r.type]){let o=this.options.extensions.renderers[r.type].call({parser:this},r);if(o!==false||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){n+=o||"";continue}}let i=r;switch(i.type){case"escape":{n+=t.text(i);break}case"html":{n+=t.html(i);break}case"link":{n+=t.link(i);break}case"image":{n+=t.image(i);break}case"checkbox":{n+=t.checkbox(i);break}case"strong":{n+=t.strong(i);break}case"em":{n+=t.em(i);break}case"codespan":{n+=t.codespan(i);break}case"br":{n+=t.br(i);break}case"del":{n+=t.del(i);break}case"text":{n+=t.text(i);break}default:{let o='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return n}};var P=class{options;block;constructor(e){this.options=e||T}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?x.lex:x.lexInline}provideParser(e=this.block){return e?b.parse:b.parseInline}};var q=class{defaults=M();options=this.setOptions;parse=this.parseMarkdown(true);parseInline=this.parseMarkdown(false);Parser=b;Renderer=y;TextRenderer=L;Lexer=x;Tokenizer=w;Hooks=P;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let s3 of e)switch(n=n.concat(t.call(this,s3)),s3.type){case"table":{let r=s3;for(let i of r.header)n=n.concat(this.walkTokens(i.tokens,t));for(let i of r.rows)for(let o of i)n=n.concat(this.walkTokens(o.tokens,t));break}case"list":{let r=s3;n=n.concat(this.walkTokens(r.items,t));break}default:{let r=s3;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(i=>{let o=r[i].flat(1/0);n=n.concat(this.walkTokens(o,t))}):r.tokens&&(n=n.concat(this.walkTokens(r.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s3={...n};if(s3.async=this.defaults.async||s3.async||false,n.extensions&&(n.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let i=t.renderers[r.name];i?t.renderers[r.name]=function(...o){let u2=r.renderer.apply(this,o);return u2===false&&(u2=i.apply(this,o)),u2}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=t[r.level];i?i.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s3.extensions=t),n.renderer){let r=this.defaults.renderer||new y(this.defaults);for(let i in n.renderer){if(!(i in r))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let o=i,u2=n.renderer[o],a=r[o];r[o]=(...c)=>{let p2=u2.apply(r,c);return p2===false&&(p2=a.apply(r,c)),p2||""}}s3.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new w(this.defaults);for(let i in n.tokenizer){if(!(i in r))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let o=i,u2=n.tokenizer[o],a=r[o];r[o]=(...c)=>{let p2=u2.apply(r,c);return p2===false&&(p2=a.apply(r,c)),p2}}s3.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new P;for(let i in n.hooks){if(!(i in r))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let o=i,u2=n.hooks[o],a=r[o];P.passThroughHooks.has(i)?r[o]=c=>{if(this.defaults.async&&P.passThroughHooksRespectAsync.has(i))return(async()=>{let k2=await u2.call(r,c);return a.call(r,k2)})();let p2=u2.call(r,c);return a.call(r,p2)}:r[o]=(...c)=>{if(this.defaults.async)return(async()=>{let k2=await u2.apply(r,c);return k2===false&&(k2=await a.apply(r,c)),k2})();let p2=u2.apply(r,c);return p2===false&&(p2=a.apply(r,c)),p2}}s3.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,i=n.walkTokens;s3.walkTokens=function(o){let u2=[];return u2.push(i.call(this,o)),r&&(u2=u2.concat(r.call(this,o))),u2}}this.defaults={...this.defaults,...s3}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return x.lex(e,t??this.defaults)}parser(e,t){return b.parse(e,t??this.defaults)}parseMarkdown(e){return(n,s3)=>{let r={...s3},i={...this.defaults,...r},o=this.onError(!!i.silent,!!i.async);if(this.defaults.async===true&&r.async===false)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let u2=i.hooks?await i.hooks.preprocess(n):n,c=await(i.hooks?await i.hooks.provideLexer(e):e?x.lex:x.lexInline)(u2,i),p2=i.hooks?await i.hooks.processAllTokens(c):c;i.walkTokens&&await Promise.all(this.walkTokens(p2,i.walkTokens));let h=await(i.hooks?await i.hooks.provideParser(e):e?b.parse:b.parseInline)(p2,i);return i.hooks?await i.hooks.postprocess(h):h})().catch(o);try{i.hooks&&(n=i.hooks.preprocess(n));let a=(i.hooks?i.hooks.provideLexer(e):e?x.lex:x.lexInline)(n,i);i.hooks&&(a=i.hooks.processAllTokens(a)),i.walkTokens&&this.walkTokens(a,i.walkTokens);let p2=(i.hooks?i.hooks.provideParser(e):e?b.parse:b.parseInline)(a,i);return i.hooks&&(p2=i.hooks.postprocess(p2)),p2}catch(u2){return o(u2)}}}onError(e,t){return n=>{if(n.message+=`
190
- Please report this to https://github.com/markedjs/marked.`,e){let s3="<p>An error occurred:</p><pre>"+O(n.message+"",true)+"</pre>";return t?Promise.resolve(s3):s3}if(t)return Promise.reject(n);throw n}}};var z=new q;function g(l4,e){return z.parse(l4,e)}g.options=g.setOptions=function(l4){return z.setOptions(l4),g.defaults=z.defaults,N(g.defaults),g};g.getDefaults=M;g.defaults=T;g.use=function(...l4){return z.use(...l4),g.defaults=z.defaults,N(g.defaults),g};g.walkTokens=function(l4,e){return z.walkTokens(l4,e)};g.parseInline=z.parseInline;g.Parser=b;g.parser=b.parse;g.Renderer=y;g.TextRenderer=L;g.Lexer=x;g.lexer=x.lex;g.Tokenizer=w;g.Hooks=P;g.parse=g;var Ft=g.options;var Ut=g.setOptions;var Kt=g.use;var Wt=g.walkTokens;var Xt=g.parseInline;var Vt=b.parse;var Yt=x.lex;var STRICT_STRIKETHROUGH_REGEX=/^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/;var StrictStrikethroughTokenizer=class extends w{del(src){const match=STRICT_STRIKETHROUGH_REGEX.exec(src);if(!match){return void 0}const text=match[2];return{type:"del",raw:match[0],text,tokens:this.lexer.inlineTokens(text)}}};function trimPartialClosingFences(tokens){const token=tokens[tokens.length-1];if(token?.type==="list"){trimPartialClosingFences(token.items[token.items.length-1]?.tokens??[]);return}if(token?.type==="blockquote"){trimPartialClosingFences(token.tokens??[]);return}if(token?.type!=="code"){return}const marker=/^(`{3,}|~{3,})/.exec(token.raw)?.[1];const lastLine=token.raw.split("\n").pop();if(!marker||!lastLine||lastLine.length>=marker.length||lastLine!==marker[0]?.repeat(lastLine.length)){return}token.text=token.text.slice(0,-lastLine.length).replace(/\n$/,"")}var markdownParser=new q;markdownParser.setOptions({tokenizer:new StrictStrikethroughTokenizer});var Markdown=class{text;paddingX;paddingY;defaultTextStyle;theme;options;defaultStylePrefix;cachedText;cachedWidth;cachedLines;constructor(text,paddingX,paddingY,theme,defaultTextStyle,options){this.text=text;this.paddingX=paddingX;this.paddingY=paddingY;this.theme=theme;this.defaultTextStyle=defaultTextStyle;this.options=options?{...options}:{}}setText(text){this.text=text;this.invalidate()}invalidate(){this.cachedText=void 0;this.cachedWidth=void 0;this.cachedLines=void 0}render(width){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===width){return this.cachedLines}const contentWidth=Math.max(1,width-this.paddingX*2);if(!this.text||this.text.trim()===""){const result2=[];this.cachedText=this.text;this.cachedWidth=width;this.cachedLines=result2;return result2}const normalizedText=this.text.replace(/\t/g," ");const tokens=markdownParser.lexer(normalizedText);trimPartialClosingFences(tokens);const renderedLines=[];for(let i=0;i<tokens.length;i++){const token=tokens[i];const nextToken=tokens[i+1];const tokenLines=this.renderToken(token,contentWidth,nextToken?.type);for(const tokenLine of tokenLines){renderedLines.push(tokenLine)}}const wrappedLines=[];for(const line of renderedLines){if(isImageLine(line)){wrappedLines.push(line)}else{for(const wrappedLine of wrapTextWithAnsi(line,contentWidth)){wrappedLines.push(wrappedLine)}}}const leftMargin=" ".repeat(this.paddingX);const rightMargin=" ".repeat(this.paddingX);const bgFn=this.defaultTextStyle?.bgColor;const contentLines=[];for(const line of wrappedLines){if(isImageLine(line)){contentLines.push(line);continue}const lineWithMargins=leftMargin+line+rightMargin;if(bgFn){contentLines.push(applyBackgroundToLine(lineWithMargins,width,bgFn))}else{const visibleLen=visibleWidth(lineWithMargins);const paddingNeeded=Math.max(0,width-visibleLen);contentLines.push(lineWithMargins+" ".repeat(paddingNeeded))}}const emptyLine=" ".repeat(width);const emptyLines=[];for(let i=0;i<this.paddingY;i++){const line=bgFn?applyBackgroundToLine(emptyLine,width,bgFn):emptyLine;emptyLines.push(line)}const result=emptyLines.concat(contentLines,emptyLines);this.cachedText=this.text;this.cachedWidth=width;this.cachedLines=result;return result.length>0?result:[""]}applyDefaultStyle(text){if(!this.defaultTextStyle){return text}let styled=text;if(this.defaultTextStyle.color){styled=this.defaultTextStyle.color(styled)}if(this.defaultTextStyle.bold){styled=this.theme.bold(styled)}if(this.defaultTextStyle.italic){styled=this.theme.italic(styled)}if(this.defaultTextStyle.strikethrough){styled=this.theme.strikethrough(styled)}if(this.defaultTextStyle.underline){styled=this.theme.underline(styled)}return styled}getDefaultStylePrefix(){if(!this.defaultTextStyle){return""}if(this.defaultStylePrefix!==void 0){return this.defaultStylePrefix}const sentinel="\0";let styled=sentinel;if(this.defaultTextStyle.color){styled=this.defaultTextStyle.color(styled)}if(this.defaultTextStyle.bold){styled=this.theme.bold(styled)}if(this.defaultTextStyle.italic){styled=this.theme.italic(styled)}if(this.defaultTextStyle.strikethrough){styled=this.theme.strikethrough(styled)}if(this.defaultTextStyle.underline){styled=this.theme.underline(styled)}const sentinelIndex=styled.indexOf(sentinel);this.defaultStylePrefix=sentinelIndex>=0?styled.slice(0,sentinelIndex):"";return this.defaultStylePrefix}getStylePrefix(styleFn){const sentinel="\0";const styled=styleFn(sentinel);const sentinelIndex=styled.indexOf(sentinel);return sentinelIndex>=0?styled.slice(0,sentinelIndex):""}getDefaultInlineStyleContext(){return{applyText:text=>this.applyDefaultStyle(text),stylePrefix:this.getDefaultStylePrefix()}}renderToken(token,width,nextTokenType,styleContext){const lines=[];switch(token.type){case"heading":{const headingLevel=token.depth;const headingPrefix=`${"#".repeat(headingLevel)} `;let headingStyleFn;if(headingLevel===1){headingStyleFn=text=>this.theme.heading(this.theme.bold(this.theme.underline(text)))}else{headingStyleFn=text=>this.theme.heading(this.theme.bold(text))}const headingStyleContext={applyText:headingStyleFn,stylePrefix:this.getStylePrefix(headingStyleFn)};const headingText=this.renderInlineTokens(token.tokens||[],headingStyleContext);const styledHeading=headingLevel>=3?headingStyleFn(headingPrefix)+headingText:headingText;lines.push(styledHeading);if(nextTokenType&&nextTokenType!=="space"){lines.push("")}break}case"paragraph":{const paragraphText=this.renderInlineTokens(token.tokens||[],styleContext);lines.push(paragraphText);if(nextTokenType&&nextTokenType!=="list"&&nextTokenType!=="space"){lines.push("")}break}case"text":lines.push(this.renderInlineTokens([token],styleContext));break;case"code":{const indent=this.theme.codeBlockIndent??" ";lines.push(this.theme.codeBlockBorder(`\`\`\`${token.lang||""}`));if(this.theme.highlightCode){const highlightedLines=this.theme.highlightCode(token.text,token.lang);for(const hlLine of highlightedLines){lines.push(`${indent}${hlLine}`)}}else{const codeLines=token.text.split("\n");for(const codeLine of codeLines){lines.push(`${indent}${this.theme.codeBlock(codeLine)}`)}}lines.push(this.theme.codeBlockBorder("```"));if(nextTokenType&&nextTokenType!=="space"){lines.push("")}break}case"list":{const listLines=this.renderList(token,0,width,styleContext);lines.push(...listLines);break}case"table":{const tableLines=this.renderTable(token,width,nextTokenType,styleContext);lines.push(...tableLines);break}case"blockquote":{const quoteStyle=text=>this.theme.quote(this.theme.italic(text));const quoteStylePrefix=this.getStylePrefix(quoteStyle);const applyQuoteStyle=line=>{if(!quoteStylePrefix){return quoteStyle(line)}const lineWithReappliedStyle=line.replace(/\x1b\[0m/g,`\x1B[0m${quoteStylePrefix}`);return quoteStyle(lineWithReappliedStyle)};const quoteContentWidth=Math.max(1,width-2);const quoteInlineStyleContext={applyText:text=>text,stylePrefix:quoteStylePrefix};const quoteTokens=token.tokens||[];const renderedQuoteLines=[];for(let i=0;i<quoteTokens.length;i++){const quoteToken=quoteTokens[i];const nextQuoteToken=quoteTokens[i+1];renderedQuoteLines.push(...this.renderToken(quoteToken,quoteContentWidth,nextQuoteToken?.type,quoteInlineStyleContext))}while(renderedQuoteLines.length>0&&renderedQuoteLines[renderedQuoteLines.length-1]===""){renderedQuoteLines.pop()}for(const quoteLine of renderedQuoteLines){const styledLine=applyQuoteStyle(quoteLine);const wrappedLines=wrapTextWithAnsi(styledLine,quoteContentWidth);for(const wrappedLine of wrappedLines){lines.push(this.theme.quoteBorder("\u2502 ")+wrappedLine)}}if(nextTokenType&&nextTokenType!=="space"){lines.push("")}break}case"hr":lines.push(this.theme.hr("\u2500".repeat(Math.min(width,80))));if(nextTokenType&&nextTokenType!=="space"){lines.push("")}break;case"html":if("raw"in token&&typeof token.raw==="string"){lines.push(this.applyDefaultStyle(token.raw.trim()))}break;case"space":lines.push("");break;default:if("text"in token&&typeof token.text==="string"){lines.push(token.text)}}return lines}renderInlineTokens(tokens,styleContext){let result="";const resolvedStyleContext=styleContext??this.getDefaultInlineStyleContext();const{applyText,stylePrefix}=resolvedStyleContext;const applyTextWithNewlines=text=>{const segments=text.split("\n");return segments.map(segment=>applyText(segment)).join("\n")};for(const token of tokens){switch(token.type){case"escape":result+=applyTextWithNewlines(this.options.preserveBackslashEscapes?token.raw:token.text);break;case"text":if(token.tokens&&token.tokens.length>0){result+=this.renderInlineTokens(token.tokens,resolvedStyleContext)}else{result+=applyTextWithNewlines(token.text)}break;case"paragraph":result+=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);break;case"strong":{const boldContent=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);result+=this.theme.bold(boldContent)+stylePrefix;break}case"em":{const italicContent=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);result+=this.theme.italic(italicContent)+stylePrefix;break}case"codespan":result+=this.theme.code(token.text)+stylePrefix;break;case"link":{const linkText=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);const styledLink=this.theme.link(this.theme.underline(linkText));if(getCapabilities().hyperlinks){result+=hyperlink(styledLink,token.href)+stylePrefix}else{const hrefForComparison=token.href.startsWith("mailto:")?token.href.slice(7):token.href;if(token.text===token.href||token.text===hrefForComparison){result+=styledLink+stylePrefix}else{result+=styledLink+this.theme.linkUrl(` (${token.href})`)+stylePrefix}}break}case"br":result+="\n";break;case"del":{const delContent=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);result+=this.theme.strikethrough(delContent)+stylePrefix;break}case"html":if("raw"in token&&typeof token.raw==="string"){result+=applyTextWithNewlines(token.raw)}break;default:if("text"in token&&typeof token.text==="string"){result+=applyTextWithNewlines(token.text)}}}while(stylePrefix&&result.endsWith(stylePrefix)){result=result.slice(0,-stylePrefix.length)}return result}getOrderedListMarker(item){const match=/^(?: {0,3})(\d{1,9}[.)])[ \t]+/.exec(item.raw);return match?`${match[1]} `:void 0}getUnorderedListMarker(item){const match=/^(?: {0,3})([-+*])(?:[ \t]+|(?=\r?\n|$))/.exec(item.raw);return match?`${match[1]} `:void 0}renderList(token,depth,width,styleContext){const lines=[];const indent=" ".repeat(depth);const startNumber=typeof token.start==="number"?token.start:1;for(let i=0;i<token.items.length;i++){const item=token.items[i];const isLastItem=i===token.items.length-1;const bullet=token.ordered?this.options.preserveOrderedListMarkers?this.getOrderedListMarker(item)??`${startNumber+i}. `:`${startNumber+i}. `:this.options.preserveOrderedListMarkers?this.getUnorderedListMarker(item)??"- ":"- ";const taskMarker=item.task?`[${item.checked?"x":" "}] `:"";const marker=bullet+taskMarker;const firstPrefix=indent+this.theme.listBullet(marker);const continuationPrefix=indent+" ".repeat(visibleWidth(marker));const itemWidth=Math.max(1,width-visibleWidth(firstPrefix));let renderedAnyLine=false;for(const itemToken of item.tokens){if(itemToken.type==="list"){lines.push(...this.renderList(itemToken,depth+1,width,styleContext));renderedAnyLine=true;continue}const itemLines=this.renderToken(itemToken,itemWidth,void 0,styleContext);for(const line of itemLines){for(const wrappedLine of wrapTextWithAnsi(line,itemWidth)){const linePrefix=renderedAnyLine?continuationPrefix:firstPrefix;lines.push(linePrefix+wrappedLine);renderedAnyLine=true}}}if(!renderedAnyLine){lines.push(firstPrefix)}if(token.loose&&!isLastItem){lines.push("")}}return lines}getLongestWordWidth(text,maxWidth){const words=text.split(/\s+/).filter(word=>word.length>0);let longest=0;for(const word of words){longest=Math.max(longest,visibleWidth(word))}if(maxWidth===void 0){return longest}return Math.min(longest,maxWidth)}wrapCellText(text,maxWidth){return wrapTextWithAnsi(text,Math.max(1,maxWidth))}renderTable(token,availableWidth,nextTokenType,styleContext){const lines=[];const numCols=token.header.length;if(numCols===0){return lines}const borderOverhead=3*numCols+1;const availableForCells=availableWidth-borderOverhead;if(availableForCells<numCols){const fallbackLines=token.raw?wrapTextWithAnsi(token.raw,availableWidth):[];if(nextTokenType&&nextTokenType!=="space"){fallbackLines.push("")}return fallbackLines}const maxUnbrokenWordWidth=30;const naturalWidths=[];const minWordWidths=[];for(let i=0;i<numCols;i++){const headerText=this.renderInlineTokens(token.header[i].tokens||[],styleContext);naturalWidths[i]=visibleWidth(headerText);minWordWidths[i]=Math.max(1,this.getLongestWordWidth(headerText,maxUnbrokenWordWidth))}for(const row of token.rows){for(let i=0;i<row.length;i++){const cellText=this.renderInlineTokens(row[i].tokens||[],styleContext);naturalWidths[i]=Math.max(naturalWidths[i]||0,visibleWidth(cellText));minWordWidths[i]=Math.max(minWordWidths[i]||1,this.getLongestWordWidth(cellText,maxUnbrokenWordWidth))}}let minColumnWidths=minWordWidths;let minCellsWidth=minColumnWidths.reduce((a,b4)=>a+b4,0);if(minCellsWidth>availableForCells){minColumnWidths=new Array(numCols).fill(1);const remaining=availableForCells-numCols;if(remaining>0){const totalWeight=minWordWidths.reduce((total,width)=>total+Math.max(0,width-1),0);const growth=minWordWidths.map(width=>{const weight=Math.max(0,width-1);return totalWeight>0?Math.floor(weight/totalWeight*remaining):0});for(let i=0;i<numCols;i++){minColumnWidths[i]+=growth[i]??0}const allocated=growth.reduce((total,width)=>total+width,0);let leftover=remaining-allocated;for(let i=0;leftover>0&&i<numCols;i++){minColumnWidths[i]++;leftover--}}minCellsWidth=minColumnWidths.reduce((a,b4)=>a+b4,0)}const totalNaturalWidth=naturalWidths.reduce((a,b4)=>a+b4,0)+borderOverhead;let columnWidths;if(totalNaturalWidth<=availableWidth){columnWidths=naturalWidths.map((width,index)=>Math.max(width,minColumnWidths[index]))}else{const totalGrowPotential=naturalWidths.reduce((total,width,index)=>{return total+Math.max(0,width-minColumnWidths[index])},0);const extraWidth=Math.max(0,availableForCells-minCellsWidth);columnWidths=minColumnWidths.map((minWidth,index)=>{const naturalWidth=naturalWidths[index];const minWidthDelta=Math.max(0,naturalWidth-minWidth);let grow=0;if(totalGrowPotential>0){grow=Math.floor(minWidthDelta/totalGrowPotential*extraWidth)}return minWidth+grow});const allocated=columnWidths.reduce((a,b4)=>a+b4,0);let remaining=availableForCells-allocated;while(remaining>0){let grew=false;for(let i=0;i<numCols&&remaining>0;i++){if(columnWidths[i]<naturalWidths[i]){columnWidths[i]++;remaining--;grew=true}}if(!grew){break}}}const topBorderCells=columnWidths.map(w4=>"\u2500".repeat(w4));lines.push(`\u250C\u2500${topBorderCells.join("\u2500\u252C\u2500")}\u2500\u2510`);const headerCellLines=token.header.map((cell,i)=>{const text=this.renderInlineTokens(cell.tokens||[],styleContext);return this.wrapCellText(text,columnWidths[i])});const headerLineCount=Math.max(...headerCellLines.map(c=>c.length));for(let lineIdx=0;lineIdx<headerLineCount;lineIdx++){const rowParts=headerCellLines.map((cellLines,colIdx)=>{const text=cellLines[lineIdx]||"";const padded=text+" ".repeat(Math.max(0,columnWidths[colIdx]-visibleWidth(text)));return this.theme.bold(padded)});lines.push(`\u2502 ${rowParts.join(" \u2502 ")} \u2502`)}const separatorCells=columnWidths.map(w4=>"\u2500".repeat(w4));const separatorLine=`\u251C\u2500${separatorCells.join("\u2500\u253C\u2500")}\u2500\u2524`;lines.push(separatorLine);for(let rowIndex=0;rowIndex<token.rows.length;rowIndex++){const row=token.rows[rowIndex];const rowCellLines=row.map((cell,i)=>{const text=this.renderInlineTokens(cell.tokens||[],styleContext);return this.wrapCellText(text,columnWidths[i])});const rowLineCount=Math.max(...rowCellLines.map(c=>c.length));for(let lineIdx=0;lineIdx<rowLineCount;lineIdx++){const rowParts=rowCellLines.map((cellLines,colIdx)=>{const text=cellLines[lineIdx]||"";return text+" ".repeat(Math.max(0,columnWidths[colIdx]-visibleWidth(text)))});lines.push(`\u2502 ${rowParts.join(" \u2502 ")} \u2502`)}if(rowIndex<token.rows.length-1){lines.push(separatorLine)}}const bottomBorderCells=columnWidths.map(w4=>"\u2500".repeat(w4));lines.push(`\u2514\u2500${bottomBorderCells.join("\u2500\u2534\u2500")}\u2500\u2518`);if(nextTokenType&&nextTokenType!=="space"){lines.push("")}return lines}};var Spacer=class{lines;constructor(lines=1){this.lines=lines}setLines(lines){this.lines=lines}invalidate(){}render(_width){const result=[];for(let i=0;i<this.lines;i++){result.push("")}return result}};import*as fs2 from"fs";import{createRequire as createRequire2}from"module";import*as path3 from"path";import{fileURLToPath as fileURLToPath2}from"url";import{createRequire}from"module";import*as path2 from"path";import{fileURLToPath}from"url";var cjsRequire=createRequire(import.meta.url);var cjsRequire2=createRequire2(import.meta.url);var DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS=7;var KITTY_KEYBOARD_PROTOCOL_QUERY=`\x1B[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1B[?u\x1B[c`;import fs12 from"fs";import path27 from"path";import{fileURLToPath as fileURLToPath6}from"url";import{createHash as createHash2}from"crypto";import{createHash}from"crypto";function hashId(s3){return createHash("sha256").update(s3,"utf8").digest("hex").slice(0,16)}var CANONICAL_IMAGE_TEXT="[image]";var CANONICAL_REDACTED_THINKING_TEXT="[redacted_thinking]";function canonicalToolArgs(argsText){const trimmed=argsText.trim();if(!trimmed.startsWith("{")&&!trimmed.startsWith("["))return argsText;try{return JSON.stringify(canonicalize(JSON.parse(trimmed)))}catch{return argsText}}function canonicalize(v4){if(Array.isArray(v4))return v4.map(canonicalize);if(v4!==null&&typeof v4==="object"){const src=v4;const out={};for(const k2 of Object.keys(src).sort())out[k2]=canonicalize(src[k2]);return out}return v4}var idSalt=null;function deriveCanonicalMessageId(role,contentType,text,options={}){const seed=`${idSalt?idSalt+"|":""}${role}|${contentType}||${options.toolName??""}|${text}`+(options.mediaFingerprint!==void 0?`|${options.mediaFingerprint}`:"");return"h_"+hashId(seed)}function imageMediaFingerprint(base64OrUrl){return hashId(base64OrUrl)}function canonicalOpaqueSeed(item){if(item===null||typeof item!=="object")return hashId(String(item));const src=item;const out={};for(const k2 of Object.keys(src)){if(k2==="id"||k2==="status")continue;out[k2]=src[k2]}return hashId(JSON.stringify(out))}var ClusterCounter=class{counts=new Map;next(baseId){const n=this.counts.get(baseId)??0;this.counts.set(baseId,n+1);return n===0?baseId:`${baseId}_${n}`}};function anthropicToCore(body){const msgs=[];const cacheControls=new Map;const clusters=new ClusterCounter;const toolNames=new Map;for(const[wireIndex,m4]of body.messages.entries()){const before=msgs.length;if(m4.role==="system"){const core=systemMessageCore(m4,clusters);core.wireIndex=wireIndex;msgs.push(core);const mark=systemMessageMark(m4);if(mark)cacheControls.set(core.id,mark);continue}const blocks=typeof m4.content==="string"?[{type:"text",text:m4.content}]:m4.content;for(const b4 of blocks){switch(b4.type){case"text":{const base=deriveCanonicalMessageId(m4.role,"text",b4.text);const id=clusters.next(base);msgs.push({id,role:m4.role,contentType:"text",text:b4.text});if(b4.cache_control)cacheControls.set(id,b4.cache_control);break}case"tool_use":{const base=deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(safeStringify(b4.input)),{toolName:b4.name});const id=clusters.next(base);msgs.push({id,role:"assistant",contentType:"tool-call",toolName:b4.name,toolCallId:b4.id,text:safeStringify(b4.input)});toolNames.set(b4.id,b4.name);if(b4.cache_control)cacheControls.set(id,b4.cache_control);break}case"tool_result":{const hasNonText=Array.isArray(b4.content)&&b4.content.some(c=>c.type!=="text");const text=typeof b4.content==="string"?b4.content:b4.content.map(c=>c.type==="text"?c.text:"").join("\n");const name=toolNames.get(b4.tool_use_id);const base=deriveCanonicalMessageId("tool","tool-result",text,{toolName:name});const id=clusters.next(base);msgs.push({id,role:"tool",contentType:"tool-result",toolCallId:b4.tool_use_id,text,...name?{toolName:name}:{},...b4.is_error===true?{toolIsError:true}:{},...hasNonText?{rawAnthropicBlock:b4}:{}});if(b4.cache_control)cacheControls.set(id,b4.cache_control);break}case"thinking":{const base=deriveCanonicalMessageId("assistant","reasoning",b4.thinking);msgs.push({id:clusters.next(base),role:"assistant",contentType:"reasoning",text:b4.thinking,...b4.signature?{thinkingSignature:b4.signature}:{}});break}case"image":{const source=b4.source&&typeof b4.source==="object"&&!Array.isArray(b4.source)?b4.source:void 0;const mediaSidecar=source?.type==="base64"&&typeof source.media_type==="string"&&typeof source.data==="string"?{imageMediaType:source.media_type,imageBase64:source.data}:{};const base=deriveCanonicalMessageId(m4.role,"text",CANONICAL_IMAGE_TEXT,{mediaFingerprint:source?.type==="base64"&&typeof source.data==="string"?imageMediaFingerprint(source.data):typeof source?.url==="string"?imageMediaFingerprint(source.url):void 0});msgs.push({id:clusters.next(base),role:m4.role,contentType:"text",text:CANONICAL_IMAGE_TEXT,imagePart:true,rawAnthropicBlock:b4,...mediaSidecar});break}case"redacted_thinking":{const base=deriveCanonicalMessageId(m4.role,"text",CANONICAL_REDACTED_THINKING_TEXT);msgs.push({id:clusters.next(base),role:m4.role,contentType:"text",text:"[redacted_thinking]",rawAnthropicBlock:b4});break}default:{const unknownType=b4.type;const label=typeof unknownType==="string"?`[${unknownType}]`:"[unknown]";const base=deriveCanonicalMessageId(m4.role,"text",label);msgs.push({id:clusters.next(base),role:m4.role,contentType:"text",text:label,rawAnthropicBlock:b4});break}}}for(let k2=before;k2<msgs.length;k2++){msgs[k2].wireIndex=wireIndex}}return{msgs,cacheControls}}function systemMessageCore(m4,clusters){const label=systemMessageText(m4);const base=deriveCanonicalMessageId("system","text",label);return{id:clusters.next(base),role:"system",contentType:"text",text:label,rawAnthropicMessage:m4}}function systemMessageText(m4){const text=typeof m4.content==="string"?m4.content:m4.content.map(b4=>b4.type==="text"?b4.text:`[${b4.type}]`).join("\n");return text.length>0?text:"[system]"}function systemMessageMark(m4){if(typeof m4.content==="string")return void 0;let mark;for(const b4 of m4.content)if(b4.cache_control)mark=b4.cache_control;return mark}function safeStringify(v4){try{return JSON.stringify(v4??{})}catch{return"{}"}}var FORMS=[{open:"<think>\n",close:"\n</think>"},{open:"<thinking>\n",close:"\n</thinking>"},{open:"```thinking\n",close:"\n```"}];function splitDemotedThinking(content){let rest=content;const parts=[];for(;;){let matched=false;for(const form of FORMS){if(!rest.startsWith(form.open))continue;const end=rest.indexOf(form.close,form.open.length);if(end<0)continue;const inner=rest.slice(form.open.length,end);if(inner.length===0)continue;parts.push(inner);rest=rest.slice(end+form.close.length);if(rest.startsWith("\n"))rest=rest.slice(1);matched=true;break}if(!matched)break}if(parts.length===0)return null;return{reasoning:parts.join("\n"),text:rest}}function parseDataUrl(url){const m4=/^data:([^;,]+)(?:;base64)?,(.+)$/i.exec(url);if(!m4)return void 0;return{mediaType:m4[1],base64:m4[2]}}function imageFingerprintsOfParts(parts){const out=[];for(const part of parts){if(!part||typeof part!=="object")continue;const p2=part;if(p2.type!=="image_url")continue;const url=typeof p2.image_url?.url==="string"?p2.image_url.url:void 0;if(!url)continue;const parsed=parseDataUrl(url);out.push(imageMediaFingerprint(parsed?parsed.base64:url))}return out}function openaiToCore(body){const msgs=[];const systemParts=[];const clusters=new ClusterCounter;const toolNames=new Map;for(const[wireIndex,m4]of body.messages.entries()){const before=msgs.length;switch(m4.role){case"system":case"developer":{if(msgs.length===0){systemParts.push(stringContent(m4.content));break}const base=deriveCanonicalMessageId(m4.role,"text",stringContent(m4.content));msgs.push({id:clusters.next(base),role:"system",contentType:"text",text:stringContent(m4.content),originalRole:m4.role,rawOpenaiMessage:m4});break}case"user":{if(typeof m4.content==="string"||m4.content==null||!Array.isArray(m4.content)){const base=deriveCanonicalMessageId("user","text",typeof m4.content==="string"?m4.content:"");msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:typeof m4.content==="string"?m4.content:""});break}let lastTextCore=null;let leadingOpaque=[];let sawText=false;for(const part of m4.content){if(typeof part==="string"){const base=deriveCanonicalMessageId("user","text",part);lastTextCore={id:clusters.next(base),role:"user",contentType:"text",text:part};msgs.push(lastTextCore);sawText=true;continue}if(part?.type==="text"&&typeof part.text==="string"){const base=deriveCanonicalMessageId("user","text",part.text);lastTextCore={id:clusters.next(base),role:"user",contentType:"text",text:part.text};msgs.push(lastTextCore);sawText=true;continue}if(part?.type==="image_url"){const url=part.image_url?.url;const parsed=typeof url==="string"?parseDataUrl(url):void 0;const base=deriveCanonicalMessageId("user","text",CANONICAL_IMAGE_TEXT,{mediaFingerprint:imageMediaFingerprint(parsed?parsed.base64:typeof url==="string"?url:"")});msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:CANONICAL_IMAGE_TEXT,imagePart:true,rawOpenaiContent:part,...parsed?{imageMediaType:parsed.mediaType,imageBase64:parsed.base64}:{}});continue}if(lastTextCore){lastTextCore.rawOpenaiContentParts=[...lastTextCore.rawOpenaiContentParts??[],part]}else{leadingOpaque=[...leadingOpaque,part]}}if(leadingOpaque.length>0){if(sawText&&msgs.length>0){const firstTextCore=msgs.find((c,i)=>i>=before&&c.role==="user"&&c.contentType==="text"&&!c.rawOpenaiContent);const host=firstTextCore??msgs[msgs.length-1];host.rawOpenaiContentParts=[...leadingOpaque,...host.rawOpenaiContentParts??[]]}else{const base=deriveCanonicalMessageId("user","text","",{mediaFingerprint:imageFingerprintsOfParts(leadingOpaque).join(",")||void 0});msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:"",rawOpenaiContentParts:leadingOpaque})}}break}case"assistant":{const rawReasoning=m4.reasoning_content;const fieldPresent=typeof rawReasoning==="string";const fieldReasoning=fieldPresent?rawReasoning:"";let reasoning=fieldReasoning;let text=stringContent(m4.content);if(!reasoning){const split=splitDemotedThinking(text);if(split){reasoning=split.reasoning;text=split.text}}const blankEcho=fieldPresent&&reasoning.length===0;if(reasoning){const base=deriveCanonicalMessageId("assistant","reasoning",reasoning);msgs.push({id:clusters.next(base),role:"assistant",contentType:"reasoning",text:reasoning,reasoningContent:reasoning})}if(text){const base=deriveCanonicalMessageId("assistant","text",text);msgs.push({id:clusters.next(base),role:"assistant",contentType:"text",text,...blankEcho?{reasoningPresent:true}:{}})}if(Array.isArray(m4.tool_calls)){for(const tc of m4.tool_calls){const base=deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(tc.function.arguments??""),{toolName:tc.function.name});msgs.push({id:clusters.next(base),role:"assistant",contentType:"tool-call",toolName:tc.function.name,toolCallId:tc.id,text:tc.function.arguments??"",...blankEcho?{reasoningPresent:true}:{}});toolNames.set(tc.id,tc.function.name)}}break}case"tool":{const base=deriveCanonicalMessageId("tool","tool-result",stringContent(m4.content),{toolName:m4.name||toolNames.get(m4.tool_call_id??"")});const name=m4.name||toolNames.get(m4.tool_call_id??"");msgs.push({id:clusters.next(base),role:"tool",contentType:"tool-result",toolCallId:m4.tool_call_id??"",text:stringContent(m4.content),...name?{toolName:name}:{}});break}}for(let k2=before;k2<msgs.length;k2++){msgs[k2].wireIndex=wireIndex}}return{msgs,systemText:systemParts.join("\n\n")}}function stringContent(content){if(content==null)return"";if(typeof content==="string")return content;if(Array.isArray(content)){return content.map(p2=>typeof p2==="string"?p2:p2.type==="text"?p2.text??"":"").join("\n")}return""}var OPAQUE_ITEM_TYPES=new Set(["additional_tools","mcp_list_tools"]);function isOpaqueItem(item){return OPAQUE_ITEM_TYPES.has(item.type)}var EASY_INPUT_ROLES=new Set(["user","assistant","system","developer"]);function normalizeEasyInputItem(item){if(typeof item.type==="string")return item;if(EASY_INPUT_ROLES.has(String(item.role))){return{...item,type:"message"}}return item}function shouldDropAllReasoning(){return(process.env.ACP_REASONING_KEEP??"").trim().toLowerCase()==="none"}function partText(part){if(part.type==="input_text"||part.type==="output_text"){return typeof part.text==="string"?part.text:""}return""}function messageContent(content){return typeof content==="string"?content:content.map(partText).join("\n")}function userDisplayText(content,text){if(typeof content==="string")return text;const hasImage=content.some(part=>part.type==="input_image");const hasTextPart=content.some(part=>part.type==="input_text"||part.type==="output_text");return!text||hasImage&&!hasTextPart?"[image]":text}function reasoningText(item){const fromParts=(parts,type)=>{if(!Array.isArray(parts))return"";const texts=[];for(const part of parts){if(part&&typeof part==="object"&&"type"in part&&"text"in part){const rec=part;if(rec.type===type&&typeof rec.text==="string")texts.push(rec.text)}}return texts.join("\n")};const content="content"in item?item.content:void 0;const summary="summary"in item?item.summary:void 0;return fromParts(content,"reasoning_text")||fromParts(summary,"summary_text")}function responsesToCore(body){const msgs=[];const systemParts=[];const preamble=[];const customToolCallIds=new Set;const layout=[];let droppedReasoning=0;const clusters=new ClusterCounter;const toolNames=new Map;let idx=0;if(typeof body.instructions==="string"&&body.instructions.trim())systemParts.push(body.instructions);if(typeof body.input==="string"){const id=clusters.next(deriveCanonicalMessageId("user","text",body.input));msgs.push({id,role:"user",contentType:"text",text:body.input});return{msgs,systemParts,preamble,customToolCallIds,layout,droppedReasoning,stringInput:{original:body.input,coreId:id}}}let sysDevHead=true;for(const[wireIndex,raw]of body.input.entries()){const item=normalizeEasyInputItem(raw);let coreId;const before=msgs.length;if(isOpaqueItem(item))preamble.push(item);switch(item.type){case"reasoning":{if(shouldDropAllReasoning()){droppedReasoning++;continue}const text=reasoningText(item);const rid=text.length>0?text:canonicalOpaqueSeed(item);coreId=clusters.next(deriveCanonicalMessageId("assistant","reasoning",rid));msgs.push({id:coreId,role:"assistant",contentType:"reasoning",text:rid,rawResponsesItem:item});break}case"message":{const message=item;const text=messageContent(message.content);if(message.role==="system"||message.role==="developer"){if(sysDevHead){systemParts.push(text);idx++;continue}const midBase=deriveCanonicalMessageId(message.role,"text",text);msgs.push({id:clusters.next(midBase),role:"system",contentType:"text",text,originalRole:message.role,rawResponsesItem:item});break}else if(message.role==="user"||message.role==="assistant"&&text){const role2=message.role;const splittable=role2==="user"&&Array.isArray(message.content)&&message.content.length>1&&message.content.every(part=>typeof part==="object"&&part!==null&&(part.type==="input_text"||part.type==="output_text"||part.type==="input_image"));if(splittable){for(const rawPart of message.content){const part=typeof rawPart==="object"&&rawPart!==null?rawPart:void 0;if(!part)continue;if((part.type==="input_text"||part.type==="output_text")&&typeof part.text==="string"&&part.text.length>0){const base=deriveCanonicalMessageId("user","text",part.text);msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:part.text})}else if(part.type==="input_image"&&typeof part.image_url==="string"){const image=parseDataUrl(part.image_url);const base=deriveCanonicalMessageId("user","text",CANONICAL_IMAGE_TEXT,{mediaFingerprint:imageMediaFingerprint(image?image.base64:part.image_url)});msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:CANONICAL_IMAGE_TEXT,imagePart:true,rawResponsesItem:item,...image?{imageMediaType:image.mediaType,imageBase64:image.base64}:{}})}}break}let effText=text;if(role2==="assistant"){const split=splitDemotedThinking(text);if(split){msgs.push({id:clusters.next(deriveCanonicalMessageId("assistant","reasoning",split.reasoning)),role:"assistant",contentType:"reasoning",text:split.reasoning,rawResponsesItem:item});effText=split.text}}const hasImage=Array.isArray(message.content)&&message.content.some(part=>part.type==="input_image");if(effText||role2==="user"&&hasImage){const displayText=role2==="user"?userDisplayText(message.content,effText):effText;const mediaFingerprint=Array.isArray(message.content)?message.content.flatMap(part=>{if(part?.type==="input_image"&&typeof part.image_url==="string"){const raw2=part.image_url;const decoded=parseDataUrl(raw2);return[imageMediaFingerprint(decoded?decoded.base64:raw2)]}return[]}).join(",")||void 0:void 0;coreId=clusters.next(deriveCanonicalMessageId(role2,"text",displayText,{mediaFingerprint}));const imageUrl=Array.isArray(message.content)?message.content.find(part=>part.type==="input_image"&&typeof part.image_url==="string")?.image_url:void 0;const image=typeof imageUrl==="string"?parseDataUrl(imageUrl):void 0;msgs.push({id:coreId,role:role2,contentType:"text",text:displayText,rawResponsesItem:item,...image?{imageMediaType:image.mediaType,imageBase64:image.base64}:{}})}}break}case"function_call":{const call=item;coreId=clusters.next(deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(call.arguments??""),{toolName:call.name}));msgs.push({id:coreId,role:"assistant",contentType:"tool-call",toolName:call.name,toolCallId:call.call_id,text:call.arguments??"",rawResponsesItem:item});toolNames.set(call.call_id,call.name);break}case"function_call_output":{const output=item;const text=typeof output.output==="string"?output.output:JSON.stringify(output.output);coreId=clusters.next(deriveCanonicalMessageId("tool","tool-result",text,{toolName:toolNames.get(output.call_id)}));const name=toolNames.get(output.call_id);msgs.push({id:coreId,role:"tool",contentType:"tool-result",toolCallId:output.call_id,text,...name?{toolName:name}:{},rawResponsesItem:item});break}case"computer_call":case"computer_call_output":case"file_search_call":case"web_search_call":case"image_generation_call":case"code_interpreter_call":case"mcp_call":{const rid=canonicalOpaqueSeed(item);coreId=clusters.next(deriveCanonicalMessageId("assistant","responses-call",rid));msgs.push({id:coreId,role:"assistant",contentType:"reasoning",text:rid,rawResponsesItem:item});break}case"custom_tool_call":{const ctc=item;const callId=ctc.call_id??`call_${idx}`;customToolCallIds.add(callId);const argText=ctc.input??ctc.arguments??"";coreId=clusters.next(deriveCanonicalMessageId("assistant","tool-call",argText,{toolName:ctc.name??"custom"}));msgs.push({id:coreId,role:"assistant",contentType:"tool-call",toolName:ctc.name??"custom",toolCallId:callId,text:argText,rawResponsesItem:item});toolNames.set(callId,ctc.name??"custom");break}case"custom_tool_call_output":{const ctco=item;const callId=ctco.call_id??`call_${idx}`;customToolCallIds.add(callId);const outText=typeof ctco.output==="string"?ctco.output:JSON.stringify(ctco.output??"");coreId=clusters.next(deriveCanonicalMessageId("tool","tool-result",outText,{toolName:toolNames.get(callId)}));const name=toolNames.get(callId);msgs.push({id:coreId,role:"tool",contentType:"tool-result",toolCallId:callId,text:outText,...name?{toolName:name}:{},rawResponsesItem:item});break}default:if(!isOpaqueItem(item))preamble.push(item);break}for(let k2=before;k2<msgs.length;k2++){msgs[k2].wireIndex=wireIndex}const role=item.role;const isSysDevMsgItem=(item.type===void 0||item.type==="message")&&(role==="system"||role==="developer");if(!isSysDevMsgItem&&item.type!=="additional_tools"&&item.type!=="mcp_list_tools")sysDevHead=false;const produced=msgs.slice(before).map(m4=>m4.id);layout.push({original:item,...produced.length>0?{coreId:produced[0]}:{},...produced.length>1?{coreIds:produced}:{}});idx++}return{msgs,systemParts,preamble,customToolCallIds,layout,droppedReasoning}}function createSubagentNamespaces(){const anchors=new Map;return{namespaceFor(identityValue,instructions){if(typeof instructions!=="string"||instructions.trim().length===0)return identityValue;const fp=hashId(instructions);const anchor=anchors.get(identityValue);if(anchor===void 0){anchors.set(identityValue,fp);return identityValue}return anchor===fp?identityValue:`${identityValue}|sub:${fp}`}}}var defaultNamespaces=createSubagentNamespaces();function detectWireFormat(payload){if(payload===null||typeof payload!=="object")return void 0;const p2=payload;if(Array.isArray(p2.contents))return"google";if(Array.isArray(p2.input))return"responses";const messages=p2.messages;if(!Array.isArray(messages))return void 0;if("system"in p2||"anthropic_version"in p2)return"anthropic";for(const m4 of messages){if(m4===null||typeof m4!=="object")continue;const c=m4.content;if(Array.isArray(c)){for(const b4 of c){if(b4&&typeof b4==="object"&&typeof b4.type==="string"){if(b4.type==="tool_use"||b4.type==="tool_result"||b4.type==="thinking")return"anthropic";if(b4.type==="text"&&"cache_control"in b4)return"anthropic"}}}if(Array.isArray(m4.tool_calls))return"openai";if(m4.role==="tool"&&typeof m4.tool_call_id==="string")return"openai";if(m4.role==="system"||m4.role==="developer")return"openai"}return"openai"}var DEFAULT_MAX_FUTURE_SKEW_MS=2*60*1e3;var DEFAULT_RECENT_CHECKPOINT_WINDOW_MS=10*60*1e3;var MAX_CHECKPOINT_CHARS=512;var TAG_OPEN="<bili-chain ";var TAG_CLOSE="/>";var ATTRS=["v","processor","issued-at","request-id","digest"];function validAttrValue(name,raw){switch(name){case"v":return/^\d+$/.test(raw)&&Number(raw)>=1;case"issued-at":return/^\d{1,16}$/.test(raw);case"processor":return/^[A-Za-z0-9._-]{1,64}$/.test(raw);case"request-id":return/^[A-Za-z0-9._:-]{1,64}$/.test(raw);case"digest":return/^sha256:[0-9a-f]{64}$/.test(raw)}}function parseChainCheckpoint(text){if(typeof text!=="string"||text.length===0||text.length>MAX_CHECKPOINT_CHARS)return null;if(!text.startsWith(TAG_OPEN)||!text.endsWith(TAG_CLOSE))return null;const inner=text.slice(TAG_OPEN.length,-TAG_CLOSE.length);const found={};for(const token of inner.split(/\s+/)){const m4=/^([a-z][a-z0-9-]*)="([^"]*)"$/.exec(token);if(!m4)return null;const name=m4[1];if(!ATTRS.includes(name))return null;if(Object.hasOwn(found,name))return null;found[name]=m4[2]}for(const attr of ATTRS){const raw=found[attr];if(raw===void 0||!validAttrValue(attr,raw))return null}return{v:Number(found.v),processor:found.processor,issuedAt:Number(found["issued-at"]),requestId:found["request-id"],digest:found.digest}}function stripEmbeddedChainCarriers(parsed,wire){if(parsed===null||typeof parsed!=="object"||Array.isArray(parsed))return 0;const body=parsed;let stripped=0;if(wire==="google"){const contents=body.contents;if(!Array.isArray(contents))return 0;for(let i=contents.length-1;i>=0;i--){const c=contents[i];if(!c||typeof c!=="object"||Array.isArray(c))continue;const ct2=c;const role=typeof ct2.role==="string"?ct2.role:"user";if(role!=="user"&&role!=="model")continue;const parts=ct2.parts;if(!Array.isArray(parts))continue;let removed=0;for(let j4=parts.length-1;j4>=0;j4--){const p2=parts[j4];if(p2&&typeof p2==="object"&&!Array.isArray(p2)&&Object.keys(p2).length===1&&typeof p2.text==="string"){if(parseChainCheckpoint(p2.text)){parts.splice(j4,1);removed++}}}if(removed>0){if(parts.length===0)contents.splice(i,1);stripped+=removed}}return stripped}if(wire==="responses"){const input=body.input;if(!Array.isArray(input))return 0;for(let i=input.length-1;i>=0;i--){const item=input[i];if(!item||typeof item!=="object"||Array.isArray(item))continue;const it2=item;if(it2.type!=="message")continue;const role=typeof it2.role==="string"?it2.role:"";if(role!=="user"&&role!=="assistant")continue;const content=it2.content;if(typeof content==="string"){if(parseChainCheckpoint(content)){input.splice(i,1);stripped++}continue}if(!Array.isArray(content))continue;let removed=0;for(let j4=content.length-1;j4>=0;j4--){const p2=content[j4];if(p2&&typeof p2==="object"&&!Array.isArray(p2)){const po2=p2;if(po2.type==="input_text"&&typeof po2.text==="string"&&Object.keys(po2).length===2&&parseChainCheckpoint(po2.text)){content.splice(j4,1);removed++}}}if(removed>0){if(content.length===0)input.splice(i,1);stripped+=removed}}return stripped}const messages=body.messages;if(!Array.isArray(messages))return 0;for(let i=messages.length-1;i>=0;i--){const rec=messages[i];if(!rec||typeof rec!=="object"||Array.isArray(rec))continue;const m4=rec;if(m4.role!=="user"&&m4.role!=="assistant")continue;const content=m4.content;if(typeof content==="string"){if(parseChainCheckpoint(content)){messages.splice(i,1);stripped++}continue}if(!Array.isArray(content))continue;let removed=0;for(let j4=content.length-1;j4>=0;j4--){const p2=content[j4];if(p2&&typeof p2==="object"&&!Array.isArray(p2)){const po2=p2;if(po2.type==="text"&&typeof po2.text==="string"&&Object.keys(po2).length===2&&parseChainCheckpoint(po2.text)){content.splice(j4,1);removed++}}}if(removed>0){if(content.length===0)messages.splice(i,1);stripped+=removed}}return stripped}var ZERO_DIGEST="sha256:"+"0".repeat(64);import{randomUUID as randomUUID5}from"crypto";init_logger();import{createHash as createHash15}from"crypto";import{createHash as createHash14,randomUUID as randomUUID4}from"crypto";import{closeSync,existsSync as existsSync6,fsyncSync,mkdirSync as mkdirSync6,openSync,readdirSync,readFileSync as readFileSync7,renameSync as renameSync2,rmSync,statSync as statSync7,writeFileSync as writeFileSync6}from"fs";import{readdir as readdir2,readFile as readFile4,rm as rm2}from"fs/promises";import*as path20 from"path";init_paths();init_knobs();init_logger();init_runtime_status();init_version();import{createCipheriv,createDecipheriv,randomBytes as randomBytes2}from"crypto";import*as zlib from"zlib";var ENCRYPT_MAGIC=Buffer.from("BILIENC1","utf8");var ZSTD_MAGIC=Buffer.from("BILIZSTD1","utf8");var NONCE_LEN=12;var TAG_LEN=16;var ENCRYPT_HEADER_LEN=ENCRYPT_MAGIC.length+2+NONCE_LEN;var MIN_ENCRYPTED_LEN=ENCRYPT_HEADER_LEN+TAG_LEN;var PLAIN_HEADER_LEN=ZSTD_MAGIC.length+2;init_logger();init_billing();init_state_hydration();init_shadow();init_backend();init_ingest();init_store();init_logger();init_paths();import{randomUUID as randomUUID2}from"crypto";import{mkdirSync as mkdirSync5,writeFileSync as writeFileSync5}from"fs";import{dirname as dirname6,join as join5}from"path";init_knobs();function parseToolOutcome(value){return value==="applied"||value==="partial"||value==="refused"||value==="success"||value==="failure"?value:void 0}function parseBlocksCreated(value){return typeof value==="number"&&Number.isInteger(value)&&value>=0?value:void 0}function partialOutcomeNote(blocksCreated){const created=blocksCreated!==void 0?`${blocksCreated} block(s) created; `:"";return`[acp-result: PARTIAL \u2014 ${created}some requested range(s) were NOT folded. Retry ONLY the failed range(s) listed above; do not re-fold the ranges that were applied.]`}import{createHash as createHash13,randomUUID as randomUUID3}from"crypto";import{AsyncLocalStorage as AsyncLocalStorage3}from"async_hooks";init_logger();import{createHash as createHash12}from"crypto";import{createHash as createHash11}from"crypto";init_client_config();import fs9 from"fs";import path19 from"path";import path18 from"path";import{fileURLToPath as fileURLToPath5}from"url";var originWaiter;async function awaitNativeProxyOrigin(){return originWaiter===void 0?void 0:originWaiter.wait()}init_dsh_channel();var SCAN_CACHE_TTL_MS=5*60*1e3;var CONFLICT_ACTIVE_WINDOW_MS=7*24*60*60*1e3;init_logger();init_logger();init_billing();init_util();var BOOT_ID=randomUUID3();var SEAM_BODY_CAP=512*1024;var BODY_FULL_CAP=8*1024*1024;var captures=new AsyncLocalStorage3;var LEARNED_IMAGE_COST_TTL_MS=24*60*60*1e3;var{join:join7}=path20;init_version();init_knobs();init_config();init_config();init_paths();init_logger();init_external_summary_settings();import*as path21 from"path";init_turn_separator();init_turn_separator();var ABORT_REANCHOR_MAX_AGE_MS=30*60*1e3;var MAX_SESSIONS=maxSessions();var MAX_RESIDENT_BYTES=sessionResidentMaxBytes();var SPLIT_CANARY_FRESH_MS=10*60*1e3;init_knobs();var CODEX_FORGED_HANDOFF_HEADER="[bili] context summary after compaction:";var FORGED_SUMMARY_HEADER="[Compressed conversation section]";function buildAcplikeName(){const cores=["acp","apc","cap","cpa","pac","pca"];const ci2=ch=>`[${ch}${ch.toUpperCase()}]`;const attestedDrift=["[aA][cC][cC][eE][sS][sS][pP]","[aA][cC][aA][cC][pP]","[aA][cC][bB]"];const fourLetter=new Set;const threeLetter=new Set;for(const c of cores){threeLetter.add(ci2(c.charAt(0))+ci2(c.charAt(1))+ci2(c.charAt(2)));for(let pos=0;pos<=c.length;pos++){fourLetter.add(c.slice(0,pos).split("").map(ci2).join("")+"[aAcCpPiI]"+c.slice(pos).split("").map(ci2).join(""))}}return[...attestedDrift,...fourLetter,...threeLetter].join("|")}var ACP_NAME_ALT=`(?:${buildAcplikeName()})`;var NAME=ACP_NAME_ALT;var REF_TOKEN="m\\d{4,}";var REFS_RUN=REF_TOKEN+"(?:\\s*(?:[\u2013\u2014,-]\\s*)?"+REF_TOKEN+")*";var REFS_ONLY=new RegExp("^\\s*"+REFS_RUN+"\\s*$");var PENDING_REF_SPAN=new RegExp("^\\s*"+REFS_RUN+"(?:\\s*(?:[\\u2013\\u2014,\\-]\\s*)?(?:m\\d{0,3})?)?\\s*$");var PAIRED_BODY="\\s*(?:"+REFS_RUN+")?\\s*";var PAIRED=new RegExp("<"+NAME+"(?:\\s[^<>]*)?>("+PAIRED_BODY+")<\\/"+NAME+">");var ORPHAN_REF_CLOSE=new RegExp("(?<![\\w>])"+REFS_RUN+"\\s*<\\/"+NAME+"(?=[\\s>])[^<>]{0,32}>");var ORPHAN_RUN_BEFORE=new RegExp("(?<![\\w>])"+REFS_RUN+"\\s*$");var LONE_OPEN=new RegExp("<"+NAME+"(?:\\s[^<>]*)?>");var LONE_CLOSE=new RegExp("<\\/"+NAME+"(?=[\\s>])[^<>]{0,32}>");var DEGEN_PAIR=new RegExp("<"+NAME+"(?:\\s[^<>]*)?>\\s*m\\d{4,}\\s*<\\/[^<>]{1,32}>","g");var SELF_CLOSE=new RegExp("<"+NAME+"(?:\\s[^<>]*)?\\/>");var PARTIAL_TAIL=new RegExp("(<"+NAME+"\\s[^<>]*|<"+NAME+"\\s*=\\s*[^<>]*|<\\/"+NAME+"(?:\\s[^<>]{0,32})?|<\\/?[aAcCpPiI]*(?:/)?|(?<![\\w>])\\s*"+REFS_RUN+"\\s*<[^<>]*|(?<![\\w>])\\s*"+REFS_RUN+"(?:\\s*(?:[\\u2013\\u2014,\\-]\\s*)?(?:m\\d{0,3})?)?\\s*|(?<![\\w>])\\s*m\\d{0,3})$");var TRUNC_OPEN=new RegExp("<"+NAME+"\\s[^<>]*$|<"+NAME+"\\s*=\\s*[^<>]*$");var TRUNC_CLOSE=new RegExp("<\\/"+NAME+"(?:\\s[^<>]{0,32})?$");var TRUNC_REF_CLOSE=new RegExp("m\\d{4,}\\s*\\x3c\\/([a-zA-Z]{0,32})$");var DEAD_REF_CLOSE=new RegExp("(?<![\\w>])m\\d{4,}\\s*\\x3c\\/[a-zA-Z]{0,32}(?![a-zA-Z])(?![^\\x3c\\x3e]{0,32}\\x3e)","g");var BROKEN_ATTRS=new RegExp("<"+NAME+"\\s[^<>]*(?=<)");var MANGLED_OPEN=new RegExp("<"+NAME+"\\s*=\\s*[^<>]*>");var DEFINITE_TAIL=new RegExp("^<"+NAME+"\\s|^<"+NAME+"=|^<\\/"+NAME);var OPEN_WITH_ATTRS=new RegExp("^<"+NAME+"\\s");var CLOSE_NAME_ANCHORED=new RegExp("^"+NAME);var MARKER_HEAD=new RegExp("^\\p{So}(?:[ \\t])?\\[ACP\\]","u");var MARKER_LINE=new RegExp("^\\p{So}(?:[ \\t])?\\[ACP\\][^\\n]*\\n?","gmu");function stripMarkerLines(text){return text.replace(MARKER_LINE,"")}var MARKER_LINE_PROBE=new RegExp(MARKER_LINE.source,"mu");var RENDER_TAG_DETECT=new RegExp("<\\/?"+NAME+"(?=[\\s>])|\\\\u003c\\/?"+NAME+"(?=[\\s>\\\\])|<"+NAME+"\\s*\\/|\\\\u003c"+NAME+"\\s*\\/");var BROAD_TAG_HEAD_TAIL=new RegExp("<\\/?[A-Za-z0-9]{0,16}$");var RAW_WS="(?:\\\\[a-z]|\\s|\\\\)*";var TC_PARAM_REF_RAW=new RegExp(`\\x3c(?:antml:)?parameter(?:\\s*=\\s*["']?ref["']?|\\s+name\\s*=\\s*["']ref["'])?[^<>]*\\x3e`+RAW_WS+"m\\d{4,}"+RAW_WS+"\\x3c\\/(?:antml:)?parameter","i");var CHAIN_OPEN_ESCAPED="\\u003c"+TAG_OPEN.slice(1);function reEscape(s3){return s3.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function prefixAlts(s3,minLen){const out=[];for(let k2=minLen;k2<s3.length;k2++)out.push(reEscape(s3.slice(0,k2)));return out}var CHAIN_PARTIAL_TAIL=new RegExp("("+[...new Set([...prefixAlts(TAG_OPEN,1),reEscape(TAG_OPEN),...prefixAlts(CHAIN_OPEN_ESCAPED,1),reEscape(CHAIN_OPEN_ESCAPED)])].join("|")+")$");var HEAD_PREFIX_TAIL=new RegExp("(?:^|\n)("+[...new Set([...prefixAlts(CODEX_FORGED_HANDOFF_HEADER,1),...prefixAlts(FORGED_SUMMARY_HEADER,1)])].join("|")+")$");var TAG_PARTIAL_TAIL=new RegExp("(<"+NAME+"\\s[^<>]*|<\\/"+NAME+"(?:\\s[^<>]{0,32})?|<\\/?[aAcCpPiI]*(?:/)?)$");var PANEL_BOX_TOP="\u256D";var PANEL_BOX_TITLE="ACP Context Analysis";var PANEL_BOX_FOOTER="Tag visibility: tags injected to LLM only (deep copy), not persisted in session, not shown in terminal.";var PANEL_FALLBACK_HEADER="\u{1F4CA} ACP status";var CACHE_REPORT_OPEN="[acp-cache]";var CACHE_REPORT_CLOSE="[/acp-cache]";var RULE_REPORT_OPEN="[acp-rule]";var RULE_REPORT_CLOSE="[/acp-rule]";var STATUS_REPORT_OPEN="[acp-status]";var STATUS_REPORT_CLOSE="[/acp-status]";function wrapCacheReport(report){return`${CACHE_REPORT_OPEN}
190
+ Please report this to https://github.com/markedjs/marked.`,e){let s3="<p>An error occurred:</p><pre>"+O(n.message+"",true)+"</pre>";return t?Promise.resolve(s3):s3}if(t)return Promise.reject(n);throw n}}};var z=new q;function g(l4,e){return z.parse(l4,e)}g.options=g.setOptions=function(l4){return z.setOptions(l4),g.defaults=z.defaults,N(g.defaults),g};g.getDefaults=M;g.defaults=T;g.use=function(...l4){return z.use(...l4),g.defaults=z.defaults,N(g.defaults),g};g.walkTokens=function(l4,e){return z.walkTokens(l4,e)};g.parseInline=z.parseInline;g.Parser=b;g.parser=b.parse;g.Renderer=y;g.TextRenderer=L;g.Lexer=x;g.lexer=x.lex;g.Tokenizer=w;g.Hooks=P;g.parse=g;var Ft=g.options;var Ut=g.setOptions;var Kt=g.use;var Wt=g.walkTokens;var Xt=g.parseInline;var Vt=b.parse;var Yt=x.lex;var STRICT_STRIKETHROUGH_REGEX=/^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/;var StrictStrikethroughTokenizer=class extends w{del(src){const match=STRICT_STRIKETHROUGH_REGEX.exec(src);if(!match){return void 0}const text=match[2];return{type:"del",raw:match[0],text,tokens:this.lexer.inlineTokens(text)}}};function trimPartialClosingFences(tokens){const token=tokens[tokens.length-1];if(token?.type==="list"){trimPartialClosingFences(token.items[token.items.length-1]?.tokens??[]);return}if(token?.type==="blockquote"){trimPartialClosingFences(token.tokens??[]);return}if(token?.type!=="code"){return}const marker=/^(`{3,}|~{3,})/.exec(token.raw)?.[1];const lastLine=token.raw.split("\n").pop();if(!marker||!lastLine||lastLine.length>=marker.length||lastLine!==marker[0]?.repeat(lastLine.length)){return}token.text=token.text.slice(0,-lastLine.length).replace(/\n$/,"")}var markdownParser=new q;markdownParser.setOptions({tokenizer:new StrictStrikethroughTokenizer});var Markdown=class{text;paddingX;paddingY;defaultTextStyle;theme;options;defaultStylePrefix;cachedText;cachedWidth;cachedLines;constructor(text,paddingX,paddingY,theme,defaultTextStyle,options){this.text=text;this.paddingX=paddingX;this.paddingY=paddingY;this.theme=theme;this.defaultTextStyle=defaultTextStyle;this.options=options?{...options}:{}}setText(text){this.text=text;this.invalidate()}invalidate(){this.cachedText=void 0;this.cachedWidth=void 0;this.cachedLines=void 0}render(width){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===width){return this.cachedLines}const contentWidth=Math.max(1,width-this.paddingX*2);if(!this.text||this.text.trim()===""){const result2=[];this.cachedText=this.text;this.cachedWidth=width;this.cachedLines=result2;return result2}const normalizedText=this.text.replace(/\t/g," ");const tokens=markdownParser.lexer(normalizedText);trimPartialClosingFences(tokens);const renderedLines=[];for(let i=0;i<tokens.length;i++){const token=tokens[i];const nextToken=tokens[i+1];const tokenLines=this.renderToken(token,contentWidth,nextToken?.type);for(const tokenLine of tokenLines){renderedLines.push(tokenLine)}}const wrappedLines=[];for(const line of renderedLines){if(isImageLine(line)){wrappedLines.push(line)}else{for(const wrappedLine of wrapTextWithAnsi(line,contentWidth)){wrappedLines.push(wrappedLine)}}}const leftMargin=" ".repeat(this.paddingX);const rightMargin=" ".repeat(this.paddingX);const bgFn=this.defaultTextStyle?.bgColor;const contentLines=[];for(const line of wrappedLines){if(isImageLine(line)){contentLines.push(line);continue}const lineWithMargins=leftMargin+line+rightMargin;if(bgFn){contentLines.push(applyBackgroundToLine(lineWithMargins,width,bgFn))}else{const visibleLen=visibleWidth(lineWithMargins);const paddingNeeded=Math.max(0,width-visibleLen);contentLines.push(lineWithMargins+" ".repeat(paddingNeeded))}}const emptyLine=" ".repeat(width);const emptyLines=[];for(let i=0;i<this.paddingY;i++){const line=bgFn?applyBackgroundToLine(emptyLine,width,bgFn):emptyLine;emptyLines.push(line)}const result=emptyLines.concat(contentLines,emptyLines);this.cachedText=this.text;this.cachedWidth=width;this.cachedLines=result;return result.length>0?result:[""]}applyDefaultStyle(text){if(!this.defaultTextStyle){return text}let styled=text;if(this.defaultTextStyle.color){styled=this.defaultTextStyle.color(styled)}if(this.defaultTextStyle.bold){styled=this.theme.bold(styled)}if(this.defaultTextStyle.italic){styled=this.theme.italic(styled)}if(this.defaultTextStyle.strikethrough){styled=this.theme.strikethrough(styled)}if(this.defaultTextStyle.underline){styled=this.theme.underline(styled)}return styled}getDefaultStylePrefix(){if(!this.defaultTextStyle){return""}if(this.defaultStylePrefix!==void 0){return this.defaultStylePrefix}const sentinel="\0";let styled=sentinel;if(this.defaultTextStyle.color){styled=this.defaultTextStyle.color(styled)}if(this.defaultTextStyle.bold){styled=this.theme.bold(styled)}if(this.defaultTextStyle.italic){styled=this.theme.italic(styled)}if(this.defaultTextStyle.strikethrough){styled=this.theme.strikethrough(styled)}if(this.defaultTextStyle.underline){styled=this.theme.underline(styled)}const sentinelIndex=styled.indexOf(sentinel);this.defaultStylePrefix=sentinelIndex>=0?styled.slice(0,sentinelIndex):"";return this.defaultStylePrefix}getStylePrefix(styleFn){const sentinel="\0";const styled=styleFn(sentinel);const sentinelIndex=styled.indexOf(sentinel);return sentinelIndex>=0?styled.slice(0,sentinelIndex):""}getDefaultInlineStyleContext(){return{applyText:text=>this.applyDefaultStyle(text),stylePrefix:this.getDefaultStylePrefix()}}renderToken(token,width,nextTokenType,styleContext){const lines=[];switch(token.type){case"heading":{const headingLevel=token.depth;const headingPrefix=`${"#".repeat(headingLevel)} `;let headingStyleFn;if(headingLevel===1){headingStyleFn=text=>this.theme.heading(this.theme.bold(this.theme.underline(text)))}else{headingStyleFn=text=>this.theme.heading(this.theme.bold(text))}const headingStyleContext={applyText:headingStyleFn,stylePrefix:this.getStylePrefix(headingStyleFn)};const headingText=this.renderInlineTokens(token.tokens||[],headingStyleContext);const styledHeading=headingLevel>=3?headingStyleFn(headingPrefix)+headingText:headingText;lines.push(styledHeading);if(nextTokenType&&nextTokenType!=="space"){lines.push("")}break}case"paragraph":{const paragraphText=this.renderInlineTokens(token.tokens||[],styleContext);lines.push(paragraphText);if(nextTokenType&&nextTokenType!=="list"&&nextTokenType!=="space"){lines.push("")}break}case"text":lines.push(this.renderInlineTokens([token],styleContext));break;case"code":{const indent=this.theme.codeBlockIndent??" ";lines.push(this.theme.codeBlockBorder(`\`\`\`${token.lang||""}`));if(this.theme.highlightCode){const highlightedLines=this.theme.highlightCode(token.text,token.lang);for(const hlLine of highlightedLines){lines.push(`${indent}${hlLine}`)}}else{const codeLines=token.text.split("\n");for(const codeLine of codeLines){lines.push(`${indent}${this.theme.codeBlock(codeLine)}`)}}lines.push(this.theme.codeBlockBorder("```"));if(nextTokenType&&nextTokenType!=="space"){lines.push("")}break}case"list":{const listLines=this.renderList(token,0,width,styleContext);lines.push(...listLines);break}case"table":{const tableLines=this.renderTable(token,width,nextTokenType,styleContext);lines.push(...tableLines);break}case"blockquote":{const quoteStyle=text=>this.theme.quote(this.theme.italic(text));const quoteStylePrefix=this.getStylePrefix(quoteStyle);const applyQuoteStyle=line=>{if(!quoteStylePrefix){return quoteStyle(line)}const lineWithReappliedStyle=line.replace(/\x1b\[0m/g,`\x1B[0m${quoteStylePrefix}`);return quoteStyle(lineWithReappliedStyle)};const quoteContentWidth=Math.max(1,width-2);const quoteInlineStyleContext={applyText:text=>text,stylePrefix:quoteStylePrefix};const quoteTokens=token.tokens||[];const renderedQuoteLines=[];for(let i=0;i<quoteTokens.length;i++){const quoteToken=quoteTokens[i];const nextQuoteToken=quoteTokens[i+1];renderedQuoteLines.push(...this.renderToken(quoteToken,quoteContentWidth,nextQuoteToken?.type,quoteInlineStyleContext))}while(renderedQuoteLines.length>0&&renderedQuoteLines[renderedQuoteLines.length-1]===""){renderedQuoteLines.pop()}for(const quoteLine of renderedQuoteLines){const styledLine=applyQuoteStyle(quoteLine);const wrappedLines=wrapTextWithAnsi(styledLine,quoteContentWidth);for(const wrappedLine of wrappedLines){lines.push(this.theme.quoteBorder("\u2502 ")+wrappedLine)}}if(nextTokenType&&nextTokenType!=="space"){lines.push("")}break}case"hr":lines.push(this.theme.hr("\u2500".repeat(Math.min(width,80))));if(nextTokenType&&nextTokenType!=="space"){lines.push("")}break;case"html":if("raw"in token&&typeof token.raw==="string"){lines.push(this.applyDefaultStyle(token.raw.trim()))}break;case"space":lines.push("");break;default:if("text"in token&&typeof token.text==="string"){lines.push(token.text)}}return lines}renderInlineTokens(tokens,styleContext){let result="";const resolvedStyleContext=styleContext??this.getDefaultInlineStyleContext();const{applyText,stylePrefix}=resolvedStyleContext;const applyTextWithNewlines=text=>{const segments=text.split("\n");return segments.map(segment=>applyText(segment)).join("\n")};for(const token of tokens){switch(token.type){case"escape":result+=applyTextWithNewlines(this.options.preserveBackslashEscapes?token.raw:token.text);break;case"text":if(token.tokens&&token.tokens.length>0){result+=this.renderInlineTokens(token.tokens,resolvedStyleContext)}else{result+=applyTextWithNewlines(token.text)}break;case"paragraph":result+=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);break;case"strong":{const boldContent=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);result+=this.theme.bold(boldContent)+stylePrefix;break}case"em":{const italicContent=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);result+=this.theme.italic(italicContent)+stylePrefix;break}case"codespan":result+=this.theme.code(token.text)+stylePrefix;break;case"link":{const linkText=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);const styledLink=this.theme.link(this.theme.underline(linkText));if(getCapabilities().hyperlinks){result+=hyperlink(styledLink,token.href)+stylePrefix}else{const hrefForComparison=token.href.startsWith("mailto:")?token.href.slice(7):token.href;if(token.text===token.href||token.text===hrefForComparison){result+=styledLink+stylePrefix}else{result+=styledLink+this.theme.linkUrl(` (${token.href})`)+stylePrefix}}break}case"br":result+="\n";break;case"del":{const delContent=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);result+=this.theme.strikethrough(delContent)+stylePrefix;break}case"html":if("raw"in token&&typeof token.raw==="string"){result+=applyTextWithNewlines(token.raw)}break;default:if("text"in token&&typeof token.text==="string"){result+=applyTextWithNewlines(token.text)}}}while(stylePrefix&&result.endsWith(stylePrefix)){result=result.slice(0,-stylePrefix.length)}return result}getOrderedListMarker(item){const match=/^(?: {0,3})(\d{1,9}[.)])[ \t]+/.exec(item.raw);return match?`${match[1]} `:void 0}getUnorderedListMarker(item){const match=/^(?: {0,3})([-+*])(?:[ \t]+|(?=\r?\n|$))/.exec(item.raw);return match?`${match[1]} `:void 0}renderList(token,depth,width,styleContext){const lines=[];const indent=" ".repeat(depth);const startNumber=typeof token.start==="number"?token.start:1;for(let i=0;i<token.items.length;i++){const item=token.items[i];const isLastItem=i===token.items.length-1;const bullet=token.ordered?this.options.preserveOrderedListMarkers?this.getOrderedListMarker(item)??`${startNumber+i}. `:`${startNumber+i}. `:this.options.preserveOrderedListMarkers?this.getUnorderedListMarker(item)??"- ":"- ";const taskMarker=item.task?`[${item.checked?"x":" "}] `:"";const marker=bullet+taskMarker;const firstPrefix=indent+this.theme.listBullet(marker);const continuationPrefix=indent+" ".repeat(visibleWidth(marker));const itemWidth=Math.max(1,width-visibleWidth(firstPrefix));let renderedAnyLine=false;for(const itemToken of item.tokens){if(itemToken.type==="list"){lines.push(...this.renderList(itemToken,depth+1,width,styleContext));renderedAnyLine=true;continue}const itemLines=this.renderToken(itemToken,itemWidth,void 0,styleContext);for(const line of itemLines){for(const wrappedLine of wrapTextWithAnsi(line,itemWidth)){const linePrefix=renderedAnyLine?continuationPrefix:firstPrefix;lines.push(linePrefix+wrappedLine);renderedAnyLine=true}}}if(!renderedAnyLine){lines.push(firstPrefix)}if(token.loose&&!isLastItem){lines.push("")}}return lines}getLongestWordWidth(text,maxWidth){const words=text.split(/\s+/).filter(word=>word.length>0);let longest=0;for(const word of words){longest=Math.max(longest,visibleWidth(word))}if(maxWidth===void 0){return longest}return Math.min(longest,maxWidth)}wrapCellText(text,maxWidth){return wrapTextWithAnsi(text,Math.max(1,maxWidth))}renderTable(token,availableWidth,nextTokenType,styleContext){const lines=[];const numCols=token.header.length;if(numCols===0){return lines}const borderOverhead=3*numCols+1;const availableForCells=availableWidth-borderOverhead;if(availableForCells<numCols){const fallbackLines=token.raw?wrapTextWithAnsi(token.raw,availableWidth):[];if(nextTokenType&&nextTokenType!=="space"){fallbackLines.push("")}return fallbackLines}const maxUnbrokenWordWidth=30;const naturalWidths=[];const minWordWidths=[];for(let i=0;i<numCols;i++){const headerText=this.renderInlineTokens(token.header[i].tokens||[],styleContext);naturalWidths[i]=visibleWidth(headerText);minWordWidths[i]=Math.max(1,this.getLongestWordWidth(headerText,maxUnbrokenWordWidth))}for(const row of token.rows){for(let i=0;i<row.length;i++){const cellText=this.renderInlineTokens(row[i].tokens||[],styleContext);naturalWidths[i]=Math.max(naturalWidths[i]||0,visibleWidth(cellText));minWordWidths[i]=Math.max(minWordWidths[i]||1,this.getLongestWordWidth(cellText,maxUnbrokenWordWidth))}}let minColumnWidths=minWordWidths;let minCellsWidth=minColumnWidths.reduce((a,b4)=>a+b4,0);if(minCellsWidth>availableForCells){minColumnWidths=new Array(numCols).fill(1);const remaining=availableForCells-numCols;if(remaining>0){const totalWeight=minWordWidths.reduce((total,width)=>total+Math.max(0,width-1),0);const growth=minWordWidths.map(width=>{const weight=Math.max(0,width-1);return totalWeight>0?Math.floor(weight/totalWeight*remaining):0});for(let i=0;i<numCols;i++){minColumnWidths[i]+=growth[i]??0}const allocated=growth.reduce((total,width)=>total+width,0);let leftover=remaining-allocated;for(let i=0;leftover>0&&i<numCols;i++){minColumnWidths[i]++;leftover--}}minCellsWidth=minColumnWidths.reduce((a,b4)=>a+b4,0)}const totalNaturalWidth=naturalWidths.reduce((a,b4)=>a+b4,0)+borderOverhead;let columnWidths;if(totalNaturalWidth<=availableWidth){columnWidths=naturalWidths.map((width,index)=>Math.max(width,minColumnWidths[index]))}else{const totalGrowPotential=naturalWidths.reduce((total,width,index)=>{return total+Math.max(0,width-minColumnWidths[index])},0);const extraWidth=Math.max(0,availableForCells-minCellsWidth);columnWidths=minColumnWidths.map((minWidth,index)=>{const naturalWidth=naturalWidths[index];const minWidthDelta=Math.max(0,naturalWidth-minWidth);let grow=0;if(totalGrowPotential>0){grow=Math.floor(minWidthDelta/totalGrowPotential*extraWidth)}return minWidth+grow});const allocated=columnWidths.reduce((a,b4)=>a+b4,0);let remaining=availableForCells-allocated;while(remaining>0){let grew=false;for(let i=0;i<numCols&&remaining>0;i++){if(columnWidths[i]<naturalWidths[i]){columnWidths[i]++;remaining--;grew=true}}if(!grew){break}}}const topBorderCells=columnWidths.map(w4=>"\u2500".repeat(w4));lines.push(`\u250C\u2500${topBorderCells.join("\u2500\u252C\u2500")}\u2500\u2510`);const headerCellLines=token.header.map((cell,i)=>{const text=this.renderInlineTokens(cell.tokens||[],styleContext);return this.wrapCellText(text,columnWidths[i])});const headerLineCount=Math.max(...headerCellLines.map(c=>c.length));for(let lineIdx=0;lineIdx<headerLineCount;lineIdx++){const rowParts=headerCellLines.map((cellLines,colIdx)=>{const text=cellLines[lineIdx]||"";const padded=text+" ".repeat(Math.max(0,columnWidths[colIdx]-visibleWidth(text)));return this.theme.bold(padded)});lines.push(`\u2502 ${rowParts.join(" \u2502 ")} \u2502`)}const separatorCells=columnWidths.map(w4=>"\u2500".repeat(w4));const separatorLine=`\u251C\u2500${separatorCells.join("\u2500\u253C\u2500")}\u2500\u2524`;lines.push(separatorLine);for(let rowIndex=0;rowIndex<token.rows.length;rowIndex++){const row=token.rows[rowIndex];const rowCellLines=row.map((cell,i)=>{const text=this.renderInlineTokens(cell.tokens||[],styleContext);return this.wrapCellText(text,columnWidths[i])});const rowLineCount=Math.max(...rowCellLines.map(c=>c.length));for(let lineIdx=0;lineIdx<rowLineCount;lineIdx++){const rowParts=rowCellLines.map((cellLines,colIdx)=>{const text=cellLines[lineIdx]||"";return text+" ".repeat(Math.max(0,columnWidths[colIdx]-visibleWidth(text)))});lines.push(`\u2502 ${rowParts.join(" \u2502 ")} \u2502`)}if(rowIndex<token.rows.length-1){lines.push(separatorLine)}}const bottomBorderCells=columnWidths.map(w4=>"\u2500".repeat(w4));lines.push(`\u2514\u2500${bottomBorderCells.join("\u2500\u2534\u2500")}\u2500\u2518`);if(nextTokenType&&nextTokenType!=="space"){lines.push("")}return lines}};var Spacer=class{lines;constructor(lines=1){this.lines=lines}setLines(lines){this.lines=lines}invalidate(){}render(_width){const result=[];for(let i=0;i<this.lines;i++){result.push("")}return result}};import*as fs2 from"fs";import{createRequire as createRequire2}from"module";import*as path3 from"path";import{fileURLToPath as fileURLToPath2}from"url";import{createRequire}from"module";import*as path2 from"path";import{fileURLToPath}from"url";var cjsRequire=createRequire(import.meta.url);var cjsRequire2=createRequire2(import.meta.url);var DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS=7;var KITTY_KEYBOARD_PROTOCOL_QUERY=`\x1B[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1B[?u\x1B[c`;import fs12 from"fs";import path27 from"path";import{fileURLToPath as fileURLToPath6}from"url";import{createHash as createHash2}from"crypto";import{createHash}from"crypto";function hashId(s3){return createHash("sha256").update(s3,"utf8").digest("hex").slice(0,16)}var CANONICAL_IMAGE_TEXT="[image]";var CANONICAL_REDACTED_THINKING_TEXT="[redacted_thinking]";function canonicalToolArgs(argsText){const trimmed=argsText.trim();if(!trimmed.startsWith("{")&&!trimmed.startsWith("["))return argsText;try{return JSON.stringify(canonicalize(JSON.parse(trimmed)))}catch{return argsText}}function canonicalize(v4){if(Array.isArray(v4))return v4.map(canonicalize);if(v4!==null&&typeof v4==="object"){const src=v4;const out={};for(const k2 of Object.keys(src).sort())out[k2]=canonicalize(src[k2]);return out}return v4}var idSalt=null;function deriveCanonicalMessageId(role,contentType,text,options={}){const seed=`${idSalt?idSalt+"|":""}${role}|${contentType}||${options.toolName??""}|${text}`+(options.mediaFingerprint!==void 0?`|${options.mediaFingerprint}`:"");return"h_"+hashId(seed)}function imageMediaFingerprint(base64OrUrl){return hashId(base64OrUrl)}function canonicalOpaqueSeed(item){if(item===null||typeof item!=="object")return hashId(String(item));const src=item;const out={};for(const k2 of Object.keys(src)){if(k2==="id"||k2==="status")continue;out[k2]=src[k2]}return hashId(JSON.stringify(out))}var ClusterCounter=class{counts=new Map;next(baseId){const n=this.counts.get(baseId)??0;this.counts.set(baseId,n+1);return n===0?baseId:`${baseId}_${n}`}};function anthropicToCore(body){const msgs=[];const cacheControls=new Map;const clusters=new ClusterCounter;const toolNames=new Map;for(const[wireIndex,m4]of body.messages.entries()){const before=msgs.length;if(m4.role==="system"){const core=systemMessageCore(m4,clusters);core.wireIndex=wireIndex;msgs.push(core);const mark=systemMessageMark(m4);if(mark)cacheControls.set(core.id,mark);continue}const blocks=typeof m4.content==="string"?[{type:"text",text:m4.content}]:m4.content;for(const b4 of blocks){switch(b4.type){case"text":{const base=deriveCanonicalMessageId(m4.role,"text",b4.text);const id=clusters.next(base);msgs.push({id,role:m4.role,contentType:"text",text:b4.text});if(b4.cache_control)cacheControls.set(id,b4.cache_control);break}case"tool_use":{const base=deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(safeStringify(b4.input)),{toolName:b4.name});const id=clusters.next(base);msgs.push({id,role:"assistant",contentType:"tool-call",toolName:b4.name,toolCallId:b4.id,text:safeStringify(b4.input)});toolNames.set(b4.id,b4.name);if(b4.cache_control)cacheControls.set(id,b4.cache_control);break}case"tool_result":{const hasNonText=Array.isArray(b4.content)&&b4.content.some(c=>c.type!=="text");const text=typeof b4.content==="string"?b4.content:b4.content.map(c=>c.type==="text"?c.text:"").join("\n");const name=toolNames.get(b4.tool_use_id);const base=deriveCanonicalMessageId("tool","tool-result",text,{toolName:name});const id=clusters.next(base);msgs.push({id,role:"tool",contentType:"tool-result",toolCallId:b4.tool_use_id,text,...name?{toolName:name}:{},...b4.is_error===true?{toolIsError:true}:{},...hasNonText?{rawAnthropicBlock:b4}:{}});if(b4.cache_control)cacheControls.set(id,b4.cache_control);break}case"thinking":{const base=deriveCanonicalMessageId("assistant","reasoning",b4.thinking);msgs.push({id:clusters.next(base),role:"assistant",contentType:"reasoning",text:b4.thinking,...b4.signature?{thinkingSignature:b4.signature}:{}});break}case"image":{const source=b4.source&&typeof b4.source==="object"&&!Array.isArray(b4.source)?b4.source:void 0;const mediaSidecar=source?.type==="base64"&&typeof source.media_type==="string"&&typeof source.data==="string"?{imageMediaType:source.media_type,imageBase64:source.data}:{};const base=deriveCanonicalMessageId(m4.role,"text",CANONICAL_IMAGE_TEXT,{mediaFingerprint:source?.type==="base64"&&typeof source.data==="string"?imageMediaFingerprint(source.data):typeof source?.url==="string"?imageMediaFingerprint(source.url):void 0});msgs.push({id:clusters.next(base),role:m4.role,contentType:"text",text:CANONICAL_IMAGE_TEXT,imagePart:true,rawAnthropicBlock:b4,...mediaSidecar});break}case"redacted_thinking":{const base=deriveCanonicalMessageId(m4.role,"text",CANONICAL_REDACTED_THINKING_TEXT);msgs.push({id:clusters.next(base),role:m4.role,contentType:"text",text:"[redacted_thinking]",rawAnthropicBlock:b4});break}default:{const unknownType=b4.type;const label=typeof unknownType==="string"?`[${unknownType}]`:"[unknown]";const base=deriveCanonicalMessageId(m4.role,"text",label);msgs.push({id:clusters.next(base),role:m4.role,contentType:"text",text:label,rawAnthropicBlock:b4});break}}}for(let k2=before;k2<msgs.length;k2++){msgs[k2].wireIndex=wireIndex}}return{msgs,cacheControls}}function systemMessageCore(m4,clusters){const label=systemMessageText(m4);const base=deriveCanonicalMessageId("system","text",label);return{id:clusters.next(base),role:"system",contentType:"text",text:label,rawAnthropicMessage:m4}}function systemMessageText(m4){const text=typeof m4.content==="string"?m4.content:m4.content.map(b4=>b4.type==="text"?b4.text:`[${b4.type}]`).join("\n");return text.length>0?text:"[system]"}function systemMessageMark(m4){if(typeof m4.content==="string")return void 0;let mark;for(const b4 of m4.content)if(b4.cache_control)mark=b4.cache_control;return mark}function safeStringify(v4){try{return JSON.stringify(v4??{})}catch{return"{}"}}var FORMS=[{open:"<think>\n",close:"\n</think>"},{open:"<thinking>\n",close:"\n</thinking>"},{open:"```thinking\n",close:"\n```"}];function splitDemotedThinking(content){let rest=content;const parts=[];for(;;){let matched=false;for(const form of FORMS){if(!rest.startsWith(form.open))continue;const end=rest.indexOf(form.close,form.open.length);if(end<0)continue;const inner=rest.slice(form.open.length,end);if(inner.length===0)continue;parts.push(inner);rest=rest.slice(end+form.close.length);if(rest.startsWith("\n"))rest=rest.slice(1);matched=true;break}if(!matched)break}if(parts.length===0)return null;return{reasoning:parts.join("\n"),text:rest}}function parseDataUrl(url){const m4=/^data:([^;,]+)(?:;base64)?,(.+)$/i.exec(url);if(!m4)return void 0;return{mediaType:m4[1],base64:m4[2]}}function imageFingerprintsOfParts(parts){const out=[];for(const part of parts){if(!part||typeof part!=="object")continue;const p2=part;if(p2.type!=="image_url")continue;const url=typeof p2.image_url?.url==="string"?p2.image_url.url:void 0;if(!url)continue;const parsed=parseDataUrl(url);out.push(imageMediaFingerprint(parsed?parsed.base64:url))}return out}function openaiToCore(body){const msgs=[];const systemParts=[];const clusters=new ClusterCounter;const toolNames=new Map;for(const[wireIndex,m4]of body.messages.entries()){const before=msgs.length;switch(m4.role){case"system":case"developer":{if(msgs.length===0){systemParts.push(stringContent(m4.content));break}const base=deriveCanonicalMessageId(m4.role,"text",stringContent(m4.content));msgs.push({id:clusters.next(base),role:"system",contentType:"text",text:stringContent(m4.content),originalRole:m4.role,rawOpenaiMessage:m4});break}case"user":{if(typeof m4.content==="string"||m4.content==null||!Array.isArray(m4.content)){const base=deriveCanonicalMessageId("user","text",typeof m4.content==="string"?m4.content:"");msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:typeof m4.content==="string"?m4.content:""});break}let lastTextCore=null;let leadingOpaque=[];let sawText=false;for(const part of m4.content){if(typeof part==="string"){const base=deriveCanonicalMessageId("user","text",part);lastTextCore={id:clusters.next(base),role:"user",contentType:"text",text:part};msgs.push(lastTextCore);sawText=true;continue}if(part?.type==="text"&&typeof part.text==="string"){const base=deriveCanonicalMessageId("user","text",part.text);lastTextCore={id:clusters.next(base),role:"user",contentType:"text",text:part.text};msgs.push(lastTextCore);sawText=true;continue}if(part?.type==="image_url"){const url=part.image_url?.url;const parsed=typeof url==="string"?parseDataUrl(url):void 0;const base=deriveCanonicalMessageId("user","text",CANONICAL_IMAGE_TEXT,{mediaFingerprint:imageMediaFingerprint(parsed?parsed.base64:typeof url==="string"?url:"")});msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:CANONICAL_IMAGE_TEXT,imagePart:true,rawOpenaiContent:part,...parsed?{imageMediaType:parsed.mediaType,imageBase64:parsed.base64}:{}});continue}if(lastTextCore){lastTextCore.rawOpenaiContentParts=[...lastTextCore.rawOpenaiContentParts??[],part]}else{leadingOpaque=[...leadingOpaque,part]}}if(leadingOpaque.length>0){if(sawText&&msgs.length>0){const firstTextCore=msgs.find((c,i)=>i>=before&&c.role==="user"&&c.contentType==="text"&&!c.rawOpenaiContent);const host=firstTextCore??msgs[msgs.length-1];host.rawOpenaiContentParts=[...leadingOpaque,...host.rawOpenaiContentParts??[]]}else{const base=deriveCanonicalMessageId("user","text","",{mediaFingerprint:imageFingerprintsOfParts(leadingOpaque).join(",")||void 0});msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:"",rawOpenaiContentParts:leadingOpaque})}}break}case"assistant":{const rawReasoning=m4.reasoning_content;const fieldPresent=typeof rawReasoning==="string";const fieldReasoning=fieldPresent?rawReasoning:"";let reasoning=fieldReasoning;let text=stringContent(m4.content);if(!reasoning){const split=splitDemotedThinking(text);if(split){reasoning=split.reasoning;text=split.text}}const blankEcho=fieldPresent&&reasoning.length===0;if(reasoning){const base=deriveCanonicalMessageId("assistant","reasoning",reasoning);msgs.push({id:clusters.next(base),role:"assistant",contentType:"reasoning",text:reasoning,reasoningContent:reasoning})}if(text){const base=deriveCanonicalMessageId("assistant","text",text);msgs.push({id:clusters.next(base),role:"assistant",contentType:"text",text,...blankEcho?{reasoningPresent:true}:{}})}if(Array.isArray(m4.tool_calls)){for(const tc of m4.tool_calls){const base=deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(tc.function.arguments??""),{toolName:tc.function.name});msgs.push({id:clusters.next(base),role:"assistant",contentType:"tool-call",toolName:tc.function.name,toolCallId:tc.id,text:tc.function.arguments??"",...blankEcho?{reasoningPresent:true}:{}});toolNames.set(tc.id,tc.function.name)}}break}case"tool":{const base=deriveCanonicalMessageId("tool","tool-result",stringContent(m4.content),{toolName:m4.name||toolNames.get(m4.tool_call_id??"")});const name=m4.name||toolNames.get(m4.tool_call_id??"");msgs.push({id:clusters.next(base),role:"tool",contentType:"tool-result",toolCallId:m4.tool_call_id??"",text:stringContent(m4.content),...name?{toolName:name}:{}});break}}for(let k2=before;k2<msgs.length;k2++){msgs[k2].wireIndex=wireIndex}}return{msgs,systemText:systemParts.join("\n\n")}}function stringContent(content){if(content==null)return"";if(typeof content==="string")return content;if(Array.isArray(content)){return content.map(p2=>typeof p2==="string"?p2:p2.type==="text"?p2.text??"":"").join("\n")}return""}var OPAQUE_ITEM_TYPES=new Set(["additional_tools","mcp_list_tools"]);function isOpaqueItem(item){return OPAQUE_ITEM_TYPES.has(item.type)}var EASY_INPUT_ROLES=new Set(["user","assistant","system","developer"]);function normalizeEasyInputItem(item){if(typeof item.type==="string")return item;if(EASY_INPUT_ROLES.has(String(item.role))){return{...item,type:"message"}}return item}function shouldDropAllReasoning(){return(process.env.ACP_REASONING_KEEP??"").trim().toLowerCase()==="none"}function partText(part){if(part.type==="input_text"||part.type==="output_text"){return typeof part.text==="string"?part.text:""}return""}function messageContent(content){return typeof content==="string"?content:content.map(partText).join("\n")}function userDisplayText(content,text){if(typeof content==="string")return text;const hasImage=content.some(part=>part.type==="input_image");const hasTextPart=content.some(part=>part.type==="input_text"||part.type==="output_text");return!text||hasImage&&!hasTextPart?"[image]":text}function reasoningText(item){const fromParts=(parts,type)=>{if(!Array.isArray(parts))return"";const texts=[];for(const part of parts){if(part&&typeof part==="object"&&"type"in part&&"text"in part){const rec=part;if(rec.type===type&&typeof rec.text==="string")texts.push(rec.text)}}return texts.join("\n")};const content="content"in item?item.content:void 0;const summary="summary"in item?item.summary:void 0;return fromParts(content,"reasoning_text")||fromParts(summary,"summary_text")}function responsesToCore(body){const msgs=[];const systemParts=[];const preamble=[];const customToolCallIds=new Set;const layout=[];let droppedReasoning=0;const clusters=new ClusterCounter;const toolNames=new Map;let idx=0;if(typeof body.instructions==="string"&&body.instructions.trim())systemParts.push(body.instructions);if(typeof body.input==="string"){const id=clusters.next(deriveCanonicalMessageId("user","text",body.input));msgs.push({id,role:"user",contentType:"text",text:body.input});return{msgs,systemParts,preamble,customToolCallIds,layout,droppedReasoning,stringInput:{original:body.input,coreId:id}}}let sysDevHead=true;for(const[wireIndex,raw]of body.input.entries()){const item=normalizeEasyInputItem(raw);let coreId;const before=msgs.length;if(isOpaqueItem(item))preamble.push(item);switch(item.type){case"reasoning":{if(shouldDropAllReasoning()){droppedReasoning++;continue}const text=reasoningText(item);const rid=text.length>0?text:canonicalOpaqueSeed(item);coreId=clusters.next(deriveCanonicalMessageId("assistant","reasoning",rid));msgs.push({id:coreId,role:"assistant",contentType:"reasoning",text:rid,rawResponsesItem:item});break}case"message":{const message=item;const text=messageContent(message.content);if(message.role==="system"||message.role==="developer"){if(sysDevHead){systemParts.push(text);idx++;continue}const midBase=deriveCanonicalMessageId(message.role,"text",text);msgs.push({id:clusters.next(midBase),role:"system",contentType:"text",text,originalRole:message.role,rawResponsesItem:item});break}else if(message.role==="user"||message.role==="assistant"&&text){const role2=message.role;const splittable=role2==="user"&&Array.isArray(message.content)&&message.content.length>1&&message.content.every(part=>typeof part==="object"&&part!==null&&(part.type==="input_text"||part.type==="output_text"||part.type==="input_image"));if(splittable){for(const rawPart of message.content){const part=typeof rawPart==="object"&&rawPart!==null?rawPart:void 0;if(!part)continue;if((part.type==="input_text"||part.type==="output_text")&&typeof part.text==="string"&&part.text.length>0){const base=deriveCanonicalMessageId("user","text",part.text);msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:part.text})}else if(part.type==="input_image"&&typeof part.image_url==="string"){const image=parseDataUrl(part.image_url);const base=deriveCanonicalMessageId("user","text",CANONICAL_IMAGE_TEXT,{mediaFingerprint:imageMediaFingerprint(image?image.base64:part.image_url)});msgs.push({id:clusters.next(base),role:"user",contentType:"text",text:CANONICAL_IMAGE_TEXT,imagePart:true,rawResponsesItem:item,...image?{imageMediaType:image.mediaType,imageBase64:image.base64}:{}})}}break}let effText=text;if(role2==="assistant"){const split=splitDemotedThinking(text);if(split){msgs.push({id:clusters.next(deriveCanonicalMessageId("assistant","reasoning",split.reasoning)),role:"assistant",contentType:"reasoning",text:split.reasoning,rawResponsesItem:item});effText=split.text}}const hasImage=Array.isArray(message.content)&&message.content.some(part=>part.type==="input_image");if(effText||role2==="user"&&hasImage){const displayText=role2==="user"?userDisplayText(message.content,effText):effText;const mediaFingerprint=Array.isArray(message.content)?message.content.flatMap(part=>{if(part?.type==="input_image"&&typeof part.image_url==="string"){const raw2=part.image_url;const decoded=parseDataUrl(raw2);return[imageMediaFingerprint(decoded?decoded.base64:raw2)]}return[]}).join(",")||void 0:void 0;coreId=clusters.next(deriveCanonicalMessageId(role2,"text",displayText,{mediaFingerprint}));const imageUrl=Array.isArray(message.content)?message.content.find(part=>part.type==="input_image"&&typeof part.image_url==="string")?.image_url:void 0;const image=typeof imageUrl==="string"?parseDataUrl(imageUrl):void 0;msgs.push({id:coreId,role:role2,contentType:"text",text:displayText,rawResponsesItem:item,...image?{imageMediaType:image.mediaType,imageBase64:image.base64}:{}})}}break}case"function_call":{const call=item;coreId=clusters.next(deriveCanonicalMessageId("assistant","tool-call",canonicalToolArgs(call.arguments??""),{toolName:call.name}));msgs.push({id:coreId,role:"assistant",contentType:"tool-call",toolName:call.name,toolCallId:call.call_id,text:call.arguments??"",rawResponsesItem:item});toolNames.set(call.call_id,call.name);break}case"function_call_output":{const output=item;const text=typeof output.output==="string"?output.output:JSON.stringify(output.output);coreId=clusters.next(deriveCanonicalMessageId("tool","tool-result",text,{toolName:toolNames.get(output.call_id)}));const name=toolNames.get(output.call_id);msgs.push({id:coreId,role:"tool",contentType:"tool-result",toolCallId:output.call_id,text,...name?{toolName:name}:{},rawResponsesItem:item});break}case"computer_call":case"computer_call_output":case"file_search_call":case"web_search_call":case"image_generation_call":case"code_interpreter_call":case"mcp_call":{const rid=canonicalOpaqueSeed(item);coreId=clusters.next(deriveCanonicalMessageId("assistant","responses-call",rid));msgs.push({id:coreId,role:"assistant",contentType:"reasoning",text:rid,rawResponsesItem:item});break}case"custom_tool_call":{const ctc=item;const callId=ctc.call_id??`call_${idx}`;customToolCallIds.add(callId);const argText=ctc.input??ctc.arguments??"";coreId=clusters.next(deriveCanonicalMessageId("assistant","tool-call",argText,{toolName:ctc.name??"custom"}));msgs.push({id:coreId,role:"assistant",contentType:"tool-call",toolName:ctc.name??"custom",toolCallId:callId,text:argText,rawResponsesItem:item});toolNames.set(callId,ctc.name??"custom");break}case"custom_tool_call_output":{const ctco=item;const callId=ctco.call_id??`call_${idx}`;customToolCallIds.add(callId);const outText=typeof ctco.output==="string"?ctco.output:JSON.stringify(ctco.output??"");coreId=clusters.next(deriveCanonicalMessageId("tool","tool-result",outText,{toolName:toolNames.get(callId)}));const name=toolNames.get(callId);msgs.push({id:coreId,role:"tool",contentType:"tool-result",toolCallId:callId,text:outText,...name?{toolName:name}:{},rawResponsesItem:item});break}default:if(!isOpaqueItem(item))preamble.push(item);break}for(let k2=before;k2<msgs.length;k2++){msgs[k2].wireIndex=wireIndex}const role=item.role;const isSysDevMsgItem=(item.type===void 0||item.type==="message")&&(role==="system"||role==="developer");if(!isSysDevMsgItem&&item.type!=="additional_tools"&&item.type!=="mcp_list_tools")sysDevHead=false;const produced=msgs.slice(before).map(m4=>m4.id);layout.push({original:item,...produced.length>0?{coreId:produced[0]}:{},...produced.length>1?{coreIds:produced}:{}});idx++}return{msgs,systemParts,preamble,customToolCallIds,layout,droppedReasoning}}function createSubagentNamespaces(){const anchors=new Map;return{namespaceFor(identityValue,instructions){if(typeof instructions!=="string"||instructions.trim().length===0)return identityValue;const fp=hashId(instructions);const anchor=anchors.get(identityValue);if(anchor===void 0){anchors.set(identityValue,fp);return identityValue}return anchor===fp?identityValue:`${identityValue}|sub:${fp}`}}}var defaultNamespaces=createSubagentNamespaces();function detectWireFormat(payload){if(payload===null||typeof payload!=="object")return void 0;const p2=payload;if(Array.isArray(p2.contents))return"google";if(Array.isArray(p2.input))return"responses";const messages=p2.messages;if(!Array.isArray(messages))return void 0;if("system"in p2||"anthropic_version"in p2)return"anthropic";for(const m4 of messages){if(m4===null||typeof m4!=="object")continue;const c=m4.content;if(Array.isArray(c)){for(const b4 of c){if(b4&&typeof b4==="object"&&typeof b4.type==="string"){if(b4.type==="tool_use"||b4.type==="tool_result"||b4.type==="thinking")return"anthropic";if(b4.type==="text"&&"cache_control"in b4)return"anthropic"}}}if(Array.isArray(m4.tool_calls))return"openai";if(m4.role==="tool"&&typeof m4.tool_call_id==="string")return"openai";if(m4.role==="system"||m4.role==="developer")return"openai"}return"openai"}var DEFAULT_MAX_FUTURE_SKEW_MS=2*60*1e3;var DEFAULT_RECENT_CHECKPOINT_WINDOW_MS=10*60*1e3;var MAX_CHECKPOINT_CHARS=512;var TAG_OPEN="<bili-chain ";var TAG_CLOSE="/>";var ATTRS=["v","processor","issued-at","request-id","digest"];function validAttrValue(name,raw){switch(name){case"v":return/^\d+$/.test(raw)&&Number(raw)>=1;case"issued-at":return/^\d{1,16}$/.test(raw);case"processor":return/^[A-Za-z0-9._-]{1,64}$/.test(raw);case"request-id":return/^[A-Za-z0-9._:-]{1,64}$/.test(raw);case"digest":return/^sha256:[0-9a-f]{64}$/.test(raw)}}function parseChainCheckpoint(text){if(typeof text!=="string"||text.length===0||text.length>MAX_CHECKPOINT_CHARS)return null;if(!text.startsWith(TAG_OPEN)||!text.endsWith(TAG_CLOSE))return null;const inner=text.slice(TAG_OPEN.length,-TAG_CLOSE.length);const found={};for(const token of inner.split(/\s+/)){const m4=/^([a-z][a-z0-9-]*)="([^"]*)"$/.exec(token);if(!m4)return null;const name=m4[1];if(!ATTRS.includes(name))return null;if(Object.hasOwn(found,name))return null;found[name]=m4[2]}for(const attr of ATTRS){const raw=found[attr];if(raw===void 0||!validAttrValue(attr,raw))return null}return{v:Number(found.v),processor:found.processor,issuedAt:Number(found["issued-at"]),requestId:found["request-id"],digest:found.digest}}function stripEmbeddedChainCarriers(parsed,wire){if(parsed===null||typeof parsed!=="object"||Array.isArray(parsed))return 0;const body=parsed;let stripped=0;if(wire==="google"){const contents=body.contents;if(!Array.isArray(contents))return 0;for(let i=contents.length-1;i>=0;i--){const c=contents[i];if(!c||typeof c!=="object"||Array.isArray(c))continue;const ct2=c;const role=typeof ct2.role==="string"?ct2.role:"user";if(role!=="user"&&role!=="model")continue;const parts=ct2.parts;if(!Array.isArray(parts))continue;let removed=0;for(let j4=parts.length-1;j4>=0;j4--){const p2=parts[j4];if(p2&&typeof p2==="object"&&!Array.isArray(p2)&&Object.keys(p2).length===1&&typeof p2.text==="string"){if(parseChainCheckpoint(p2.text)){parts.splice(j4,1);removed++}}}if(removed>0){if(parts.length===0)contents.splice(i,1);stripped+=removed}}return stripped}if(wire==="responses"){const input=body.input;if(!Array.isArray(input))return 0;for(let i=input.length-1;i>=0;i--){const item=input[i];if(!item||typeof item!=="object"||Array.isArray(item))continue;const it2=item;if(it2.type!=="message")continue;const role=typeof it2.role==="string"?it2.role:"";if(role!=="user"&&role!=="assistant")continue;const content=it2.content;if(typeof content==="string"){if(parseChainCheckpoint(content)){input.splice(i,1);stripped++}continue}if(!Array.isArray(content))continue;let removed=0;for(let j4=content.length-1;j4>=0;j4--){const p2=content[j4];if(p2&&typeof p2==="object"&&!Array.isArray(p2)){const po2=p2;if(po2.type==="input_text"&&typeof po2.text==="string"&&Object.keys(po2).length===2&&parseChainCheckpoint(po2.text)){content.splice(j4,1);removed++}}}if(removed>0){if(content.length===0)input.splice(i,1);stripped+=removed}}return stripped}const messages=body.messages;if(!Array.isArray(messages))return 0;for(let i=messages.length-1;i>=0;i--){const rec=messages[i];if(!rec||typeof rec!=="object"||Array.isArray(rec))continue;const m4=rec;if(m4.role!=="user"&&m4.role!=="assistant")continue;const content=m4.content;if(typeof content==="string"){if(parseChainCheckpoint(content)){messages.splice(i,1);stripped++}continue}if(!Array.isArray(content))continue;let removed=0;for(let j4=content.length-1;j4>=0;j4--){const p2=content[j4];if(p2&&typeof p2==="object"&&!Array.isArray(p2)){const po2=p2;if(po2.type==="text"&&typeof po2.text==="string"&&Object.keys(po2).length===2&&parseChainCheckpoint(po2.text)){content.splice(j4,1);removed++}}}if(removed>0){if(content.length===0)messages.splice(i,1);stripped+=removed}}return stripped}var ZERO_DIGEST="sha256:"+"0".repeat(64);import{randomUUID as randomUUID5}from"crypto";init_logger();import{createHash as createHash15}from"crypto";import{createHash as createHash14,randomUUID as randomUUID4}from"crypto";import{closeSync,existsSync as existsSync6,fsyncSync,mkdirSync as mkdirSync6,openSync,readdirSync,readFileSync as readFileSync7,renameSync as renameSync2,rmSync,statSync as statSync7,writeFileSync as writeFileSync6}from"fs";import{readdir as readdir2,readFile as readFile4,rm as rm2}from"fs/promises";import*as path20 from"path";init_paths();init_knobs();init_logger();init_runtime_status();init_version();import{createCipheriv,createDecipheriv,randomBytes as randomBytes2}from"crypto";import*as zlib from"zlib";var ENCRYPT_MAGIC=Buffer.from("BILIENC1","utf8");var ZSTD_MAGIC=Buffer.from("BILIZSTD1","utf8");var NONCE_LEN=12;var TAG_LEN=16;var ENCRYPT_HEADER_LEN=ENCRYPT_MAGIC.length+2+NONCE_LEN;var MIN_ENCRYPTED_LEN=ENCRYPT_HEADER_LEN+TAG_LEN;var PLAIN_HEADER_LEN=ZSTD_MAGIC.length+2;init_logger();init_billing();init_state_hydration();init_shadow();init_logger();var HOT_ATTACH_WINDOW_MS=10*6e4;var ATTACH_SILENCE_MS=5*6e4;init_backend();init_ingest();init_store();init_logger();init_paths();import{randomUUID as randomUUID2}from"crypto";import{mkdirSync as mkdirSync5,writeFileSync as writeFileSync5}from"fs";import{dirname as dirname6,join as join5}from"path";init_knobs();function parseToolOutcome(value){return value==="applied"||value==="partial"||value==="refused"||value==="success"||value==="failure"?value:void 0}function parseBlocksCreated(value){return typeof value==="number"&&Number.isInteger(value)&&value>=0?value:void 0}function partialOutcomeNote(blocksCreated){const created=blocksCreated!==void 0?`${blocksCreated} block(s) created; `:"";return`[acp-result: PARTIAL \u2014 ${created}some requested range(s) were NOT folded. Retry ONLY the failed range(s) listed above; do not re-fold the ranges that were applied.]`}import{createHash as createHash13,randomUUID as randomUUID3}from"crypto";import{AsyncLocalStorage as AsyncLocalStorage3}from"async_hooks";init_logger();import{createHash as createHash12}from"crypto";import{createHash as createHash11}from"crypto";init_client_config();import fs9 from"fs";import path19 from"path";import path18 from"path";import{fileURLToPath as fileURLToPath5}from"url";var originWaiter;async function awaitNativeProxyOrigin(){return originWaiter===void 0?void 0:originWaiter.wait()}init_dsh_channel();var SCAN_CACHE_TTL_MS=5*60*1e3;var CONFLICT_ACTIVE_WINDOW_MS=7*24*60*60*1e3;init_logger();init_logger();init_billing();init_util();var BOOT_ID=randomUUID3();var SEAM_BODY_CAP=512*1024;var BODY_FULL_CAP=8*1024*1024;var captures=new AsyncLocalStorage3;var LEARNED_IMAGE_COST_TTL_MS=24*60*60*1e3;var{join:join7}=path20;var FROZEN_SKIP_NOTICE_COOLDOWN_MS=10*6e4;init_version();init_knobs();init_config();init_config();init_paths();init_logger();init_external_summary_settings();import*as path21 from"path";init_turn_separator();init_turn_separator();var ABORT_REANCHOR_MAX_AGE_MS=30*60*1e3;var MAX_SESSIONS=maxSessions();var MAX_RESIDENT_BYTES=sessionResidentMaxBytes();var SPLIT_CANARY_FRESH_MS=10*60*1e3;init_knobs();var CODEX_FORGED_HANDOFF_HEADER="[bili] context summary after compaction:";var FORGED_SUMMARY_HEADER="[Compressed conversation section]";function buildAcplikeName(){const cores=["acp","apc","cap","cpa","pac","pca"];const ci2=ch=>`[${ch}${ch.toUpperCase()}]`;const attestedDrift=["[aA][cC][cC][eE][sS][sS][pP]","[aA][cC][aA][cC][pP]","[aA][cC][bB]"];const fourLetter=new Set;const threeLetter=new Set;for(const c of cores){threeLetter.add(ci2(c.charAt(0))+ci2(c.charAt(1))+ci2(c.charAt(2)));for(let pos=0;pos<=c.length;pos++){fourLetter.add(c.slice(0,pos).split("").map(ci2).join("")+"[aAcCpPiI]"+c.slice(pos).split("").map(ci2).join(""))}}return[...attestedDrift,...fourLetter,...threeLetter].join("|")}var ACP_NAME_ALT=`(?:${buildAcplikeName()})`;var NAME=ACP_NAME_ALT;var REF_TOKEN="m\\d{4,}";var REFS_RUN=REF_TOKEN+"(?:\\s*(?:[\u2013\u2014,-]\\s*)?"+REF_TOKEN+")*";var REFS_ONLY=new RegExp("^\\s*"+REFS_RUN+"\\s*$");var PENDING_REF_SPAN=new RegExp("^\\s*"+REFS_RUN+"(?:\\s*(?:[\\u2013\\u2014,\\-]\\s*)?(?:m\\d{0,3})?)?\\s*$");var PAIRED_BODY="\\s*(?:"+REFS_RUN+")?\\s*";var PAIRED=new RegExp("<"+NAME+"(?:\\s[^<>]*)?>("+PAIRED_BODY+")<\\/"+NAME+">");var ORPHAN_REF_CLOSE=new RegExp("(?<![\\w>])"+REFS_RUN+"\\s*<\\/"+NAME+"(?=[\\s>])[^<>]{0,32}>");var ORPHAN_RUN_BEFORE=new RegExp("(?<![\\w>])"+REFS_RUN+"\\s*$");var LONE_OPEN=new RegExp("<"+NAME+"(?:\\s[^<>]*)?>");var LONE_CLOSE=new RegExp("<\\/"+NAME+"(?=[\\s>])[^<>]{0,32}>");var DEGEN_PAIR=new RegExp("<"+NAME+"(?:\\s[^<>]*)?>\\s*m\\d{4,}\\s*<\\/[^<>]{1,32}>","g");var SELF_CLOSE=new RegExp("<"+NAME+"(?:\\s[^<>]*)?\\/>");var PARTIAL_TAIL=new RegExp("(<"+NAME+"\\s[^<>]*|<"+NAME+"\\s*=\\s*[^<>]*|<\\/"+NAME+"(?:\\s[^<>]{0,32})?|<\\/?[aAcCpPiI]*(?:/)?|(?<![\\w>])\\s*"+REFS_RUN+"\\s*<[^<>]*|(?<![\\w>])\\s*"+REFS_RUN+"(?:\\s*(?:[\\u2013\\u2014,\\-]\\s*)?(?:m\\d{0,3})?)?\\s*|(?<![\\w>])\\s*m\\d{0,3})$");var TRUNC_OPEN=new RegExp("<"+NAME+"\\s[^<>]*$|<"+NAME+"\\s*=\\s*[^<>]*$");var TRUNC_CLOSE=new RegExp("<\\/"+NAME+"(?:\\s[^<>]{0,32})?$");var TRUNC_REF_CLOSE=new RegExp("m\\d{4,}\\s*\\x3c\\/([a-zA-Z]{0,32})$");var DEAD_REF_CLOSE=new RegExp("(?<![\\w>])m\\d{4,}\\s*\\x3c\\/[a-zA-Z]{0,32}(?![a-zA-Z])(?![^\\x3c\\x3e]{0,32}\\x3e)","g");var BROKEN_ATTRS=new RegExp("<"+NAME+"\\s[^<>]*(?=<)");var MANGLED_OPEN=new RegExp("<"+NAME+"\\s*=\\s*[^<>]*>");var DEFINITE_TAIL=new RegExp("^<"+NAME+"\\s|^<"+NAME+"=|^<\\/"+NAME);var OPEN_WITH_ATTRS=new RegExp("^<"+NAME+"\\s");var CLOSE_NAME_ANCHORED=new RegExp("^"+NAME);var MARKER_HEAD=new RegExp("^\\p{So}(?:[ \\t])?\\[ACP\\]","u");var MARKER_LINE=new RegExp("^\\p{So}(?:[ \\t])?\\[ACP\\][^\\n]*\\n?","gmu");function stripMarkerLines(text){return text.replace(MARKER_LINE,"")}var MARKER_LINE_PROBE=new RegExp(MARKER_LINE.source,"mu");var RENDER_TAG_DETECT=new RegExp("<\\/?"+NAME+"(?=[\\s>])|\\\\u003c\\/?"+NAME+"(?=[\\s>\\\\])|<"+NAME+"\\s*\\/|\\\\u003c"+NAME+"\\s*\\/");var BROAD_TAG_HEAD_TAIL=new RegExp("<\\/?[A-Za-z0-9]{0,16}$");var RAW_WS="(?:\\\\[a-z]|\\s|\\\\)*";var TC_PARAM_REF_RAW=new RegExp(`\\x3c(?:antml:)?parameter(?:\\s*=\\s*["']?ref["']?|\\s+name\\s*=\\s*["']ref["'])?[^<>]*\\x3e`+RAW_WS+"m\\d{4,}"+RAW_WS+"\\x3c\\/(?:antml:)?parameter","i");var CHAIN_OPEN_ESCAPED="\\u003c"+TAG_OPEN.slice(1);function reEscape(s3){return s3.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function prefixAlts(s3,minLen){const out=[];for(let k2=minLen;k2<s3.length;k2++)out.push(reEscape(s3.slice(0,k2)));return out}var CHAIN_PARTIAL_TAIL=new RegExp("("+[...new Set([...prefixAlts(TAG_OPEN,1),reEscape(TAG_OPEN),...prefixAlts(CHAIN_OPEN_ESCAPED,1),reEscape(CHAIN_OPEN_ESCAPED)])].join("|")+")$");var HEAD_PREFIX_TAIL=new RegExp("(?:^|\n)("+[...new Set([...prefixAlts(CODEX_FORGED_HANDOFF_HEADER,1),...prefixAlts(FORGED_SUMMARY_HEADER,1)])].join("|")+")$");var TAG_PARTIAL_TAIL=new RegExp("(<"+NAME+"\\s[^<>]*|<\\/"+NAME+"(?:\\s[^<>]{0,32})?|<\\/?[aAcCpPiI]*(?:/)?)$");var PANEL_BOX_TOP="\u256D";var PANEL_BOX_TITLE="ACP Context Analysis";var PANEL_BOX_FOOTER="Tag visibility: tags injected to LLM only (deep copy), not persisted in session, not shown in terminal.";var PANEL_FALLBACK_HEADER="\u{1F4CA} ACP status";var CACHE_REPORT_OPEN="[acp-cache]";var CACHE_REPORT_CLOSE="[/acp-cache]";var RULE_REPORT_OPEN="[acp-rule]";var RULE_REPORT_CLOSE="[/acp-rule]";var STATUS_REPORT_OPEN="[acp-status]";var STATUS_REPORT_CLOSE="[/acp-status]";function wrapCacheReport(report){return`${CACHE_REPORT_OPEN}
191
191
  ${report}
192
192
  ${CACHE_REPORT_CLOSE}`}function wrapRuleReport(report){return`${RULE_REPORT_OPEN}
193
193
  ${report}