@knightcodeai/cli 0.19.0 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/dist/bundle/chunks/anthropic-messages-5ZM7Z2XQ.js +6 -0
- package/dist/bundle/chunks/{azure-openai-responses-ZZQJJY7B.js → azure-openai-responses-OUS4VJNA.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
- package/dist/bundle/chunks/chunk-5ZES34QN.js +2 -0
- package/dist/bundle/chunks/{chunk-T47GKPON.js → chunk-6GRVIFTN.js} +1 -1
- package/dist/bundle/chunks/{chunk-IIS4JDFO.js → chunk-6KWPS3LA.js} +23 -22
- package/dist/bundle/chunks/{chunk-R7X2RAGR.js → chunk-6X7IXVQH.js} +4 -4
- package/dist/bundle/chunks/{chunk-RZDCZFG7.js → chunk-B7A4GIBK.js} +1 -1
- package/dist/bundle/chunks/{chunk-JSLSFYBX.js → chunk-BWGDAXFH.js} +1 -1
- package/dist/bundle/chunks/{chunk-3QKQRXCZ.js → chunk-DFRYMT3C.js} +3 -3
- package/dist/bundle/chunks/{chunk-BTRAS32C.js → chunk-IIWY7U5S.js} +1 -1
- package/dist/bundle/chunks/{chunk-OQHO44L6.js → chunk-J63X3FRT.js} +1 -1
- package/dist/bundle/chunks/{chunk-KRDGPCZM.js → chunk-JMJS643J.js} +1 -1
- package/dist/bundle/chunks/{chunk-C62RVFZT.js → chunk-L6QGGIZG.js} +2 -2
- package/dist/bundle/chunks/{chunk-AA6MLWWY.js → chunk-MZ5UVOTP.js} +1 -1
- package/dist/bundle/chunks/chunk-N5M3XNPN.js +2 -0
- package/dist/bundle/chunks/{chunk-GPHSXYPT.js → chunk-RKNFSQUG.js} +1 -1
- package/dist/bundle/chunks/{chunk-2QXPCKUQ.js → chunk-VQBEVSZH.js} +1 -1
- package/dist/bundle/chunks/{cli-SIPOI5P3.js → cli-72YA573P.js} +1 -1
- package/dist/bundle/chunks/cloudflare-workers-ai-system-one-AWHNPEAT.js +2 -0
- package/dist/bundle/chunks/{easter-egg-3d-BVWLABZN.js → easter-egg-3d-XXPCDCZV.js} +1 -1
- package/dist/bundle/chunks/{execute-6UIHV2DR.js → execute-KWIUMPDE.js} +1 -1
- package/dist/bundle/chunks/{google-generative-ai-RFCCCXK6.js → google-generative-ai-HPLZ2ABU.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-WN3JAZCD.js → google-vertex-E3UTTTIG.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-GIGX6BW6.js → mistral-conversations-KT4C4XTZ.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-3Y7R752C.js → openai-codex-responses-BCLSSOJ6.js} +1 -1
- package/dist/bundle/chunks/openai-completions-GTNAEXX6.js +7 -0
- package/dist/bundle/chunks/{openai-decisions-MLI3SMFN.js → openai-decisions-CSQTW3S4.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-BNRA5YTD.js → openai-responses-ILFXLMJW.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-JWVDFQJ4.js → openrouter-images-J66HXAMB.js} +1 -1
- package/dist/bundle/chunks/{runtime-AROIXIAV.js → runtime-OW5JKWBE.js} +1 -1
- package/dist/bundle/chunks/typesafe-system-one-QA5VXBEZ.js +2 -0
- package/dist/bundle/chunks/{virtual-modules-IYKQM2DL.js → virtual-modules-5DLTLPP7.js} +1 -1
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/core/export-html/template.css +9 -0
- package/dist/core/export-html/template.js +165 -45
- package/docs/app-server.md +66 -8
- package/docs/app-server.schema.json +6200 -1048
- package/docs/containerization.md +2 -2
- package/docs/declarative-views.md +118 -0
- package/docs/desktop.md +26 -0
- package/docs/docs.json +4 -0
- package/docs/extensions.md +4 -2
- package/docs/models-configuration.md +9 -0
- package/docs/models.md +8 -4
- package/examples/extensions/README.md +1 -0
- package/examples/extensions/desktop-view.ts +72 -0
- package/examples/extensions/gondolin/index.ts +8 -10
- package/examples/extensions/gondolin/package-lock.json +20 -30
- package/examples/extensions/gondolin/package.json +1 -1
- package/package.json +1 -1
- package/dist/bundle/chunks/anthropic-messages-34POCEPV.js +0 -6
- package/dist/bundle/chunks/chunk-2QXUEOVY.js +0 -2
- package/dist/bundle/chunks/cloudflare-workers-ai-system-one-QHP5M5HC.js +0 -2
- package/dist/bundle/chunks/openai-completions-HBXENZUJ.js +0 -7
- package/dist/bundle/chunks/typesafe-system-one-5LELZY2F.js +0 -2
|
@@ -84,7 +84,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
84
84
|
`,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let previousLine=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=previousLine+currentLine,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(previousLine.length)}}else{this.pushUndoSnapshot();let wasKill=this.lastAction==="kill",oldCursorCol=this.state.cursorCol;this.moveWordBackwards();let deleteFrom=this.state.cursorCol;this.setCursorCol(oldCursorCol);let deletedText=currentLine.slice(deleteFrom,this.state.cursorCol);this.killRing.push(deletedText,{prepend:!0,accumulate:wasKill}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(0,deleteFrom)+currentLine.slice(this.state.cursorCol),this.setCursorCol(deleteFrom)}this.onChange&&this.onChange(this.getText())}deleteWordForward(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=currentLine.length){if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
|
|
85
85
|
`,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let nextLine=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=currentLine+nextLine,this.state.lines.splice(this.state.cursorLine+1,1)}}else{this.pushUndoSnapshot();let wasKill=this.lastAction==="kill",oldCursorCol=this.state.cursorCol;this.moveWordForwards();let deleteTo=this.state.cursorCol;this.setCursorCol(oldCursorCol);let deletedText=currentLine.slice(this.state.cursorCol,deleteTo);this.killRing.push(deletedText,{prepend:!1,accumulate:wasKill}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(0,this.state.cursorCol)+currentLine.slice(deleteTo)}this.onChange&&this.onChange(this.getText())}handleForwardDelete(){this.exitHistoryBrowsing(),this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<currentLine.length){this.pushUndoSnapshot();let afterCursor=currentLine.slice(this.state.cursorCol),firstGrapheme=[...this.segment(afterCursor,"grapheme")][0],graphemeLength=firstGrapheme?firstGrapheme.segment.length:1,before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol+graphemeLength);this.state.lines[this.state.cursorLine]=before+after}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot();let nextLine=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=currentLine+nextLine,this.state.lines.splice(this.state.cursorLine+1,1)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(textBeforeCursor)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(textBeforeCursor)&&this.tryTriggerAutocomplete()}}buildVisualLineMap(width){let visualLines=[];for(let i=0;i<this.state.lines.length;i++){let line=this.state.lines[i]||"",lineVisWidth=visibleWidth(line);if(line.length===0)visualLines.push({logicalLine:i,startCol:0,length:0});else if(lineVisWidth<=width)visualLines.push({logicalLine:i,startCol:0,length:line.length});else{let chunks=wordWrapLine(line,width,[...this.segment(line,"grapheme")]);for(let chunk of chunks)visualLines.push({logicalLine:i,startCol:chunk.startIndex,length:chunk.endIndex-chunk.startIndex})}}return visualLines}findVisualLineAt(visualLines,line,col){for(let i=0;i<visualLines.length;i++){let vl=visualLines[i];if(!vl||vl.logicalLine!==line)continue;let offset=col-vl.startCol,isLastSegmentOfLine=i===visualLines.length-1||visualLines[i+1]?.logicalLine!==vl.logicalLine;if(offset>=0&&(offset<vl.length||isLastSegmentOfLine&&offset===vl.length))return i}return visualLines.length-1}findCurrentVisualLine(visualLines){return this.findVisualLineAt(visualLines,this.state.cursorLine,this.state.cursorCol)}moveCursor(deltaLine,deltaCol){this.lastAction=null;let visualLines=this.buildVisualLineMap(this.lastWidth),currentVisualLine=this.findCurrentVisualLine(visualLines);if(deltaLine!==0){let targetVisualLine=currentVisualLine+deltaLine;targetVisualLine>=0&&targetVisualLine<visualLines.length&&this.moveToVisualLine(visualLines,currentVisualLine,targetVisualLine)}if(deltaCol!==0){let currentLine=this.state.lines[this.state.cursorLine]||"";if(deltaCol>0)if(this.state.cursorCol<currentLine.length){let afterCursor=currentLine.slice(this.state.cursorCol),firstGrapheme=[...this.segment(afterCursor,"grapheme")][0];this.setCursorCol(this.state.cursorCol+(firstGrapheme?firstGrapheme.segment.length:1))}else if(this.state.cursorLine<this.state.lines.length-1)this.state.cursorLine++,this.setCursorCol(0);else{let currentVL=visualLines[currentVisualLine];currentVL&&(this.preferredVisualCol=this.state.cursorCol-currentVL.startCol)}else if(this.state.cursorCol>0){let beforeCursor=currentLine.slice(0,this.state.cursorCol),graphemes=[...this.segment(beforeCursor,"grapheme")],lastGrapheme=graphemes[graphemes.length-1];this.setCursorCol(this.state.cursorCol-(lastGrapheme?lastGrapheme.segment.length:1))}else if(this.state.cursorLine>0){this.state.cursorLine--;let prevLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(prevLine.length)}}this.autocompleteState&&this.updateAutocomplete()}pageScroll(direction){this.lastAction=null;let terminalRows=this.tui.terminal.rows,pageSize=Math.max(5,Math.floor(terminalRows*.3)),visualLines=this.buildVisualLineMap(this.lastWidth),currentVisualLine=this.findCurrentVisualLine(visualLines),targetVisualLine=Math.max(0,Math.min(visualLines.length-1,currentVisualLine+direction*pageSize));this.moveToVisualLine(visualLines,currentVisualLine,targetVisualLine)}moveWordBackwards(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.state.cursorLine--;let prevLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(prevLine.length)}return}this.setCursorCol(findWordBackward(currentLine,this.state.cursorCol,{segment:text=>this.segment(text,"word"),isAtomicSegment:isPasteMarker}))}yank(){if(this.killRing.length===0)return;this.pushUndoSnapshot();let text=this.killRing.peek();this.insertYankedText(text),this.lastAction="yank"}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndoSnapshot(),this.deleteYankedText(),this.killRing.rotate();let text=this.killRing.peek();this.insertYankedText(text),this.lastAction="yank"}insertYankedText(text){this.exitHistoryBrowsing();let lines=text.split(`
|
|
86
86
|
`);if(lines.length===1){let currentLine=this.state.lines[this.state.cursorLine]||"",before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+text+after,this.setCursorCol(this.state.cursorCol+text.length)}else{let currentLine=this.state.lines[this.state.cursorLine]||"",before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+(lines[0]||"");for(let i=1;i<lines.length-1;i++)this.state.lines.splice(this.state.cursorLine+i,0,lines[i]||"");let lastLineIndex=this.state.cursorLine+lines.length-1;this.state.lines.splice(lastLineIndex,0,(lines[lines.length-1]||"")+after),this.state.cursorLine=lastLineIndex,this.setCursorCol((lines[lines.length-1]||"").length)}this.onChange&&this.onChange(this.getText())}deleteYankedText(){let yankedText=this.killRing.peek();if(!yankedText)return;let yankLines=yankedText.split(`
|
|
87
|
-
`);if(yankLines.length===1){let currentLine=this.state.lines[this.state.cursorLine]||"",deleteLen=yankedText.length,before=currentLine.slice(0,this.state.cursorCol-deleteLen),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+after,this.setCursorCol(this.state.cursorCol-deleteLen)}else{let startLine=this.state.cursorLine-(yankLines.length-1),startCol=(this.state.lines[startLine]||"").length-(yankLines[0]||"").length,afterCursor=(this.state.lines[this.state.cursorLine]||"").slice(this.state.cursorCol),beforeYank=(this.state.lines[startLine]||"").slice(0,startCol);this.state.lines.splice(startLine,yankLines.length,beforeYank+afterCursor),this.state.cursorLine=startLine,this.setCursorCol(startCol)}this.onChange&&this.onChange(this.getText())}pushUndoSnapshot(){this.undoStack.push({state:this.state,pastes:this.pastes,pasteCounter:this.pasteCounter})}undo(){this.exitHistoryBrowsing();let snapshot=this.undoStack.pop();snapshot&&(Object.assign(this.state,snapshot.state),this.pastes=snapshot.pastes,this.pasteCounter=snapshot.pasteCounter,this.lastAction=null,this.preferredVisualCol=null,this.onChange&&this.onChange(this.getText()))}jumpToChar(char,direction){this.lastAction=null;let isForward=direction==="forward",lines=this.state.lines,end=isForward?lines.length:-1,step=isForward?1:-1;for(let lineIdx=this.state.cursorLine;lineIdx!==end;lineIdx+=step){let line=lines[lineIdx]||"",searchFrom=lineIdx===this.state.cursorLine?isForward?this.state.cursorCol+1:this.state.cursorCol-1:void 0,idx=isForward?line.indexOf(char,searchFrom):line.lastIndexOf(char,searchFrom);if(idx!==-1){this.state.cursorLine=lineIdx,this.setCursorCol(idx);return}}}moveWordForwards(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=currentLine.length){this.state.cursorLine<this.state.lines.length-1&&(this.state.cursorLine++,this.setCursorCol(0));return}this.setCursorCol(findWordForward(currentLine,this.state.cursorCol,{segment:text=>this.segment(text,"word"),isAtomicSegment:isPasteMarker}))}isSlashMenuAllowed(){return this.state.cursorLine===0}isAtStartOfMessage(){if(!this.isSlashMenuAllowed())return!1;let beforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return beforeCursor.trim()===""||beforeCursor.trim()==="/"}isInSlashCommandContext(textBeforeCursor){return this.isSlashMenuAllowed()&&textBeforeCursor.trimStart().startsWith("/")}getBestAutocompleteMatchIndex(items,prefix){if(!prefix)return-1;let firstPrefixIndex=-1;for(let i=0;i<items.length;i++){let value=items[i].value;if(value===prefix)return i;firstPrefixIndex===-1&&value.startsWith(prefix)&&(firstPrefixIndex=i)}return firstPrefixIndex}createAutocompleteList(prefix,items){let layout=prefix.startsWith("/")?SLASH_COMMAND_SELECT_LIST_LAYOUT:void 0,list=new SelectList(items,this.autocompleteMaxVisible,this.theme.selectList,layout);return list.onSelect=selected=>{if(!this.autocompleteProvider)return;this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.cancelAutocomplete(),this.onChange?.(this.getText())},list}tryTriggerAutocomplete(explicitTab=!1){this.requestAutocomplete({force:!1,explicitTab})}handleTabCompletion(){if(!this.autocompleteProvider)return;let beforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(beforeCursor)&&!beforeCursor.trimStart().includes(" ")?this.handleSlashCommandCompletion():this.forceFileAutocomplete(!0)}handleSlashCommandCompletion(){this.requestAutocomplete({force:!1,explicitTab:!0})}forceFileAutocomplete(explicitTab=!1){this.requestAutocomplete({force:!0,explicitTab})}requestAutocomplete(options){if(!this.autocompleteProvider||options.force&&!(!this.autocompleteProvider.shouldTriggerFileCompletion||this.autocompleteProvider.shouldTriggerFileCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol)))return;this.cancelAutocompleteRequest();let startToken=++this.autocompleteStartToken,debounceMs=this.getAutocompleteDebounceMs(options);if(debounceMs>0){this.autocompleteDebounceTimer=setTimeout(()=>{this.autocompleteDebounceTimer=void 0,this.startAutocompleteRequest(startToken,options)},debounceMs);return}this.startAutocompleteRequest(startToken,options)}async startAutocompleteRequest(startToken,options){let previousTask=this.autocompleteRequestTask;this.autocompleteRequestTask=(async()=>{if(await previousTask,startToken!==this.autocompleteStartToken||!this.autocompleteProvider)return;let controller=new AbortController;this.autocompleteAbort=controller;let requestId=++this.autocompleteRequestId,snapshotText=this.getText(),snapshotLine=this.state.cursorLine,snapshotCol=this.state.cursorCol;await this.runAutocompleteRequest(requestId,controller,snapshotText,snapshotLine,snapshotCol,options)})(),await this.autocompleteRequestTask}setAutocompleteTriggerCharacters(triggerCharacters){let next=[...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS];for(let character of triggerCharacters)character.length!==1||character==="/"||isWhitespaceChar(character)||next.includes(character)||next.push(character);this.autocompleteTriggerCharacters=next,this.autocompleteTriggerPattern=buildTriggerPattern(next),this.autocompleteDebouncePattern=buildDebouncePattern(next)}getAutocompleteDebounceMs(options){if(options.explicitTab||options.force)return 0;let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return this.autocompleteDebouncePattern.test(textBeforeCursor)?ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS:0}async runAutocompleteRequest(requestId,controller,snapshotText,snapshotLine,snapshotCol,options){if(!this.autocompleteProvider)return;let suggestions=await this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol,{signal:controller.signal,force:options.force});if(this.isAutocompleteRequestCurrent(requestId,controller,snapshotText,snapshotLine,snapshotCol)){if(this.autocompleteAbort=void 0,!suggestions||!Array.isArray(suggestions.items)||suggestions.items.length===0){this.cancelAutocomplete(),this.tui.requestRender();return}if(options.force&&options.explicitTab&&suggestions.items.length===1){let item=suggestions.items[0];this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,item,suggestions.prefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.onChange&&this.onChange(this.getText()),this.tui.requestRender();return}this.applyAutocompleteSuggestions(suggestions,options.force?"force":"regular"),this.tui.requestRender()}}isAutocompleteRequestCurrent(requestId,controller,snapshotText,snapshotLine,snapshotCol){return!controller.signal.aborted&&requestId===this.autocompleteRequestId&&this.getText()===snapshotText&&this.state.cursorLine===snapshotLine&&this.state.cursorCol===snapshotCol}applyAutocompleteSuggestions(suggestions,state){this.autocompletePrefix=suggestions.prefix,this.autocompleteList=this.createAutocompleteList(suggestions.prefix,suggestions.items);let bestMatchIndex=this.getBestAutocompleteMatchIndex(suggestions.items,suggestions.prefix);bestMatchIndex>=0&&this.autocompleteList.setSelectedIndex(bestMatchIndex),this.autocompleteState=state}cancelAutocompleteRequest(){this.autocompleteStartToken+=1,this.autocompleteDebounceTimer&&(clearTimeout(this.autocompleteDebounceTimer),this.autocompleteDebounceTimer=void 0),this.autocompleteAbort?.abort(),this.autocompleteAbort=void 0}clearAutocompleteUi(){this.autocompleteState=null,this.autocompleteList=void 0,this.autocompletePrefix=""}cancelAutocomplete(){this.cancelAutocompleteRequest(),this.clearAutocompleteUi()}isShowingAutocomplete(){return this.autocompleteState!==null}updateAutocomplete(){!this.autocompleteState||!this.autocompleteProvider||this.requestAutocomplete({force:this.autocompleteState==="force",explicitTab:!1})}};var Gutter=class{child;firstPrefix;restPrefix;gutterWidth;constructor(child,firstPrefix,restPrefix){this.child=child,this.firstPrefix=firstPrefix,this.restPrefix=restPrefix,this.gutterWidth=visibleWidth(firstPrefix)}getChild(){return this.child}setPrefixes(firstPrefix,restPrefix){this.firstPrefix=firstPrefix,this.restPrefix=restPrefix,this.gutterWidth=visibleWidth(firstPrefix)}invalidate(){this.child.invalidate?.()}handleMouse(event){if(!(event.x<this.gutterWidth))return dispatchMouseEvent(this.child,{...event,x:event.x-this.gutterWidth,width:Math.max(1,event.width-this.gutterWidth)})}render(width){let contentWidth=Math.max(1,width-this.gutterWidth),childLines=this.child.render(contentWidth);if(childLines.length===0)return[];let lines=[];for(let i=0;i<childLines.length;i++){let line=childLines[i];if(isImageLine(line)){lines.push(line);continue}lines.push((i===0?this.firstPrefix:this.restPrefix)+line)}return lines}};var LAYOUT_NODE=Symbol.for("@knightcode/tui/layout-node");function getLayoutNode(component){let candidate=component;return typeof candidate[LAYOUT_NODE]=="function"?candidate[LAYOUT_NODE]():void 0}function isStackEntry(child){return!("render"in child)}function normalizeSize(value,fallback){return value===void 0||!Number.isFinite(value)?fallback:Math.max(0,Math.floor(value))}var Stack=class extends Container{entries=[];gap;align;constructor(children=[],options={}){super(),this.gap=normalizeSize(options.gap,0),this.align=options.align??"stretch";for(let child of children)isStackEntry(child)?this.addChild(child.component,child):this.addChild(child)}addChild(component,options={}){super.addChild(component),this.entries.push({component,...options.basis===void 0?{}:{basis:options.basis},...options.grow===void 0?{}:{grow:normalizeSize(options.grow,0)},...options.shrink===void 0?{}:{shrink:normalizeSize(options.shrink,1)},...options.minSize===void 0?{}:{minSize:normalizeSize(options.minSize,0)},...options.maxSize===void 0?{}:{maxSize:normalizeSize(options.maxSize,Number.MAX_SAFE_INTEGER)},...options.visible===void 0?{}:{visible:options.visible}})}removeChild(component){super.removeChild(component);let index=this.entries.findIndex(entry=>entry.component===component);index!==-1&&this.entries.splice(index,1)}clear(){super.clear(),this.entries.length=0}[LAYOUT_NODE](){return{type:this.layoutType,entries:this.entries,gap:this.gap,align:this.align}}};function visibleStackEntries(entries,viewport){return entries.filter(entry=>entry.visible?.(viewport)??!0)}function clampSize(size,entry){let min=Math.max(0,Math.floor(entry.minSize??0)),max=Math.max(min,Math.floor(entry.maxSize??Number.MAX_SAFE_INTEGER));return Math.max(min,Math.min(max,Math.max(0,Math.floor(size))))}function distribute(sizes,entries,amount,mode){let remaining=amount;for(;remaining>0;){let candidates=entries.map((entry,index)=>({entry,index})).filter(({entry,index})=>mode==="grow"?(entry.grow??0)>0&&sizes[index]<(entry.maxSize??Number.MAX_SAFE_INTEGER):(entry.shrink??1)>0&&sizes[index]>(entry.minSize??0));if(candidates.length===0)return;let totalWeight=candidates.reduce((sum,{entry,index})=>sum+(mode==="grow"?entry.grow??0:(entry.shrink??1)*Math.max(1,sizes[index])),0),distributed=0;for(let{entry,index}of candidates){if(remaining<=0)break;let weight=mode==="grow"?entry.grow??0:(entry.shrink??1)*Math.max(1,sizes[index]),proposed=Math.max(1,Math.floor(remaining*weight/totalWeight)),capacity=mode==="grow"?(entry.maxSize??Number.MAX_SAFE_INTEGER)-sizes[index]:sizes[index]-(entry.minSize??0),delta=Math.min(remaining,proposed,capacity);delta<=0||(sizes[index]=sizes[index]+(mode==="grow"?delta:-delta),remaining-=delta,distributed+=delta)}if(distributed===0)return}}function allocateStackSizes(entries,intrinsicSizes,availableSize,gap){let sizes=entries.map((entry,index)=>clampSize(entry.basis===void 0||entry.basis==="auto"?intrinsicSizes[index]??0:entry.basis,entry));if(availableSize===void 0)return sizes;let contentSize=Math.max(0,Math.floor(availableSize)-Math.max(0,entries.length-1)*gap),total=sizes.reduce((sum,size)=>sum+size,0);return total<contentSize?distribute(sizes,entries,contentSize-total,"grow"):total>contentSize&&distribute(sizes,entries,total-contentSize,"shrink"),sizes}var HStack=class extends Stack{layoutType="hstack";constructor(children=[],options={}){super(children,options)}render(width){let safeWidth=Math.max(1,width),viewport={width:safeWidth,height:Number.MAX_SAFE_INTEGER},entries=visibleStackEntries(this.entries,viewport);if(entries.length===0)return[];let intrinsicWidths=entries.map(entry=>entry.component.render(safeWidth).reduce((max,line)=>Math.max(max,visibleWidth(line)),0)),widths=allocateStackSizes(entries,intrinsicWidths,safeWidth,this.gap),rendered=entries.map((entry,index)=>widths[index]===0?[]:entry.component.render(widths[index])),height=rendered.reduce((max,lines)=>Math.max(max,lines.length),0),result=Array.from({length:height},()=>""),x2=0;for(let index=0;index<rendered.length;index++){let lines=rendered[index],childWidth=widths[index],offset=0;this.align==="center"?offset=Math.floor((height-lines.length)/2):this.align==="end"&&(offset=height-lines.length);for(let row=0;row<lines.length;row++){let target=row+offset;target<0||target>=result.length||(result[target]=compositeTuiLine(result[target],lines[row],x2,childWidth,safeWidth))}x2+=childWidth+this.gap}return result}};var imageTranscoder,pngCache=new Map;function setImageTranscoder(transcoder){imageTranscoder=transcoder,pngCache.clear()}function toPng(base64Data,mimeType){if(!imageTranscoder)return null;let cached=pngCache.get(base64Data),png=cached===void 0?imageTranscoder(base64Data,mimeType):cached;return pngCache.delete(base64Data),pngCache.set(base64Data,png),pngCache.size>32&&pngCache.delete(pngCache.keys().next().value),png}var Image=class{base64Data;mimeType;dimensions;theme;options;imageId;pngData;cachedLines;cachedWidth;constructor(base64Data,mimeType,theme2,options={},dimensions){this.base64Data=base64Data,this.mimeType=mimeType,this.theme=theme2,this.options=options,this.dimensions=dimensions||getImageDimensions(base64Data,mimeType)||{widthPx:800,heightPx:600},this.imageId=options.imageId}getImageId(){return this.imageId}invalidate(){this.cachedLines=void 0,this.cachedWidth=void 0}render(width){if(this.cachedLines&&this.cachedWidth===width)return this.cachedLines;let maxWidth=Math.max(1,Math.min(width-2,this.options.maxWidthCells??60)),cellDimensions2=getCellDimensions(),defaultMaxHeight=Math.max(1,Math.ceil(maxWidth*cellDimensions2.widthPx/cellDimensions2.heightPx)),maxHeight=this.options.maxHeightCells??defaultMaxHeight,caps=getCapabilities(),data=this.base64Data,dimensions=this.dimensions;caps.images==="kitty"&&this.mimeType!=="image/png"&&(this.pngData??=toPng(this.base64Data,this.mimeType)??void 0,data=this.pngData??null,data&&(dimensions=getPngDimensions(data)??dimensions));let lines;if(caps.images&&data){caps.images==="kitty"&&this.imageId===void 0&&(this.imageId=allocateImageId());let result=renderImage(data,dimensions,{maxWidthCells:maxWidth,maxHeightCells:maxHeight,imageId:this.imageId,moveCursor:!1});if(result)if(result.imageId&&(this.imageId=result.imageId),caps.images==="kitty"){lines=[result.sequence];for(let i=0;i<result.rows-1;i++)lines.push("")}else{lines=[];for(let i=0;i<result.rows-1;i++)lines.push("");let rowOffset=result.rows-1,moveUp=rowOffset>0?`\x1B[${rowOffset}A`:"";lines.push(moveUp+result.sequence)}else{let fallback=imageFallback(this.mimeType,this.dimensions,this.options.filename);lines=[truncateToWidth(this.theme.fallbackColor(fallback),width)]}}else{let fallback=imageFallback(this.mimeType,this.dimensions,this.options.filename);lines=[truncateToWidth(this.theme.fallbackColor(fallback),width)]}return this.cachedLines=lines,this.cachedWidth=width,lines}};var segmenter=getGraphemeSegmenter(),Input=class{value="";cursor=0;prompt;placeholder;placeholderStyle;renderedStartColumn=0;onSubmit;onEscape;focused=!1;pasteBuffer="";isInPaste=!1;killRing=new KillRing;lastAction=null;undoStack=new UndoStack;constructor(options={}){this.prompt=options.prompt??"> ",this.placeholder=options.placeholder??"",this.placeholderStyle=options.placeholderStyle??(text=>text)}getValue(){return this.value}setValue(value){this.value=value,this.cursor=Math.min(this.cursor,value.length)}handleInput(data){if(data.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",data=data.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=data;let endIndex=this.pasteBuffer.indexOf("\x1B[201~");if(endIndex!==-1){let pasteContent=this.pasteBuffer.substring(0,endIndex);this.handlePaste(pasteContent),this.isInPaste=!1;let remaining=this.pasteBuffer.substring(endIndex+6);this.pasteBuffer="",remaining&&this.handleInput(remaining)}return}let kb=getKeybindings();if(kb.matches(data,"tui.select.cancel")){this.onEscape&&this.onEscape();return}if(kb.matches(data,"tui.editor.undo")){this.undo();return}if(kb.matches(data,"tui.input.submit")||data===`
|
|
87
|
+
`);if(yankLines.length===1){let currentLine=this.state.lines[this.state.cursorLine]||"",deleteLen=yankedText.length,before=currentLine.slice(0,this.state.cursorCol-deleteLen),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+after,this.setCursorCol(this.state.cursorCol-deleteLen)}else{let startLine=this.state.cursorLine-(yankLines.length-1),startCol=(this.state.lines[startLine]||"").length-(yankLines[0]||"").length,afterCursor=(this.state.lines[this.state.cursorLine]||"").slice(this.state.cursorCol),beforeYank=(this.state.lines[startLine]||"").slice(0,startCol);this.state.lines.splice(startLine,yankLines.length,beforeYank+afterCursor),this.state.cursorLine=startLine,this.setCursorCol(startCol)}this.onChange&&this.onChange(this.getText())}pushUndoSnapshot(){this.undoStack.push({state:this.state,pastes:this.pastes,pasteCounter:this.pasteCounter})}undo(){this.exitHistoryBrowsing();let snapshot=this.undoStack.pop();snapshot&&(Object.assign(this.state,snapshot.state),this.pastes=snapshot.pastes,this.pasteCounter=snapshot.pasteCounter,this.lastAction=null,this.preferredVisualCol=null,this.onChange&&this.onChange(this.getText()))}jumpToChar(char,direction){this.lastAction=null;let isForward=direction==="forward",lines=this.state.lines,end=isForward?lines.length:-1,step=isForward?1:-1;for(let lineIdx=this.state.cursorLine;lineIdx!==end;lineIdx+=step){let line=lines[lineIdx]||"",searchFrom=lineIdx===this.state.cursorLine?isForward?this.state.cursorCol+1:this.state.cursorCol-1:void 0,idx=isForward?line.indexOf(char,searchFrom):line.lastIndexOf(char,searchFrom);if(idx!==-1){this.state.cursorLine=lineIdx,this.setCursorCol(idx);return}}}moveWordForwards(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=currentLine.length){this.state.cursorLine<this.state.lines.length-1&&(this.state.cursorLine++,this.setCursorCol(0));return}this.setCursorCol(findWordForward(currentLine,this.state.cursorCol,{segment:text=>this.segment(text,"word"),isAtomicSegment:isPasteMarker}))}isSlashMenuAllowed(){return this.state.cursorLine===0}isAtStartOfMessage(){if(!this.isSlashMenuAllowed())return!1;let beforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return beforeCursor.trim()===""||beforeCursor.trim()==="/"}isInSlashCommandContext(textBeforeCursor){return this.isSlashMenuAllowed()&&textBeforeCursor.trimStart().startsWith("/")}getBestAutocompleteMatchIndex(items,prefix){if(!prefix)return-1;let firstPrefixIndex=-1;for(let i=0;i<items.length;i++){let value=items[i].value;if(value===prefix)return i;firstPrefixIndex===-1&&value.startsWith(prefix)&&(firstPrefixIndex=i)}return firstPrefixIndex}createAutocompleteList(prefix,items){let layout=prefix.startsWith("/")?SLASH_COMMAND_SELECT_LIST_LAYOUT:void 0,list=new SelectList(items,this.autocompleteMaxVisible,this.theme.selectList,layout);return list.onSelect=selected=>{if(!this.autocompleteProvider)return;this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.cancelAutocomplete(),this.onChange?.(this.getText())},list}tryTriggerAutocomplete(explicitTab=!1){this.requestAutocomplete({force:!1,explicitTab})}handleTabCompletion(){if(!this.autocompleteProvider)return;let beforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(beforeCursor)&&!beforeCursor.trimStart().includes(" ")?this.handleSlashCommandCompletion():this.forceFileAutocomplete(!0)}handleSlashCommandCompletion(){this.requestAutocomplete({force:!1,explicitTab:!0})}forceFileAutocomplete(explicitTab=!1){this.requestAutocomplete({force:!0,explicitTab})}requestAutocomplete(options){if(!this.autocompleteProvider||options.force&&!(!this.autocompleteProvider.shouldTriggerFileCompletion||this.autocompleteProvider.shouldTriggerFileCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol)))return;this.cancelAutocompleteRequest();let startToken=++this.autocompleteStartToken,debounceMs=this.getAutocompleteDebounceMs(options);if(debounceMs>0){this.autocompleteDebounceTimer=setTimeout(()=>{this.autocompleteDebounceTimer=void 0,this.startAutocompleteRequest(startToken,options)},debounceMs);return}this.startAutocompleteRequest(startToken,options)}async startAutocompleteRequest(startToken,options){let previousTask=this.autocompleteRequestTask;this.autocompleteRequestTask=(async()=>{if(await previousTask,startToken!==this.autocompleteStartToken||!this.autocompleteProvider)return;let controller=new AbortController;this.autocompleteAbort=controller;let requestId=++this.autocompleteRequestId,snapshotText=this.getText(),snapshotLine=this.state.cursorLine,snapshotCol=this.state.cursorCol;await this.runAutocompleteRequest(requestId,controller,snapshotText,snapshotLine,snapshotCol,options)})(),await this.autocompleteRequestTask}setAutocompleteTriggerCharacters(triggerCharacters){let next=[...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS];for(let character of triggerCharacters)character.length!==1||character==="/"||isWhitespaceChar(character)||next.includes(character)||next.push(character);this.autocompleteTriggerCharacters=next,this.autocompleteTriggerPattern=buildTriggerPattern(next),this.autocompleteDebouncePattern=buildDebouncePattern(next)}getAutocompleteDebounceMs(options){if(options.explicitTab||options.force)return 0;let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return this.autocompleteDebouncePattern.test(textBeforeCursor)?ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS:0}async runAutocompleteRequest(requestId,controller,snapshotText,snapshotLine,snapshotCol,options){if(!this.autocompleteProvider)return;let suggestions=await this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol,{signal:controller.signal,force:options.force});if(this.isAutocompleteRequestCurrent(requestId,controller,snapshotText,snapshotLine,snapshotCol)){if(this.autocompleteAbort=void 0,!suggestions||!Array.isArray(suggestions.items)||suggestions.items.length===0){this.cancelAutocomplete(),this.tui.requestRender();return}if(options.force&&options.explicitTab&&suggestions.items.length===1){let item=suggestions.items[0];this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,item,suggestions.prefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.onChange&&this.onChange(this.getText()),this.tui.requestRender();return}this.applyAutocompleteSuggestions(suggestions,options.force?"force":"regular"),this.tui.requestRender()}}isAutocompleteRequestCurrent(requestId,controller,snapshotText,snapshotLine,snapshotCol){return!controller.signal.aborted&&requestId===this.autocompleteRequestId&&this.getText()===snapshotText&&this.state.cursorLine===snapshotLine&&this.state.cursorCol===snapshotCol}applyAutocompleteSuggestions(suggestions,state){this.autocompletePrefix=suggestions.prefix,this.autocompleteList=this.createAutocompleteList(suggestions.prefix,suggestions.items);let bestMatchIndex=this.getBestAutocompleteMatchIndex(suggestions.items,suggestions.prefix);bestMatchIndex>=0&&this.autocompleteList.setSelectedIndex(bestMatchIndex),this.autocompleteState=state}cancelAutocompleteRequest(){this.autocompleteStartToken+=1,this.autocompleteDebounceTimer&&(clearTimeout(this.autocompleteDebounceTimer),this.autocompleteDebounceTimer=void 0),this.autocompleteAbort?.abort(),this.autocompleteAbort=void 0}clearAutocompleteUi(){this.autocompleteState=null,this.autocompleteList=void 0,this.autocompletePrefix=""}cancelAutocomplete(){this.cancelAutocompleteRequest(),this.clearAutocompleteUi()}isShowingAutocomplete(){return this.autocompleteState!==null}updateAutocomplete(){!this.autocompleteState||!this.autocompleteProvider||this.requestAutocomplete({force:this.autocompleteState==="force",explicitTab:!1})}};var Gutter=class{child;firstPrefix;restPrefix;gutterWidth;constructor(child,firstPrefix,restPrefix){this.child=child,this.firstPrefix=firstPrefix,this.restPrefix=restPrefix,this.gutterWidth=visibleWidth(firstPrefix)}getChild(){return this.child}setPrefixes(firstPrefix,restPrefix){this.firstPrefix=firstPrefix,this.restPrefix=restPrefix,this.gutterWidth=visibleWidth(firstPrefix)}invalidate(){this.child.invalidate?.()}handleMouse(event){if(!(event.x<this.gutterWidth))return dispatchMouseEvent(this.child,{...event,x:event.x-this.gutterWidth,width:Math.max(1,event.width-this.gutterWidth)})}render(width){let contentWidth=Math.max(1,width-this.gutterWidth),squeezed=this.gutterWidth+contentWidth>width,childLines=this.child.render(contentWidth);if(childLines.length===0)return[];let lines=[];for(let i=0;i<childLines.length;i++){let line=childLines[i];if(isImageLine(line)){lines.push(line);continue}let prefixed=(i===0?this.firstPrefix:this.restPrefix)+line;lines.push(squeezed?truncateToWidth(prefixed,width,""):prefixed)}return lines}};var LAYOUT_NODE=Symbol.for("@knightcode/tui/layout-node");function getLayoutNode(component){let candidate=component;return typeof candidate[LAYOUT_NODE]=="function"?candidate[LAYOUT_NODE]():void 0}function isStackEntry(child){return!("render"in child)}function normalizeSize(value,fallback){return value===void 0||!Number.isFinite(value)?fallback:Math.max(0,Math.floor(value))}var Stack=class extends Container{entries=[];gap;align;constructor(children=[],options={}){super(),this.gap=normalizeSize(options.gap,0),this.align=options.align??"stretch";for(let child of children)isStackEntry(child)?this.addChild(child.component,child):this.addChild(child)}addChild(component,options={}){super.addChild(component),this.entries.push({component,...options.basis===void 0?{}:{basis:options.basis},...options.grow===void 0?{}:{grow:normalizeSize(options.grow,0)},...options.shrink===void 0?{}:{shrink:normalizeSize(options.shrink,1)},...options.minSize===void 0?{}:{minSize:normalizeSize(options.minSize,0)},...options.maxSize===void 0?{}:{maxSize:normalizeSize(options.maxSize,Number.MAX_SAFE_INTEGER)},...options.visible===void 0?{}:{visible:options.visible}})}removeChild(component){super.removeChild(component);let index=this.entries.findIndex(entry=>entry.component===component);index!==-1&&this.entries.splice(index,1)}clear(){super.clear(),this.entries.length=0}[LAYOUT_NODE](){return{type:this.layoutType,entries:this.entries,gap:this.gap,align:this.align}}};function visibleStackEntries(entries,viewport){return entries.filter(entry=>entry.visible?.(viewport)??!0)}function clampSize(size,entry){let min=Math.max(0,Math.floor(entry.minSize??0)),max=Math.max(min,Math.floor(entry.maxSize??Number.MAX_SAFE_INTEGER));return Math.max(min,Math.min(max,Math.max(0,Math.floor(size))))}function distribute(sizes,entries,amount,mode){let remaining=amount;for(;remaining>0;){let candidates=entries.map((entry,index)=>({entry,index})).filter(({entry,index})=>mode==="grow"?(entry.grow??0)>0&&sizes[index]<(entry.maxSize??Number.MAX_SAFE_INTEGER):(entry.shrink??1)>0&&sizes[index]>(entry.minSize??0));if(candidates.length===0)return;let totalWeight=candidates.reduce((sum,{entry,index})=>sum+(mode==="grow"?entry.grow??0:(entry.shrink??1)*Math.max(1,sizes[index])),0),distributed=0;for(let{entry,index}of candidates){if(remaining<=0)break;let weight=mode==="grow"?entry.grow??0:(entry.shrink??1)*Math.max(1,sizes[index]),proposed=Math.max(1,Math.floor(remaining*weight/totalWeight)),capacity=mode==="grow"?(entry.maxSize??Number.MAX_SAFE_INTEGER)-sizes[index]:sizes[index]-(entry.minSize??0),delta=Math.min(remaining,proposed,capacity);delta<=0||(sizes[index]=sizes[index]+(mode==="grow"?delta:-delta),remaining-=delta,distributed+=delta)}if(distributed===0)return}}function allocateStackSizes(entries,intrinsicSizes,availableSize,gap){let sizes=entries.map((entry,index)=>clampSize(entry.basis===void 0||entry.basis==="auto"?intrinsicSizes[index]??0:entry.basis,entry));if(availableSize===void 0)return sizes;let contentSize=Math.max(0,Math.floor(availableSize)-Math.max(0,entries.length-1)*gap),total=sizes.reduce((sum,size)=>sum+size,0);return total<contentSize?distribute(sizes,entries,contentSize-total,"grow"):total>contentSize&&distribute(sizes,entries,total-contentSize,"shrink"),sizes}var HStack=class extends Stack{layoutType="hstack";constructor(children=[],options={}){super(children,options)}render(width){let safeWidth=Math.max(1,width),viewport={width:safeWidth,height:Number.MAX_SAFE_INTEGER},entries=visibleStackEntries(this.entries,viewport);if(entries.length===0)return[];let intrinsicWidths=entries.map(entry=>entry.component.render(safeWidth).reduce((max,line)=>Math.max(max,visibleWidth(line)),0)),widths=allocateStackSizes(entries,intrinsicWidths,safeWidth,this.gap),rendered=entries.map((entry,index)=>widths[index]===0?[]:entry.component.render(widths[index])),height=rendered.reduce((max,lines)=>Math.max(max,lines.length),0),result=Array.from({length:height},()=>""),x2=0;for(let index=0;index<rendered.length;index++){let lines=rendered[index],childWidth=widths[index],offset=0;this.align==="center"?offset=Math.floor((height-lines.length)/2):this.align==="end"&&(offset=height-lines.length);for(let row=0;row<lines.length;row++){let target=row+offset;target<0||target>=result.length||(result[target]=compositeTuiLine(result[target],lines[row],x2,childWidth,safeWidth))}x2+=childWidth+this.gap}return result}};var imageTranscoder,pngCache=new Map;function setImageTranscoder(transcoder){imageTranscoder=transcoder,pngCache.clear()}function toPng(base64Data,mimeType){if(!imageTranscoder)return null;let cached=pngCache.get(base64Data),png=cached===void 0?imageTranscoder(base64Data,mimeType):cached;return pngCache.delete(base64Data),pngCache.set(base64Data,png),pngCache.size>32&&pngCache.delete(pngCache.keys().next().value),png}var Image=class{base64Data;mimeType;dimensions;theme;options;imageId;pngData;cachedLines;cachedWidth;constructor(base64Data,mimeType,theme2,options={},dimensions){this.base64Data=base64Data,this.mimeType=mimeType,this.theme=theme2,this.options=options,this.dimensions=dimensions||getImageDimensions(base64Data,mimeType)||{widthPx:800,heightPx:600},this.imageId=options.imageId}getImageId(){return this.imageId}invalidate(){this.cachedLines=void 0,this.cachedWidth=void 0}render(width){if(this.cachedLines&&this.cachedWidth===width)return this.cachedLines;let maxWidth=Math.max(1,Math.min(width-2,this.options.maxWidthCells??60)),cellDimensions2=getCellDimensions(),defaultMaxHeight=Math.max(1,Math.ceil(maxWidth*cellDimensions2.widthPx/cellDimensions2.heightPx)),maxHeight=this.options.maxHeightCells??defaultMaxHeight,caps=getCapabilities(),data=this.base64Data,dimensions=this.dimensions;caps.images==="kitty"&&this.mimeType!=="image/png"&&(this.pngData??=toPng(this.base64Data,this.mimeType)??void 0,data=this.pngData??null,data&&(dimensions=getPngDimensions(data)??dimensions));let lines;if(caps.images&&data){caps.images==="kitty"&&this.imageId===void 0&&(this.imageId=allocateImageId());let result=renderImage(data,dimensions,{maxWidthCells:maxWidth,maxHeightCells:maxHeight,imageId:this.imageId,moveCursor:!1});if(result)if(result.imageId&&(this.imageId=result.imageId),caps.images==="kitty"){lines=[result.sequence];for(let i=0;i<result.rows-1;i++)lines.push("")}else{lines=[];for(let i=0;i<result.rows-1;i++)lines.push("");let rowOffset=result.rows-1,moveUp=rowOffset>0?`\x1B[${rowOffset}A`:"";lines.push(moveUp+result.sequence)}else{let fallback=imageFallback(this.mimeType,this.dimensions,this.options.filename);lines=[truncateToWidth(this.theme.fallbackColor(fallback),width)]}}else{let fallback=imageFallback(this.mimeType,this.dimensions,this.options.filename);lines=[truncateToWidth(this.theme.fallbackColor(fallback),width)]}return this.cachedLines=lines,this.cachedWidth=width,lines}};var segmenter=getGraphemeSegmenter(),Input=class{value="";cursor=0;prompt;placeholder;placeholderStyle;renderedStartColumn=0;onSubmit;onEscape;focused=!1;pasteBuffer="";isInPaste=!1;killRing=new KillRing;lastAction=null;undoStack=new UndoStack;constructor(options={}){this.prompt=options.prompt??"> ",this.placeholder=options.placeholder??"",this.placeholderStyle=options.placeholderStyle??(text=>text)}getValue(){return this.value}setValue(value){this.value=value,this.cursor=Math.min(this.cursor,value.length)}handleInput(data){if(data.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",data=data.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=data;let endIndex=this.pasteBuffer.indexOf("\x1B[201~");if(endIndex!==-1){let pasteContent=this.pasteBuffer.substring(0,endIndex);this.handlePaste(pasteContent),this.isInPaste=!1;let remaining=this.pasteBuffer.substring(endIndex+6);this.pasteBuffer="",remaining&&this.handleInput(remaining)}return}let kb=getKeybindings();if(kb.matches(data,"tui.select.cancel")){this.onEscape&&this.onEscape();return}if(kb.matches(data,"tui.editor.undo")){this.undo();return}if(kb.matches(data,"tui.input.submit")||data===`
|
|
88
88
|
`){this.onSubmit&&this.onSubmit(this.value);return}if(kb.matches(data,"tui.editor.deleteCharBackward")){this.handleBackspace();return}if(kb.matches(data,"tui.editor.deleteCharForward")){this.handleForwardDelete();return}if(kb.matches(data,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(kb.matches(data,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(kb.matches(data,"tui.editor.deleteToLineStart")){this.deleteToLineStart();return}if(kb.matches(data,"tui.editor.deleteToLineEnd")){this.deleteToLineEnd();return}if(kb.matches(data,"tui.editor.yank")){this.yank();return}if(kb.matches(data,"tui.editor.yankPop")){this.yankPop();return}if(kb.matches(data,"tui.editor.cursorLeft")){if(this.lastAction=null,this.cursor>0){let beforeCursor=this.value.slice(0,this.cursor),graphemes=[...segmenter.segment(beforeCursor)],lastGrapheme=graphemes[graphemes.length-1];this.cursor-=lastGrapheme?lastGrapheme.segment.length:1}return}if(kb.matches(data,"tui.editor.cursorRight")){if(this.lastAction=null,this.cursor<this.value.length){let afterCursor=this.value.slice(this.cursor),firstGrapheme=[...segmenter.segment(afterCursor)][0];this.cursor+=firstGrapheme?firstGrapheme.segment.length:1}return}if(kb.matches(data,"tui.editor.cursorLineStart")){this.lastAction=null,this.cursor=0;return}if(kb.matches(data,"tui.editor.cursorLineEnd")){this.lastAction=null,this.cursor=this.value.length;return}if(kb.matches(data,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(kb.matches(data,"tui.editor.cursorWordRight")){this.moveWordForwards();return}let kittyPrintable=decodeKittyPrintable(data);if(kittyPrintable!==void 0){this.insertCharacter(kittyPrintable);return}[...data].some(ch=>{let code=ch.charCodeAt(0);return code<32||code===127||code>=128&&code<=159})||this.insertCharacter(data)}handleMouse(event){if(event.type!=="press"||event.button!=="left"||event.y!==0)return;let visibleColumn=Math.max(0,event.x-2),targetColumn=this.renderedStartColumn+visibleColumn,currentColumn=0;this.cursor=this.value.length;for(let grapheme of segmenter.segment(this.value)){let nextColumn=currentColumn+visibleWidth(grapheme.segment);if(targetColumn<nextColumn){this.cursor=grapheme.index;break}currentColumn=nextColumn}return this.lastAction=null,{handled:!0,focus:!0}}insertCharacter(char){(isWhitespaceChar(char)||this.lastAction!=="type-word")&&this.pushUndo(),this.lastAction="type-word",this.value=this.value.slice(0,this.cursor)+char+this.value.slice(this.cursor),this.cursor+=char.length}handleBackspace(){if(this.lastAction=null,this.cursor>0){this.pushUndo();let beforeCursor=this.value.slice(0,this.cursor),graphemes=[...segmenter.segment(beforeCursor)],lastGrapheme=graphemes[graphemes.length-1],graphemeLength=lastGrapheme?lastGrapheme.segment.length:1;this.value=this.value.slice(0,this.cursor-graphemeLength)+this.value.slice(this.cursor),this.cursor-=graphemeLength}}handleForwardDelete(){if(this.lastAction=null,this.cursor<this.value.length){this.pushUndo();let afterCursor=this.value.slice(this.cursor),firstGrapheme=[...segmenter.segment(afterCursor)][0],graphemeLength=firstGrapheme?firstGrapheme.segment.length:1;this.value=this.value.slice(0,this.cursor)+this.value.slice(this.cursor+graphemeLength)}}deleteToLineStart(){if(this.cursor===0)return;this.pushUndo();let deletedText=this.value.slice(0,this.cursor);this.killRing.push(deletedText,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(this.cursor),this.cursor=0}deleteToLineEnd(){if(this.cursor>=this.value.length)return;this.pushUndo();let deletedText=this.value.slice(this.cursor);this.killRing.push(deletedText,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)}deleteWordBackwards(){if(this.cursor===0)return;let wasKill=this.lastAction==="kill";this.pushUndo();let oldCursor=this.cursor;this.moveWordBackwards();let deleteFrom=this.cursor;this.cursor=oldCursor;let deletedText=this.value.slice(deleteFrom,this.cursor);this.killRing.push(deletedText,{prepend:!0,accumulate:wasKill}),this.lastAction="kill",this.value=this.value.slice(0,deleteFrom)+this.value.slice(this.cursor),this.cursor=deleteFrom}deleteWordForward(){if(this.cursor>=this.value.length)return;let wasKill=this.lastAction==="kill";this.pushUndo();let oldCursor=this.cursor;this.moveWordForwards();let deleteTo=this.cursor;this.cursor=oldCursor;let deletedText=this.value.slice(this.cursor,deleteTo);this.killRing.push(deletedText,{prepend:!1,accumulate:wasKill}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)+this.value.slice(deleteTo)}yank(){let text=this.killRing.peek();text&&(this.pushUndo(),this.value=this.value.slice(0,this.cursor)+text+this.value.slice(this.cursor),this.cursor+=text.length,this.lastAction="yank")}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndo();let prevText=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor-prevText.length)+this.value.slice(this.cursor),this.cursor-=prevText.length,this.killRing.rotate();let text=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor)+text+this.value.slice(this.cursor),this.cursor+=text.length,this.lastAction="yank"}pushUndo(){this.undoStack.push({value:this.value,cursor:this.cursor})}undo(){let snapshot=this.undoStack.pop();snapshot&&(this.value=snapshot.value,this.cursor=snapshot.cursor,this.lastAction=null)}moveWordBackwards(){this.cursor!==0&&(this.lastAction=null,this.cursor=findWordBackward(this.value,this.cursor))}moveWordForwards(){this.cursor>=this.value.length||(this.lastAction=null,this.cursor=findWordForward(this.value,this.cursor))}handlePaste(pastedText){this.lastAction=null,this.pushUndo();let cleanText=pastedText.replace(/\r\n/g,"").replace(/\r/g,"").replace(/\n/g,"").replace(/\t/g," ");this.value=this.value.slice(0,this.cursor)+cleanText+this.value.slice(this.cursor),this.cursor+=cleanText.length}invalidate(){}render(width){let availableWidth=width-visibleWidth(this.prompt);if(availableWidth<=0)return[truncateToWidth(this.prompt,width,"")];if(this.value.length===0&&this.placeholder){let placeholder=truncateToWidth(this.placeholder,availableWidth,""),atCursor2=[...segmenter.segment(placeholder)][0]?.segment??" ",afterCursor2=placeholder.slice(atCursor2.length),marker2=this.focused?CURSOR_MARKER:"",cursorChar2=renderFakeCursor(this.placeholderStyle(atCursor2)),textWithCursor2=marker2+cursorChar2+this.placeholderStyle(afterCursor2),padding2=" ".repeat(Math.max(0,availableWidth-visibleWidth(textWithCursor2)));return[this.prompt+textWithCursor2+padding2]}let visibleText="",cursorDisplay=this.cursor;this.renderedStartColumn=0;let totalWidth=visibleWidth(this.value);if(totalWidth<availableWidth)visibleText=this.value;else{let scrollWidth=this.cursor===this.value.length?availableWidth-1:availableWidth,cursorCol=visibleWidth(this.value.slice(0,this.cursor));if(scrollWidth>0){let halfWidth=Math.floor(scrollWidth/2),startCol=0;cursorCol<halfWidth?startCol=0:cursorCol>totalWidth-halfWidth?startCol=Math.max(0,totalWidth-scrollWidth):startCol=Math.max(0,cursorCol-halfWidth),this.renderedStartColumn=startCol,visibleText=sliceByColumn(this.value,startCol,scrollWidth,!0),cursorDisplay=sliceByColumn(this.value,startCol,Math.max(0,cursorCol-startCol),!0).length}else visibleText="",cursorDisplay=0}let cursorGrapheme=[...segmenter.segment(visibleText.slice(cursorDisplay))][0],beforeCursor=visibleText.slice(0,cursorDisplay),atCursor=cursorGrapheme?.segment??" ",afterCursor=visibleText.slice(cursorDisplay+atCursor.length),marker=this.focused?CURSOR_MARKER:"",cursorChar=renderFakeCursor(atCursor),textWithCursor=beforeCursor+marker+cursorChar+afterCursor,visualLength=visibleWidth(textWithCursor),padding=" ".repeat(Math.max(0,availableWidth-visualLength));return[this.prompt+textWithCursor+padding]}};var CJK="\\u1100-\\u11ff\\u20a9\\u2329-\\u232a\\u2630-\\u2637\\u268a-\\u268f\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u2ff0-\\u303e\\u3041-\\u3096\\u3099-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u3190-\\u31e5\\u31ef-\\u321e\\u3220-\\u3247\\u3250-\\ua48c\\ua490-\\ua4c6\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufaff\\ufe10-\\ufe19\\ufe30-\\ufe52\\ufe54-\\ufe66\\ufe68-\\ufe6b\\uff01-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc\\uffe0-\\uffe6\\uffe8-\\uffee\\u{16fe0}-\\u{16fe4}\\u{16ff0}-\\u{16ff6}\\u{17000}-\\u{18cda}\\u{18cff}-\\u{18d20}\\u{18d80}-\\u{18df2}\\u{18e00}-\\u{19191}\\u{191a0}-\\u{191d2}\\u{1aff0}-\\u{1aff3}\\u{1aff5}-\\u{1affb}\\u{1affd}-\\u{1affe}\\u{1b000}-\\u{1b128}\\u{1b132}\\u{1b150}-\\u{1b152}\\u{1b155}\\u{1b164}-\\u{1b168}\\u{1b170}-\\u{1b2fb}\\u{1d300}-\\u{1d356}\\u{1d360}-\\u{1d376}\\u{1f1ae}\\u{1f200}\\u{1f202}\\u{1f210}-\\u{1f219}\\u{1f21b}-\\u{1f22e}\\u{1f230}-\\u{1f231}\\u{1f237}\\u{1f23b}\\u{1f240}-\\u{1f248}\\u{1f260}-\\u{1f265}\\u{1f7da}\\u{20000}-\\u{3fffd}",cjkTest=new RegExp(`[${CJK}]`,"u"),punctuationCjk=new RegExp(`^((?![*_])[\\s\\p{P}\\p{S}${CJK}])`,"u");function buildRDelimAst(punct,punctSpace,notPunctSpace){return new RegExp(`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)${punct}(\\*+)(?=[\\s]|$)|${notPunctSpace}(\\*+)(?!\\*)(?=${punctSpace}|$)|(?!\\*)${punctSpace}(\\*+)(?=${notPunctSpace})|[\\s](\\*+)(?!\\*)(?=${punct})|(?!\\*)${punct}(\\*+)(?!\\*)(?=${punct})|${notPunctSpace}(\\*+)(?=${notPunctSpace})`,"gu")}function buildRDelimUnd(punct,punctSpace,notPunctSpace){return new RegExp(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)${punct}(_+)(?=[\\s]|$)|${notPunctSpace}(_+)(?!_)(?=${punctSpace}|$)|(?!_)${punctSpace}(_+)(?=${notPunctSpace})|[\\s](_+)(?!_)(?=${punct})|(?!_)${punct}(_+)(?!_)(?=${punct})`,"gu")}function buildRDelimDel(punct,punctSpace,notPunctSpace){return new RegExp(`^[^~]+(?=[^~])|(?!~)${punct}(~~?)(?=[\\s]|$)|${notPunctSpace}(~~?)(?!~)(?=${punctSpace}|$)|(?!~)${punctSpace}(~~?)(?=${notPunctSpace})|[\\s](~~?)(?!~)(?=${punct})|(?!~)${punct}(~~?)(?!~)(?=${punct})|${notPunctSpace}(~~?)(?=${notPunctSpace})`,"gu")}var cjkPunct=`[\\p{P}\\p{S}${CJK}]`,cjkPunctSpace=`[\\s\\p{P}\\p{S}${CJK}]`,cjkNotPunctSpace=`[^\\s\\p{P}\\p{S}${CJK}]`,cjkDelPunct=`(?![*_])[\\p{P}\\p{S}${CJK}]`,cjkDelPunctSpace=`(?![*_])[\\s\\p{P}\\p{S}${CJK}]`,cjkDelNotPunctSpace=`(?:[^\\s\\p{P}\\p{S}${CJK}]|[*_])`,cjkPunctGfm=`(?!~)[\\p{P}\\p{S}${CJK}]`,cjkPunctSpaceGfm=`(?!~)[\\s\\p{P}\\p{S}${CJK}]`,cjkNotPunctSpaceGfm=`(?:[^\\s\\p{P}\\p{S}${CJK}]|~)`,emStrongRDelimAstCjk=buildRDelimAst(cjkPunct,cjkPunctSpace,cjkNotPunctSpace),emStrongRDelimAstCjkGfm=buildRDelimAst(cjkPunctGfm,cjkPunctSpaceGfm,cjkNotPunctSpaceGfm),emStrongRDelimUndCjk=buildRDelimUnd(cjkPunct,cjkPunctSpace,cjkNotPunctSpace),delRDelimCjk=buildRDelimDel(cjkDelPunct,cjkDelPunctSpace,cjkDelNotPunctSpace);function isPrevCharCjk(prevChar,maskedSrc,src){let prevIsCjk=punctuationCjk.test(prevChar);if(!prevIsCjk&&prevChar){let prevIdx=maskedSrc.length-src.length;if(prevIdx>=1){let idx=prevIdx-1,code=maskedSrc.charCodeAt(idx);if(code>=65024&&code<=65038&&idx>=1&&(idx--,code=maskedSrc.charCodeAt(idx)),(code&64512)===56320&&idx>=1){let cp=maskedSrc.codePointAt(idx-1);cp!==void 0&&cp>65535&&(cp>=917760&&cp<=917999?prevIsCjk=!0:prevIsCjk=cjkTest.test(String.fromCodePoint(cp)))}else prevIsCjk=cjkTest.test(String.fromCharCode(code))}}return prevIsCjk}function isCjkAdjacentToDelimiter(rightMatch,clippedMaskedSrc){if(!(rightMatch[1]||rightMatch[2]||rightMatch[3]||rightMatch[4]))return!1;let charBefore=String.fromCodePoint(rightMatch[0].codePointAt(0)),afterPos=rightMatch.index+rightMatch[0].length,charAfter=afterPos<clippedMaskedSrc.length?String.fromCodePoint(clippedMaskedSrc.codePointAt(afterPos)):"";return cjkTest.test(charBefore)||cjkTest.test(charAfter)}function usesModernEmStrongLayout(match){return match.length>=5}function hasEmStrongLeadContent(match){return!!(match[1]||match[2]||match[3]||match[4])}function isEmStrongUnderscoreWordChar(match){return usesModernEmStrongLayout(match)?!!match[4]:!!match[3]}function getEmStrongOpeningPunctuation(match){return usesModernEmStrongLayout(match)?match[1]||match[3]||"":match[1]||match[2]||""}function markedCjkFriendly(){return{tokenizer:{emStrong(src,maskedSrc,prevChar=""){let{rules}=this,match=rules.inline.emStrongLDelim.exec(src);if(!match)return!1;let modernEmStrongLayout=usesModernEmStrongLayout(match);if(modernEmStrongLayout&&!hasEmStrongLeadContent(match))return;if(isEmStrongUnderscoreWordChar(match)&&prevChar.match(rules.other.unicodeAlphaNumeric))return!1;let nextChar=getEmStrongOpeningPunctuation(match),prevIsCjk=isPrevCharCjk(prevChar,maskedSrc,src);if(!nextChar||!prevChar||rules.inline.punctuation.exec(prevChar)||prevIsCjk||cjkTest.test(nextChar)){let lLength=[...match[0]].length-1,rDelim,rLength,delimTotal=lLength,midDelimTotal=0,prevCharIsSameDelimiter=modernEmStrongLayout&&prevChar===match[0][0],isGfm=rules.inline.emStrongRDelimAst.source.includes("(?!~)"),endReg;match[0][0]==="*"?endReg=isGfm?emStrongRDelimAstCjkGfm:emStrongRDelimAstCjk:endReg=emStrongRDelimUndCjk,endReg.lastIndex=0;let clippedMaskedSrc=maskedSrc.slice(-1*src.length+lLength),rMatch;for(;(rMatch=endReg.exec(clippedMaskedSrc))!=null;){if(rDelim=rMatch[1]||rMatch[2]||rMatch[3]||rMatch[4]||rMatch[5]||rMatch[6],!rDelim)continue;rLength=[...rDelim].length;let isCjkAdjacent=isCjkAdjacentToDelimiter(rMatch,clippedMaskedSrc),isLeftOnly=!!(rMatch[3]||rMatch[4]),isBoth=!!(rMatch[5]||rMatch[6]);if(isLeftOnly&&!isCjkAdjacent){delimTotal+=rLength;continue}if(isBoth||isCjkAdjacent){if(lLength%3&&!((lLength+rLength)%3)){midDelimTotal+=rLength;continue}if(prevCharIsSameDelimiter&&isBoth)break}if(delimTotal-=rLength,delimTotal>0)continue;rLength=Math.min(rLength,rLength+delimTotal+midDelimTotal);let lastCharLength=rMatch[0].codePointAt(0)>65535?2:1,raw=src.slice(0,lLength+rMatch.index+lastCharLength+rLength);if(Math.min(lLength,rLength)%2){let text2=raw.slice(1,-1);return{type:"em",raw,text:text2,tokens:this.lexer.inlineTokens(text2)}}let text=raw.slice(2,-2);return{type:"strong",raw,text,tokens:this.lexer.inlineTokens(text)}}}},del(src,maskedSrc,prevChar=""){let{rules}=this,match=rules.inline.delLDelim.exec(src);if(!match)return!1;let nextChar=match[1]||"",prevIsCjk=isPrevCharCjk(prevChar,maskedSrc,src);if(!nextChar||!prevChar||rules.inline.punctuation.exec(prevChar)||prevIsCjk||cjkTest.test(nextChar)){let lLength=[...match[0]].length-1,rDelim,rLength,delimTotal=lLength;delRDelimCjk.lastIndex=0;let clippedMaskedSrc=maskedSrc.slice(-1*src.length+lLength),rMatch;for(;(rMatch=delRDelimCjk.exec(clippedMaskedSrc))!=null;){if(rDelim=rMatch[1]||rMatch[2]||rMatch[3]||rMatch[4]||rMatch[5]||rMatch[6],!rDelim||(rLength=[...rDelim].length,rLength!==lLength))continue;let isCjkAdjacent=isCjkAdjacentToDelimiter(rMatch,clippedMaskedSrc);if((rMatch[3]||rMatch[4])&&!isCjkAdjacent){delimTotal+=rLength;continue}if(delimTotal-=rLength,delimTotal>0)continue;rLength=Math.min(rLength,rLength+delimTotal);let lastCharLength=rMatch[0].codePointAt(0)>65535?2:1,raw=src.slice(0,lLength+rMatch.index+lastCharLength+rLength),text=raw.slice(lLength,-lLength);return{type:"del",raw,text,tokens:this.lexer.inlineTokens(text)}}}}}}}var SYMBOLS={alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03F5",varepsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",vartheta:"\u03D1",iota:"\u03B9",kappa:"\u03BA",varkappa:"\u03F0",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",pi:"\u03C0",varpi:"\u03D6",rho:"\u03C1",varrho:"\u03F1",sigma:"\u03C3",varsigma:"\u03C2",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03D5",varphi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",Gamma:"\u0393",Delta:"\u0394",Theta:"\u0398",Lambda:"\u039B",Xi:"\u039E",Pi:"\u03A0",Sigma:"\u03A3",Upsilon:"\u03A5",Phi:"\u03A6",Psi:"\u03A8",Omega:"\u03A9",pm:"\xB1",mp:"\u2213",times:"\xD7",div:"\xF7",cdot:"\xB7",ast:"\u2217",star:"\u22C6",circ:"\u2218",bullet:"\u2022",oplus:"\u2295",ominus:"\u2296",otimes:"\u2297",oslash:"\u2298",odot:"\u2299",bigcirc:"\u25CB",dagger:"\u2020",ddagger:"\u2021",amalg:"\u2A3F",uplus:"\u228E",sqcap:"\u2293",sqcup:"\u2294",bowtie:"\u22C8",Join:"\u22C8",ltimes:"\u22C9",rtimes:"\u22CA",leftouterjoin:"\u27D5",rightouterjoin:"\u27D6",fullouterjoin:"\u27D7",triangleleft:"\u25C1",triangleright:"\u25B7",wr:"\u2240",cap:"\u2229",cup:"\u222A",bigcap:"\u22C2",bigcup:"\u22C3",bigwedge:"\u22C0",bigvee:"\u22C1",bigsqcup:"\u2A06",biguplus:"\u2A04",bigoplus:"\u2A01",bigotimes:"\u2A02",bigodot:"\u2A00",setminus:"\u2216",in:"\u2208",notin:"\u2209",ni:"\u220B",subset:"\u2282",supset:"\u2283",subseteq:"\u2286",supseteq:"\u2287",sqsubset:"\u228F",sqsupset:"\u2290",sqsubseteq:"\u2291",sqsupseteq:"\u2292",prec:"\u227A",preceq:"\u227C",succ:"\u227B",succeq:"\u227D",ll:"\u226A",gg:"\u226B",le:"\u2264",leq:"\u2264",leqslant:"\u2264",ge:"\u2265",geq:"\u2265",geqslant:"\u2265",ne:"\u2260",neq:"\u2260",equiv:"\u2261",approx:"\u2248",sim:"\u223C",simeq:"\u2243",cong:"\u2245",asymp:"\u224D",doteq:"\u2250",propto:"\u221D",parallel:"\u2225",perp:"\u22A5",mid:"\u2223",vdash:"\u22A2",dashv:"\u22A3",models:"\u22A8",Vdash:"\u22A9",Vvdash:"\u22AA",nvdash:"\u22AC",nvDash:"\u22AD",forall:"\u2200",exists:"\u2203",nexists:"\u2204",neg:"\xAC",land:"\u2227",wedge:"\u2227",lor:"\u2228",vee:"\u2228",to:"\u2192",rightarrow:"\u2192",longrightarrow:"\u2192",leftarrow:"\u2190",longleftarrow:"\u2190",gets:"\u2190",leftrightarrow:"\u2194",longleftrightarrow:"\u2194",hookleftarrow:"\u21A9",hookrightarrow:"\u21AA",twoheadleftarrow:"\u219E",twoheadrightarrow:"\u21A0",leftharpoonup:"\u21BC",leftharpoondown:"\u21BD",rightharpoonup:"\u21C0",rightharpoondown:"\u21C1",rightleftharpoons:"\u21CC",leftrightharpoons:"\u21CB",nearrow:"\u2197",searrow:"\u2198",swarrow:"\u2199",nwarrow:"\u2196",rightsquigarrow:"\u21DD",leadsto:"\u21DD",Rightarrow:"\u21D2",Longrightarrow:"\u21D2",Leftarrow:"\u21D0",Longleftarrow:"\u21D0",Leftrightarrow:"\u21D4",Longleftrightarrow:"\u21D4",implies:"\u21D2",iff:"\u21D4",mapsto:"\u21A6",longmapsto:"\u21A6",uparrow:"\u2191",downarrow:"\u2193",partial:"\u2202",nabla:"\u2207",int:"\u222B",iint:"\u222C",iiint:"\u222D",oint:"\u222E",sum:"\u2211",prod:"\u220F",coprod:"\u2210",infty:"\u221E",emptyset:"\u2205",varnothing:"\u2205",angle:"\u2220",therefore:"\u2234",because:"\u2235",aleph:"\u2135",beth:"\u2136",gimel:"\u2137",daleth:"\u2138",top:"\u22A4",bot:"\u22A5",triangle:"\u25B3",square:"\u25A1",lozenge:"\u25CA",checkmark:"\u2713",complement:"\u2201",wp:"\u2118",prime:"\u2032",ldots:"\u2026",dots:"\u2026",cdots:"\u22EF",vdots:"\u22EE",ddots:"\u22F1",ell:"\u2113",hbar:"\u210F",Im:"\u2111",Re:"\u211C",langle:"\u27E8",rangle:"\u27E9",vert:"|",lvert:"|",rvert:"|",Vert:"\u2016",lVert:"\u2016",rVert:"\u2016",lbrace:"{",rbrace:"}",backslash:"\\",lfloor:"\u230A",rfloor:"\u230B",lceil:"\u2308",rceil:"\u2309",colon:":"},NAMED_OPERATORS=new Set(["arccos","arcsin","arctan","arg","cos","cosh","cot","coth","csc","deg","det","dim","exp","gcd","hom","inf","ker","lg","lim","liminf","limsup","ln","log","max","min","Pr","sec","sin","sinh","sup","tan","tanh"]),LIMIT_OPERATORS=new Set(["argmax","argmin","inf","injlim","lim","liminf","limsup","max","min","projlim","sup"]),DISPLAY_LIMIT_SYMBOLS=new Set(["bigcap","bigcup","bigodot","bigoplus","bigotimes","bigsqcup","biguplus","bigvee","bigwedge","coprod","int","iint","iiint","oint","prod","sum"]),RELATION_COMMANDS=new Set(["Leftarrow","Leftrightarrow","Longleftarrow","Longleftrightarrow","Longrightarrow","Rightarrow","Join","Vdash","Vvdash","approx","asymp","bowtie","cong","dashv","fullouterjoin","doteq","fullouterjoin","downarrow","equiv","ge","geq","geqslant","gets","gg","hookleftarrow","hookrightarrow","iff","implies","in","leadsto","le","leftarrow","leftharpoondown","leftharpoonup","leftrightarrow","leftrightharpoons","leftouterjoin","leq","leqslant","ll","longleftarrow","longleftrightarrow","longmapsto","longrightarrow","ltimes","mapsto","mid","models","ne","nearrow","neq","ni","notin","nvdash","nvDash","nwarrow","parallel","perp","prec","preceq","propto","rightharpoondown","rightharpoonup","rightleftharpoons","rightouterjoin","rightarrow","rightsquigarrow","rtimes","searrow","sim","simeq","sqsubset","sqsubseteq","sqsupset","sqsupseteq","subset","subseteq","succ","succeq","supset","supseteq","swarrow","to","triangleleft","triangleright","twoheadleftarrow","twoheadrightarrow","uparrow","vdash"]),NEGATED_SYMBOLS={"<":"\u226E",">":"\u226F","=":"\u2260","\u2208":"\u2209","\u220B":"\u220C","\u2223":"\u2224","\u2225":"\u2226","\u223C":"\u2241","\u2243":"\u2244","\u2245":"\u2247","\u2248":"\u2249","\u2261":"\u2262","\u2264":"\u2270","\u2265":"\u2271","\u227A":"\u2280","\u227B":"\u2281","\u2282":"\u2284","\u2283":"\u2285","\u2286":"\u2288","\u2287":"\u2289","\u22A2":"\u22AC","\u22A8":"\u22AD","\u2194":"\u21AE","\u2190":"\u219A","\u2192":"\u219B","\u21D2":"\u21CF","\u21D0":"\u21CD","\u21D4":"\u21CE","\u227C":"\u22E0","\u227D":"\u22E1"},BLACKBOARD={C:"\u2102",H:"\u210D",N:"\u2115",P:"\u2119",Q:"\u211A",R:"\u211D",Z:"\u2124"},SUPERSCRIPTS={0:"\u2070",1:"\xB9",2:"\xB2",3:"\xB3",4:"\u2074",5:"\u2075",6:"\u2076",7:"\u2077",8:"\u2078",9:"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB"},SUBSCRIPTS={0:"\u2080",1:"\u2081",2:"\u2082",3:"\u2083",4:"\u2084",5:"\u2085",6:"\u2086",7:"\u2087",8:"\u2088",9:"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",h:"\u2095",i:"\u1D62",j:"\u2C7C",k:"\u2096",l:"\u2097",m:"\u2098",n:"\u2099",o:"\u2092",p:"\u209A",r:"\u1D63",s:"\u209B",t:"\u209C",u:"\u1D64",v:"\u1D65",x:"\u2093"},SPACING_COMMANDS=new Set([",",":",";"," ",">","enspace","enskip","medspace","quad","qquad","thickspace","thinspace"]),NEGATIVE_SPACING_COMMANDS=new Set(["!","negmedspace","negthickspace","negthinspace"]),NEGATIVE_SPACE="\0",FONT_SWITCH_COMMANDS=new Set(["bf","cal","it","rm","sf","sl","tt"]),IGNORED_COMMANDS=new Set(["displaystyle","limits","nolimits","scriptstyle","scriptscriptstyle","textstyle"]),SIZE_COMMANDS=new Set(["big","Big","bigg","Bigg","bigl","Bigl","biggl","Biggl","bigr","Bigr","biggr","Biggr"]),PLAIN_WRAPPERS=new Set(["emph","mathcal","mathbf","mathfrak","mathit","mathrm","mathnormal","mathscr","mathsf","mathtt","mathup","mbox","overbrace","pmb","smash","substack","text","textbf","textit","textmd","textnormal","textrm","textsc","textsf","textsl","texttt","textup","underbrace","bm","boldsymbol"]),ACCENTS={acute:"\u0301",bar:"\u0305",breve:"\u0306",check:"\u030C",ddot:"\u0308",dot:"\u0307",grave:"\u0300",hat:"\u0302",mathring:"\u030A",overleftarrow:"\u20D6",overleftrightarrow:"\u20E1",overline:"\u0305",overrightarrow:"\u20D7",tilde:"\u0303",underline:"\u0332",vec:"\u20D7",widehat:"\u0302",widetilde:"\u0303"};function replaceCharacters(value,replacements){let result="";for(let character of value){let replacement=replacements[character];if(replacement===void 0)return;result+=replacement}return result}function normalizeScriptValue(value){return value.trim().replace(/\s*([=+-])\s*/g,"$1")}function formatUnicodeScript(value,kind){return replaceCharacters(normalizeScriptValue(value),kind==="sub"?SUBSCRIPTS:SUPERSCRIPTS)}function formatScript(value,kind){value=normalizeScriptValue(value);let unicode=formatUnicodeScript(value,kind);if(unicode!==void 0)return unicode;let prefix=kind==="sub"?"_":"^";return Array.from(value).length===1||kind==="sub"&&/^[A-Za-z]+$/.test(value)?`${prefix}${value}`:`${prefix}(${value})`}function formatFraction(numerator,denominator){numerator=numerator.trim(),denominator=denominator.trim();let simpleNumerator=/^[\p{L}\p{N}.]+$/u.test(numerator),simpleDenominator=/^[\p{N}.]+$/u.test(denominator)||Array.from(denominator).length===1;return`${simpleNumerator?numerator:`(${numerator})`}/${simpleDenominator?denominator:`(${denominator})`}`}function formatRoot(value,symbol="\u221A"){return value=value.trim(),/^[\p{L}\p{N}.]+$/u.test(value)?`${symbol}${value}`:`${symbol}(${value})`}var NAMED_OPERATOR_START="\u{F0004}",NAMED_OPERATOR_END="\u{F0005}",NAMED_OPERATOR_LEFT_SPACING_PATTERN=/(?<=[\p{L}\p{N})\]}\u{f0001}])\u{f0004}/gu,NAMED_OPERATOR_RIGHT_SPACING_PATTERN=/\u{f0005}(?=[\p{L}\p{N}√\u{f0000}])/gu;function normalizeOutput(value){return value.replace(NAMED_OPERATOR_LEFT_SPACING_PATTERN," ").replaceAll(NAMED_OPERATOR_START,"").replace(NAMED_OPERATOR_RIGHT_SPACING_PATTERN," ").replaceAll(NAMED_OPERATOR_END,"").split(`
|
|
89
89
|
`).map(line=>line.replace(/[ \t]+/g," ").trim()).filter((line,index,lines)=>line.length>0||index>0&&index<lines.length-1).join(`
|
|
90
90
|
`).trim()}var LAYOUT_MARKER_START="\u{F0000}",LAYOUT_MARKER_END="\u{F0001}",LAYOUT_MARKER_PATTERN=/\u{f0000}(\d+)\u{f0001}/gu,TRAILING_LAYOUT_MARKER_PATTERN=/\u{f0000}(\d+)\u{f0001}$/u,PROTECTED_SPACE="\u{F0002}";function padLayoutLine(line,width,centered=!1){let padding=Math.max(0,width-visibleWidth(line)),left=centered?Math.floor(padding/2):0;return`${" ".repeat(left)}${line}${" ".repeat(padding-left)}`}function joinLayouts(layouts){if(layouts.length===0)return{lines:[""],width:0,baseline:0};let baseline=Math.max(...layouts.map(layout=>layout.baseline)),below=Math.max(...layouts.map(layout=>layout.lines.length-layout.baseline-1)),lines=[];for(let row=0;row<=baseline+below;row++){let line="";for(let layout of layouts){let sourceRow=row-baseline+layout.baseline;line+=sourceRow>=0&&sourceRow<layout.lines.length?padLayoutLine(layout.lines[sourceRow]??"",layout.width):" ".repeat(layout.width)}lines.push(line.trimEnd())}return{lines,width:layouts.reduce((width,layout)=>width+layout.width,0),baseline}}function renderLayout(source,nodes){let renderedLines=[],firstBaseline=0;for(let sourceLine of source.split(`
|
|
@@ -128,4 +128,4 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
128
128
|
`)}}function getLanguageFromPath(filePath){let ext=filePath.split(".").pop()?.toLowerCase();return ext?{ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",py:"python",rb:"ruby",rs:"rust",go:"go",java:"java",kt:"kotlin",swift:"swift",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",hpp:"cpp",cs:"csharp",php:"php",sh:"bash",bash:"bash",zsh:"bash",fish:"fish",ps1:"powershell",sql:"sql",html:"html",htm:"html",css:"css",scss:"scss",sass:"sass",less:"less",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",md:"markdown",markdown:"markdown",dockerfile:"dockerfile",makefile:"makefile",cmake:"cmake",lua:"lua",perl:"perl",r:"r",scala:"scala",clj:"clojure",ex:"elixir",exs:"elixir",erl:"erlang",hs:"haskell",ml:"ocaml",vim:"vim",graphql:"graphql",proto:"protobuf",tf:"hcl",hcl:"hcl"}[ext]:void 0}function getMarkdownTheme(){return{heading:text=>theme.fg("mdHeading",text),link:text=>theme.fg("mdLink",text),linkUrl:text=>theme.fg("mdLinkUrl",text),code:text=>theme.fg("mdCode",text),codeBlock:text=>theme.fg("mdCodeBlock",text),codeBlockBorder:text=>theme.fg("mdCodeBlockBorder",text),quote:text=>theme.fg("mdQuote",text),quoteBorder:text=>theme.fg("mdQuoteBorder",text),hr:text=>theme.fg("mdHr",text),listBullet:text=>theme.fg("mdListBullet",text),bold:text=>theme.bold(text),italic:text=>theme.italic(text),underline:text=>theme.underline(text),strikethrough:text=>theme.strikethrough(text),highlightCode:(code,lang)=>{let validLang=lang&&supportsLanguage(lang)?lang:void 0;if(!validLang)return code.split(`
|
|
129
129
|
`).map(line=>theme.fg("mdCodeBlock",line));let opts={language:validLang,ignoreIllegals:!0,theme:getCliHighlightTheme(theme)};try{return highlight(code,opts).split(`
|
|
130
130
|
`)}catch{return code.split(`
|
|
131
|
-
`).map(line=>theme.fg("mdCodeBlock",line))}}}}function getSelectListTheme(){return{selectedPrefix:text=>theme.fg("accent",text),selectedText:text=>theme.fg("accent",text),description:text=>theme.fg("muted",text),scrollInfo:text=>theme.fg("muted",text),noMatch:text=>theme.fg("muted",text)}}function getEditorTheme(){return{borderColor:text=>theme.getEditorBorderColor()(text),selectList:getSelectListTheme()}}function getSettingsListTheme(){return{label:(text,selected)=>selected?theme.fg("accent",text):text,value:(text,selected)=>selected?theme.fg("accent",text):theme.fg("muted",text),description:text=>theme.fg("dim",text),cursor:theme.fg("accent","\u2192 "),hint:text=>theme.fg("dim",text)}}function formatKeyPart(part,options){let displayPart=process.platform==="darwin"&&part.toLowerCase()==="alt"?"option":part;return options.capitalize?displayPart.charAt(0).toUpperCase()+displayPart.slice(1):displayPart}function formatKeyText(key,options={}){return key.split("/").map(k2=>k2.split("+").map(part=>formatKeyPart(part,options)).join("+")).join("/")}function formatKeys(keys,options={}){return keys.length===0?"":formatKeyText(keys.join("/"),options)}function keyText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding))}function keyDisplayText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding),{capitalize:!0})}function keyDisplayTextPrimary(keybinding){let keys=getKeybindings().getKeys(keybinding);return keys.length?formatKeyText(keys[0],{capitalize:!0}):""}function keyHint(keybinding,description){return theme.fg("dim",keyText(keybinding))+theme.fg("muted",` ${description}`)}function rawKeyHint(key,description){return theme.fg("dim",formatKeyText(key))+theme.fg("muted",` ${description}`)}export{Z,fuzzyMatch,fuzzyFilter,visibleWidth,wrapTextWithAnsi,truncateToWidth,sliceByColumn,CombinedAutocompleteProvider,indexedColor,rgbColor,parseColor,colorToRgb,mixColors,foregroundAnsi,backgroundAnsi,Key,matchesKey,detectCapabilities,getCapabilities,getTerminalColorMode,setCapabilityOverrides,getImageDimensions,hyperlink,imageFallback,Container,isViewportTUI,Box,TUI_KEYBINDINGS,KeybindingsManager,setKeybindings,getKeybindings,Text,Loader,CancellableLoader,SelectList,Editor,Gutter,setImageTranscoder,Image,Input,Markdown,MouseRegion,ScrollView,SettingsList,Spacer,TruncatedText,VStack,getNativeClipboard,ProcessTerminal,TuiAltScreen,TuiMainScreen,src_exports,FS_WATCH_RETRY_DELAY_MS,closeWatcher,watchWithErrorHandler,loadAllHighlightLanguages,SYSTEM_THEME_NAME,THEME_TOKENS,setThemeJsonValidator,setTerminalColors,setTerminalColorScheme,markTerminalColorsPending,Theme,getAvailableThemes,getAvailableThemesWithPaths,loadThemeFromPath,getThemeByName,parseAutoThemeSetting,resolveThemeSetting,getTerminalTheme,theme,setRegisteredThemes,initTheme,setTheme,setThemeInstance,onThemeChange,stopThemeWatcher,getResolvedThemeColors,getThemeExportColors,highlightCode,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getEditorTheme,getSettingsListTheme,formatKeyText,keyText,keyDisplayText,keyDisplayTextPrimary,keyHint,rawKeyHint};
|
|
131
|
+
`).map(line=>theme.fg("mdCodeBlock",line))}}}}function getSelectListTheme(){return{selectedPrefix:text=>theme.fg("accent",text),selectedText:text=>theme.fg("accent",text),description:text=>theme.fg("muted",text),scrollInfo:text=>theme.fg("muted",text),noMatch:text=>theme.fg("muted",text)}}function getEditorTheme(){return{borderColor:text=>theme.getEditorBorderColor()(text),selectList:getSelectListTheme()}}function getSettingsListTheme(){return{label:(text,selected)=>selected?theme.fg("accent",text):text,value:(text,selected)=>selected?theme.fg("accent",text):theme.fg("muted",text),description:text=>theme.fg("dim",text),cursor:theme.fg("accent","\u2192 "),hint:text=>theme.fg("dim",text)}}function formatKeyPart(part,options){let displayPart=process.platform==="darwin"&&part.toLowerCase()==="alt"?"option":part;return options.capitalize?displayPart.charAt(0).toUpperCase()+displayPart.slice(1):displayPart}function formatKeyText(key,options={}){return key.split("/").map(k2=>k2.split("+").map(part=>formatKeyPart(part,options)).join("+")).join("/")}function formatKeys(keys,options={}){return keys.length===0?"":formatKeyText(keys.join("/"),options)}function keyText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding))}function keyDisplayText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding),{capitalize:!0})}function keyDisplayTextPrimary(keybinding){let keys=getKeybindings().getKeys(keybinding);return keys.length?formatKeyText(keys[0],{capitalize:!0}):""}function keyHint(keybinding,description){return theme.fg("dim",keyText(keybinding))+theme.fg("muted",` ${description}`)}function rawKeyHint(key,description){return theme.fg("dim",formatKeyText(key))+theme.fg("muted",` ${description}`)}export{Z,fuzzyMatch,fuzzyFilter,visibleWidth,wrapTextWithAnsi,truncateToWidth,sliceByColumn,CombinedAutocompleteProvider,indexedColor,rgbColor,parseColor,colorToRgb,mixColors,foregroundAnsi,backgroundAnsi,Key,matchesKey,detectCapabilities,getCapabilities,getTerminalColorMode,setCapabilityOverrides,getImageDimensions,hyperlink,imageFallback,Container,isViewportTUI,Box,TUI_KEYBINDINGS,KeybindingsManager,setKeybindings,getKeybindings,Text,Loader,CancellableLoader,SelectList,Editor,Gutter,HStack,setImageTranscoder,Image,Input,Markdown,MouseRegion,ScrollView,SettingsList,Spacer,TruncatedText,VStack,getNativeClipboard,ProcessTerminal,TuiAltScreen,TuiMainScreen,src_exports,FS_WATCH_RETRY_DELAY_MS,closeWatcher,watchWithErrorHandler,loadAllHighlightLanguages,SYSTEM_THEME_NAME,THEME_TOKENS,setThemeJsonValidator,setTerminalColors,setTerminalColorScheme,markTerminalColorsPending,Theme,getAvailableThemes,getAvailableThemesWithPaths,loadThemeFromPath,getThemeByName,parseAutoThemeSetting,resolveThemeSetting,getTerminalTheme,theme,setRegisteredThemes,initTheme,setTheme,setThemeInstance,onThemeChange,stopThemeWatcher,getResolvedThemeColors,getThemeExportColors,highlightCode,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getEditorTheme,getSettingsListTheme,formatKeyText,keyText,keyDisplayText,keyDisplayTextPrimary,keyHint,rawKeyHint};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __kcCreateRequire } from "node:module"; const require = __kcCreateRequire(import.meta.url);
|
|
2
|
-
import{retryProviderRequest}from"./chunk-57BPR4HF.js";import{headersToRecord,providerHeadersToRecord}from"./chunk-DVFCXHT4.js";import{calculateCost}from"./chunk-
|
|
2
|
+
import{retryProviderRequest}from"./chunk-57BPR4HF.js";import{headersToRecord,providerHeadersToRecord}from"./chunk-DVFCXHT4.js";import{calculateCost}from"./chunk-6GRVIFTN.js";import{getIdentityHeaders}from"./chunk-UU4A4NV5.js";function httpError(label,response,body){let error=new Error(`${label} returned ${response.status}`);return error.status=response.status,error.headers=response.headers,error.body=body,error}function timeoutError(timeoutMs){let error=new Error(`Request timed out after ${timeoutMs}ms`);return error.name="TimeoutError",error.status=void 0,error.headers=void 0,error.body="",error}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function requiredNumber(label,value,field){if(typeof value!="number"||!Number.isFinite(value))throw new Error(`${label} returned an invalid ${field}`);return value}function requestHeaders(model,apiKey,optionsHeaders,identity){return providerHeadersToRecord(getIdentityHeaders(model,identity),{authorization:`Bearer ${apiKey}`,"content-type":"application/json"},model.headers,optionsHeaders)??{}}async function postClassifierRequest(label,url,model,body,options,noRetryStatuses){if(!options?.apiKey)throw new Error(`No API key for provider: ${model.provider}`);let apiKey=options.apiKey,payload=body,transformed=await options.onPayload?.(payload,model);transformed!==void 0&&(payload=transformed);let requestFetch=options.fetch??globalThis.fetch,{response,json}=await retryProviderRequest(async()=>{let timeoutSignal=options.timeoutMs!==void 0?AbortSignal.timeout(options.timeoutMs):void 0,signal=options.signal&&timeoutSignal?AbortSignal.any([options.signal,timeoutSignal]):options.signal??timeoutSignal;try{let next=await requestFetch(url,{method:"POST",headers:requestHeaders(model,apiKey,options.headers,options.identity),body:JSON.stringify(payload),signal});if(!next.ok)throw httpError(label,next,await next.text());return{response:next,json:await next.json()}}catch(error){throw timeoutSignal?.aborted&&!options.signal?.aborted?timeoutError(options.timeoutMs):error}},{maxRetries:options.maxRetries??2,maxRetryDelayMs:options.maxRetryDelayMs,signal:options.signal,noRetryStatuses});return await options.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),json}function tokenCount(value){return typeof value=="number"&&Number.isFinite(value)&&value>0?value:0}function parseClassifierUsage(value,model){if(!isRecord(value)||value.input_tokens===void 0&&value.output_tokens===void 0)return;let input=tokenCount(value.input_tokens),output=tokenCount(value.output_tokens),usage={input,output,cacheRead:0,cacheWrite:0,totalTokens:input+output,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return calculateCost(model,usage),usage}export{isRecord,requiredNumber,postClassifierRequest,parseClassifierUsage};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __kcCreateRequire } from "node:module"; const require = __kcCreateRequire(import.meta.url);
|
|
2
|
+
import{isRecord,parseClassifierUsage,postClassifierRequest,requiredNumber}from"./chunk-MZ5UVOTP.js";import{formatProviderError,normalizeProviderError}from"./chunk-4CRI7BMY.js";var IMAGE_OPT_IN_HEADERS={"TypeSafe-Danger-Zone-Images":"true"};function probabilities(label,value,id){if(!isRecord(value))throw new Error(`${label} returned invalid probabilities for ${id}`);return Object.fromEntries(Object.entries(value).map(([key,probability])=>[key,requiredNumber(label,probability,`probability for ${id}.${key}`)]))}function parseAnswers(label,value,context){if(!isRecord(value))throw new Error(`${label} returned an unexpected response`);let answers=[];for(let[id,question]of Object.entries(context.questions)){let answer=value[id];if(!isRecord(answer))throw new Error(`${label} did not return an answer for ${id}`);if(question.type==="choice"){if(answer.type!=="choice"||typeof answer.choice!="string")throw new Error(`${label} did not return a choice answer for ${id}`);answers.push([id,{type:"choice",choice:answer.choice,probabilities:probabilities(label,answer.probabilities,id),confidence:requiredNumber(label,answer.confidence,`confidence for ${id}`)}])}else if(question.type==="score"){if(answer.type!=="score")throw new Error(`${label} did not return a score answer for ${id}`);answers.push([id,{type:"score",score:requiredNumber(label,answer.score,`score for ${id}`),confidence:requiredNumber(label,answer.confidence,`confidence for ${id}`)}])}else{if(answer.type!=="noul")throw new Error(`${label} did not return a bool answer for ${id}`);answers.push([id,{type:"bool",probability:requiredNumber(label,answer.noul,`probability for ${id}`)}])}}return Object.fromEntries(answers)}var ASSET_FORMATS={"image/png":"png","image/jpeg":"jpeg"},DATA_URL_TYPES=new Set(["image/png","image/jpeg","image/webp"]),MAX_DATA_URL_IMAGES=4;function addImages(label,model,input,images,request){if(input==="images"){if(images.length>MAX_DATA_URL_IMAGES)throw new Error(`${label} accepts at most ${MAX_DATA_URL_IMAGES} images for ${model.id}, got ${images.length}`);request.images=images.map(image=>{if(!DATA_URL_TYPES.has(image.mimeType))throw new Error(`${label} accepts PNG, JPEG, and WebP images for ${model.id}, got ${image.mimeType}`);return`data:${image.mimeType};base64,${image.data}`});return}if(input==="state-image-urls"){let parts=images.map(image=>({type:"image_url",image_url:{url:`data:${image.mimeType};base64,${image.data}`}}));request.state=[...parts,request.state];return}let assets={};images.forEach((image,index)=>{let format=ASSET_FORMATS[image.mimeType];if(!format)throw new Error(`${label} accepts PNG and JPEG images for ${model.id}, got ${image.mimeType}`);assets[`<image-${index+1}>`]={type:"image",format,data_base64:image.data}}),request.assets=assets,request.state=[...Object.keys(assets),request.state]}function wireRequest(context){return{state:context.state,questions:Object.fromEntries(Object.entries(context.questions).map(([id,question])=>[id,question.type==="bool"?{...question,type:"noul"}:question]))}}async function classifySystemOne(transport,model,context,options){let output={api:model.api,provider:model.provider,model:model.id,answers:{},stopReason:"stop",timestamp:Date.now()};try{if(model.api!==transport.api)throw new Error(`Unsupported classifier API: ${model.api}`);let request=wireRequest(context),requestOptions=options;if(context.images?.length){if(!model.input.includes("image"))throw new Error(`${transport.label} does not support image input for ${model.id}`);let detected=transport.detectCompat(model),imageInput=model.compat?.imageInput??detected.imageInput;addImages(transport.label,model,imageInput,context.images,request),(model.compat?.sendImageOptInHeader??detected.sendImageOptInHeader)&&(requestOptions={...options,headers:{...IMAGE_OPT_IN_HEADERS,...options?.headers}})}let body=await postClassifierRequest(transport.label,transport.url(model),model,transport.payload(model,request),requestOptions),result=transport.output(body),usage=parseClassifierUsage(result.usage,model);return usage&&(output.usage=usage),output.answers=parseAnswers(transport.label,result.answers,context),output}catch(error){return output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error),`${transport.label} error`),output}}export{classifySystemOne};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __kcCreateRequire } from "node:module"; const require = __kcCreateRequire(import.meta.url);
|
|
2
|
-
import{clampThinkingLevel,getSystemMessageText}from"./chunk-T47GKPON.js";var UnsupportedStrictJsonSchemaError=class extends Error{},UNSUPPORTED_STRICT_SCHEMA_KEYS=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function isJsonSchemaObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStructuredSchema(schema){if(!isJsonSchemaObject(schema))return!1;let types=typeof schema.type=="string"?[schema.type]:Array.isArray(schema.type)?schema.type:[];return types.includes("object")||types.includes("array")||schema.properties!==void 0||schema.items!==void 0}function schemaAllowsNull(schema){return isJsonSchemaObject(schema)?schema.type==="null"||Array.isArray(schema.type)&&schema.type.includes("null")||schema.const===null||Array.isArray(schema.enum)&&schema.enum.includes(null)?!0:Array.isArray(schema.anyOf)&&schema.anyOf.some(variant=>schemaAllowsNull(variant)):!1}function makeJsonSchemaNodeStrict(schema,isUnsupportedKeyword){if(!isJsonSchemaObject(schema))throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");for(let key of UNSUPPORTED_STRICT_SCHEMA_KEYS)if(schema[key]!==void 0)throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);if(isUnsupportedKeyword){for(let[key,value]of Object.entries(schema))if(value!==void 0&&isUnsupportedKeyword(key,value))throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`)}if(schema.anyOf!==void 0){if(!Array.isArray(schema.anyOf)||schema.anyOf.length===0)throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");for(let variant of schema.anyOf){if(isStructuredSchema(variant))throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");makeJsonSchemaNodeStrict(variant,isUnsupportedKeyword)}}if(schema.items!==void 0){if(Array.isArray(schema.items))throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");makeJsonSchemaNodeStrict(schema.items,isUnsupportedKeyword)}let isObjectSchema=schema.type==="object";if(schema.properties!==void 0&&!isObjectSchema)throw new UnsupportedStrictJsonSchemaError("properties require type object");if(!isObjectSchema)return;if(schema.additionalProperties!==void 0&&schema.additionalProperties!==!1)throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");if(schema.properties!==void 0&&!isJsonSchemaObject(schema.properties))throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");if(schema.required!==void 0&&(!Array.isArray(schema.required)||schema.required.some(key=>typeof key!="string")))throw new UnsupportedStrictJsonSchemaError("object required must be a string array");let properties=schema.properties??{},propertyNames=Object.keys(properties),required=new Set(Array.isArray(schema.required)?schema.required:[]);if([...required].some(key=>!propertyNames.includes(key)))throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");for(let[key,property]of Object.entries(properties))makeJsonSchemaNodeStrict(property,isUnsupportedKeyword),!required.has(key)&&!schemaAllowsNull(property)&&(properties[key]={anyOf:[property,{type:"null"}]});schema.required=propertyNames,schema.additionalProperties=!1}function makeStrictJsonSchema(schema,isUnsupportedKeyword){let cloned=structuredClone(schema);if(!isJsonSchemaObject(cloned))throw new UnsupportedStrictJsonSchemaError("root schema must have type object");if(makeJsonSchemaNodeStrict(cloned,isUnsupportedKeyword),cloned.type!=="object")throw new UnsupportedStrictJsonSchemaError("root schema must have type object");return cloned}function getJsonSchemaToolParameters(tool,strict){return strict===!0?makeStrictJsonSchema(tool.parameters):tool.parameters}function getGrammarToolInput(toolName,arguments_,inputProperty){let input=arguments_[inputProperty];if(typeof input!="string")throw new Error(`Grammar tool call "${toolName}" requires argument "${inputProperty}" to be a string.`);return input}function appendGrammarToolInputJsonDelta(buffer,inputProperty,nextInput,close){if(buffer.closed){if(close&&nextInput===buffer.input)return;throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`)}if(!nextInput.startsWith(buffer.input))throw new Error(`grammar tool input for property "${inputProperty}" changed non-monotonically`);let inputDelta=nextInput.slice(buffer.input.length);if(!close&&inputDelta.length===0)return;let delta="";return buffer.started||(delta+=`{${JSON.stringify(inputProperty)}:"`,buffer.started=!0),delta+=JSON.stringify(inputDelta).slice(1,-1),buffer.input=nextInput,close&&(delta+='"}',buffer.closed=!0),delta}function inferGrammarInputProperty(tool){let schema=tool.parameters;if(schema.type!=="object")throw new Error("grammar constrained sampling requires an object parameter schema");if(!Array.isArray(schema.required)||schema.required.length!==1||typeof schema.required[0]!="string")throw new Error("grammar constrained sampling requires exactly one required string property");let inputProperty=schema.required[0];if(!schema.properties?.[inputProperty])throw new Error(`grammar constrained sampling requires a properties entry for ${inputProperty}`);if(schema.properties[inputProperty]?.type!=="string")throw new Error(`grammar constrained sampling property ${inputProperty} must have type string`);return inputProperty}function resolveJsonSchemaStrictSampling(tool,supportsStrictMode,isUnsupportedKeyword){let config=tool.constrainedSampling;if(!(!config||config.type!=="json_schema")){if(supportsStrictMode)try{return makeStrictJsonSchema(tool.parameters,isUnsupportedKeyword),!0}catch(error){if(!(error instanceof UnsupportedStrictJsonSchemaError))throw error;if(config.strict!=="require")return;throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error.message}.`)}if(config.strict==="require")throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}function resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools){let config=tool.constrainedSampling;if(!config||config.type!=="grammar"||!supportsOpenAIGrammarTools)return;let larkDefinition=config.variants.openai_lark,regexDefinition=config.variants.openai_regex,hasLarkDefinition=typeof larkDefinition=="string"&&larkDefinition.trim().length>0,hasRegexDefinition=typeof regexDefinition=="string"&®exDefinition.trim().length>0;if(!hasLarkDefinition&&!hasRegexDefinition)throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:hasLarkDefinition?"lark":"regex",definition:hasLarkDefinition?larkDefinition:regexDefinition,inputProperty:inferGrammarInputProperty(tool)}}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: ${message}.`)}}function createGrammarToolInputProperties(tools,supportsOpenAIGrammarTools){let properties=new Map;for(let tool of tools??[]){let grammar=resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools);grammar&&properties.set(tool.name,grammar.inputProperty)}return properties}var CHARS_PER_TOKEN=3.5,ESTIMATED_IMAGE_CHARS=4800;function calculateContextTokens(usage){return usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite}function safeJsonStringify(value){try{return JSON.stringify(value)??"undefined"}catch{return"[unserializable]"}}function estimateTextAndImageContentChars(content){if(typeof content=="string")return content.length;let chars=0;for(let block of content)chars+=block.type==="text"?block.text.length:ESTIMATED_IMAGE_CHARS;return chars}function estimateTextTokens(text){return Math.ceil(text.length/CHARS_PER_TOKEN)}function estimateTextAndImageContentTokens(content){return Math.ceil(estimateTextAndImageContentChars(content)/CHARS_PER_TOKEN)}function estimateMessageTokens(message){let chars=0;if(message.role==="system")return estimateTextTokens(getSystemMessageText(message))+estimateToolsTokens(message.toolsAdded)+estimateToolsTokens(message.toolsRemoved);if(message.role==="user"||message.role==="toolResult")return estimateTextAndImageContentTokens(message.content);for(let block of message.content)block.type==="text"?chars+=block.text.length:block.type==="thinking"?chars+=block.thinking.length:chars+=block.name.length+safeJsonStringify(block.arguments).length;return Math.ceil(chars/CHARS_PER_TOKEN)}function getLastAssistantUsageInfo(messages){let latestPrefixTimestamp=Number.NEGATIVE_INFINITY,usageInfo;for(let i=0;i<messages.length;i++){let message=messages[i];if(message.role==="assistant"){let assistant=message;assistant.timestamp>=latestPrefixTimestamp&&assistant.stopReason!=="aborted"&&assistant.stopReason!=="error"&&calculateContextTokens(assistant.usage)>0&&(usageInfo={usage:assistant.usage,index:i})}latestPrefixTimestamp=Math.max(latestPrefixTimestamp,message.timestamp)}return usageInfo}function estimateContextTokens(context){let messages="messages"in context?context.messages:context,usageInfo=getLastAssistantUsageInfo(messages);if(usageInfo){let usageTokens=calculateContextTokens(usageInfo.usage),trailingTokens=0;for(let i=usageInfo.index+1;i<messages.length;i++)trailingTokens+=estimateMessageTokens(messages[i]);return{tokens:usageTokens+trailingTokens,usageTokens,trailingTokens,lastUsageIndex:usageInfo.index}}let tokens=0;for(let message of messages)tokens+=estimateMessageTokens(message);return{tokens,usageTokens:0,trailingTokens:tokens,lastUsageIndex:null}}function estimateToolsTokens(tools){return!tools||tools.length===0?0:estimateTextTokens(safeJsonStringify(tools))}var CONTEXT_SAFETY_TOKENS=4096,MIN_MAX_TOKENS=1,ESTIMATE_UNDERCOUNT_MARGIN=1.5;function clampMaxTokensToContext(model,context,maxTokens){if(model.contextWindow<=0)return Math.max(MIN_MAX_TOKENS,maxTokens);let estimate=estimateContextTokens(context),promptTokens=estimate.usageTokens+Math.ceil(estimate.trailingTokens*ESTIMATE_UNDERCOUNT_MARGIN),available=model.contextWindow-promptTokens-CONTEXT_SAFETY_TOKENS;return Math.min(maxTokens,Math.max(MIN_MAX_TOKENS,available))}function resolveSamplingParams(model,thinkingLevel,requestParams){let effectiveThinkingLevel=clampThinkingLevel(model,thinkingLevel),thinkingLevelParams=model.samplingParamsByThinkingLevel?.[effectiveThinkingLevel];return model.samplingParams||thinkingLevelParams||requestParams?{...model.samplingParams,...thinkingLevelParams,...requestParams}:void 0}function buildBaseOptions(model,context,options,apiKey){let samplingParams=resolveSamplingParams(model,options?.reasoning??"off",options?.samplingParams);return{temperature:options?.temperature,samplingParams,maxTokens:clampMaxTokensToContext(model,context,options?.maxTokens??model.maxTokens),signal:options?.signal,telemetry:options?.telemetry,apiKey:apiKey||options?.apiKey,fetch:options?.fetch,transport:options?.transport,cacheRetention:options?.cacheRetention,sessionId:options?.sessionId,headers:options?.headers,identity:options?.identity,onPayload:options?.onPayload,onResponse:options?.onResponse,onProviderStreamEvent:options?.onProviderStreamEvent,timeoutMs:options?.timeoutMs,websocketConnectTimeoutMs:options?.websocketConnectTimeoutMs,maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,metadata:options?.metadata,env:options?.env}}var MIN_ANSWER_TOKENS=1024,DEFAULT_THINKING_BUDGETS={minimal:1024,low:2048,medium:8192,high:16384};function clampReasoning(effort){return effort==="xhigh"||effort==="max"?"high":effort}function thinkingBudgetForLevel(reasoningLevel,customBudgets){let budgets={...DEFAULT_THINKING_BUDGETS,...customBudgets},level=clampReasoning(reasoningLevel);return budgets[level]}function clampThinkingBudgetToAnswerRoom(thinkingBudget,ceiling){return Math.min(thinkingBudget,Math.max(0,ceiling-MIN_ANSWER_TOKENS))}function adjustMaxTokensForThinking(baseMaxTokens,modelMaxTokens,reasoningLevel,customBudgets){let thinkingBudget=thinkingBudgetForLevel(reasoningLevel,customBudgets),maxTokens=baseMaxTokens===void 0?modelMaxTokens:Math.min(baseMaxTokens+thinkingBudget,modelMaxTokens);return maxTokens<=thinkingBudget&&(thinkingBudget=clampThinkingBudgetToAnswerRoom(thinkingBudget,maxTokens)),{maxTokens,thinkingBudget}}var NON_VISION_USER_IMAGE_PLACEHOLDER="(image omitted: model does not support images)",NON_VISION_TOOL_IMAGE_PLACEHOLDER="(tool image omitted: model does not support images)",ERROR_TOOL_IMAGE_PLACEHOLDER="(image attached after the tool results)";function splitErrorToolResultImages(msg){if(!msg.isError)return;let images=msg.content.filter(block=>block.type==="image");if(images.length!==0)return{content:replaceImagesWithPlaceholder(msg.content,ERROR_TOOL_IMAGE_PLACEHOLDER),caption:`Images from the error result of tool call ${msg.toolCallId} (${msg.toolName}):`,images}}function replaceImagesWithPlaceholder(content,placeholder){let result=[],previousWasPlaceholder=!1;for(let block of content){if(block.type==="image"){previousWasPlaceholder||result.push({type:"text",text:placeholder}),previousWasPlaceholder=!0;continue}result.push(block),previousWasPlaceholder=block.text===placeholder}return result}function downgradeUnsupportedImages(messages,model){return model.input.includes("image")?messages:messages.map(msg=>msg.role==="user"&&Array.isArray(msg.content)?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_USER_IMAGE_PLACEHOLDER)}:msg.role==="toolResult"?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_TOOL_IMAGE_PLACEHOLDER)}:msg)}function transformMessages(messages,model,normalizeToolCallId){let toolCallIdMap=new Map,normalizedMessages=messages.map(msg=>msg.content==null?{...msg,content:[]}:msg),transformed=downgradeUnsupportedImages(normalizedMessages,model).map(msg=>{if(msg.role==="system"||msg.role==="user")return msg;if(msg.role==="toolResult"){let normalizedId=toolCallIdMap.get(msg.toolCallId);return normalizedId&&normalizedId!==msg.toolCallId?{...msg,toolCallId:normalizedId}:msg}if(msg.role==="assistant"){let assistantMsg=msg,isSameModel=assistantMsg.provider===model.provider&&assistantMsg.api===model.api&&assistantMsg.model===model.id,transformedContent=assistantMsg.content.flatMap(block=>{if(block.type==="thinking")return isSameModel?block.redacted||block.thinkingSignature?block:!block.thinking||block.thinking.trim()===""?[]:block:[];if(block.type==="text")return isSameModel?block:{type:"text",text:block.text};if(block.type==="toolCall"){let toolCall=block,normalizedToolCall=toolCall;if(!isSameModel&&toolCall.thoughtSignature&&(normalizedToolCall={...toolCall},delete normalizedToolCall.thoughtSignature),!isSameModel&&normalizeToolCallId){let normalizedId=normalizeToolCallId(toolCall.id,model,assistantMsg);normalizedId!==toolCall.id&&(toolCallIdMap.set(toolCall.id,normalizedId),normalizedToolCall={...normalizedToolCall,id:normalizedId})}return normalizedToolCall}return block});return{...assistantMsg,content:transformedContent}}return msg}),result=[],pendingToolCalls=[],existingToolResultIds=new Set,heldSystemMessages=[],closePendingToolCalls=()=>{if(pendingToolCalls.length>0){for(let tc of pendingToolCalls)existingToolResultIds.has(tc.id)||result.push({role:"toolResult",toolCallId:tc.id,toolName:tc.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});pendingToolCalls=[],existingToolResultIds=new Set}result.push(...heldSystemMessages),heldSystemMessages.length=0};for(let i=0;i<transformed.length;i++){let msg=transformed[i];if(msg.role==="assistant"){closePendingToolCalls();let assistantMsg=msg;if(assistantMsg.stopReason==="error"||assistantMsg.stopReason==="aborted")continue;let toolCalls=assistantMsg.content.filter(b=>b.type==="toolCall");toolCalls.length>0&&(pendingToolCalls=toolCalls,existingToolResultIds=new Set),result.push(msg)}else msg.role==="toolResult"?(existingToolResultIds.add(msg.toolCallId),result.push(msg)):msg.role==="system"?pendingToolCalls.length>0?heldSystemMessages.push(msg):result.push(msg):(msg.role==="user"&&closePendingToolCalls(),result.push(msg))}return closePendingToolCalls(),result}export{getJsonSchemaToolParameters,getGrammarToolInput,appendGrammarToolInputJsonDelta,resolveJsonSchemaStrictSampling,resolveGrammarConstrainedSampling,createGrammarToolInputProperties,clampMaxTokensToContext,resolveSamplingParams,buildBaseOptions,MIN_ANSWER_TOKENS,thinkingBudgetForLevel,clampThinkingBudgetToAnswerRoom,adjustMaxTokensForThinking,splitErrorToolResultImages,transformMessages};
|
|
2
|
+
import{clampThinkingLevel,getSystemMessageText}from"./chunk-6GRVIFTN.js";var UnsupportedStrictJsonSchemaError=class extends Error{},UNSUPPORTED_STRICT_SCHEMA_KEYS=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function isJsonSchemaObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStructuredSchema(schema){if(!isJsonSchemaObject(schema))return!1;let types=typeof schema.type=="string"?[schema.type]:Array.isArray(schema.type)?schema.type:[];return types.includes("object")||types.includes("array")||schema.properties!==void 0||schema.items!==void 0}function schemaAllowsNull(schema){return isJsonSchemaObject(schema)?schema.type==="null"||Array.isArray(schema.type)&&schema.type.includes("null")||schema.const===null||Array.isArray(schema.enum)&&schema.enum.includes(null)?!0:Array.isArray(schema.anyOf)&&schema.anyOf.some(variant=>schemaAllowsNull(variant)):!1}function makeJsonSchemaNodeStrict(schema,isUnsupportedKeyword){if(!isJsonSchemaObject(schema))throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");for(let key of UNSUPPORTED_STRICT_SCHEMA_KEYS)if(schema[key]!==void 0)throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);if(isUnsupportedKeyword){for(let[key,value]of Object.entries(schema))if(value!==void 0&&isUnsupportedKeyword(key,value))throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`)}if(schema.anyOf!==void 0){if(!Array.isArray(schema.anyOf)||schema.anyOf.length===0)throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");for(let variant of schema.anyOf){if(isStructuredSchema(variant))throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");makeJsonSchemaNodeStrict(variant,isUnsupportedKeyword)}}if(schema.items!==void 0){if(Array.isArray(schema.items))throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");makeJsonSchemaNodeStrict(schema.items,isUnsupportedKeyword)}let isObjectSchema=schema.type==="object";if(schema.properties!==void 0&&!isObjectSchema)throw new UnsupportedStrictJsonSchemaError("properties require type object");if(!isObjectSchema)return;if(schema.additionalProperties!==void 0&&schema.additionalProperties!==!1)throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");if(schema.properties!==void 0&&!isJsonSchemaObject(schema.properties))throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");if(schema.required!==void 0&&(!Array.isArray(schema.required)||schema.required.some(key=>typeof key!="string")))throw new UnsupportedStrictJsonSchemaError("object required must be a string array");let properties=schema.properties??{},propertyNames=Object.keys(properties),required=new Set(Array.isArray(schema.required)?schema.required:[]);if([...required].some(key=>!propertyNames.includes(key)))throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");for(let[key,property]of Object.entries(properties))makeJsonSchemaNodeStrict(property,isUnsupportedKeyword),!required.has(key)&&!schemaAllowsNull(property)&&(properties[key]={anyOf:[property,{type:"null"}]});schema.required=propertyNames,schema.additionalProperties=!1}function makeStrictJsonSchema(schema,isUnsupportedKeyword){let cloned=structuredClone(schema);if(!isJsonSchemaObject(cloned))throw new UnsupportedStrictJsonSchemaError("root schema must have type object");if(makeJsonSchemaNodeStrict(cloned,isUnsupportedKeyword),cloned.type!=="object")throw new UnsupportedStrictJsonSchemaError("root schema must have type object");return cloned}function getJsonSchemaToolParameters(tool,strict){return strict===!0?makeStrictJsonSchema(tool.parameters):tool.parameters}function getGrammarToolInput(toolName,arguments_,inputProperty){let input=arguments_[inputProperty];if(typeof input!="string")throw new Error(`Grammar tool call "${toolName}" requires argument "${inputProperty}" to be a string.`);return input}function appendGrammarToolInputJsonDelta(buffer,inputProperty,nextInput,close){if(buffer.closed){if(close&&nextInput===buffer.input)return;throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`)}if(!nextInput.startsWith(buffer.input))throw new Error(`grammar tool input for property "${inputProperty}" changed non-monotonically`);let inputDelta=nextInput.slice(buffer.input.length);if(!close&&inputDelta.length===0)return;let delta="";return buffer.started||(delta+=`{${JSON.stringify(inputProperty)}:"`,buffer.started=!0),delta+=JSON.stringify(inputDelta).slice(1,-1),buffer.input=nextInput,close&&(delta+='"}',buffer.closed=!0),delta}function inferGrammarInputProperty(tool){let schema=tool.parameters;if(schema.type!=="object")throw new Error("grammar constrained sampling requires an object parameter schema");if(!Array.isArray(schema.required)||schema.required.length!==1||typeof schema.required[0]!="string")throw new Error("grammar constrained sampling requires exactly one required string property");let inputProperty=schema.required[0];if(!schema.properties?.[inputProperty])throw new Error(`grammar constrained sampling requires a properties entry for ${inputProperty}`);if(schema.properties[inputProperty]?.type!=="string")throw new Error(`grammar constrained sampling property ${inputProperty} must have type string`);return inputProperty}function resolveJsonSchemaStrictSampling(tool,supportsStrictMode,isUnsupportedKeyword){let config=tool.constrainedSampling;if(!(!config||config.type!=="json_schema")){if(supportsStrictMode)try{return makeStrictJsonSchema(tool.parameters,isUnsupportedKeyword),!0}catch(error){if(!(error instanceof UnsupportedStrictJsonSchemaError))throw error;if(config.strict!=="require")return;throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error.message}.`)}if(config.strict==="require")throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}function resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools){let config=tool.constrainedSampling;if(!config||config.type!=="grammar"||!supportsOpenAIGrammarTools)return;let larkDefinition=config.variants.openai_lark,regexDefinition=config.variants.openai_regex,hasLarkDefinition=typeof larkDefinition=="string"&&larkDefinition.trim().length>0,hasRegexDefinition=typeof regexDefinition=="string"&®exDefinition.trim().length>0;if(!hasLarkDefinition&&!hasRegexDefinition)throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:hasLarkDefinition?"lark":"regex",definition:hasLarkDefinition?larkDefinition:regexDefinition,inputProperty:inferGrammarInputProperty(tool)}}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: ${message}.`)}}function createGrammarToolInputProperties(tools,supportsOpenAIGrammarTools){let properties=new Map;for(let tool of tools??[]){let grammar=resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools);grammar&&properties.set(tool.name,grammar.inputProperty)}return properties}var CHARS_PER_TOKEN=3.5,ESTIMATED_IMAGE_CHARS=4800;function calculateContextTokens(usage){return usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite}function safeJsonStringify(value){try{return JSON.stringify(value)??"undefined"}catch{return"[unserializable]"}}function estimateTextAndImageContentChars(content){if(typeof content=="string")return content.length;let chars=0;for(let block of content)chars+=block.type==="text"?block.text.length:ESTIMATED_IMAGE_CHARS;return chars}function estimateTextTokens(text){return Math.ceil(text.length/CHARS_PER_TOKEN)}function estimateTextAndImageContentTokens(content){return Math.ceil(estimateTextAndImageContentChars(content)/CHARS_PER_TOKEN)}function estimateMessageTokens(message){let chars=0;if(message.role==="system")return estimateTextTokens(getSystemMessageText(message))+estimateToolsTokens(message.toolsAdded)+estimateToolsTokens(message.toolsRemoved);if(message.role==="user"||message.role==="toolResult")return estimateTextAndImageContentTokens(message.content);for(let block of message.content)block.type==="text"?chars+=block.text.length:block.type==="thinking"?chars+=block.thinking.length:chars+=block.name.length+safeJsonStringify(block.arguments).length;return Math.ceil(chars/CHARS_PER_TOKEN)}function getLastAssistantUsageInfo(messages){let latestPrefixTimestamp=Number.NEGATIVE_INFINITY,usageInfo;for(let i=0;i<messages.length;i++){let message=messages[i];if(message.role==="assistant"){let assistant=message;assistant.timestamp>=latestPrefixTimestamp&&assistant.stopReason!=="aborted"&&assistant.stopReason!=="error"&&calculateContextTokens(assistant.usage)>0&&(usageInfo={usage:assistant.usage,index:i})}latestPrefixTimestamp=Math.max(latestPrefixTimestamp,message.timestamp)}return usageInfo}function estimateContextTokens(context){let messages="messages"in context?context.messages:context,usageInfo=getLastAssistantUsageInfo(messages);if(usageInfo){let usageTokens=calculateContextTokens(usageInfo.usage),trailingTokens=0;for(let i=usageInfo.index+1;i<messages.length;i++)trailingTokens+=estimateMessageTokens(messages[i]);return{tokens:usageTokens+trailingTokens,usageTokens,trailingTokens,lastUsageIndex:usageInfo.index}}let tokens=0;for(let message of messages)tokens+=estimateMessageTokens(message);return{tokens,usageTokens:0,trailingTokens:tokens,lastUsageIndex:null}}function estimateToolsTokens(tools){return!tools||tools.length===0?0:estimateTextTokens(safeJsonStringify(tools))}var CONTEXT_SAFETY_TOKENS=4096,MIN_MAX_TOKENS=1,ESTIMATE_UNDERCOUNT_MARGIN=1.5;function clampMaxTokensToContext(model,context,maxTokens){if(model.contextWindow<=0)return Math.max(MIN_MAX_TOKENS,maxTokens);let estimate=estimateContextTokens(context),promptTokens=estimate.usageTokens+Math.ceil(estimate.trailingTokens*ESTIMATE_UNDERCOUNT_MARGIN),available=model.contextWindow-promptTokens-CONTEXT_SAFETY_TOKENS;return Math.min(maxTokens,Math.max(MIN_MAX_TOKENS,available))}function resolveSamplingParams(model,thinkingLevel,requestParams){let effectiveThinkingLevel=clampThinkingLevel(model,thinkingLevel),thinkingLevelParams=model.samplingParamsByThinkingLevel?.[effectiveThinkingLevel];return model.samplingParams||thinkingLevelParams||requestParams?{...model.samplingParams,...thinkingLevelParams,...requestParams}:void 0}function buildBaseOptions(model,context,options,apiKey){let samplingParams=resolveSamplingParams(model,options?.reasoning??"off",options?.samplingParams);return{temperature:options?.temperature,samplingParams,maxTokens:clampMaxTokensToContext(model,context,options?.maxTokens??model.maxTokens),signal:options?.signal,telemetry:options?.telemetry,apiKey:apiKey||options?.apiKey,fetch:options?.fetch,transport:options?.transport,cacheRetention:options?.cacheRetention,sessionId:options?.sessionId,headers:options?.headers,identity:options?.identity,onPayload:options?.onPayload,onResponse:options?.onResponse,onProviderStreamEvent:options?.onProviderStreamEvent,timeoutMs:options?.timeoutMs,websocketConnectTimeoutMs:options?.websocketConnectTimeoutMs,maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,metadata:options?.metadata,env:options?.env}}var MIN_ANSWER_TOKENS=1024,DEFAULT_THINKING_BUDGETS={minimal:1024,low:2048,medium:8192,high:16384};function clampReasoning(effort){return effort==="xhigh"||effort==="max"?"high":effort}function thinkingBudgetForLevel(reasoningLevel,customBudgets){let budgets={...DEFAULT_THINKING_BUDGETS,...customBudgets},level=clampReasoning(reasoningLevel);return budgets[level]}function clampThinkingBudgetToAnswerRoom(thinkingBudget,ceiling){return Math.min(thinkingBudget,Math.max(0,ceiling-MIN_ANSWER_TOKENS))}function adjustMaxTokensForThinking(baseMaxTokens,modelMaxTokens,reasoningLevel,customBudgets){let thinkingBudget=thinkingBudgetForLevel(reasoningLevel,customBudgets),maxTokens=baseMaxTokens===void 0?modelMaxTokens:Math.min(baseMaxTokens+thinkingBudget,modelMaxTokens);return maxTokens<=thinkingBudget&&(thinkingBudget=clampThinkingBudgetToAnswerRoom(thinkingBudget,maxTokens)),{maxTokens,thinkingBudget}}var NON_VISION_USER_IMAGE_PLACEHOLDER="(image omitted: model does not support images)",NON_VISION_TOOL_IMAGE_PLACEHOLDER="(tool image omitted: model does not support images)",ERROR_TOOL_IMAGE_PLACEHOLDER="(image attached after the tool results)";function splitErrorToolResultImages(msg){if(!msg.isError)return;let images=msg.content.filter(block=>block.type==="image");if(images.length!==0)return{content:replaceImagesWithPlaceholder(msg.content,ERROR_TOOL_IMAGE_PLACEHOLDER),caption:`Images from the error result of tool call ${msg.toolCallId} (${msg.toolName}):`,images}}function replaceImagesWithPlaceholder(content,placeholder){let result=[],previousWasPlaceholder=!1;for(let block of content){if(block.type==="image"){previousWasPlaceholder||result.push({type:"text",text:placeholder}),previousWasPlaceholder=!0;continue}result.push(block),previousWasPlaceholder=block.text===placeholder}return result}function downgradeUnsupportedImages(messages,model){return model.input.includes("image")?messages:messages.map(msg=>msg.role==="user"&&Array.isArray(msg.content)?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_USER_IMAGE_PLACEHOLDER)}:msg.role==="toolResult"?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_TOOL_IMAGE_PLACEHOLDER)}:msg)}function transformMessages(messages,model,normalizeToolCallId){let toolCallIdMap=new Map,normalizedMessages=messages.map(msg=>msg.content==null?{...msg,content:[]}:msg),transformed=downgradeUnsupportedImages(normalizedMessages,model).map(msg=>{if(msg.role==="system"||msg.role==="user")return msg;if(msg.role==="toolResult"){let normalizedId=toolCallIdMap.get(msg.toolCallId);return normalizedId&&normalizedId!==msg.toolCallId?{...msg,toolCallId:normalizedId}:msg}if(msg.role==="assistant"){let assistantMsg=msg,isSameModel=assistantMsg.provider===model.provider&&assistantMsg.api===model.api&&assistantMsg.model===model.id,transformedContent=assistantMsg.content.flatMap(block=>{if(block.type==="thinking")return isSameModel?block.redacted||block.thinkingSignature?block:!block.thinking||block.thinking.trim()===""?[]:block:[];if(block.type==="text")return isSameModel?block:{type:"text",text:block.text};if(block.type==="toolCall"){let toolCall=block,normalizedToolCall=toolCall;if(!isSameModel&&toolCall.thoughtSignature&&(normalizedToolCall={...toolCall},delete normalizedToolCall.thoughtSignature),!isSameModel&&normalizeToolCallId){let normalizedId=normalizeToolCallId(toolCall.id,model,assistantMsg);normalizedId!==toolCall.id&&(toolCallIdMap.set(toolCall.id,normalizedId),normalizedToolCall={...normalizedToolCall,id:normalizedId})}return normalizedToolCall}return block});return{...assistantMsg,content:transformedContent}}return msg}),result=[],pendingToolCalls=[],existingToolResultIds=new Set,heldSystemMessages=[],closePendingToolCalls=()=>{if(pendingToolCalls.length>0){for(let tc of pendingToolCalls)existingToolResultIds.has(tc.id)||result.push({role:"toolResult",toolCallId:tc.id,toolName:tc.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});pendingToolCalls=[],existingToolResultIds=new Set}result.push(...heldSystemMessages),heldSystemMessages.length=0};for(let i=0;i<transformed.length;i++){let msg=transformed[i];if(msg.role==="assistant"){closePendingToolCalls();let assistantMsg=msg;if(assistantMsg.stopReason==="error"||assistantMsg.stopReason==="aborted")continue;let toolCalls=assistantMsg.content.filter(b=>b.type==="toolCall");toolCalls.length>0&&(pendingToolCalls=toolCalls,existingToolResultIds=new Set),result.push(msg)}else msg.role==="toolResult"?(existingToolResultIds.add(msg.toolCallId),result.push(msg)):msg.role==="system"?pendingToolCalls.length>0?heldSystemMessages.push(msg):result.push(msg):(msg.role==="user"&&closePendingToolCalls(),result.push(msg))}return closePendingToolCalls(),result}export{getJsonSchemaToolParameters,getGrammarToolInput,appendGrammarToolInputJsonDelta,resolveJsonSchemaStrictSampling,resolveGrammarConstrainedSampling,createGrammarToolInputProperties,clampMaxTokensToContext,resolveSamplingParams,buildBaseOptions,MIN_ANSWER_TOKENS,thinkingBudgetForLevel,clampThinkingBudgetToAnswerRoom,adjustMaxTokensForThinking,splitErrorToolResultImages,transformMessages};
|
|
@@ -6,4 +6,4 @@ import{getBinDir}from"./chunk-BPNRVFVQ.js";import{accessSync,constants}from"node
|
|
|
6
6
|
|
|
7
7
|
Searched Git Bash in:
|
|
8
8
|
${paths.map(p=>` ${p}`).join(`
|
|
9
|
-
`)}`)}if(shellPathExists("/bin/bash"))return getBashShellConfig("/bin/bash");let bashOnPath=findExecutableOnPath("bash");return bashOnPath?getBashShellConfig(bashOnPath):{shell:"sh",args:["-c"]}}var POWERSHELL_ARGS=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command"];function getPowerShellConfig(){if(process.platform!=="win32")throw new Error("The powershell tool is only available on Windows.");let shell=findExecutableOnPath("pwsh.exe"),programFiles=process.env.ProgramFiles;if(!shell&&programFiles){let pwsh7=win32.join(programFiles,"PowerShell","7","pwsh.exe");shellPathExists(pwsh7)&&(shell=pwsh7)}shell??=findExecutableOnPath("powershell.exe");let systemRoot=process.env.SystemRoot;if(!shell&&systemRoot){let windowsPowerShell=win32.join(systemRoot,"System32","WindowsPowerShell","v1.0","powershell.exe");shellPathExists(windowsPowerShell)&&(shell=windowsPowerShell)}if(!shell)throw new Error("No PowerShell executable found. Install PowerShell or add powershell.exe/pwsh.exe to PATH.");return{shell,args:[...POWERSHELL_ARGS]}}function getShellEnv(){let binDir=getBinDir(),pathKey=Object.keys(process.env).find(key=>key.toLowerCase()==="path")??"PATH",currentPath=process.env[pathKey]??"",updatedPath=currentPath.split(delimiter).filter(Boolean).includes(binDir)?currentPath:[binDir,currentPath].filter(Boolean).join(delimiter);return{...process.env,[pathKey]:updatedPath}}function sanitizeBinaryOutput(str){return str.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\uFFF9-\uFFFB]/g,"")}var trackedDetachedChildPids=new Set;function trackDetachedChildPid(pid){trackedDetachedChildPids.add(pid)}function untrackDetachedChildPid(pid){trackedDetachedChildPids.delete(pid)}function killTrackedDetachedChildren(){for(let pid of trackedDetachedChildPids)killProcessTree(pid);trackedDetachedChildPids.clear()}function killProcessTree(pid){if(process.platform==="win32")try{spawn(join(process.env.SystemRoot||"C:\\Windows","System32","taskkill.exe"),["/F","/T","/PID",String(pid)],{stdio:"ignore",detached:!0,windowsHide:!0}).once("error",()=>{})}catch{}else
|
|
9
|
+
`)}`)}if(shellPathExists("/bin/bash"))return getBashShellConfig("/bin/bash");let bashOnPath=findExecutableOnPath("bash");return bashOnPath?getBashShellConfig(bashOnPath):{shell:"sh",args:["-c"]}}var POWERSHELL_ARGS=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command"];function getPowerShellConfig(){if(process.platform!=="win32")throw new Error("The powershell tool is only available on Windows.");let shell=findExecutableOnPath("pwsh.exe"),programFiles=process.env.ProgramFiles;if(!shell&&programFiles){let pwsh7=win32.join(programFiles,"PowerShell","7","pwsh.exe");shellPathExists(pwsh7)&&(shell=pwsh7)}shell??=findExecutableOnPath("powershell.exe");let systemRoot=process.env.SystemRoot;if(!shell&&systemRoot){let windowsPowerShell=win32.join(systemRoot,"System32","WindowsPowerShell","v1.0","powershell.exe");shellPathExists(windowsPowerShell)&&(shell=windowsPowerShell)}if(!shell)throw new Error("No PowerShell executable found. Install PowerShell or add powershell.exe/pwsh.exe to PATH.");return{shell,args:[...POWERSHELL_ARGS]}}function getShellEnv(){let binDir=getBinDir(),pathKey=Object.keys(process.env).find(key=>key.toLowerCase()==="path")??"PATH",currentPath=process.env[pathKey]??"",updatedPath=currentPath.split(delimiter).filter(Boolean).includes(binDir)?currentPath:[binDir,currentPath].filter(Boolean).join(delimiter);return{...process.env,[pathKey]:updatedPath}}function sanitizeBinaryOutput(str){return str.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\uFFF9-\uFFFB]/g,"")}var trackedDetachedChildPids=new Set;function trackDetachedChildPid(pid){trackedDetachedChildPids.add(pid)}function untrackDetachedChildPid(pid){trackedDetachedChildPids.delete(pid)}function killTrackedDetachedChildren(){for(let pid of trackedDetachedChildPids)killProcessTree(pid);trackedDetachedChildPids.clear()}function killProcessTree(pid){if(process.platform==="win32")try{spawn(join(process.env.SystemRoot||"C:\\Windows","System32","taskkill.exe"),["/F","/T","/PID",String(pid)],{stdio:"ignore",detached:!0,windowsHide:!0}).once("error",()=>{})}catch{}else{if(process.platform==="darwin")try{process.kill(-pid,"SIGSTOP")}catch{}try{process.kill(-pid,"SIGKILL")}catch{try{process.kill(pid,"SIGKILL")}catch{}}}}export{getShellConfig,getPowerShellConfig,getShellEnv,sanitizeBinaryOutput,trackDetachedChildPid,untrackDetachedChildPid,killTrackedDetachedChildren,killProcessTree};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __kcCreateRequire } from "node:module"; const require = __kcCreateRequire(import.meta.url);
|
|
2
|
-
import{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer}from"./chunk-
|
|
2
|
+
import{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer}from"./chunk-BWGDAXFH.js";import{ModelRuntime,ProjectTrustStore,addMcpServerConfig,loadMcpConfig,openBrowser,removeMcpServerConfig}from"./chunk-6X7IXVQH.js";import{getMcpToolExposure,validateMcpServerConfig}from"./chunk-IIWY7U5S.js";import"./chunk-CCP7VAJU.js";import"./chunk-VQBEVSZH.js";import{source_default}from"./chunk-KQKUEQJA.js";import{APP_NAME,CONFIG_DIR_NAME}from"./chunk-BPNRVFVQ.js";import"./chunk-NDQ5OW6U.js";import"./chunk-HSL72VZI.js";import"./chunk-AANBXVWQ.js";import"./chunk-6GRVIFTN.js";import"./chunk-BRKUE2MD.js";import"./chunk-FA32X2UJ.js";import"./chunk-ETOMYYZC.js";import"./chunk-UU4A4NV5.js";import"./chunk-AHB7JV5B.js";import{existsSync}from"node:fs";import{join}from"node:path";import{createInterface}from"node:readline/promises";var HELP=`${source_default.bold("Usage:")}
|
|
3
3
|
${APP_NAME} mcp add <server> [options] -- <command> [args...]
|
|
4
4
|
${APP_NAME} mcp add <server> [options] --url <url>
|
|
5
5
|
${APP_NAME} mcp remove <server> [-l]
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __kcCreateRequire } from "node:module"; const require = __kcCreateRequire(import.meta.url);
|
|
2
|
+
import{classifySystemOne}from"./chunk-N5M3XNPN.js";import{isRecord}from"./chunk-MZ5UVOTP.js";import"./chunk-4CRI7BMY.js";import"./chunk-57BPR4HF.js";import"./chunk-DVFCXHT4.js";import"./chunk-6GRVIFTN.js";import"./chunk-ETOMYYZC.js";import"./chunk-UU4A4NV5.js";import"./chunk-AHB7JV5B.js";var LABEL="Cloudflare Workers AI";function cloudflareErrorMessage(errors){if(Array.isArray(errors)){let messages=errors.map(error=>isRecord(error)&&typeof error.message=="string"?error.message:void 0).filter(message=>message!==void 0);if(messages.length>0)return`${LABEL} error: ${messages.join("; ")}`}return`${LABEL} request failed`}var transport={api:"cloudflare-workers-ai-system-one",label:LABEL,detectCompat:model=>({imageInput:model.id.startsWith("@cf/cloudflare/clef")?"images":"assets",sendImageOptInHeader:!1}),url:model=>new URL("run",`${model.baseUrl.replace(/\/+$/u,"")}/`),payload:(model,request)=>({model:model.id,input:request}),output:body=>{if(!isRecord(body))throw new Error(`${LABEL} returned an unexpected response`);if(body.success===!1)throw new Error(cloudflareErrorMessage(body.errors));let result=body.result;if(!isRecord(result))throw new Error(`${LABEL} returned an unexpected response`);if("answers"in result)return result;if(result.state!=="Completed")throw new Error(`${LABEL} run did not complete (state: ${String(result.state)})`);if(!isRecord(result.result))throw new Error(`${LABEL} returned an unexpected response`);return result.result}},classify=(model,context,options)=>classifySystemOne(transport,model,context,options);export{classify};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __kcCreateRequire } from "node:module"; const require = __kcCreateRequire(import.meta.url);
|
|
2
|
-
import{ARMIN_HEIGHT,ARMIN_WIDTH,isArminPixel}from"./chunk-RZDCZFG7.js";import{backgroundAnsi,colorToRgb,foregroundAnsi,formatKeyText,getKeybindings,indexedColor,rgbColor,theme,visibleWidth}from"./chunk-C62RVFZT.js";import"./chunk-KQKUEQJA.js";import"./chunk-BPNRVFVQ.js";import"./chunk-O6JSP6YG.js";import"./chunk-AHB7JV5B.js";var DEPTH=.7,FLY_START=.1,FLY_DURATION=1.3,START_SCALE=.1;function createModel(columns,rows,pixel,options){let blocks=[];for(let row=0;row<rows;row++)for(let column=0;column<columns;column++){let color=pixel(column,row);color&&blocks.push({home:[column,row,0],color})}return{columns,rows,blocks,cameraDistance:options.cameraDistance,radius:Math.hypot(columns/2,rows/2,1+DEPTH/2),widthShare:options.widthShare,puzzleMoves:random=>options.puzzleMoves(random,blocks.length),origin:options.origin}}function arminModel(color){return createModel(ARMIN_WIDTH,ARMIN_HEIGHT,(column,row)=>isArminPixel(column,row)?color:void 0,{cameraDistance:80,widthShare:.45,puzzleMoves:(random,blockCount)=>Math.round(blockCount*(.03+random*.04)),origin:void 0})}var PUZZLE_START=FLY_START+FLY_DURATION+3,PUZZLE_STEP=.3,PUZZLE_STEPS=12,PUZZLE_RETURN=1,PUZZLE_HOLD=.6,PUZZLE_CYCLE=PUZZLE_STEP*PUZZLE_STEPS+PUZZLE_RETURN+PUZZLE_HOLD,PUZZLE_MOVES=[[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]];function shuffleSteps(model,cycle){let{columns,rows}=model,positions=model.blocks.map(block=>block.home),steps=[positions],lastMoved=new Set,random=cycle*7919+1,next=()=>hash(random++),key=([x,y,z])=>((z+1)*rows+y)*columns+x;for(let step=0;step<PUZZLE_STEPS;step++){let occupied=new Set(positions.map(key)),nextPositions=[...positions],moved=new Set,moveCount=model.puzzleMoves(next());for(let move=0;move<moveCount;move++){let candidates=[];for(let block=0;block<positions.length;block++){if(moved.has(block))continue;let[x,y,z]=positions[block];for(let[dx,dy,dz]of PUZZLE_MOVES){let target=[x+dx,y+dy,z+dz];target[0]<0||target[0]>=columns||target[1]<0||target[1]>=rows||target[2]<-1||target[2]>1||occupied.has(key(target))||candidates.push({block,target})}}let fresh=candidates.filter(candidate=>!lastMoved.has(candidate.block)),pool=fresh.length>0?fresh:candidates,choice=pool[Math.floor(next()*pool.length)];if(!choice)break;occupied.add(key(choice.target)),nextPositions[choice.block]=choice.target,moved.add(choice.block)}lastMoved.clear();for(let block of moved)lastMoved.add(block);positions=nextPositions,steps.push(positions)}return steps}var FRAME_MS=1e3/30,DUST_DURATION=.35,WAVE_SPREAD=.55,WAVE_JITTER=.12,DISSOLVE_END=FLY_START+WAVE_SPREAD+WAVE_JITTER+DUST_DURATION,BACKGROUND_FADE=.5,EXIT_DURATION=1.1,STARS_START=2.5,STARS_FADE=2,STAR_DENSITY=.018,STAR_TINTS=[[255,255,255],[170,195,255],[255,225,170],[255,190,205]],LOGO_COLOR_STEP=5,LIGHT_HALO_STRENGTH=.3,HALO_RADIUS_X=6,HALO_RADIUS_Y=3,HALO_LEVELS=32,STAR_ALPHA_LEVELS=8,STAR_FLICKER_LEVELS=3,HINT_FADE=.5,DOT_BITS=[1,8,2,16,4,32,64,128],BRAILLE=Array.from({length:256},(_,bits)=>String.fromCharCode(10240+bits)),LIGHT=normalize([-.45,-.6,.75]),HALF_VECTOR=normalize([LIGHT[0],LIGHT[1],LIGHT[2]+1]);function normalize(v){let length=Math.hypot(v[0],v[1],v[2]);return[v[0]/length,v[1]/length,v[2]/length]}function clamp01(value){return value<0?0:value>1?1:value}function smooth(value){let t=clamp01(value);return t*t*t*(t*(t*6-15)+10)}function easeOut(value){let t=1-clamp01(value);return 1-t*t*t}function mix(a,b,amount){return[a[0]+(b[0]-a[0])*amount,a[1]+(b[1]-a[1])*amount,a[2]+(b[2]-a[2])*amount]}function hash(value){let x=Math.imul(value^2654435769,2246822507);return x^=x>>>13,x=Math.imul(x,3266489909),x^=x>>>16,(x>>>0)/4294967296}function isLight([r,g,b]){return .2126*r+.7152*g+.0722*b>128}function toRgb(color){let{r,g,b}=colorToRgb(color);return[r,g,b]}function glyphInk(text,seed){return text.trim()===""?0:/^[.,:;'`\-_·]$/.test(text)?2:/^[\u2500-\u257f]$/.test(text)?3:4+Math.floor(seed*3)}var segmenter=new Intl.Segmenter;function parseScreen(lines,width,foreground,background){let palette=index=>toRgb(indexedColor(index));return lines.map(line=>{let cells=[],fg,bg,dim=!1,inverse=!1,applySgr=params=>{let codes=params===""?["0"]:params.split(";");for(let i2=0;i2<codes.length;i2++){let parts=codes[i2].split(":").map(part=>Number.parseInt(part,10)),code=parts[0]??0;if(code===38||code===48){let args;if(parts.length>1)args=parts.slice(1).filter(part=>!Number.isNaN(part));else{let kind=Number.parseInt(codes[i2+1]??"",10),count=kind===5?2:kind===2?4:1;args=codes.slice(i2+1,i2+1+count).map(part=>Number.parseInt(part,10)),i2+=count}let color;args[0]===5&&args[1]!==void 0?color=palette(args[1]):args[0]===2&&args.length>=4&&(color=[args[1],args[2],args[3]]),color&&(code===38?fg=color:bg=color)}else code===0?(fg=void 0,bg=void 0,dim=!1,inverse=!1):code===2?dim=!0:code===22?dim=!1:code===7?inverse=!0:code===27?inverse=!1:code>=30&&code<=37?fg=palette(code-30):code>=90&&code<=97?fg=palette(code-90+8):code===39?fg=void 0:code>=40&&code<=47?bg=palette(code-40):code>=100&&code<=107?bg=palette(code-100+8):code===49&&(bg=void 0)}},pushText=text=>{for(let{segment}of segmenter.segment(text)){let glyphWidth=visibleWidth(segment);if(glyphWidth===0||cells.length+glyphWidth>width)continue;let cellFg=fg??foreground,cellBg=bg;inverse&&(cellFg=bg??background,cellBg=fg??foreground),dim&&(cellFg=mix(cellFg,cellBg??background,.4));let cell={text:segment,width:glyphWidth,fg:cellFg,bg:cellBg,delay:0,ink:0,seed:0};cells.push(cell),glyphWidth===2&&cells.push({...cell,text:"",width:0})}},i=0;for(;i<line.length;){let sequenceStart=line.indexOf("\x1B",i);if(sequenceStart===-1){pushText(line.slice(i));break}sequenceStart>i&&pushText(line.slice(i,sequenceStart));let kind=line[sequenceStart+1];if(kind==="["){let end=sequenceStart+2;for(;end<line.length&&(line.charCodeAt(end)<64||line.charCodeAt(end)>126);)end++;line[end]==="m"&&applySgr(line.slice(sequenceStart+2,end)),i=end+1}else if(kind==="]"||kind==="_"||kind==="P"||kind==="^"){let bell=line.indexOf("\x07",sequenceStart+2),st=line.indexOf("\x1B\\",sequenceStart+2);if(bell===-1&&st===-1)break;i=bell!==-1&&(st===-1||bell<st)?bell+1:st+2}else i=sequenceStart+2}return cells})}function rotation(yaw,pitch,roll){let[sy,cy,sx,cx,sz,cz]=[Math.sin(yaw),Math.cos(yaw),Math.sin(pitch),Math.cos(pitch),Math.sin(roll),Math.cos(roll)],ry=[cy,0,sy,0,1,0,-sy,0,cy],rx=[1,0,0,0,cx,-sx,0,sx,cx],rz=[cz,-sz,0,sz,cz,0,0,0,1];return multiply(rz,multiply(rx,ry))}function multiply(a,b){let result=new Array(9);for(let row=0;row<3;row++)for(let column=0;column<3;column++)result[row*3+column]=a[row*3]*b[column]+a[row*3+1]*b[3+column]+a[row*3+2]*b[6+column];return result}var SPIN_RAMP=1.4,SPIN_SPEED=Math.PI*2/PUZZLE_CYCLE,SPIN_LINGER=.6,FIRST_FRONT_VIEW=PUZZLE_START+PUZZLE_STEP*PUZZLE_STEPS+PUZZLE_RETURN+PUZZLE_HOLD/2;function baseSpinPhase(time){let elapsed=time-FLY_START;if(elapsed<=0)return 0;let u=elapsed/SPIN_RAMP;return u<1?SPIN_SPEED*SPIN_RAMP*(u**6-3*u**5+2.5*u**4):SPIN_SPEED*(SPIN_RAMP*.5+elapsed-SPIN_RAMP)}var SPIN_ALIGNMENT=Math.PI*2-baseSpinPhase(FIRST_FRONT_VIEW)%(Math.PI*2);function spinPhase(time){return baseSpinPhase(time)+SPIN_ALIGNMENT*smooth((time-FLY_START)/FLY_DURATION)}function spinAngle(time){let phase=spinPhase(time);return phase-SPIN_LINGER*Math.sin(phase)}var BlockRaster=class{bits=new Uint8Array(0);counts=new Uint8Array(0);rgb=new Float32Array(0);haloAmount=new Float32Array(0);haloRgb=new Float32Array(0);width=0;height=0;depth=new Float32Array(0);faceIds=new Uint16Array(0);dirty;haloDirty;cameraDistance;constructor(cameraDistance){this.cameraDistance=cameraDistance}render(width,height,pose,boxes,background,haloStrength){let dotWidth=width*2,dotHeight=height*4;if(width!==this.width||height!==this.height)this.width=width,this.height=height,this.bits=new Uint8Array(width*height),this.counts=new Uint8Array(width*height),this.rgb=new Float32Array(width*height*3),this.haloAmount=new Float32Array(width*height),this.haloRgb=new Float32Array(width*height*3),this.haloDirty=void 0,this.depth=new Float32Array(dotWidth*dotHeight).fill(1/0),this.faceIds=new Uint16Array(dotWidth*dotHeight),this.dirty=void 0;else if(this.dirty){let{minX:minX2,minY:minY2,maxX:maxX2,maxY:maxY2}=this.dirty;for(let row=minY2;row<=maxY2;row++)this.bits.fill(0,row*width+minX2,row*width+maxX2+1),this.counts.fill(0,row*width+minX2,row*width+maxX2+1),this.rgb.fill(0,(row*width+minX2)*3,(row*width+maxX2+1)*3);this.dirty=void 0}if(this.haloDirty){let{minX:minX2,minY:minY2,maxX:maxX2,maxY:maxY2}=this.haloDirty;for(let row=minY2;row<=maxY2;row++)this.haloAmount.fill(0,row*width+minX2,row*width+maxX2+1),this.haloRgb.fill(0,(row*width+minX2)*3,(row*width+maxX2+1)*3);this.haloDirty=void 0}let m=rotation(pose.yaw,pose.pitch,pose.roll),{centerX,centerY,scale}=pose,cameraDistance=this.cameraDistance,origin=[m[6]*cameraDistance,m[7]*cameraDistance,m[8]*cameraDistance],light=isLight(background),faces=this.visibleFaces(m,origin,pose,boxes,dotWidth,dotHeight,light);if(faces.length===0)return;let minX=dotWidth,minY=dotHeight,maxX=-1,maxY=-1;for(let face of faces)minX=Math.min(minX,face.minX),minY=Math.min(minY,face.minY),maxX=Math.max(maxX,face.maxX),maxY=Math.max(maxY,face.maxY);if(maxX<minX||maxY<minY)return;let depth=this.depth,faceIds=this.faceIds;for(let faceIndex=0;faceIndex<faces.length;faceIndex++){let face=faces[faceIndex],a=face.axis,u=(a+1)%3,v=(a+2)%3,originA=origin[a],originU=origin[u],originV=origin[v],stepA=m[a]/scale,stepU=m[u]/scale,stepV=m[v]/scale,sx=(face.minX+.5-centerX)/scale;for(let dotY=face.minY;dotY<=face.maxY;dotY++){let sy=(dotY+.5-centerY)/scale,directionA=m[a]*sx+m[3+a]*sy-m[6+a]*cameraDistance,directionU=m[u]*sx+m[3+u]*sy-m[6+u]*cameraDistance,directionV=m[v]*sx+m[3+v]*sy-m[6+v]*cameraDistance,index=dotY*dotWidth+face.minX;for(let dotX=face.minX;dotX<=face.maxX;dotX++,index++){let t=(face.plane-originA)/directionA;if(t>0&&t<depth[index]){let hitU=originU+t*directionU,hitV=originV+t*directionV;hitU>=face.uMin&&hitU<=face.uMax&&hitV>=face.vMin&&hitV<=face.vMax&&(depth[index]=t,faceIds[index]=faceIndex+1)}directionA+=stepA,directionU+=stepU,directionV+=stepV}}}let bits=this.bits,counts=this.counts,rgb=this.rgb,cellMinX=width,cellMinY=height,cellMaxX=-1,cellMaxY=-1;for(let dotY=minY;dotY<=maxY;dotY++){let index=dotY*dotWidth+minX;for(let dotX=minX;dotX<=maxX;dotX++,index++){let id=faceIds[index];if(id===0)continue;let face=faces[id-1],fog=clamp01(.15-cameraDistance*(1-depth[index])*.12)*(light?.5:1);faceIds[index]=0,depth[index]=1/0;let cellX=dotX>>1,cellY=dotY>>2,cell=cellY*width+cellX;bits[cell]|=DOT_BITS[(dotY&3)*2+(dotX&1)],counts[cell]++,rgb[cell*3]+=face.red+(background[0]-face.red)*fog,rgb[cell*3+1]+=face.green+(background[1]-face.green)*fog,rgb[cell*3+2]+=face.blue+(background[2]-face.blue)*fog,cellX<cellMinX&&(cellMinX=cellX),cellX>cellMaxX&&(cellMaxX=cellX),cellY<cellMinY&&(cellMinY=cellY),cellY>cellMaxY&&(cellMaxY=cellY)}}cellMaxX>=0&&(this.dirty={minX:cellMinX,minY:cellMinY,maxX:cellMaxX,maxY:cellMaxY}),haloStrength>0&&this.renderHalo(haloStrength)}renderHalo(strength){let cells=this.dirty;if(!cells)return;let{width,height,counts,rgb}=this,minX=Math.max(0,cells.minX-HALO_RADIUS_X),maxX=Math.min(width-1,cells.maxX+HALO_RADIUS_X),minY=Math.max(0,cells.minY-HALO_RADIUS_Y),maxY=Math.min(height-1,cells.maxY+HALO_RADIUS_Y),regionWidth=maxX-minX+1,tent=radius=>{let weights=Array.from({length:radius*2+1},(_,i)=>radius+1-Math.abs(i-radius)),total=weights.reduce((sum,weight)=>sum+weight,0);return weights.map(weight=>weight/total)},weightsX=tent(HALO_RADIUS_X),weightsY=tent(HALO_RADIUS_Y),rows=cells.maxY-cells.minY+1,horizontal=new Float32Array(rows*regionWidth*4);for(let y=cells.minY;y<=cells.maxY;y++)for(let x=minX;x<=maxX;x++){let coverage=0,red=0,green=0,blue=0;for(let dx=-HALO_RADIUS_X;dx<=HALO_RADIUS_X;dx++){let sourceX=x+dx;if(sourceX<cells.minX||sourceX>cells.maxX)continue;let source=y*width+sourceX,count=counts[source];if(count===0)continue;let weight=weightsX[dx+HALO_RADIUS_X]/8;coverage+=count*weight,red+=rgb[source*3]*weight,green+=rgb[source*3+1]*weight,blue+=rgb[source*3+2]*weight}let target=((y-cells.minY)*regionWidth+(x-minX))*4;horizontal[target]=coverage,horizontal[target+1]=red,horizontal[target+2]=green,horizontal[target+3]=blue}for(let y=minY;y<=maxY;y++)for(let x=minX;x<=maxX;x++){let coverage=0,red=0,green=0,blue=0;for(let dy=-HALO_RADIUS_Y;dy<=HALO_RADIUS_Y;dy++){let sourceY=y+dy;if(sourceY<cells.minY||sourceY>cells.maxY)continue;let weight=weightsY[dy+HALO_RADIUS_Y],source=((sourceY-cells.minY)*regionWidth+(x-minX))*4;coverage+=horizontal[source]*weight,red+=horizontal[source+1]*weight,green+=horizontal[source+2]*weight,blue+=horizontal[source+3]*weight}let target=y*width+x,count=counts[target];if(count>0&&count/8>coverage&&(coverage=count/8,red=rgb[target*3]/count*coverage,green=rgb[target*3+1]/count*coverage,blue=rgb[target*3+2]/count*coverage),coverage<=0)continue;let amount=Math.round(strength*Math.min(1,coverage)**.7*HALO_LEVELS)/HALO_LEVELS;amount<=0||(this.haloAmount[target]=amount,this.haloRgb[target*3]=Math.round(red/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP,this.haloRgb[target*3+1]=Math.round(green/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP,this.haloRgb[target*3+2]=Math.round(blue/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP)}this.haloDirty={minX,minY,maxX,maxY}}visibleFaces(m,origin,pose,boxes,dotWidth,dotHeight,lightBackground){let faces=[],cameraDistance=this.cameraDistance;for(let box of boxes)for(let a=0;a<3;a++){let u=(a+1)%3,v=(a+2)%3;for(let side of[-1,1]){let plane=side>0?box.max[a]:box.min[a];if((origin[a]-plane)*side<=0||boxes.some(other=>other!==box&&(side>0?other.min[a]:other.max[a])===plane&&other.min[u]<=box.min[u]&&other.max[u]>=box.max[u]&&other.min[v]<=box.min[v]&&other.max[v]>=box.max[v]))continue;let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0,corner=[0,0,0];for(let cornerU of[box.min[u],box.max[u]])for(let cornerV of[box.min[v],box.max[v]]){corner[a]=plane,corner[u]=cornerU,corner[v]=cornerV;let x=m[0]*corner[0]+m[1]*corner[1]+m[2]*corner[2],y=m[3]*corner[0]+m[4]*corner[1]+m[5]*corner[2],z=m[6]*corner[0]+m[7]*corner[1]+m[8]*corner[2],perspective=pose.scale*cameraDistance/(cameraDistance-z),screenX=pose.centerX+x*perspective,screenY=pose.centerY+y*perspective;minX=Math.min(minX,screenX),minY=Math.min(minY,screenY),maxX=Math.max(maxX,screenX),maxY=Math.max(maxY,screenY)}let face={minX:Math.max(0,Math.floor(minX)),minY:Math.max(0,Math.floor(minY)),maxX:Math.min(dotWidth-1,Math.ceil(maxX)),maxY:Math.min(dotHeight-1,Math.ceil(maxY))};if(face.maxX<face.minX||face.maxY<face.minY)continue;let nx=m[a]*side,ny=m[3+a]*side,nz=m[6+a]*side,diffuse=Math.max(0,nx*LIGHT[0]+ny*LIGHT[1]+nz*LIGHT[2]),rim=Math.max(0,nx*.8-nz*.3),specular=lightBackground?0:Math.max(0,nx*HALF_VECTOR[0]+ny*HALF_VECTOR[1]+nz*HALF_VECTOR[2])**24*.6*255,light=lightBackground?Math.min(1,.55+diffuse*.45+rim*.1):.45+diffuse*.78+rim*.25;faces.push({axis:a,plane,uMin:box.min[u],uMax:box.max[u],vMin:box.min[v],vMax:box.max[v],...face,red:Math.min(255,box.color[0]*light+specular),green:Math.min(255,box.color[1]*light+specular),blue:Math.min(255,box.color[2]*light+specular)})}}return faces}},playing=!1;async function playEasterEgg3d(tui,screen,egg){if(playing)return;playing=!0;let reported=await tui.queryTerminalColors({timeoutMs:100}),dark=theme.appearance==="dark",toRgbTuple=(rgb,fallback)=>rgb?[rgb.r,rgb.g,rgb.b]:fallback,colors={foreground:toRgbTuple(reported.foreground,toRgb(theme.colors.text)),background:toRgbTuple(reported.background,dark?[0,0,0]:[255,255,255])};if(tui.hasOverlay()||egg.kind!=="armin"){playing=!1;return}let model=arminModel(toRgb(theme.colors.accent)),animation=new EasterEgg3dAnimation(tui,screen,model,colors,()=>{playing=!1,overlay.hide()}),overlay=tui.showOverlay(animation,{anchor:"top-left",width:"100%",maxHeight:"100%"})}var EasterEgg3dAnimation=class{tui;screen;model;foreground;background;onDone;startTime=performance.now();lastRender=performance.now();timer;exit;shuffle;screenWidth=-1;screenHeight=-1;stars=[];cells=[];ansiCache=new Map;raster;constructor(tui,screen,model,colors,onDone){this.tui=tui,this.screen=screen,this.model=model,this.raster=new BlockRaster(model.cameraDistance),this.foreground=colors.foreground,this.background=colors.background,this.onDone=onDone,this.timer=setInterval(()=>{this.exit&&this.exitProgress()>=1||performance.now()-this.lastRender>1e3?this.finish():this.tui.requestRender()},FRAME_MS),this.timer.unref?.()}close(){if(this.exit){this.finish();return}let time=this.elapsed(),yaw=spinAngle(time),turn=Math.PI*2;this.exit={start:performance.now(),time,yaw,targetYaw:Math.ceil(yaw/turn)*turn,offsets:this.blockOffsets(time)}}handleInput(data){let keybindings=getKeybindings();(keybindings.matches(data,"tui.select.cancel")||keybindings.matches(data,"app.clear"))&&this.close()}handleMouse(event){return event.type==="click"&&this.close(),{handled:!0,render:!1}}invalidate(){this.screenWidth=-1,this.screenHeight=-1,this.ansiCache.clear()}render(width){let height=Math.max(1,this.tui.terminal.rows),foreground=this.foreground,background=this.background;this.lastRender=performance.now(),(width!==this.screenWidth||height!==this.screenHeight)&&(this.screenWidth=width,this.screenHeight=height,this.cells=this.prepareCells(width,foreground),this.stars=this.prepareStars(width,height));let dissolveTime,pose,hintAlpha,starAlpha,offsets;if(this.exit){let progress=this.exitProgress(),landing=clamp01(progress/.8),settle=1-smooth(landing);dissolveTime=Math.min(this.exit.time,DISSOLVE_END)*(1-progress),pose=this.pose(width,height,this.flyProgress(this.exit.time)*settle,this.exit.time),pose.yaw=this.exit.yaw+(this.exit.targetYaw-this.exit.yaw)*easeOut(landing),pose.pitch*=settle,pose.roll*=settle,hintAlpha=this.hintAlpha(this.exit.time)*(1-smooth(progress/.2)),starAlpha=this.starAlpha(this.exit.time)*(1-smooth(progress/.3));let gather=1-smooth(progress/.5);offsets=this.exit.offsets.map(([x,y,z])=>[x*gather,y*gather,z*gather])}else{let time=this.elapsed();dissolveTime=time,pose=this.pose(width,height,this.flyProgress(time),time),hintAlpha=this.hintAlpha(time),starAlpha=this.starAlpha(time),offsets=this.blockOffsets(time)}let{columns,rows}=this.model,boxes=this.model.blocks.map((block,index)=>{let[dx,dy,dz]=offsets[index],x=block.home[0]-columns/2+dx,y=block.home[1]-rows/2+dy;return{min:[x,y,dz-DEPTH/2],max:[x+1,y+1,dz+DEPTH/2],color:block.color}}),raster=this.raster;raster.render(width,height,pose,boxes,background,isLight(background)?LIGHT_HALO_STRENGTH:0);let halo=(index,base)=>{let amount=raster.haloAmount[index];if(amount<=0)return base;let color=raster.haloRgb;return mix(base??background,[color[index*3],color[index*3+1],color[index*3+2]],amount)},backgroundFade=smooth(dissolveTime/BACKGROUND_FADE),textFade=smooth(dissolveTime/.6)*.3,textActive=dissolveTime<DISSOLVE_END||backgroundFade<1,hint=this.hint(width,height,hintAlpha,background),frame=Math.floor(dissolveTime*14),now=this.elapsed(),starLevel=Math.round(starAlpha*STAR_ALPHA_LEVELS)/STAR_ALPHA_LEVELS,starfield=index=>{if(starLevel<=0)return;let star=this.stars[index];if(!star)return;let flicker=Math.round((.5+.5*Math.sin(now*star.speed+star.phase))*STAR_FLICKER_LEVELS)/STAR_FLICKER_LEVELS;return{text:star.glyph,fg:mix(background,mix(foreground,star.tint,.5),star.strength*(.7+.3*flicker)*starLevel)}},lines=[];for(let row=0;row<height;row++){let cells=this.cells[row]??[],line="",currentFg=-1,currentBg=-1,emit=(text,fg,bg)=>{let fgKey=fg?this.pack(fg):-1,bgKey=bg?this.pack(bg):-1;fgKey!==currentFg&&text!==" "&&(line+=fg?this.ansi(fgKey,!1):"\x1B[39m",currentFg=fgKey),bgKey!==currentBg&&(line+=bg?this.ansi(bgKey,!0):"\x1B[49m",currentBg=bgKey),line+=text};for(let column=0;column<width;column++){let index=row*width+column,cell=textActive?cells[column]:void 0,cellBg=halo(index,cell?.bg&&backgroundFade<1?mix(cell.bg,background,backgroundFade):void 0);if(hint&&row===hint.row&&column>=hint.start&&column<hint.start+hint.text.length){let offset=column-hint.start;emit(hint.text[offset],offset<hint.keyLength?hint.keyColor:hint.color,cellBg);continue}let dots=raster.bits[index];if(dots){let step=LOGO_COLOR_STEP*raster.counts[index],rgb=raster.rgb,color=[Math.round(rgb[index*3]/step)*LOGO_COLOR_STEP,Math.round(rgb[index*3+1]/step)*LOGO_COLOR_STEP,Math.round(rgb[index*3+2]/step)*LOGO_COLOR_STEP];emit(BRAILLE[dots],color,cellBg);continue}if(!cell){let star=starfield(index);emit(star?.text??" ",star?.fg,cellBg);continue}let dust=(dissolveTime-cell.delay)/DUST_DURATION;if(dust<0&&cell.width===2&&!raster.bits[index+1]){emit(cell.text,mix(cell.fg,background,textFade),cellBg),column++;continue}if(dust<0&&cell.width===1){emit(cell.text,mix(cell.fg,background,textFade),cellBg);continue}let dotCount=dust<0?cell.ink:Math.round(cell.ink*(1-clamp01(dust)));if(dotCount<=0){let star=starfield(index);emit(star?.text??" ",star?.fg,cellBg);continue}let bits=0,placed=0;for(let attempt=0;placed<dotCount&&attempt<32;attempt++){let bit=DOT_BITS[Math.floor(hash(cell.seed*7919+frame*131+attempt)*8)];bits&bit||(bits|=bit,placed++)}let fade=textFade+(1-textFade)*clamp01(dust)**.8;emit(BRAILLE[bits],mix(cell.fg,background,fade),cellBg)}lines.push(`${line}\x1B[0m`)}return lines}elapsed(){return(performance.now()-this.startTime)/1e3}exitProgress(){return this.exit?clamp01((performance.now()-this.exit.start)/1e3/EXIT_DURATION):0}finish(){this.timer&&(clearInterval(this.timer),this.timer=void 0,this.onDone())}blockOffsets(time){let blocks=this.model.blocks,home=()=>blocks.map(()=>[0,0,0]);if(time<PUZZLE_START)return home();let cycle=Math.floor((time-PUZZLE_START)/PUZZLE_CYCLE),local=time-PUZZLE_START-cycle*PUZZLE_CYCLE;this.shuffle?.cycle!==cycle&&(this.shuffle={cycle,steps:shuffleSteps(this.model,cycle)});let steps=this.shuffle.steps,offset=(position,index)=>{let block=blocks[index].home;return[position[0]-block[0],position[1]-block[1],position[2]-block[2]]},shuffleEnd=PUZZLE_STEP*PUZZLE_STEPS;if(local<shuffleEnd){let step=Math.floor(local/PUZZLE_STEP),progress=smooth((local-step*PUZZLE_STEP)/PUZZLE_STEP);return steps[step].map((from,index)=>{let a=offset(from,index),b=offset(steps[step+1][index],index);return[a[0]+(b[0]-a[0])*progress,a[1]+(b[1]-a[1])*progress,a[2]+(b[2]-a[2])*progress]})}if(local<shuffleEnd+PUZZLE_RETURN){let u=(local-shuffleEnd)/PUZZLE_RETURN,remaining=1-smooth(u),arc=Math.sin(Math.PI*clamp01(u))*.8;return steps[PUZZLE_STEPS].map((position,index)=>{let[x,y,z]=offset(position,index);return[x*remaining,y*remaining,z*remaining+(index%2===0?arc:-arc)]})}return home()}flyProgress(time){return smooth((time-FLY_START)/FLY_DURATION)}starAlpha(time){return smooth((time-STARS_START)/STARS_FADE)}hintAlpha(time){return smooth((time-FLY_START-FLY_DURATION)/HINT_FADE)}pose(width,height,progress,time){let{columns,rows,cameraDistance,radius,widthShare,origin}=this.model,reach=radius*(cameraDistance/(cameraDistance-radius)),startScale=origin?2*(cameraDistance-DEPTH/2)/cameraDistance:START_SCALE,endScale=Math.max(startScale,Math.min(width*2*widthShare,(height*4-8)*.48)/reach),endX=width,endY=height*2-2,startX=origin?origin.column*2+columns:endX,startY=origin?origin.row*4+rows:endY;return{centerX:startX+(endX-startX)*progress,centerY:startY+(endY-startY)*progress,scale:startScale*(endScale/startScale)**progress,yaw:spinAngle(time),pitch:.3*Math.sin(spinPhase(time))*progress,roll:.06*Math.sin(2*spinPhase(time))*progress}}hint(width,height,alpha,background){if(alpha<=0)return;let key=formatKeyText(getKeybindings().getKeys("tui.select.cancel")[0]??"escape"),text=`${key} to return`;if(!(text.length>width))return{row:height-2,start:Math.floor((width-text.length)/2),text,keyLength:key.length,keyColor:mix(background,toRgb(theme.colors.muted),alpha),color:mix(background,toRgb(theme.colors.dim),alpha)}}prepareStars(width,height){let stars=new Array(width*height);for(let index=0;index<width*height;index++){if(hash(index*3+20973)>=STAR_DENSITY)continue;let random=salt=>hash(index*7+salt*40503);stars[index]={glyph:BRAILLE[DOT_BITS[Math.floor(random(1)*8)]],tint:STAR_TINTS[Math.floor(random(2)*STAR_TINTS.length)],strength:.1+random(3)*.12,phase:random(4)*Math.PI*2,speed:.4+random(5)*.8}}return stars}prepareCells(width,foreground){let cells=parseScreen(this.screen,width,foreground,this.background),height=Math.max(1,this.tui.terminal.rows),{columns,rows,origin}=this.model,centerX=origin?origin.column+columns/2:width/2,centerY=origin?origin.row+rows/4:height/2,farthest=Math.hypot(Math.max(centerX,width-centerX),Math.max(centerY,height-centerY)*2);for(let row=0;row<cells.length;row++){let line=cells[row];for(let column=0;column<line.length;column++){let cell=line[column],owner=cell.width===0?line[column-1]:cell,seed=hash(row*65537+column);if(cell.width!==0){let distance=Math.hypot(column-centerX,(row-centerY)*2)/farthest;cell.delay=FLY_START+distance*WAVE_SPREAD+seed*WAVE_JITTER}else cell.delay=owner.delay;cell.seed=row*65537+column,cell.ink=glyphInk(owner.text,seed)}}if(origin)for(let row=origin.row;row<origin.row+Math.ceil(rows/2);row++){let line=cells[row];if(line)for(let column=origin.column;column<origin.column+columns;column++){let cell=line[column];cell&&(cell.text=" ",cell.width=1,cell.ink=0,cell.bg=void 0)}}return cells}pack(color){return Math.round(color[0])<<16|Math.round(color[1])<<8|Math.round(color[2])}ansi(key,isBackground){let cacheKey=key*2+(isBackground?1:0),value=this.ansiCache.get(cacheKey);if(value===void 0){let color=rgbColor(key>>16&255,key>>8&255,key&255),mode=theme.getColorMode();value=isBackground?backgroundAnsi(color,mode):foregroundAnsi(color,mode),this.ansiCache.set(cacheKey,value)}return value}};export{EasterEgg3dAnimation,playEasterEgg3d};
|
|
2
|
+
import{ARMIN_HEIGHT,ARMIN_WIDTH,isArminPixel}from"./chunk-B7A4GIBK.js";import{backgroundAnsi,colorToRgb,foregroundAnsi,formatKeyText,getKeybindings,indexedColor,rgbColor,theme,visibleWidth}from"./chunk-L6QGGIZG.js";import"./chunk-KQKUEQJA.js";import"./chunk-BPNRVFVQ.js";import"./chunk-O6JSP6YG.js";import"./chunk-AHB7JV5B.js";var DEPTH=.7,FLY_START=.1,FLY_DURATION=1.3,START_SCALE=.1;function createModel(columns,rows,pixel,options){let blocks=[];for(let row=0;row<rows;row++)for(let column=0;column<columns;column++){let color=pixel(column,row);color&&blocks.push({home:[column,row,0],color})}return{columns,rows,blocks,cameraDistance:options.cameraDistance,radius:Math.hypot(columns/2,rows/2,1+DEPTH/2),widthShare:options.widthShare,puzzleMoves:random=>options.puzzleMoves(random,blocks.length),origin:options.origin}}function arminModel(color){return createModel(ARMIN_WIDTH,ARMIN_HEIGHT,(column,row)=>isArminPixel(column,row)?color:void 0,{cameraDistance:80,widthShare:.45,puzzleMoves:(random,blockCount)=>Math.round(blockCount*(.03+random*.04)),origin:void 0})}var PUZZLE_START=FLY_START+FLY_DURATION+3,PUZZLE_STEP=.3,PUZZLE_STEPS=12,PUZZLE_RETURN=1,PUZZLE_HOLD=.6,PUZZLE_CYCLE=PUZZLE_STEP*PUZZLE_STEPS+PUZZLE_RETURN+PUZZLE_HOLD,PUZZLE_MOVES=[[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]];function shuffleSteps(model,cycle){let{columns,rows}=model,positions=model.blocks.map(block=>block.home),steps=[positions],lastMoved=new Set,random=cycle*7919+1,next=()=>hash(random++),key=([x,y,z])=>((z+1)*rows+y)*columns+x;for(let step=0;step<PUZZLE_STEPS;step++){let occupied=new Set(positions.map(key)),nextPositions=[...positions],moved=new Set,moveCount=model.puzzleMoves(next());for(let move=0;move<moveCount;move++){let candidates=[];for(let block=0;block<positions.length;block++){if(moved.has(block))continue;let[x,y,z]=positions[block];for(let[dx,dy,dz]of PUZZLE_MOVES){let target=[x+dx,y+dy,z+dz];target[0]<0||target[0]>=columns||target[1]<0||target[1]>=rows||target[2]<-1||target[2]>1||occupied.has(key(target))||candidates.push({block,target})}}let fresh=candidates.filter(candidate=>!lastMoved.has(candidate.block)),pool=fresh.length>0?fresh:candidates,choice=pool[Math.floor(next()*pool.length)];if(!choice)break;occupied.add(key(choice.target)),nextPositions[choice.block]=choice.target,moved.add(choice.block)}lastMoved.clear();for(let block of moved)lastMoved.add(block);positions=nextPositions,steps.push(positions)}return steps}var FRAME_MS=1e3/30,DUST_DURATION=.35,WAVE_SPREAD=.55,WAVE_JITTER=.12,DISSOLVE_END=FLY_START+WAVE_SPREAD+WAVE_JITTER+DUST_DURATION,BACKGROUND_FADE=.5,EXIT_DURATION=1.1,STARS_START=2.5,STARS_FADE=2,STAR_DENSITY=.018,STAR_TINTS=[[255,255,255],[170,195,255],[255,225,170],[255,190,205]],LOGO_COLOR_STEP=5,LIGHT_HALO_STRENGTH=.3,HALO_RADIUS_X=6,HALO_RADIUS_Y=3,HALO_LEVELS=32,STAR_ALPHA_LEVELS=8,STAR_FLICKER_LEVELS=3,HINT_FADE=.5,DOT_BITS=[1,8,2,16,4,32,64,128],BRAILLE=Array.from({length:256},(_,bits)=>String.fromCharCode(10240+bits)),LIGHT=normalize([-.45,-.6,.75]),HALF_VECTOR=normalize([LIGHT[0],LIGHT[1],LIGHT[2]+1]);function normalize(v){let length=Math.hypot(v[0],v[1],v[2]);return[v[0]/length,v[1]/length,v[2]/length]}function clamp01(value){return value<0?0:value>1?1:value}function smooth(value){let t=clamp01(value);return t*t*t*(t*(t*6-15)+10)}function easeOut(value){let t=1-clamp01(value);return 1-t*t*t}function mix(a,b,amount){return[a[0]+(b[0]-a[0])*amount,a[1]+(b[1]-a[1])*amount,a[2]+(b[2]-a[2])*amount]}function hash(value){let x=Math.imul(value^2654435769,2246822507);return x^=x>>>13,x=Math.imul(x,3266489909),x^=x>>>16,(x>>>0)/4294967296}function isLight([r,g,b]){return .2126*r+.7152*g+.0722*b>128}function toRgb(color){let{r,g,b}=colorToRgb(color);return[r,g,b]}function glyphInk(text,seed){return text.trim()===""?0:/^[.,:;'`\-_·]$/.test(text)?2:/^[\u2500-\u257f]$/.test(text)?3:4+Math.floor(seed*3)}var segmenter=new Intl.Segmenter;function parseScreen(lines,width,foreground,background){let palette=index=>toRgb(indexedColor(index));return lines.map(line=>{let cells=[],fg,bg,dim=!1,inverse=!1,applySgr=params=>{let codes=params===""?["0"]:params.split(";");for(let i2=0;i2<codes.length;i2++){let parts=codes[i2].split(":").map(part=>Number.parseInt(part,10)),code=parts[0]??0;if(code===38||code===48){let args;if(parts.length>1)args=parts.slice(1).filter(part=>!Number.isNaN(part));else{let kind=Number.parseInt(codes[i2+1]??"",10),count=kind===5?2:kind===2?4:1;args=codes.slice(i2+1,i2+1+count).map(part=>Number.parseInt(part,10)),i2+=count}let color;args[0]===5&&args[1]!==void 0?color=palette(args[1]):args[0]===2&&args.length>=4&&(color=[args[1],args[2],args[3]]),color&&(code===38?fg=color:bg=color)}else code===0?(fg=void 0,bg=void 0,dim=!1,inverse=!1):code===2?dim=!0:code===22?dim=!1:code===7?inverse=!0:code===27?inverse=!1:code>=30&&code<=37?fg=palette(code-30):code>=90&&code<=97?fg=palette(code-90+8):code===39?fg=void 0:code>=40&&code<=47?bg=palette(code-40):code>=100&&code<=107?bg=palette(code-100+8):code===49&&(bg=void 0)}},pushText=text=>{for(let{segment}of segmenter.segment(text)){let glyphWidth=visibleWidth(segment);if(glyphWidth===0||cells.length+glyphWidth>width)continue;let cellFg=fg??foreground,cellBg=bg;inverse&&(cellFg=bg??background,cellBg=fg??foreground),dim&&(cellFg=mix(cellFg,cellBg??background,.4));let cell={text:segment,width:glyphWidth,fg:cellFg,bg:cellBg,delay:0,ink:0,seed:0};cells.push(cell),glyphWidth===2&&cells.push({...cell,text:"",width:0})}},i=0;for(;i<line.length;){let sequenceStart=line.indexOf("\x1B",i);if(sequenceStart===-1){pushText(line.slice(i));break}sequenceStart>i&&pushText(line.slice(i,sequenceStart));let kind=line[sequenceStart+1];if(kind==="["){let end=sequenceStart+2;for(;end<line.length&&(line.charCodeAt(end)<64||line.charCodeAt(end)>126);)end++;line[end]==="m"&&applySgr(line.slice(sequenceStart+2,end)),i=end+1}else if(kind==="]"||kind==="_"||kind==="P"||kind==="^"){let bell=line.indexOf("\x07",sequenceStart+2),st=line.indexOf("\x1B\\",sequenceStart+2);if(bell===-1&&st===-1)break;i=bell!==-1&&(st===-1||bell<st)?bell+1:st+2}else i=sequenceStart+2}return cells})}function rotation(yaw,pitch,roll){let[sy,cy,sx,cx,sz,cz]=[Math.sin(yaw),Math.cos(yaw),Math.sin(pitch),Math.cos(pitch),Math.sin(roll),Math.cos(roll)],ry=[cy,0,sy,0,1,0,-sy,0,cy],rx=[1,0,0,0,cx,-sx,0,sx,cx],rz=[cz,-sz,0,sz,cz,0,0,0,1];return multiply(rz,multiply(rx,ry))}function multiply(a,b){let result=new Array(9);for(let row=0;row<3;row++)for(let column=0;column<3;column++)result[row*3+column]=a[row*3]*b[column]+a[row*3+1]*b[3+column]+a[row*3+2]*b[6+column];return result}var SPIN_RAMP=1.4,SPIN_SPEED=Math.PI*2/PUZZLE_CYCLE,SPIN_LINGER=.6,FIRST_FRONT_VIEW=PUZZLE_START+PUZZLE_STEP*PUZZLE_STEPS+PUZZLE_RETURN+PUZZLE_HOLD/2;function baseSpinPhase(time){let elapsed=time-FLY_START;if(elapsed<=0)return 0;let u=elapsed/SPIN_RAMP;return u<1?SPIN_SPEED*SPIN_RAMP*(u**6-3*u**5+2.5*u**4):SPIN_SPEED*(SPIN_RAMP*.5+elapsed-SPIN_RAMP)}var SPIN_ALIGNMENT=Math.PI*2-baseSpinPhase(FIRST_FRONT_VIEW)%(Math.PI*2);function spinPhase(time){return baseSpinPhase(time)+SPIN_ALIGNMENT*smooth((time-FLY_START)/FLY_DURATION)}function spinAngle(time){let phase=spinPhase(time);return phase-SPIN_LINGER*Math.sin(phase)}var BlockRaster=class{bits=new Uint8Array(0);counts=new Uint8Array(0);rgb=new Float32Array(0);haloAmount=new Float32Array(0);haloRgb=new Float32Array(0);width=0;height=0;depth=new Float32Array(0);faceIds=new Uint16Array(0);dirty;haloDirty;cameraDistance;constructor(cameraDistance){this.cameraDistance=cameraDistance}render(width,height,pose,boxes,background,haloStrength){let dotWidth=width*2,dotHeight=height*4;if(width!==this.width||height!==this.height)this.width=width,this.height=height,this.bits=new Uint8Array(width*height),this.counts=new Uint8Array(width*height),this.rgb=new Float32Array(width*height*3),this.haloAmount=new Float32Array(width*height),this.haloRgb=new Float32Array(width*height*3),this.haloDirty=void 0,this.depth=new Float32Array(dotWidth*dotHeight).fill(1/0),this.faceIds=new Uint16Array(dotWidth*dotHeight),this.dirty=void 0;else if(this.dirty){let{minX:minX2,minY:minY2,maxX:maxX2,maxY:maxY2}=this.dirty;for(let row=minY2;row<=maxY2;row++)this.bits.fill(0,row*width+minX2,row*width+maxX2+1),this.counts.fill(0,row*width+minX2,row*width+maxX2+1),this.rgb.fill(0,(row*width+minX2)*3,(row*width+maxX2+1)*3);this.dirty=void 0}if(this.haloDirty){let{minX:minX2,minY:minY2,maxX:maxX2,maxY:maxY2}=this.haloDirty;for(let row=minY2;row<=maxY2;row++)this.haloAmount.fill(0,row*width+minX2,row*width+maxX2+1),this.haloRgb.fill(0,(row*width+minX2)*3,(row*width+maxX2+1)*3);this.haloDirty=void 0}let m=rotation(pose.yaw,pose.pitch,pose.roll),{centerX,centerY,scale}=pose,cameraDistance=this.cameraDistance,origin=[m[6]*cameraDistance,m[7]*cameraDistance,m[8]*cameraDistance],light=isLight(background),faces=this.visibleFaces(m,origin,pose,boxes,dotWidth,dotHeight,light);if(faces.length===0)return;let minX=dotWidth,minY=dotHeight,maxX=-1,maxY=-1;for(let face of faces)minX=Math.min(minX,face.minX),minY=Math.min(minY,face.minY),maxX=Math.max(maxX,face.maxX),maxY=Math.max(maxY,face.maxY);if(maxX<minX||maxY<minY)return;let depth=this.depth,faceIds=this.faceIds;for(let faceIndex=0;faceIndex<faces.length;faceIndex++){let face=faces[faceIndex],a=face.axis,u=(a+1)%3,v=(a+2)%3,originA=origin[a],originU=origin[u],originV=origin[v],stepA=m[a]/scale,stepU=m[u]/scale,stepV=m[v]/scale,sx=(face.minX+.5-centerX)/scale;for(let dotY=face.minY;dotY<=face.maxY;dotY++){let sy=(dotY+.5-centerY)/scale,directionA=m[a]*sx+m[3+a]*sy-m[6+a]*cameraDistance,directionU=m[u]*sx+m[3+u]*sy-m[6+u]*cameraDistance,directionV=m[v]*sx+m[3+v]*sy-m[6+v]*cameraDistance,index=dotY*dotWidth+face.minX;for(let dotX=face.minX;dotX<=face.maxX;dotX++,index++){let t=(face.plane-originA)/directionA;if(t>0&&t<depth[index]){let hitU=originU+t*directionU,hitV=originV+t*directionV;hitU>=face.uMin&&hitU<=face.uMax&&hitV>=face.vMin&&hitV<=face.vMax&&(depth[index]=t,faceIds[index]=faceIndex+1)}directionA+=stepA,directionU+=stepU,directionV+=stepV}}}let bits=this.bits,counts=this.counts,rgb=this.rgb,cellMinX=width,cellMinY=height,cellMaxX=-1,cellMaxY=-1;for(let dotY=minY;dotY<=maxY;dotY++){let index=dotY*dotWidth+minX;for(let dotX=minX;dotX<=maxX;dotX++,index++){let id=faceIds[index];if(id===0)continue;let face=faces[id-1],fog=clamp01(.15-cameraDistance*(1-depth[index])*.12)*(light?.5:1);faceIds[index]=0,depth[index]=1/0;let cellX=dotX>>1,cellY=dotY>>2,cell=cellY*width+cellX;bits[cell]|=DOT_BITS[(dotY&3)*2+(dotX&1)],counts[cell]++,rgb[cell*3]+=face.red+(background[0]-face.red)*fog,rgb[cell*3+1]+=face.green+(background[1]-face.green)*fog,rgb[cell*3+2]+=face.blue+(background[2]-face.blue)*fog,cellX<cellMinX&&(cellMinX=cellX),cellX>cellMaxX&&(cellMaxX=cellX),cellY<cellMinY&&(cellMinY=cellY),cellY>cellMaxY&&(cellMaxY=cellY)}}cellMaxX>=0&&(this.dirty={minX:cellMinX,minY:cellMinY,maxX:cellMaxX,maxY:cellMaxY}),haloStrength>0&&this.renderHalo(haloStrength)}renderHalo(strength){let cells=this.dirty;if(!cells)return;let{width,height,counts,rgb}=this,minX=Math.max(0,cells.minX-HALO_RADIUS_X),maxX=Math.min(width-1,cells.maxX+HALO_RADIUS_X),minY=Math.max(0,cells.minY-HALO_RADIUS_Y),maxY=Math.min(height-1,cells.maxY+HALO_RADIUS_Y),regionWidth=maxX-minX+1,tent=radius=>{let weights=Array.from({length:radius*2+1},(_,i)=>radius+1-Math.abs(i-radius)),total=weights.reduce((sum,weight)=>sum+weight,0);return weights.map(weight=>weight/total)},weightsX=tent(HALO_RADIUS_X),weightsY=tent(HALO_RADIUS_Y),rows=cells.maxY-cells.minY+1,horizontal=new Float32Array(rows*regionWidth*4);for(let y=cells.minY;y<=cells.maxY;y++)for(let x=minX;x<=maxX;x++){let coverage=0,red=0,green=0,blue=0;for(let dx=-HALO_RADIUS_X;dx<=HALO_RADIUS_X;dx++){let sourceX=x+dx;if(sourceX<cells.minX||sourceX>cells.maxX)continue;let source=y*width+sourceX,count=counts[source];if(count===0)continue;let weight=weightsX[dx+HALO_RADIUS_X]/8;coverage+=count*weight,red+=rgb[source*3]*weight,green+=rgb[source*3+1]*weight,blue+=rgb[source*3+2]*weight}let target=((y-cells.minY)*regionWidth+(x-minX))*4;horizontal[target]=coverage,horizontal[target+1]=red,horizontal[target+2]=green,horizontal[target+3]=blue}for(let y=minY;y<=maxY;y++)for(let x=minX;x<=maxX;x++){let coverage=0,red=0,green=0,blue=0;for(let dy=-HALO_RADIUS_Y;dy<=HALO_RADIUS_Y;dy++){let sourceY=y+dy;if(sourceY<cells.minY||sourceY>cells.maxY)continue;let weight=weightsY[dy+HALO_RADIUS_Y],source=((sourceY-cells.minY)*regionWidth+(x-minX))*4;coverage+=horizontal[source]*weight,red+=horizontal[source+1]*weight,green+=horizontal[source+2]*weight,blue+=horizontal[source+3]*weight}let target=y*width+x,count=counts[target];if(count>0&&count/8>coverage&&(coverage=count/8,red=rgb[target*3]/count*coverage,green=rgb[target*3+1]/count*coverage,blue=rgb[target*3+2]/count*coverage),coverage<=0)continue;let amount=Math.round(strength*Math.min(1,coverage)**.7*HALO_LEVELS)/HALO_LEVELS;amount<=0||(this.haloAmount[target]=amount,this.haloRgb[target*3]=Math.round(red/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP,this.haloRgb[target*3+1]=Math.round(green/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP,this.haloRgb[target*3+2]=Math.round(blue/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP)}this.haloDirty={minX,minY,maxX,maxY}}visibleFaces(m,origin,pose,boxes,dotWidth,dotHeight,lightBackground){let faces=[],cameraDistance=this.cameraDistance;for(let box of boxes)for(let a=0;a<3;a++){let u=(a+1)%3,v=(a+2)%3;for(let side of[-1,1]){let plane=side>0?box.max[a]:box.min[a];if((origin[a]-plane)*side<=0||boxes.some(other=>other!==box&&(side>0?other.min[a]:other.max[a])===plane&&other.min[u]<=box.min[u]&&other.max[u]>=box.max[u]&&other.min[v]<=box.min[v]&&other.max[v]>=box.max[v]))continue;let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0,corner=[0,0,0];for(let cornerU of[box.min[u],box.max[u]])for(let cornerV of[box.min[v],box.max[v]]){corner[a]=plane,corner[u]=cornerU,corner[v]=cornerV;let x=m[0]*corner[0]+m[1]*corner[1]+m[2]*corner[2],y=m[3]*corner[0]+m[4]*corner[1]+m[5]*corner[2],z=m[6]*corner[0]+m[7]*corner[1]+m[8]*corner[2],perspective=pose.scale*cameraDistance/(cameraDistance-z),screenX=pose.centerX+x*perspective,screenY=pose.centerY+y*perspective;minX=Math.min(minX,screenX),minY=Math.min(minY,screenY),maxX=Math.max(maxX,screenX),maxY=Math.max(maxY,screenY)}let face={minX:Math.max(0,Math.floor(minX)),minY:Math.max(0,Math.floor(minY)),maxX:Math.min(dotWidth-1,Math.ceil(maxX)),maxY:Math.min(dotHeight-1,Math.ceil(maxY))};if(face.maxX<face.minX||face.maxY<face.minY)continue;let nx=m[a]*side,ny=m[3+a]*side,nz=m[6+a]*side,diffuse=Math.max(0,nx*LIGHT[0]+ny*LIGHT[1]+nz*LIGHT[2]),rim=Math.max(0,nx*.8-nz*.3),specular=lightBackground?0:Math.max(0,nx*HALF_VECTOR[0]+ny*HALF_VECTOR[1]+nz*HALF_VECTOR[2])**24*.6*255,light=lightBackground?Math.min(1,.55+diffuse*.45+rim*.1):.45+diffuse*.78+rim*.25;faces.push({axis:a,plane,uMin:box.min[u],uMax:box.max[u],vMin:box.min[v],vMax:box.max[v],...face,red:Math.min(255,box.color[0]*light+specular),green:Math.min(255,box.color[1]*light+specular),blue:Math.min(255,box.color[2]*light+specular)})}}return faces}},playing=!1;async function playEasterEgg3d(tui,screen,egg){if(playing)return;playing=!0;let reported=await tui.queryTerminalColors({timeoutMs:100}),dark=theme.appearance==="dark",toRgbTuple=(rgb,fallback)=>rgb?[rgb.r,rgb.g,rgb.b]:fallback,colors={foreground:toRgbTuple(reported.foreground,toRgb(theme.colors.text)),background:toRgbTuple(reported.background,dark?[0,0,0]:[255,255,255])};if(tui.hasOverlay()||egg.kind!=="armin"){playing=!1;return}let model=arminModel(toRgb(theme.colors.accent)),animation=new EasterEgg3dAnimation(tui,screen,model,colors,()=>{playing=!1,overlay.hide()}),overlay=tui.showOverlay(animation,{anchor:"top-left",width:"100%",maxHeight:"100%"})}var EasterEgg3dAnimation=class{tui;screen;model;foreground;background;onDone;startTime=performance.now();lastRender=performance.now();timer;exit;shuffle;screenWidth=-1;screenHeight=-1;stars=[];cells=[];ansiCache=new Map;raster;constructor(tui,screen,model,colors,onDone){this.tui=tui,this.screen=screen,this.model=model,this.raster=new BlockRaster(model.cameraDistance),this.foreground=colors.foreground,this.background=colors.background,this.onDone=onDone,this.timer=setInterval(()=>{this.exit&&this.exitProgress()>=1||performance.now()-this.lastRender>1e3?this.finish():this.tui.requestRender()},FRAME_MS),this.timer.unref?.()}close(){if(this.exit){this.finish();return}let time=this.elapsed(),yaw=spinAngle(time),turn=Math.PI*2;this.exit={start:performance.now(),time,yaw,targetYaw:Math.ceil(yaw/turn)*turn,offsets:this.blockOffsets(time)}}handleInput(data){let keybindings=getKeybindings();(keybindings.matches(data,"tui.select.cancel")||keybindings.matches(data,"app.clear"))&&this.close()}handleMouse(event){return event.type==="click"&&this.close(),{handled:!0,render:!1}}invalidate(){this.screenWidth=-1,this.screenHeight=-1,this.ansiCache.clear()}render(width){let height=Math.max(1,this.tui.terminal.rows),foreground=this.foreground,background=this.background;this.lastRender=performance.now(),(width!==this.screenWidth||height!==this.screenHeight)&&(this.screenWidth=width,this.screenHeight=height,this.cells=this.prepareCells(width,foreground),this.stars=this.prepareStars(width,height));let dissolveTime,pose,hintAlpha,starAlpha,offsets;if(this.exit){let progress=this.exitProgress(),landing=clamp01(progress/.8),settle=1-smooth(landing);dissolveTime=Math.min(this.exit.time,DISSOLVE_END)*(1-progress),pose=this.pose(width,height,this.flyProgress(this.exit.time)*settle,this.exit.time),pose.yaw=this.exit.yaw+(this.exit.targetYaw-this.exit.yaw)*easeOut(landing),pose.pitch*=settle,pose.roll*=settle,hintAlpha=this.hintAlpha(this.exit.time)*(1-smooth(progress/.2)),starAlpha=this.starAlpha(this.exit.time)*(1-smooth(progress/.3));let gather=1-smooth(progress/.5);offsets=this.exit.offsets.map(([x,y,z])=>[x*gather,y*gather,z*gather])}else{let time=this.elapsed();dissolveTime=time,pose=this.pose(width,height,this.flyProgress(time),time),hintAlpha=this.hintAlpha(time),starAlpha=this.starAlpha(time),offsets=this.blockOffsets(time)}let{columns,rows}=this.model,boxes=this.model.blocks.map((block,index)=>{let[dx,dy,dz]=offsets[index],x=block.home[0]-columns/2+dx,y=block.home[1]-rows/2+dy;return{min:[x,y,dz-DEPTH/2],max:[x+1,y+1,dz+DEPTH/2],color:block.color}}),raster=this.raster;raster.render(width,height,pose,boxes,background,isLight(background)?LIGHT_HALO_STRENGTH:0);let halo=(index,base)=>{let amount=raster.haloAmount[index];if(amount<=0)return base;let color=raster.haloRgb;return mix(base??background,[color[index*3],color[index*3+1],color[index*3+2]],amount)},backgroundFade=smooth(dissolveTime/BACKGROUND_FADE),textFade=smooth(dissolveTime/.6)*.3,textActive=dissolveTime<DISSOLVE_END||backgroundFade<1,hint=this.hint(width,height,hintAlpha,background),frame=Math.floor(dissolveTime*14),now=this.elapsed(),starLevel=Math.round(starAlpha*STAR_ALPHA_LEVELS)/STAR_ALPHA_LEVELS,starfield=index=>{if(starLevel<=0)return;let star=this.stars[index];if(!star)return;let flicker=Math.round((.5+.5*Math.sin(now*star.speed+star.phase))*STAR_FLICKER_LEVELS)/STAR_FLICKER_LEVELS;return{text:star.glyph,fg:mix(background,mix(foreground,star.tint,.5),star.strength*(.7+.3*flicker)*starLevel)}},lines=[];for(let row=0;row<height;row++){let cells=this.cells[row]??[],line="",currentFg=-1,currentBg=-1,emit=(text,fg,bg)=>{let fgKey=fg?this.pack(fg):-1,bgKey=bg?this.pack(bg):-1;fgKey!==currentFg&&text!==" "&&(line+=fg?this.ansi(fgKey,!1):"\x1B[39m",currentFg=fgKey),bgKey!==currentBg&&(line+=bg?this.ansi(bgKey,!0):"\x1B[49m",currentBg=bgKey),line+=text};for(let column=0;column<width;column++){let index=row*width+column,cell=textActive?cells[column]:void 0,cellBg=halo(index,cell?.bg&&backgroundFade<1?mix(cell.bg,background,backgroundFade):void 0);if(hint&&row===hint.row&&column>=hint.start&&column<hint.start+hint.text.length){let offset=column-hint.start;emit(hint.text[offset],offset<hint.keyLength?hint.keyColor:hint.color,cellBg);continue}let dots=raster.bits[index];if(dots){let step=LOGO_COLOR_STEP*raster.counts[index],rgb=raster.rgb,color=[Math.round(rgb[index*3]/step)*LOGO_COLOR_STEP,Math.round(rgb[index*3+1]/step)*LOGO_COLOR_STEP,Math.round(rgb[index*3+2]/step)*LOGO_COLOR_STEP];emit(BRAILLE[dots],color,cellBg);continue}if(!cell){let star=starfield(index);emit(star?.text??" ",star?.fg,cellBg);continue}let dust=(dissolveTime-cell.delay)/DUST_DURATION;if(dust<0&&cell.width===2&&!raster.bits[index+1]){emit(cell.text,mix(cell.fg,background,textFade),cellBg),column++;continue}if(dust<0&&cell.width===1){emit(cell.text,mix(cell.fg,background,textFade),cellBg);continue}let dotCount=dust<0?cell.ink:Math.round(cell.ink*(1-clamp01(dust)));if(dotCount<=0){let star=starfield(index);emit(star?.text??" ",star?.fg,cellBg);continue}let bits=0,placed=0;for(let attempt=0;placed<dotCount&&attempt<32;attempt++){let bit=DOT_BITS[Math.floor(hash(cell.seed*7919+frame*131+attempt)*8)];bits&bit||(bits|=bit,placed++)}let fade=textFade+(1-textFade)*clamp01(dust)**.8;emit(BRAILLE[bits],mix(cell.fg,background,fade),cellBg)}lines.push(`${line}\x1B[0m`)}return lines}elapsed(){return(performance.now()-this.startTime)/1e3}exitProgress(){return this.exit?clamp01((performance.now()-this.exit.start)/1e3/EXIT_DURATION):0}finish(){this.timer&&(clearInterval(this.timer),this.timer=void 0,this.onDone())}blockOffsets(time){let blocks=this.model.blocks,home=()=>blocks.map(()=>[0,0,0]);if(time<PUZZLE_START)return home();let cycle=Math.floor((time-PUZZLE_START)/PUZZLE_CYCLE),local=time-PUZZLE_START-cycle*PUZZLE_CYCLE;this.shuffle?.cycle!==cycle&&(this.shuffle={cycle,steps:shuffleSteps(this.model,cycle)});let steps=this.shuffle.steps,offset=(position,index)=>{let block=blocks[index].home;return[position[0]-block[0],position[1]-block[1],position[2]-block[2]]},shuffleEnd=PUZZLE_STEP*PUZZLE_STEPS;if(local<shuffleEnd){let step=Math.floor(local/PUZZLE_STEP),progress=smooth((local-step*PUZZLE_STEP)/PUZZLE_STEP);return steps[step].map((from,index)=>{let a=offset(from,index),b=offset(steps[step+1][index],index);return[a[0]+(b[0]-a[0])*progress,a[1]+(b[1]-a[1])*progress,a[2]+(b[2]-a[2])*progress]})}if(local<shuffleEnd+PUZZLE_RETURN){let u=(local-shuffleEnd)/PUZZLE_RETURN,remaining=1-smooth(u),arc=Math.sin(Math.PI*clamp01(u))*.8;return steps[PUZZLE_STEPS].map((position,index)=>{let[x,y,z]=offset(position,index);return[x*remaining,y*remaining,z*remaining+(index%2===0?arc:-arc)]})}return home()}flyProgress(time){return smooth((time-FLY_START)/FLY_DURATION)}starAlpha(time){return smooth((time-STARS_START)/STARS_FADE)}hintAlpha(time){return smooth((time-FLY_START-FLY_DURATION)/HINT_FADE)}pose(width,height,progress,time){let{columns,rows,cameraDistance,radius,widthShare,origin}=this.model,reach=radius*(cameraDistance/(cameraDistance-radius)),startScale=origin?2*(cameraDistance-DEPTH/2)/cameraDistance:START_SCALE,endScale=Math.max(startScale,Math.min(width*2*widthShare,(height*4-8)*.48)/reach),endX=width,endY=height*2-2,startX=origin?origin.column*2+columns:endX,startY=origin?origin.row*4+rows:endY;return{centerX:startX+(endX-startX)*progress,centerY:startY+(endY-startY)*progress,scale:startScale*(endScale/startScale)**progress,yaw:spinAngle(time),pitch:.3*Math.sin(spinPhase(time))*progress,roll:.06*Math.sin(2*spinPhase(time))*progress}}hint(width,height,alpha,background){if(alpha<=0)return;let key=formatKeyText(getKeybindings().getKeys("tui.select.cancel")[0]??"escape"),text=`${key} to return`;if(!(text.length>width))return{row:height-2,start:Math.floor((width-text.length)/2),text,keyLength:key.length,keyColor:mix(background,toRgb(theme.colors.muted),alpha),color:mix(background,toRgb(theme.colors.dim),alpha)}}prepareStars(width,height){let stars=new Array(width*height);for(let index=0;index<width*height;index++){if(hash(index*3+20973)>=STAR_DENSITY)continue;let random=salt=>hash(index*7+salt*40503);stars[index]={glyph:BRAILLE[DOT_BITS[Math.floor(random(1)*8)]],tint:STAR_TINTS[Math.floor(random(2)*STAR_TINTS.length)],strength:.1+random(3)*.12,phase:random(4)*Math.PI*2,speed:.4+random(5)*.8}}return stars}prepareCells(width,foreground){let cells=parseScreen(this.screen,width,foreground,this.background),height=Math.max(1,this.tui.terminal.rows),{columns,rows,origin}=this.model,centerX=origin?origin.column+columns/2:width/2,centerY=origin?origin.row+rows/4:height/2,farthest=Math.hypot(Math.max(centerX,width-centerX),Math.max(centerY,height-centerY)*2);for(let row=0;row<cells.length;row++){let line=cells[row];for(let column=0;column<line.length;column++){let cell=line[column],owner=cell.width===0?line[column-1]:cell,seed=hash(row*65537+column);if(cell.width!==0){let distance=Math.hypot(column-centerX,(row-centerY)*2)/farthest;cell.delay=FLY_START+distance*WAVE_SPREAD+seed*WAVE_JITTER}else cell.delay=owner.delay;cell.seed=row*65537+column,cell.ink=glyphInk(owner.text,seed)}}if(origin)for(let row=origin.row;row<origin.row+Math.ceil(rows/2);row++){let line=cells[row];if(line)for(let column=origin.column;column<origin.column+columns;column++){let cell=line[column];cell&&(cell.text=" ",cell.width=1,cell.ink=0,cell.bg=void 0)}}return cells}pack(color){return Math.round(color[0])<<16|Math.round(color[1])<<8|Math.round(color[2])}ansi(key,isBackground){let cacheKey=key*2+(isBackground?1:0),value=this.ansiCache.get(cacheKey);if(value===void 0){let color=rgbColor(key>>16&255,key>>8&255,key&255),mode=theme.getColorMode();value=isBackground?backgroundAnsi(color,mode):foregroundAnsi(color,mode),this.ansiCache.set(cacheKey,value)}return value}};export{EasterEgg3dAnimation,playEasterEgg3d};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __kcCreateRequire } from "node:module"; const require = __kcCreateRequire(import.meta.url);
|
|
2
|
-
import{Bm25Ranker,CODEMODE_DOCS_PATH,CODEMODE_STORE_ENTRY_TYPE,DEFAULT_TOOL_SEARCH_LIMIT,combineUsage,createToolSearchDocument,formatSize,getCodemodeCallableTools,parseCodemodeSource,renderToolSample,toCodemodeDeclaration,toCodemodeIdentifier,writeOutputFile}from"./chunk-3QKQRXCZ.js";import"./chunk-C62RVFZT.js";import"./chunk-CCP7VAJU.js";import"./chunk-2QXPCKUQ.js";import"./chunk-KQKUEQJA.js";import{getCodemodeWorkerSpecifier,getQuickJSWasmPath}from"./chunk-BPNRVFVQ.js";import"./chunk-O6JSP6YG.js";import"./chunk-AHB7JV5B.js";function isWorkerToHostMessage(value){if(typeof value!="object"||value===null)return!1;let type=value.type;return type==="call"||type==="output"||type==="done"||type==="crash"||type==="started"||type==="idle"}var DEFAULT_TIMEOUT_MS=3e5,IDENTIFIER=/^[A-Za-z_$][A-Za-z0-9_$]*$/,RESERVED_GLOBALS=new Set(["tools","ALL_TOOLS","console","text","image","exit","globalThis","store","load"]);function errorMessage(error){return error instanceof Error?error.message:String(error)}function serializeStore(store){let serialized={};for(let[key,value]of Object.entries(store??{})){let json=JSON.stringify(value);json!==void 0&&(serialized[key]=json)}return serialized}var BridgeError=class extends Error{};function parseBridgeJson(json,what){try{return JSON.parse(json)}catch{throw new BridgeError(`${what} is not valid JSON`)}}function parseStoreWrites(json){let entries=parseBridgeJson(json,"store writes");if(!Array.isArray(entries))throw new BridgeError("store writes are not an array");let writes={set:{},delete:[]};for(let entry of entries){if(!Array.isArray(entry)||typeof entry[0]!="string"||(entry.length===2?typeof entry[1]!="string":entry.length!==1))throw new BridgeError("store writes contain a malformed entry");let[key,value]=entry;value===void 0?writes.delete.push(key):writes.set[key]=parseBridgeJson(value,`store value for ${JSON.stringify(key)}`)}return writes}function parseScriptError(json){let parsed=parseBridgeJson(json,"script error");if(typeof parsed!="object"||parsed===null)throw new BridgeError("script error is not an object");let{name,message,stack}=parsed;if(typeof message!="string"||name!==void 0&&typeof name!="string"||stack!==void 0&&typeof stack!="string")throw new BridgeError("script error is malformed");return{kind:"script",name,message,stack}}function checkGlobals(globals){let names=new Set,namespaces=new Set;for(let global of globals){let parts=global.name.split(".");if(parts.length>2||!parts.every(part=>IDENTIFIER.test(part))||RESERVED_GLOBALS.has(parts[0]))throw new Error(`Invalid global name "${global.name}"`);if(names.has(global.name))throw new Error(`Global "${global.name}" is already registered`);parts.length===2&&namespaces.add(parts[0]),names.add(global.name)}for(let name of namespaces)if(names.has(name))throw new Error(`Global "${name}" conflicts with the namespace "${name}"`)}var Execution=class{promise;resolveResult;channel;unsent=[];executors;control;delivered=new Set;signal;timer;output=[];calls=[];pending=new Map;finished=!1;constructor(options){if(this.promise=new Promise(resolve=>{this.resolveResult=resolve}),this.executors=options.executors,this.control=options.control,this.signal=options.signal,Number.isFinite(options.timeoutMs)&&(this.timer=setTimeout(()=>{this.finish({kind:"timeout",message:`Execution timed out after ${options.timeoutMs} ms`})},options.timeoutMs)),options.signal&&(options.signal.aborted?this.onAbort():options.signal.addEventListener("abort",this.onAbort,{once:!0})),this.finished)return;let data={code:options.code,tools:options.tools.map(tool=>({name:tool.name,jsName:tool.jsName??toCodemodeIdentifier(tool.name),description:tool.description??""})),globals:options.globals.map(global=>({name:global.name,spread:global.spread===!0})),memoryLimitBytes:options.memoryLimitBytes,store:options.store,...options.deterministic?{deterministic:options.deterministic}:{}},events={message:message=>this.receive(message),failure:error=>this.finish(error)};new Promise(resolve=>resolve(options.launch(data,events))).then(channel=>{if(this.finished){channel.stop().catch(()=>{});return}this.channel=channel;for(let message of this.unsent.splice(0))channel.post(message)},error=>{this.finish({kind:"sandbox",message:errorMessage(error)})})}deliver(seq,now,id,outcome){if(this.finished)return;if(!Number.isFinite(now))throw new Error(`The clock value of result ${seq} is not a finite number`);if(!Number.isInteger(seq)||seq<1||this.delivered.has(seq))throw new Error(`Result number ${seq} is not a positive integer used once`);let pending=this.pending.get(id);if(pending===void 0)throw new Error(`Call ${id} is not waiting for a result`);if(!outcome.ok&&outcome.properties!==void 0){let{properties:properties2}=outcome;if(typeof properties2!="object"||properties2===null||Array.isArray(properties2))throw new Error(`The properties of result ${seq} are not an object`)}let payload=outcome.ok?outcome.value===void 0?void 0:JSON.stringify(outcome.value):outcome.message,properties=!outcome.ok&&outcome.properties!==void 0?JSON.stringify(outcome.properties):void 0;this.delivered.add(seq),this.pending.delete(id),pending.record&&(pending.record.status=outcome.ok?"ok":"error",pending.record.durationMs=performance.now()-pending.startedAt),this.post({type:"result",id,ok:outcome.ok,payload,seq,now,...properties===void 0?{}:{properties}})}abort(message){return this.finish({kind:"aborted",message}),this.promise}onAbort=()=>{let reason=this.signal?.reason;this.finish({kind:"aborted",message:reason instanceof Error?reason.message:"Execution aborted"})};post(message){this.channel?this.channel.post(message):this.unsent.push(message)}receive(message){try{this.handleMessage(message)}catch(error){this.finish({kind:"sandbox",message:error instanceof BridgeError?`Sandbox bridge broken: ${error.message}. The script may have modified built-ins such as a prototype's toJSON.`:`Sandbox host failed: ${errorMessage(error)}`})}}handleMessage(message){if(!this.finished){if(!isWorkerToHostMessage(message))throw new BridgeError("unknown message from the worker");switch(message.type){case"output":this.output.push(message.item);break;case"call":if(this.pending.has(message.id))throw new BridgeError(`duplicate call id ${message.id}`);this.control?this.forwardCall(message,this.control):this.handleCall(message);break;case"started":this.control?.onStarted?.(message.fingerprint);break;case"idle":this.control?.onIdle?.(message.seq,message.issued);break;case"done":this.handleDone(message);break;case"crash":this.finish({kind:"sandbox",message:message.message});break}}}handleDone(message){if(!message.ok){this.finish(parseScriptError(message.error),void 0,void 0,message.during);return}let value=message.value===void 0?void 0:parseBridgeJson(message.value,"return value");this.finish(void 0,value,parseStoreWrites(message.writes),message.during)}forwardCall(message,control){let{id,name,target}=message,args=message.args===void 0?void 0:parseBridgeJson(message.args,"call arguments"),record=target==="tool"?{name,status:"cancelled",durationMs:0}:void 0;record&&this.calls.push(record),this.pending.set(id,{record,startedAt:performance.now(),controller:new AbortController}),control.onCall({id,target,name,args})}async handleCall(message){let{id,name}=message,isTool=message.target==="tool",record=isTool?{name,status:"cancelled",durationMs:0}:void 0;record&&this.calls.push(record);let pending={record,startedAt:performance.now(),controller:new AbortController};this.pending.set(id,pending);let status,reply;try{let tool=(isTool?this.executors.tools:this.executors.globals).get(name);if(!tool)throw new Error(`Unknown ${isTool?"tool":"global"} "${name}"`);let args=message.args===void 0?void 0:JSON.parse(message.args),value=await tool.execute(args,{signal:pending.controller.signal});reply={type:"result",id,ok:!0,payload:value===void 0?void 0:JSON.stringify(value)},status="ok"}catch(error){reply={type:"result",id,ok:!1,payload:errorMessage(error)},status="error"}this.pending.delete(id)&&(record&&(record.status=status,record.durationMs=performance.now()-pending.startedAt),this.post(reply))}finish(error,value,writes,during){if(this.finished)return;this.finished=!0,clearTimeout(this.timer),this.signal?.removeEventListener("abort",this.onAbort);let now=performance.now();for(let pending of this.pending.values())pending.record&&(pending.record.durationMs=now-pending.startedAt),pending.controller.abort();this.pending.clear(),this.unsent=[];let ended=during===void 0?{}:{during:{seq:during.seq,issued:during.issued}},result=error?{ok:!1,error,output:this.output,calls:this.calls,...ended}:{ok:!0,value,output:this.output,calls:this.calls,storeWrites:writes??{set:{},delete:[]},...ended};if(!this.channel){this.resolveResult(result);return}this.channel.stop().catch(()=>{}).then(()=>this.resolveResult(result))}},CodemodeSandboxBase=class{toolsByName=new Map;globalsByName=new Map;timeoutMs;memoryLimitBytes;launch;running=new Set;closed=!1;constructor(options,launch){this.timeoutMs=options.timeoutMs??DEFAULT_TIMEOUT_MS,this.memoryLimitBytes=options.memoryLimitBytes,this.launch=launch;for(let tool of options.tools??[])this.registerTool(tool);checkGlobals(options.globals??[]);for(let global of options.globals??[])this.globalsByName.set(global.name,global)}registerTool(tool){if(this.toolsByName.has(tool.name))throw new Error(`Tool "${tool.name}" is already registered`);this.toolsByName.set(tool.name,tool)}unregisterTool(name){return this.toolsByName.delete(name)}get tools(){return[...this.toolsByName.values()]}get globals(){return[...this.globalsByName.values()]}execute(code,options={}){if(this.closed)return Promise.reject(new Error("Sandbox is closed"));let tools=new Map(this.toolsByName),execution=new Execution({code,tools:[...tools.values()],globals:[...this.globalsByName.values()],executors:{tools,globals:this.globalsByName},timeoutMs:options.timeoutMs??this.timeoutMs,signal:options.signal,memoryLimitBytes:this.memoryLimitBytes,store:serializeStore(options.store),launch:this.launch});return this.running.add(execution),execution.promise.finally(()=>this.running.delete(execution))}start(code,options){if(this.closed)throw new Error("Sandbox is closed");if(!Number.isFinite(options.startedAt)||options.startedAt<0)throw new Error("startedAt must be a non-negative number of milliseconds since the epoch");if(!Number.isInteger(options.seed)||options.seed<0||options.seed>4294967295)throw new Error("seed must be a 32-bit unsigned integer");let tools=options.tools??[];if(new Set(tools.map(tool=>tool.name)).size!==tools.length)throw new Error("Tool names must be unique");let scriptNames=tools.map(tool=>tool.jsName??toCodemodeIdentifier(tool.name));if(new Set(scriptNames).size!==tools.length)throw new Error("Tool script names must be unique");let globals=options.globals??[];checkGlobals(globals);let execution=new Execution({code,tools,globals,executors:{tools:new Map,globals:new Map},timeoutMs:options.timeoutMs??Number.POSITIVE_INFINITY,signal:options.signal,memoryLimitBytes:this.memoryLimitBytes,store:serializeStore(options.store),deterministic:{startedAt:options.startedAt,seed:options.seed},control:{onStarted:options.onStarted,onCall:options.onCall,onIdle:options.onIdle},launch:this.launch});return this.running.add(execution),{result:execution.promise.finally(()=>this.running.delete(execution)),deliver:(seq,now,id,outcome)=>execution.deliver(seq,now,id,outcome),get finished(){return execution.finished}}}async close(){this.closed=!0,await Promise.all([...this.running].map(execution=>execution.abort("Sandbox closed")))}};import{Worker}from"node:worker_threads";import{readFile}from"node:fs/promises";import{createRequire}from"node:module";var modules=new Map;function loadQuickJSWasm(path){let resolved=path??createRequire(import.meta.url).resolve("quickjs-wasi/quickjs.wasm"),module=modules.get(resolved);if(!module){let{WebAssembly:WebAssembly2}=globalThis;module=readFile(resolved).then(bytes=>WebAssembly2.compile(bytes)).catch(error=>{throw modules.delete(resolved),error}),modules.set(resolved,module)}return module}function defaultWorkerUrl(){return new URL(import.meta.url.endsWith(".ts")?"./worker.ts":"./worker.js",import.meta.url)}function workerLauncher(options){return async(data,events)=>{let module;try{module=await(options.wasm??loadQuickJSWasm())}catch(error){throw new Error(`Failed to load QuickJS: ${errorMessage(error)}`)}let interrupt=new SharedArrayBuffer(4),workerData={...data,wasm:module,interrupt},releaseWorker=options.acquireWorker?.(),worker;try{worker=new Worker(options.workerUrl??defaultWorkerUrl(),{workerData})}catch(error){throw releaseWorker?.(),new Error(`Failed to start worker: ${errorMessage(error)}`)}releaseWorker&&worker.once("exit",releaseWorker),worker.on("message",message=>{typeof message=="object"&&message!==null&&("watch:import"in message||"watch:require"in message)||events.message(message)}),worker.on("error",error=>{events.failure({kind:"sandbox",name:error instanceof Error?error.name:void 0,message:errorMessage(error)})}),worker.on("exit",code=>{events.failure({kind:"sandbox",message:`Worker exited with code ${code} before the script settled`})});let stop=async()=>{Atomics.store(new Int32Array(interrupt),0,1),worker.terminate().catch(()=>{}),worker.unref()};try{options.onWorkerStarted?.(new Promise(resolve=>worker.once("exit",()=>resolve())))}catch(error){throw stop(),error}return{post:message=>worker.postMessage(message),stop}}}var CodemodeSandbox=class extends CodemodeSandboxBase{constructor(options={}){super(options,workerLauncher(options))}};var decoder=new TextDecoder;var MAX_STACK_SIZE=512*1024;var wtf8Decoder=new TextDecoder,wtf8Encoder=new TextEncoder;var IMAGE_HELPER_EXPECTS='image expects a non-empty image URL string, an object with image_url, or an image block { type: "image", data, mimeType }',PRELUDE_SOURCE=`(function (bridge, toolsJson, globalsJson, storeJson) {
|
|
2
|
+
import{Bm25Ranker,CODEMODE_DOCS_PATH,CODEMODE_STORE_ENTRY_TYPE,DEFAULT_TOOL_SEARCH_LIMIT,combineUsage,createToolSearchDocument,formatSize,getCodemodeCallableTools,parseCodemodeSource,renderToolSample,toCodemodeDeclaration,toCodemodeIdentifier,writeOutputFile}from"./chunk-DFRYMT3C.js";import"./chunk-L6QGGIZG.js";import"./chunk-CCP7VAJU.js";import"./chunk-VQBEVSZH.js";import"./chunk-KQKUEQJA.js";import{getCodemodeWorkerSpecifier,getQuickJSWasmPath}from"./chunk-BPNRVFVQ.js";import"./chunk-O6JSP6YG.js";import"./chunk-AHB7JV5B.js";function isWorkerToHostMessage(value){if(typeof value!="object"||value===null)return!1;let type=value.type;return type==="call"||type==="output"||type==="done"||type==="crash"||type==="started"||type==="idle"}var DEFAULT_TIMEOUT_MS=3e5,IDENTIFIER=/^[A-Za-z_$][A-Za-z0-9_$]*$/,RESERVED_GLOBALS=new Set(["tools","ALL_TOOLS","console","text","image","exit","globalThis","store","load"]);function errorMessage(error){return error instanceof Error?error.message:String(error)}function serializeStore(store){let serialized={};for(let[key,value]of Object.entries(store??{})){let json=JSON.stringify(value);json!==void 0&&(serialized[key]=json)}return serialized}var BridgeError=class extends Error{};function parseBridgeJson(json,what){try{return JSON.parse(json)}catch{throw new BridgeError(`${what} is not valid JSON`)}}function parseStoreWrites(json){let entries=parseBridgeJson(json,"store writes");if(!Array.isArray(entries))throw new BridgeError("store writes are not an array");let writes={set:{},delete:[]};for(let entry of entries){if(!Array.isArray(entry)||typeof entry[0]!="string"||(entry.length===2?typeof entry[1]!="string":entry.length!==1))throw new BridgeError("store writes contain a malformed entry");let[key,value]=entry;value===void 0?writes.delete.push(key):writes.set[key]=parseBridgeJson(value,`store value for ${JSON.stringify(key)}`)}return writes}function parseScriptError(json){let parsed=parseBridgeJson(json,"script error");if(typeof parsed!="object"||parsed===null)throw new BridgeError("script error is not an object");let{name,message,stack}=parsed;if(typeof message!="string"||name!==void 0&&typeof name!="string"||stack!==void 0&&typeof stack!="string")throw new BridgeError("script error is malformed");return{kind:"script",name,message,stack}}function checkGlobals(globals){let names=new Set,namespaces=new Set;for(let global of globals){let parts=global.name.split(".");if(parts.length>2||!parts.every(part=>IDENTIFIER.test(part))||RESERVED_GLOBALS.has(parts[0]))throw new Error(`Invalid global name "${global.name}"`);if(names.has(global.name))throw new Error(`Global "${global.name}" is already registered`);parts.length===2&&namespaces.add(parts[0]),names.add(global.name)}for(let name of namespaces)if(names.has(name))throw new Error(`Global "${name}" conflicts with the namespace "${name}"`)}var Execution=class{promise;resolveResult;channel;unsent=[];executors;control;delivered=new Set;signal;timer;output=[];calls=[];pending=new Map;finished=!1;constructor(options){if(this.promise=new Promise(resolve=>{this.resolveResult=resolve}),this.executors=options.executors,this.control=options.control,this.signal=options.signal,Number.isFinite(options.timeoutMs)&&(this.timer=setTimeout(()=>{this.finish({kind:"timeout",message:`Execution timed out after ${options.timeoutMs} ms`})},options.timeoutMs)),options.signal&&(options.signal.aborted?this.onAbort():options.signal.addEventListener("abort",this.onAbort,{once:!0})),this.finished)return;let data={code:options.code,tools:options.tools.map(tool=>({name:tool.name,jsName:tool.jsName??toCodemodeIdentifier(tool.name),description:tool.description??""})),globals:options.globals.map(global=>({name:global.name,spread:global.spread===!0})),memoryLimitBytes:options.memoryLimitBytes,store:options.store,...options.deterministic?{deterministic:options.deterministic}:{}},events={message:message=>this.receive(message),failure:error=>this.finish(error)};new Promise(resolve=>resolve(options.launch(data,events))).then(channel=>{if(this.finished){channel.stop().catch(()=>{});return}this.channel=channel;for(let message of this.unsent.splice(0))channel.post(message)},error=>{this.finish({kind:"sandbox",message:errorMessage(error)})})}deliver(seq,now,id,outcome){if(this.finished)return;if(!Number.isFinite(now))throw new Error(`The clock value of result ${seq} is not a finite number`);if(!Number.isInteger(seq)||seq<1||this.delivered.has(seq))throw new Error(`Result number ${seq} is not a positive integer used once`);let pending=this.pending.get(id);if(pending===void 0)throw new Error(`Call ${id} is not waiting for a result`);if(!outcome.ok&&outcome.properties!==void 0){let{properties:properties2}=outcome;if(typeof properties2!="object"||properties2===null||Array.isArray(properties2))throw new Error(`The properties of result ${seq} are not an object`)}let payload=outcome.ok?outcome.value===void 0?void 0:JSON.stringify(outcome.value):outcome.message,properties=!outcome.ok&&outcome.properties!==void 0?JSON.stringify(outcome.properties):void 0;this.delivered.add(seq),this.pending.delete(id),pending.record&&(pending.record.status=outcome.ok?"ok":"error",pending.record.durationMs=performance.now()-pending.startedAt),this.post({type:"result",id,ok:outcome.ok,payload,seq,now,...properties===void 0?{}:{properties}})}abort(message){return this.finish({kind:"aborted",message}),this.promise}onAbort=()=>{let reason=this.signal?.reason;this.finish({kind:"aborted",message:reason instanceof Error?reason.message:"Execution aborted"})};post(message){this.channel?this.channel.post(message):this.unsent.push(message)}receive(message){try{this.handleMessage(message)}catch(error){this.finish({kind:"sandbox",message:error instanceof BridgeError?`Sandbox bridge broken: ${error.message}. The script may have modified built-ins such as a prototype's toJSON.`:`Sandbox host failed: ${errorMessage(error)}`})}}handleMessage(message){if(!this.finished){if(!isWorkerToHostMessage(message))throw new BridgeError("unknown message from the worker");switch(message.type){case"output":this.output.push(message.item);break;case"call":if(this.pending.has(message.id))throw new BridgeError(`duplicate call id ${message.id}`);this.control?this.forwardCall(message,this.control):this.handleCall(message);break;case"started":this.control?.onStarted?.(message.fingerprint);break;case"idle":this.control?.onIdle?.(message.seq,message.issued);break;case"done":this.handleDone(message);break;case"crash":this.finish({kind:"sandbox",message:message.message});break}}}handleDone(message){if(!message.ok){this.finish(parseScriptError(message.error),void 0,void 0,message.during);return}let value=message.value===void 0?void 0:parseBridgeJson(message.value,"return value");this.finish(void 0,value,parseStoreWrites(message.writes),message.during)}forwardCall(message,control){let{id,name,target}=message,args=message.args===void 0?void 0:parseBridgeJson(message.args,"call arguments"),record=target==="tool"?{name,status:"cancelled",durationMs:0}:void 0;record&&this.calls.push(record),this.pending.set(id,{record,startedAt:performance.now(),controller:new AbortController}),control.onCall({id,target,name,args})}async handleCall(message){let{id,name}=message,isTool=message.target==="tool",record=isTool?{name,status:"cancelled",durationMs:0}:void 0;record&&this.calls.push(record);let pending={record,startedAt:performance.now(),controller:new AbortController};this.pending.set(id,pending);let status,reply;try{let tool=(isTool?this.executors.tools:this.executors.globals).get(name);if(!tool)throw new Error(`Unknown ${isTool?"tool":"global"} "${name}"`);let args=message.args===void 0?void 0:JSON.parse(message.args),value=await tool.execute(args,{signal:pending.controller.signal});reply={type:"result",id,ok:!0,payload:value===void 0?void 0:JSON.stringify(value)},status="ok"}catch(error){reply={type:"result",id,ok:!1,payload:errorMessage(error)},status="error"}this.pending.delete(id)&&(record&&(record.status=status,record.durationMs=performance.now()-pending.startedAt),this.post(reply))}finish(error,value,writes,during){if(this.finished)return;this.finished=!0,clearTimeout(this.timer),this.signal?.removeEventListener("abort",this.onAbort);let now=performance.now();for(let pending of this.pending.values())pending.record&&(pending.record.durationMs=now-pending.startedAt),pending.controller.abort();this.pending.clear(),this.unsent=[];let ended=during===void 0?{}:{during:{seq:during.seq,issued:during.issued}},result=error?{ok:!1,error,output:this.output,calls:this.calls,...ended}:{ok:!0,value,output:this.output,calls:this.calls,storeWrites:writes??{set:{},delete:[]},...ended};if(!this.channel){this.resolveResult(result);return}this.channel.stop().catch(()=>{}).then(()=>this.resolveResult(result))}},CodemodeSandboxBase=class{toolsByName=new Map;globalsByName=new Map;timeoutMs;memoryLimitBytes;launch;running=new Set;closed=!1;constructor(options,launch){this.timeoutMs=options.timeoutMs??DEFAULT_TIMEOUT_MS,this.memoryLimitBytes=options.memoryLimitBytes,this.launch=launch;for(let tool of options.tools??[])this.registerTool(tool);checkGlobals(options.globals??[]);for(let global of options.globals??[])this.globalsByName.set(global.name,global)}registerTool(tool){if(this.toolsByName.has(tool.name))throw new Error(`Tool "${tool.name}" is already registered`);this.toolsByName.set(tool.name,tool)}unregisterTool(name){return this.toolsByName.delete(name)}get tools(){return[...this.toolsByName.values()]}get globals(){return[...this.globalsByName.values()]}execute(code,options={}){if(this.closed)return Promise.reject(new Error("Sandbox is closed"));let tools=new Map(this.toolsByName),execution=new Execution({code,tools:[...tools.values()],globals:[...this.globalsByName.values()],executors:{tools,globals:this.globalsByName},timeoutMs:options.timeoutMs??this.timeoutMs,signal:options.signal,memoryLimitBytes:this.memoryLimitBytes,store:serializeStore(options.store),launch:this.launch});return this.running.add(execution),execution.promise.finally(()=>this.running.delete(execution))}start(code,options){if(this.closed)throw new Error("Sandbox is closed");if(!Number.isFinite(options.startedAt)||options.startedAt<0)throw new Error("startedAt must be a non-negative number of milliseconds since the epoch");if(!Number.isInteger(options.seed)||options.seed<0||options.seed>4294967295)throw new Error("seed must be a 32-bit unsigned integer");let tools=options.tools??[];if(new Set(tools.map(tool=>tool.name)).size!==tools.length)throw new Error("Tool names must be unique");let scriptNames=tools.map(tool=>tool.jsName??toCodemodeIdentifier(tool.name));if(new Set(scriptNames).size!==tools.length)throw new Error("Tool script names must be unique");let globals=options.globals??[];checkGlobals(globals);let execution=new Execution({code,tools,globals,executors:{tools:new Map,globals:new Map},timeoutMs:options.timeoutMs??Number.POSITIVE_INFINITY,signal:options.signal,memoryLimitBytes:this.memoryLimitBytes,store:serializeStore(options.store),deterministic:{startedAt:options.startedAt,seed:options.seed},control:{onStarted:options.onStarted,onCall:options.onCall,onIdle:options.onIdle},launch:this.launch});return this.running.add(execution),{result:execution.promise.finally(()=>this.running.delete(execution)),deliver:(seq,now,id,outcome)=>execution.deliver(seq,now,id,outcome),get finished(){return execution.finished}}}async close(){this.closed=!0,await Promise.all([...this.running].map(execution=>execution.abort("Sandbox closed")))}};import{Worker}from"node:worker_threads";import{readFile}from"node:fs/promises";import{createRequire}from"node:module";var modules=new Map;function loadQuickJSWasm(path){let resolved=path??createRequire(import.meta.url).resolve("quickjs-wasi/quickjs.wasm"),module=modules.get(resolved);if(!module){let{WebAssembly:WebAssembly2}=globalThis;module=readFile(resolved).then(bytes=>WebAssembly2.compile(bytes)).catch(error=>{throw modules.delete(resolved),error}),modules.set(resolved,module)}return module}function defaultWorkerUrl(){return new URL(import.meta.url.endsWith(".ts")?"./worker.ts":"./worker.js",import.meta.url)}function workerLauncher(options){return async(data,events)=>{let module;try{module=await(options.wasm??loadQuickJSWasm())}catch(error){throw new Error(`Failed to load QuickJS: ${errorMessage(error)}`)}let interrupt=new SharedArrayBuffer(4),workerData={...data,wasm:module,interrupt},releaseWorker=options.acquireWorker?.(),worker;try{worker=new Worker(options.workerUrl??defaultWorkerUrl(),{workerData})}catch(error){throw releaseWorker?.(),new Error(`Failed to start worker: ${errorMessage(error)}`)}releaseWorker&&worker.once("exit",releaseWorker),worker.on("message",message=>{typeof message=="object"&&message!==null&&("watch:import"in message||"watch:require"in message)||events.message(message)}),worker.on("error",error=>{events.failure({kind:"sandbox",name:error instanceof Error?error.name:void 0,message:errorMessage(error)})}),worker.on("exit",code=>{events.failure({kind:"sandbox",message:`Worker exited with code ${code} before the script settled`})});let stop=async()=>{Atomics.store(new Int32Array(interrupt),0,1),worker.terminate().catch(()=>{}),worker.unref()};try{options.onWorkerStarted?.(new Promise(resolve=>worker.once("exit",()=>resolve())))}catch(error){throw stop(),error}return{post:message=>worker.postMessage(message),stop}}}var CodemodeSandbox=class extends CodemodeSandboxBase{constructor(options={}){super(options,workerLauncher(options))}};var decoder=new TextDecoder;var MAX_STACK_SIZE=512*1024;var wtf8Decoder=new TextDecoder,wtf8Encoder=new TextEncoder;var IMAGE_HELPER_EXPECTS='image expects a non-empty image URL string, an object with image_url, or an image block { type: "image", data, mimeType }',PRELUDE_SOURCE=`(function (bridge, toolsJson, globalsJson, storeJson) {
|
|
3
3
|
"use strict";
|
|
4
4
|
|
|
5
5
|
// Freeze every object reachable from the built-in globals, plus the intrinsics that are only
|