UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

32 lines • 92.8 kB
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
import{DynamicBorder,getEditorTheme,keyDisplayText,keyHint,observeVisibleStderrWrites,rawKeyHint,restoreStderr,sharedMarkdownTheme,takeOverStderr,theme}from"./chunk-KAQBXCAT.js";import{usageLimitScope}from"./chunk-5QZIEDOI.js";import{userWordBlocks}from"./chunk-CSCNDNNU.js";import{isWSL}from"./chunk-3MCOVENJ.js";import{signalSpawnedChild}from"./chunk-KLAX467B.js";import{appendHiddenTuiStdout}from"./chunk-WHTAR5IS.js";import{CURSOR_MARKER,Container,Editor,Input,Markdown,MouseRegion,ProcessTerminal,ScrollView,Spacer,Text,TuiAltScreen,TuiMainScreen,VStack,copyLineSources,getKeybindings,getNativeClipboard,isWarpWslSession,matchesKey,nextRenderRevision,truncateToWidth,visibleWidth}from"./chunk-4PMRUR4L.js";import{redactSensitiveOutput}from"./chunk-62OVOJPI.js";import{SERVER_FALLBACK_ABORTED_DIAGNOSTIC}from"./chunk-Z6TEQEZO.js";import{ACCOUNT_LIMIT_NEXT_STEP_LEAD,describeProviderFailureForUser,stripTurnRetrySuppressionPrefix}from"./chunk-AFDUWYAX.js";import{getDebugLogPath,stripBom}from"./chunk-QJTWAOBX.js";import{typebox_exports}from"./chunk-MIKPY3E7.js";var CODEX_OPTION=typebox_exports.Object({label:typebox_exports.String({description:"User-facing label (1-5 words)."}),description:typebox_exports.String({description:"One short sentence explaining impact/tradeoff if selected."})},{additionalProperties:!1}),CODEX_QUESTION=typebox_exports.Object({id:typebox_exports.String({pattern:"^[a-z][a-z0-9]*(_[a-z0-9]+)*$",description:"Stable identifier for mapping answers (snake_case)."}),header:typebox_exports.String({minLength:1,maxLength:12,description:"Short header label shown in the UI (12 or fewer chars)."}),question:typebox_exports.String({minLength:1,description:"Single-sentence prompt shown to the user."}),options:typebox_exports.Array(CODEX_OPTION,{minItems:2,maxItems:3,description:'Provide 2-3 mutually exclusive choices. Put the recommended option first and suffix its label with "(Recommended)". Do not include an "Other" option in this list; the client will add a free-form "Other" option automatically.'}),multiSelect:typebox_exports.Optional(typebox_exports.Boolean({description:"Set to true to allow the user to select multiple options instead of just one."}))},{additionalProperties:!1}),CODEX_PARAMS=typebox_exports.Object({questions:typebox_exports.Array(CODEX_QUESTION,{minItems:1,maxItems:3,description:"Questions to show the user. Prefer 1 and do not exceed 3"}),wait_for_answer:typebox_exports.Boolean({description:"Set true to pause here until the user answers; set false to keep working and receive the answer later as a user message."}),required:typebox_exports.Optional(typebox_exports.Boolean({description:"Set true when the answer decides whether you take an action (for example, which of two irreversible paths to take, or whether to proceed): with no answer, that action is not taken."}))},{additionalProperties:!1}),CLAUDE_OPTION=typebox_exports.Object({label:typebox_exports.String({description:"The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice."}),description:typebox_exports.Optional(typebox_exports.String({description:"Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications."}))}),CLAUDE_QUESTION=typebox_exports.Object({question:typebox_exports.String({minLength:1,description:'The complete question to ask the user. Should be clear, specific, and end with a question mark. Example: "Which library should we use for date formatting?" If multiSelect is true, phrase it accordingly, e.g. "Which features do you want to enable?"'}),header:typebox_exports.String({minLength:1,maxLength:12,description:'Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".'}),options:typebox_exports.Optional(typebox_exports.Array(CLAUDE_OPTION,{minItems:2,maxItems:4,description:"The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). There should be no Other option, that will be provided automatically."})),multiSelect:typebox_exports.Boolean({description:"Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive."})}),CLAUDE_PARAMS=typebox_exports.Object({questions:typebox_exports.Array(CLAUDE_QUESTION,{minItems:1,maxItems:4,description:"Questions to ask the user (1-4 questions)"}),waitForAnswer:typebox_exports.Boolean({description:"Set true to pause here until the user answers; set false to keep working and receive the answer later as a user message."}),required:typebox_exports.Optional(typebox_exports.Boolean({description:"Set true when the answer decides whether you take an action (for example, which of two irreversible paths to take, or whether to proceed): with no answer, that action is not taken."}))});var WAIT_FLAG_STEER_TEXT="This call omitted wait_for_answer (or waitForAnswer). Set true to pause here until the user answers, false to keep working and receive the answer later as a user message.",DEFAULT_ASK_USER_TIMEOUT_MS=1800*1e3,HEADER_MAX=12,SNAKE_CASE=/^[a-z][a-z0-9]*(_[a-z0-9]+)*$/,LIMITS={codex:{maxQuestions:3,minOptions:2,maxOptions:3,optionsRequired:!0},claude:{maxQuestions:4,minOptions:2,maxOptions:4,optionsRequired:!1}},AskUserSchemaError=class extends Error{constructor(message){super(message),this.name="AskUserSchemaError"}};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readWaitFlag(variant,args){let value=args[variant==="codex"?"wait_for_answer":"waitForAnswer"];if(typeof value!="boolean")throw new AskUserSchemaError(WAIT_FLAG_STEER_TEXT);return value}function parseOptions(raw,min,max,required,requireDescription){if(raw===void 0){if(required)throw new AskUserSchemaError(`options must contain ${min} to ${max} items`);return[]}if(!Array.isArray(raw))throw new AskUserSchemaError("options must be an array");if(raw.length<min||raw.length>max)throw new AskUserSchemaError(required?`options must contain ${min} to ${max} items`:`options must contain ${min} to ${max} items when present`);let options=[];for(let item of raw){if(!isRecord(item))throw new AskUserSchemaError("each option must be an object");let label=typeof item.label=="string"?item.label.trim():"";if(label.length===0)throw new AskUserSchemaError("option label must be non-empty");let description=typeof item.description=="string"?item.description.trim():void 0;if(requireDescription&&(description===void 0||description.length===0))throw new AskUserSchemaError("option description is required");options.push(description===void 0||description.length===0?{label}:{label,description})}return options}function parseQuestion(variant,raw,index){if(!isRecord(raw))throw new AskUserSchemaError("each question must be an object");let limits=LIMITS[variant],header=typeof raw.header=="string"?raw.header.trim():"";if(header.length===0)throw new AskUserSchemaError("header must be non-empty");if(header.length>HEADER_MAX)throw new AskUserSchemaError("header must be 12 or fewer characters");let question=typeof raw.question=="string"?raw.question.trim():"";if(question.length===0)throw new AskUserSchemaError("question must be non-empty");let options=parseOptions(raw.options,limits.minOptions,limits.maxOptions,limits.optionsRequired,variant==="codex"),id;if(variant==="claude")id=`q${index+1}`;else if(id=typeof raw.id=="string"?raw.id.trim():"",!SNAKE_CASE.test(id))throw new AskUserSchemaError("id must be snake_case");let multiSelect;if(variant==="claude"){if(typeof raw.multiSelect!="boolean")throw new AskUserSchemaError("multiSelect is required");multiSelect=raw.multiSelect}else multiSelect=raw.multiSelect===!0;return{id,header,question,options,multiSelect}}function toCanonical(variant,args,options){if(!isRecord(args))throw new AskUserSchemaError(WAIT_FLAG_STEER_TEXT);let waitForAnswer=readWaitFlag(variant,args);if(args.required!==void 0&&typeof args.required!="boolean")throw new AskUserSchemaError("required must be a boolean when present");let limits=LIMITS[variant];if(!Array.isArray(args.questions)||args.questions.length<1||args.questions.length>limits.maxQuestions)throw new AskUserSchemaError(`questions must contain 1 to ${limits.maxQuestions} items`);return{requestId:options?.requestId??crypto.randomUUID(),questions:args.questions.map((question,index)=>parseQuestion(variant,question,index)),waitForAnswer,timeoutMs:options?.timeoutMs??DEFAULT_ASK_USER_TIMEOUT_MS,...args.required===!0?{required:!0}:{}}}var INLINE_WORDS={comment:text=>text,typed:(_header,text)=>text},reference=label=>`(see [${label}] below)`;function separatedWords(requestId){let words=[],place=(base,text)=>{let taken=words.filter(word=>word.label===base||word.label.startsWith(`${base} (`)).length,label=taken===0?base:`${base} (${taken+1})`;return words.push({label,text}),reference(label)};return{words,comment:text=>place(`The user's comment for question ${requestId}`,text),typed:(header,text)=>place(`The user's answer to ${header} for question ${requestId}`,text)}}function resolveUserWordReferences(text,words){return words.reduce((resolved,word)=>resolved.split(reference(word.label)).join(word.text),text)}function readUserWordBlocks(content){let texts=content.flatMap(block=>block.type==="text"?[block.text]:[]);if(texts.length%2!==0)return;let words=[];for(let index=0;index<texts.length;index+=2){let label=/^\[(.+)\]$/s.exec(texts[index]??"")?.[1],text=texts[index+1];if(label===void 0||text===void 0)return;words.push({label,text})}return words}function headerFor(id,questions){return questions.find(question=>question.id===id)?.header??id}function questionTextFor(id,questions){return questions.find(question=>question.id===id)?.question??id}function typedText(answer){if(answer.selected.length>0)return;let text=answer.text?.trim();return text===void 0||text.length===0?void 0:text}function answerBody(answer,header,words=INLINE_WORDS,offered=[]){if(!answer)return;if(answer.selected.length>0)return answer.selected.join(", ");let text=typedText(answer);if(text!==void 0)return offered.some(option=>option.label===text)?text:words.typed(header,text)}function answeredLines(response,questions,words){let lines=[],seen=new Set;for(let question of questions){let body=answerBody(response.answers[question.id],question.header,words,question.options);body!==void 0&&(lines.push(`${question.header}: ${body}`),seen.add(question.id))}for(let[id,answer]of Object.entries(response.answers)){if(seen.has(id))continue;let header=headerFor(id,questions),body=answerBody(answer,header,words);body!==void 0&&lines.push(`${header}: ${body}`)}return lines}function unansweredLine(response,questions){let unanswered=response.unanswered.map(id=>headerFor(id,questions));return unanswered.length>0?[`Unanswered: ${unanswered.join(", ")}`]:[]}var CANCELLED_BY_USER="The user cancelled the question after answering part of it.",CANCELLED_AFTER_ANSWERS="The question was cancelled after part of it was answered.";function isCancelledWithAnswersLine(line){return line===CANCELLED_BY_USER||line===CANCELLED_AFTER_ANSWERS}function showsPartialAnswers(response){return response.status!=="cancelled"||response.cancelOrigin!=="user"&&response.cancelOrigin!=="ui_failure"?!1:Object.values(response.answers).some(answer=>answerBody(answer,"")!==void 0)}function selectedBlock(prefix,selected){return selected.length===1?[`${prefix} ${selected[0]}`]:[prefix,...selected]}var GATED_NO_ANSWER="No answer: do not take the action it gates. Keep that action pending and end the turn.";function formatGatedNoAnswer(response,questions,words,cancellationReason){let lines=[cancellationReason??(response.status==="timed_out"?`The user did not answer within ${Math.round((response.autoResolvedAfterMs??DEFAULT_ASK_USER_TIMEOUT_MS)/6e4)} minutes. (\uC0AC\uC6A9\uC790\uAC00 \uB2F5\uBCC0\uC744 \uC548\uD558\uACE0 timeout \uC73C\uB85C \uC885\uB8CC\uB428)`:response.status==="cancelled"?"The user dismissed the question.":response.status==="orphaned-after-restart"?"The pending question could not be resumed after a restart.":"This session has no user attached (subagent or headless).")],selected=answeredLines(response,questions,words);return selected.length>0&&lines.push(...selectedBlock("Before going idle the user had selected (not an answer):",selected)),lines.push(GATED_NO_ANSWER),lines.join(`
`)}function formatGatedCancellation(reason,response,requestId,questions){return formatGatedNoAnswer(response,questions,separatedWords(requestId),reason)}function formatBody(response,questions,words,required=!1){if(required&&response.status!=="answered"&&response.status!=="comment-submitted")return formatGatedNoAnswer(response,questions,words);switch(response.status){case"answered":return[...answeredLines(response,questions,words),...unansweredLine(response,questions)].join(`
`);case"comment-submitted":{let comment=response.comment?.trim()??"";return[`The user responded: ${comment.length>0?words.comment(comment):""}`,...answeredLines(response,questions,words),...unansweredLine(response,questions)].join(`
`)}case"timed_out":{let lines=[`The user did not answer within ${Math.round((response.autoResolvedAfterMs??DEFAULT_ASK_USER_TIMEOUT_MS)/6e4)} minutes. (\uC0AC\uC6A9\uC790\uAC00 \uB2F5\uBCC0\uC744 \uC548\uD558\uACE0 timeout \uC73C\uB85C \uC885\uB8CC\uB428)`],selected=answeredLines(response,questions,words);return selected.length>0&&lines.push(...selectedBlock("Before going idle the user had selected:",selected),...unansweredLine(response,questions)),lines.push("Continue the work to completion on your best judgment; do not ask this question again this turn."),lines.join(`
`)}case"cancelled":{if(!showsPartialAnswers(response))return"The user dismissed the question.";let reason=response.cancelOrigin==="ui_failure"?response.comment?.trim():void 0;return[...reason?[reason]:[],response.cancelOrigin==="user"?CANCELLED_BY_USER:CANCELLED_AFTER_ANSWERS,...answeredLines(response,questions,words),...unansweredLine(response,questions)].join(`
`)}case"orphaned-after-restart":return"The pending question could not be resumed after a restart; continue on best judgment.";case"unavailable":return"This session has no user attached (subagent or headless); decide on best judgment."}}function formatResultText(_variant,response,questions=[],required=!1){return formatBody(response,questions,INLINE_WORDS,required)}function formatModelAnswer(response,requestId,questions=[],required=!1){let placement=separatedWords(requestId);return{text:formatBody(response,questions,placement,required),words:placement.words}}function formatUserMessage(response,requestId,questions=[],required=!1){let answer=formatModelAnswer(response,requestId,questions,required),frame=`[Answer to question ${requestId}]
${answer.text}`;return answer.words.length===0?frame:[{type:"text",text:frame},...userWordBlocks(answer.words)]}function askUserAnswerDisplayText(content){if(typeof content=="string")return;let[first,...rest]=content;if(first?.type!=="text"||rest.length===0||!parseAskUserAnswerFrame(first.text))return;let words=readUserWordBlocks(rest);return words?resolveUserWordReferences(first.text,words):void 0}function parseAskUserAnswerFrame(text){let match=/^\[Answer to question ([^\]\r\n]+)\]\r?\n([\s\S]*)$/.exec(text);return match?{requestId:match[1],body:match[2]}:void 0}function selectedAnswers(answer){if(answer.selected.length>0)return answer.selected;let text=answer.text?.trim();return text===void 0||text.length===0?[]:[text]}function formatResultDetails(variant,response,requestId,questions=[],required=!1){let{words}=formatModelAnswer(response,requestId,questions,required);if(variant==="codex"){let answers2={};for(let[id,answer]of Object.entries(response.answers))answers2[id]={answers:selectedAnswers(answer)};let details2={...response.resolvedBy!==void 0?{resolvedBy:response.resolvedBy}:{},answers:answers2,unanswered:response.unanswered,status:response.status};return response.comment!==void 0&&(details2.comment=response.comment),words.length>0&&(details2.userWords=words),details2}let answers={};for(let[id,answer]of Object.entries(response.answers)){let body=answerBody(answer,headerFor(id,questions));body!==void 0&&(answers[questionTextFor(id,questions)]=body)}let details={...response.resolvedBy!==void 0?{resolvedBy:response.resolvedBy}:{},questions,answers,unanswered:response.unanswered.map(id=>questionTextFor(id,questions)),status:response.status};return response.comment!==void 0&&(details.freeText=response.comment),words.length>0&&(details.userWords=words),details}var REQUIRED_COMPACTION_ERROR_MESSAGE="Context remains above the compaction threshold because compaction did not complete. Retry the prompt to run compaction again, or start a new session.",RequiredCompactionError=class extends Error{constructor(){super(REQUIRED_COMPACTION_ERROR_MESSAGE),this.code="compaction_failed",this.name="RequiredCompactionError"}};import{randomUUID}from"node:crypto";import{unlinkSync,writeFileSync}from"node:fs";import{platform,tmpdir}from"node:os";import{join}from"node:path";import{spawn}from"node:child_process";function runClipboardCommand(command,args,options){return new Promise(resolve=>{let child=spawn(command,args,{stdio:["pipe",options?.input===void 0?"pipe":"ignore","ignore"],windowsHide:!0}),chunks=[],length=0,settled=!1,finish=result=>{settled||(settled=!0,clearTimeout(timer),resolve(result))},abort=()=>{signalSpawnedChild(child,"SIGKILL"),child.stdout?.destroy(),child.stdin?.destroy(),finish(void 0)},timer=setTimeout(abort,options?.timeoutMs??3e3);child.on("error",()=>finish(void 0)),child.on("close",code=>{settled||finish(code===0?Buffer.concat(chunks,length):void 0)}),child.stdout?.on("data",chunk=>{settled||(length+=chunk.length,length>(options?.maxBufferBytes??50*1024*1024)?abort():chunks.push(chunk))}),child.stdin?.on("error",()=>{}),child.stdin?.end(options?.input)})}var MAX_OSC52_ENCODED_LENGTH=1e5;function isRemoteSession(env){return!!(env.SSH_CONNECTION||env.SSH_CLIENT||env.SSH_TTY||env.MOSH_CONNECTION)}function emitOsc52(text){let encoded=Buffer.from(text).toString("base64");return encoded.length>MAX_OSC52_ENCODED_LENGTH?!1:(process.stdout.write(`\x1B]52;c;${encoded}\x07`),!0)}async function copyViaWindowsClipboard(text){let tmpFile=join(tmpdir(),`pi-wsl-clip-${randomUUID()}.txt`);try{writeFileSync(tmpFile,text,{encoding:"utf8",mode:384});let winPath=(await runClipboardCommand("wslpath",["-w",tmpFile],{timeoutMs:1e3}))?.toString("utf8").trim();if(!winPath)return!1;let script=`Set-Clipboard -Value ([System.IO.File]::ReadAllText('${winPath.replaceAll("'","''")}', [System.Text.Encoding]::UTF8))`;return await runClipboardCommand("powershell.exe",["-NoProfile","-Command",script],{timeoutMs:5e3})!==void 0}catch{return!1}finally{try{unlinkSync(tmpFile)}catch{}}}async function readClipboardText(){if(platform()==="linux"){let commands=[];process.env.TERMUX_VERSION&&commands.push(["termux-clipboard-get",[]]),process.env.WAYLAND_DISPLAY&&commands.push(["wl-paste",["--no-newline","--type","text"]]),process.env.DISPLAY&&commands.push(["xclip",["-selection","clipboard","-out"]],["xsel",["--clipboard","--output"]]);for(let[command,args]of commands){let bytes=await runClipboardCommand(command,args,{timeoutMs:5e3});if(bytes!==void 0)return bytes.toString("utf8")||null}}try{return await getNativeClipboard()?.getText()||null}catch{return null}}async function readClipboardFilePaths(){let paths=await getNativeClipboard()?.getFilePaths?.();return paths?.length?paths:null}async function copyToClipboard(text){let p=platform(),env=process.env,copied=!1;if(p!=="linux")try{let clipboard=getNativeClipboard();clipboard?.setText&&(await clipboard.setText(text),copied=!0)}catch{}if(!copied){let commands=[];p==="darwin"?commands.push(["pbcopy",[]]):p==="win32"?commands.push(["clip",[]]):(env.TERMUX_VERSION&&commands.push(["termux-clipboard-set",[]]),env.WAYLAND_DISPLAY&&commands.push(["wl-copy",[]]),env.DISPLAY&&commands.push(["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]));for(let[command,args]of commands)if(await runClipboardCommand(command,args,{input:text,timeoutMs:5e3})!==void 0){copied=!0;break}}let osc52Emitted=!1;!copied&&p==="linux"&&isWSL(env)&&(env.WT_SESSION&&(osc52Emitted=emitOsc52(text)),copied=osc52Emitted||await copyViaWindowsClipboard(text));let headless=p==="linux"&&!env.DISPLAY&&!env.WAYLAND_DISPLAY&&!env.TERMUX_VERSION,terminalViewer=copied&&process.stdout.isTTY===!0,oversized=!1;if(!osc52Emitted&&(isRemoteSession(env)||terminalViewer||!copied&&headless)&&(emitOsc52(text)?copied=!0:oversized=!0),!copied){if(oversized)throw new Error("Clipboard unavailable: text exceeds the OSC 52 size limit");if(p==="linux"){if(env.TERMUX_VERSION)throw new Error("Clipboard unavailable: install the Termux:API app and `termux-api` package");if(env.WAYLAND_DISPLAY)throw new Error("Clipboard unavailable: install `wl-clipboard` (`wl-copy`) or check Wayland access");if(env.DISPLAY)throw new Error("Clipboard unavailable: install `xclip` or `xsel`, or check X11 access")}throw new Error("Clipboard unavailable")}}var COMMENT_LABEL="Comment (optional; unanswered questions are reported)",OWN_ANSWER_LABEL="Type your own answer...",NOT_ANSWERED_NOTICE="You have not answered all questions",DISMISS_NOTICE="Press Esc again to dismiss (answers will be discarded)";function formatCountdownLabel(remainingMs){let totalSeconds=Math.max(0,Math.ceil(remainingMs/1e3));if(totalSeconds>=300)return`${Math.ceil(totalSeconds/60)}m`;let minutes=Math.floor(totalSeconds/60),seconds=totalSeconds%60;return`${String(minutes).padStart(2,"0")}:${String(seconds).padStart(2,"0")}`}var AskUserQuestionState=class{constructor(request){this.activeIndex=0,this.highlightIndex=0,this.focus="options",this.dismissPending=!1,this.selected=new Map,this.texts=new Map,this.request=request,this.submitRowIndex=this.commentRowIndex}get activeQuestion(){return this.request.questions[this.activeIndex]}get ownAnswerRowIndex(){return this.activeQuestion.options.length}get rowCount(){return this.ownAnswerRowIndex+1}get activeTabIndex(){return this.focus==="submit"?this.request.questions.length:this.activeIndex}get commentRowIndex(){return this.request.questions.length}get isCommentFocused(){return this.focus==="submit"&&this.submitRowIndex===this.commentRowIndex}switchQuestion(delta){this.switchTab(delta)}switchTab(delta){let count=this.request.questions.length+1,next=(this.activeTabIndex+delta+count)%count;next===this.request.questions.length?this.enterSubmit():this.jumpToQuestion(next)}advance(){if(this.activeIndex+1<this.request.questions.length){this.jumpToQuestion(this.activeIndex+1);return}this.enterSubmit()}jumpToQuestion(index){this.focus="options";let whole=Number.isFinite(index)?Math.trunc(index):0;this.activeIndex=Math.min(Math.max(0,whole),this.request.questions.length-1),this.highlightIndex=0,this.clearTransient()}enterSubmit(){this.focus="submit",this.submitRowIndex=this.commentRowIndex,this.highlightIndex=0,this.clearTransient()}returnToOptions(){this.leaveOwnAnswer(0)}leaveOwnAnswer(row){this.focus="options",this.highlightIndex=Math.min(Math.max(0,row),this.ownAnswerRowIndex),this.clearTransient()}moveSubmitRow(delta){this.submitRowIndex=Math.min(Math.max(0,this.submitRowIndex+delta),this.commentRowIndex),this.clearTransient()}focusComment(){this.submitRowIndex=this.commentRowIndex}clearTransient(){this.notice=void 0,this.dismissPending=!1}requestDismiss(){return this.hasDraft()?this.dismissPending?"cancel":(this.dismissPending=!0,this.notice=DISMISS_NOTICE,"confirm"):"cancel"}acceptPartialSubmit(){this.dismissPending=!1,this.notice=void 0}hasDraft(){return(this.comment??"").trim()!==""?!0:this.request.questions.some(question=>this.isAnswered(question.id))}selectedFor(questionId){return this.selected.get(questionId)??[]}textFor(questionId){return this.texts.get(questionId)}isSelected(questionId,label){return this.selectedFor(questionId).includes(label)}isAnswered(questionId){return this.selectedFor(questionId).length>0?!0:(this.texts.get(questionId)??"").trim()!==""}answeredCount(){return this.request.questions.filter(question=>this.isAnswered(question.id)).length}activateOption(questionId,label){let question=this.request.questions.find(entry=>entry.id===questionId);if(question?.options.some(option=>option.label===label)){if(question.multiSelect){let next=[...this.selectedFor(questionId)],index=next.indexOf(label);index>=0?next.splice(index,1):next.push(label),this.selected.set(questionId,next)}else this.selected.set(questionId,[label]);this.notice=void 0}}setOwnAnswer(questionId,text){let trimmed=text.trim();trimmed!==""&&(this.selected.delete(questionId),this.texts.set(questionId,trimmed),this.notice=void 0)}clearAnswer(questionId){this.selected.delete(questionId),this.texts.delete(questionId),this.notice=void 0}restoreDraft(draft){for(let question of this.request.questions){let answer=draft.answers?.[question.id];if(!answer)continue;let selected=answer.selected.filter(label=>question.options.some(option=>option.label===label));selected.length>0&&this.selected.set(question.id,selected),answer.text!==void 0&&answer.text.trim()!==""&&this.texts.set(question.id,answer.text.trim())}draft.comment!==void 0&&draft.comment.trim()!==""&&(this.comment=draft.comment)}answers(){let result={};for(let question of this.request.questions){let selected=this.selectedFor(question.id),text=this.texts.get(question.id);selected.length===0&&text===void 0||(result[question.id]={selected,...text!==void 0?{text}:{}})}return result}unanswered(){return this.request.questions.filter(question=>!this.isAnswered(question.id)).map(q=>q.id)}submitOutcome(forcePartial=!1){if((this.comment??"").trim()!=="")return"comment-submitted";if(this.unanswered().length===0||this.answeredCount()>0||forcePartial)return"answered"}buildResponse(status,autoResolvedAfterMs){let comment=this.comment!==void 0&&this.comment.trim()!==""?this.comment:void 0;return{status,...status==="answered"||status==="comment-submitted"?{resolvedBy:"local_ui"}:{},answers:this.answers(),...comment!==void 0?{comment}:{},unanswered:this.unanswered(),...autoResolvedAfterMs!==void 0?{autoResolvedAfterMs}:{}}}refreshDraft(){let comment=this.comment!==void 0&&this.comment.trim()!==""?this.comment:void 0;return{answers:this.answers(),...comment!==void 0?{comment}:{}}}};var AskUserCountdown=class{constructor(timeoutMs,tui,onTick,onExpire,getDeadlineAtMs){let deadline=Date.now()+timeoutMs,tick=()=>{let remaining=Math.max(0,(getDeadlineAtMs?.()??deadline)-Date.now());onTick(remaining),tui?.requestRender(),remaining===0&&!getDeadlineAtMs&&(this.dispose(),onExpire())};this.timer=setInterval(tick,1e3),this.timer.unref(),tick()}dispose(){clearInterval(this.timer),this.timer=void 0}};var DEL="\x7F";function isPrintable(data){return data.length===1&&data>=" "&&data!==DEL}function handleAskUserKeyInput(ctx,data){let kb=getKeybindings();if(matchesKey(data,"ctrl+c")){ctx.finish("cancelled");return}if(ctx.state.focus==="own-answer"){handleOwnAnswerKey(ctx,data,kb);return}if(ctx.state.focus==="submit"){handleSubmitKey(ctx,data,kb);return}handleOptionsKey(ctx,data,kb)}function saveTypedOwnAnswer(ctx){ctx.ownAnswerInput.getValue().trim()!==""?ctx.commitOwnAnswer():ctx.ownAnswerInput.setValue("")}function handleOwnAnswerKey(ctx,data,kb){let state=ctx.state;if(matchesKey(data,"ctrl+enter")){ctx.commitOwnAnswer(),ctx.attemptSubmit();return}if(kb.matches(data,"tui.select.confirm")||data===`
`){ctx.commitOwnAnswer(),state.advance(),ctx.updateAll();return}if(kb.matches(data,"tui.select.cancel")){ctx.ownAnswerInput.setValue(""),state.leaveOwnAnswer(state.ownAnswerRowIndex),ctx.updateAll();return}if(kb.matches(data,"tui.select.up")){saveTypedOwnAnswer(ctx),state.leaveOwnAnswer(state.ownAnswerRowIndex-1),ctx.updateAll();return}if(kb.matches(data,"tui.select.down")){saveTypedOwnAnswer(ctx),state.leaveOwnAnswer(state.ownAnswerRowIndex),ctx.updateAll();return}if(matchesKey(data,"tab")||matchesKey(data,"shift+tab")){saveTypedOwnAnswer(ctx),state.switchTab(matchesKey(data,"tab")?1:-1),ctx.updateAll();return}if(matchesKey(data,"backspace")&&ctx.ownAnswerInput.getValue()===""){state.leaveOwnAnswer(state.ownAnswerRowIndex),ctx.updateAll();return}ctx.ownAnswerInput.handleInput(data),ctx.emitProgress()}function handleSubmitKey(ctx,data,kb){let state=ctx.state;if(matchesKey(data,"ctrl+enter")){ctx.attemptSubmit();return}if(kb.matches(data,"tui.input.submit")||data===`
`){state.isCommentFocused?ctx.attemptSubmit():(state.jumpToQuestion(state.submitRowIndex),ctx.updateAll());return}if(kb.matches(data,"tui.select.cancel")){state.request.waitForAnswer?state.returnToOptions():ctx.finish("cancelled"),ctx.updateAll();return}if(kb.matches(data,"tui.select.up")||kb.matches(data,"tui.select.down")){state.moveSubmitRow(kb.matches(data,"tui.select.up")?-1:1),ctx.updateAll();return}if(matchesKey(data,"shift+tab")||matchesKey(data,"tab")){state.switchTab(matchesKey(data,"tab")?1:-1),ctx.updateAll();return}let commentHasText=ctx.commentInput.getValue()!=="";if((matchesKey(data,"left")||matchesKey(data,"right"))&&(!state.isCommentFocused||!commentHasText)){state.switchTab(matchesKey(data,"right")?1:-1),ctx.updateAll();return}if(matchesKey(data,"backspace")&&state.isCommentFocused&&!commentHasText){state.moveSubmitRow(-1),ctx.updateAll();return}if(!state.isCommentFocused){if(!isPrintable(data))return;state.focusComment()}ctx.commentInput.handleInput(data),state.comment=ctx.commentInput.getValue(),ctx.updateAll(),ctx.emitProgress()}function handleOptionsKey(ctx,data,kb){let state=ctx.state;if(matchesKey(data,"ctrl+enter")){ctx.attemptSubmit();return}if(kb.matches(data,"tui.select.cancel")){!state.request.waitForAnswer||state.requestDismiss()==="cancel"?ctx.finish("cancelled"):ctx.updateAll();return}if(matchesKey(data,"tab")||matchesKey(data,"right")){state.switchTab(1),ctx.updateAll();return}if(matchesKey(data,"shift+tab")||matchesKey(data,"left")){state.switchTab(-1),ctx.updateAll();return}if(kb.matches(data,"tui.select.up")||data==="k"){state.highlightIndex=Math.max(0,state.highlightIndex-1),ctx.updateAll();return}if(kb.matches(data,"tui.select.down")||data==="j"){state.highlightIndex=Math.min(state.ownAnswerRowIndex,state.highlightIndex+1),ctx.updateAll();return}if(matchesKey(data,"backspace")){state.clearAnswer(state.activeQuestion.id),ctx.emitProgress(),ctx.updateAll();return}if(data.length===1&&data>="1"&&data<="9"){let option=state.activeQuestion.options[Number(data)-1];option&&(state.activateOption(state.activeQuestion.id,option.label),ctx.emitProgress(),state.activeQuestion.multiSelect||(state.request.questions.length===1?ctx.attemptSubmit():state.advance()),ctx.updateAll());return}if(matchesKey(data,"space")){activateHighlighted(ctx,!1);return}if(kb.matches(data,"tui.select.confirm")||data===`
`){activateHighlighted(ctx,!0);return}if(data==="c"){state.enterSubmit(),ctx.updateAll();return}isPrintable(data)&&(ctx.openOwnAnswer(data),ctx.updateAll())}function activateHighlighted(ctx,confirm){let state=ctx.state;if(state.highlightIndex===state.ownAnswerRowIndex){ctx.openOwnAnswer();return}let option=state.activeQuestion.options[state.highlightIndex];option&&(state.activateOption(state.activeQuestion.id,option.label),ctx.emitProgress(),ctx.updateAll(),confirm&&(!state.activeQuestion.multiSelect&&state.request.questions.length===1?ctx.attemptSubmit():state.activeQuestion.multiSelect||(state.advance(),ctx.updateAll())))}function isQuestionMouseAction(event){return event.button==="left"&&!event.shift&&!event.alt&&!event.ctrl&&(event.type==="press"||event.type==="click"&&event.clickCount===1)}function questionMouseRegion(child,onClick){return new MouseRegion(child,event=>{if(!(!isQuestionMouseAction(event)||event.y!==0))return event.type==="click"&&onClick(),{handled:!0,focus:!0}})}var AskUserQuestionTabs=class{constructor(onClick){this.tabs=[],this.hits=[],this.width=0,this.onClick=onClick}setTabs(tabs){this.tabs=tabs}invalidate(){}render(width){if(this.hits=[],this.width=width,width<5)return[truncateToWidth("Use keys",width)];let lines=[],line=" ";for(let[index,tab]of this.tabs.entries()){let label=truncateToWidth(tab,width-2);visibleWidth(line)>1&&visibleWidth(line)+2+visibleWidth(label)>width-1&&(lines.push(line),line=" "),visibleWidth(line)>1&&(line+="  ");let start=visibleWidth(line);line+=label,this.hits.push({index,row:lines.length,start,end:visibleWidth(line)})}return lines.push(line),lines}handleMouse(event){if(!isQuestionMouseAction(event)||event.width!==this.width)return;let hit=this.hits.find(span=>event.y===span.row&&event.x>=span.start&&event.x<span.end);if(hit)return event.type==="click"&&this.onClick(hit.index),{handled:!0,focus:!0}}};function renderTitle(countdownLabel){let suffix=countdownLabel===""?"":theme.fg("muted",` \xB7 ${countdownLabel}`);return theme.fg("accent",theme.bold("Ask user"))+suffix}function renderTabLabels(state){let tabs=state.request.questions.map((question,index)=>{let answered=state.isAnswered(question.id)?theme.fg("success"," \u2713"):"",label=`${question.header}${answered}`;return index===state.activeTabIndex?theme.fg("accent",theme.bold(`\u2192 ${label}`)):theme.fg("muted",`  ${label}`)}),submit=state.activeTabIndex===state.request.questions.length?theme.fg("accent",theme.bold("\u2192 Submit")):theme.fg("muted","  Submit");return[...tabs,submit]}function renderQuestionLine(question){return theme.fg("text",question.question)}function renderQuestionList(state,focused){let lines=[],active=state.activeQuestion;active.options.forEach((option,index)=>{let highlighted=index===state.highlightIndex&&state.focus==="options",marker=state.isSelected(active.id,option.label)?theme.fg("success"," \u2713"):"",prefix=highlighted?theme.fg("accent","\u2192 "):"  ";lines.push(`${prefix}${index+1}. ${theme.fg("text",option.label)}${marker}`),option.description&&lines.push(theme.fg("muted",`     ${option.description}`))});let ownText=state.textFor(active.id),ownSuffix=ownText!==void 0?theme.fg("text",`: ${ownText}`):"",ownPrefix=state.highlightIndex===state.ownAnswerRowIndex&&state.focus==="options"?theme.fg("accent","\u2192 "):"  ",cursor=focused&&state.focus==="options"?CURSOR_MARKER:"";return lines.push(`${ownPrefix}${theme.fg("muted",OWN_ANSWER_LABEL)}${ownSuffix}${cursor}`),lines}function renderSubmitSummary(state){return state.request.questions.map((question,index)=>{let prefix=state.focus==="submit"&&state.submitRowIndex===index?theme.fg("accent","\u2192 "):"  ",answer=state.answers()[question.id];if(!answer)return`${prefix}${theme.fg("warning",`${question.header}: unanswered`)}`;let value=answer.selected.length>0?answer.selected.join(", "):answer.text??"";return`${prefix}${question.header}: ${value}`})}function renderOwnAnswerLabel(){return theme.fg("muted","Your answer (enter to save, \u2191\u2193 back to options, esc to discard)")}function renderCommentLabel(){return theme.fg("muted",COMMENT_LABEL)}function renderNotice(notice){return notice===void 0?"":theme.fg("warning",`! ${notice}`)}function renderSubmitLine(state){let answered=state.answeredCount(),total=state.request.questions.length;if(state.focus==="submit")return theme.fg("accent",theme.bold(`Submit (${answered}/${total} answered)`));let hint=state.focus==="options"&&state.activeQuestion.multiSelect?" - Enter toggles; Tab to Submit":" - Enter advances";return theme.fg("accent",theme.bold(`Submit (${answered}/${total} answered)`))+theme.fg("muted",hint)}function renderHintsLine(state){return state.focus==="submit"?state.isCommentFocused?rawKeyHint("enter","submit")+"  "+rawKeyHint("\u2191","review answers")+"  "+rawKeyHint("shift+tab","back")+"  "+rawKeyHint("tab","next question")+"  "+rawKeyHint("esc","back"):rawKeyHint("enter","edit answer")+"  "+rawKeyHint("\u2191\u2193","move")+"  "+rawKeyHint("tab","next question")+"  "+rawKeyHint("esc","back"):state.focus==="own-answer"?rawKeyHint("enter","save and next")+"  "+rawKeyHint("\u2191\u2193","back to options")+"  "+rawKeyHint("tab","next question")+"  "+rawKeyHint("esc","discard"):rawKeyHint("\u2191\u2193","move")+"  "+rawKeyHint("1-9","select")+"  "+rawKeyHint("space",state.activeQuestion.multiSelect?"toggle":"select")+"  "+rawKeyHint("enter",state.activeQuestion.multiSelect?"toggle":"next")+"  "+rawKeyHint("tab",state.activeQuestion.multiSelect?"next / Submit":"next question")+"  "+rawKeyHint("c","comment")+"  "+rawKeyHint("esc","cancel")}var AskUserQuestionComponent=class extends Container{constructor(request,done,opts={}){super(),this.ownAnswerInput=new Input,this.commentInput=new Input,this.listContainer=new Container,this.ownAnswerContainer=new Container,this.submitContainer=new Container,this.countdownLabel="",this.settled=!1,this._focused=!1,this.state=new AskUserQuestionState(request),this.doneCallback=done,this.options=opts,this.keyHandlerContext={state:this.state,ownAnswerInput:this.ownAnswerInput,commentInput:this.commentInput,finish:(status,autoResolvedAfterMs)=>this.finish(status,autoResolvedAfterMs),attemptSubmit:()=>this.attemptSubmit(),openOwnAnswer:initialText=>this.openOwnAnswer(initialText),commitOwnAnswer:()=>this.commitOwnAnswer(),emitProgress:()=>this.emitProgress(),updateAll:()=>this.updateAll()},this.addChild(new DynamicBorder),this.addChild(new Spacer(1)),this.titleText=new Text("",1,0),this.addChild(this.titleText),this.tabText=new AskUserQuestionTabs(index=>{index===this.state.request.questions.length?this.clickSubmit():(this.state.jumpToQuestion(index),this.updateAll())}),this.addChild(this.tabText),this.questionText=new Text("",1,0),this.addChild(this.questionText),this.addChild(this.listContainer),this.addChild(this.ownAnswerContainer),this.addChild(this.submitContainer),this.noticeText=new Text("",1,0),this.addChild(this.noticeText),this.submitText=new Text("",1,0),this.addChild(questionMouseRegion(this.submitText,()=>this.clickSubmit())),this.hintsText=new Text("",1,0),this.addChild(this.hintsText),this.addChild(new Spacer(1)),this.addChild(new DynamicBorder),opts.initialDraft&&(this.state.restoreDraft(opts.initialDraft),this.state.comment!==void 0&&this.commentInput.setValue(this.state.comment)),opts.initialQuestionIndex!==void 0&&this.state.jumpToQuestion(opts.initialQuestionIndex);let timeoutMs=opts.timeoutMs??request.timeoutMs;(timeoutMs>0||opts.getDeadlineAtMs)&&(this.countdown=new AskUserCountdown(timeoutMs,opts.tui,remainingMs=>{this.countdownLabel=formatCountdownLabel(remainingMs),this.updateTitle(),this.options.tui?.requestRender()},()=>this.finish("timed_out",timeoutMs),opts.getDeadlineAtMs)),this.updateAll()}get focused(){return this._focused}set focused(value){this._focused=value,this.updateAll()}handleInput(data){handleAskUserKeyInput(this.keyHandlerContext,data)}handleMouse(event){if(!(this.settled||!isQuestionMouseAction(event)))return super.handleMouse(event)}dispose(){this.countdown?.dispose()}clickSubmit(){this.state.focus==="submit"?this.attemptSubmit():(this.state.enterSubmit(),this.updateAll())}clickOption(index,submitSingleQuestion=!1){let question=this.state.activeQuestion,immediate=submitSingleQuestion&&this.state.request.questions.length===1&&!question.multiSelect;this.state.highlightIndex=index,this.state.activateOption(question.id,question.options[index].label),!question.multiSelect&&!immediate&&this.state.advance(),this.emitProgress(),this.updateAll(),immediate&&(this.options.tui?.renderNow(),this.attemptSubmit())}openOwnAnswer(initialText){this.state.focus="own-answer";let existing=this.state.textFor(this.state.activeQuestion.id)??"";this.ownAnswerInput.setValue(""),existing!==""&&this.ownAnswerInput.handleInput(existing),initialText!==void 0&&this.ownAnswerInput.handleInput(initialText),this.updateAll()}commitOwnAnswer(){this.state.setOwnAnswer(this.state.activeQuestion.id,this.ownAnswerInput.getValue()),this.ownAnswerInput.setValue(""),this.emitProgress()}attemptSubmit(){this.state.comment=this.commentInput.getValue();let outcome=this.state.submitOutcome(this.state.notice!==void 0);if(!outcome){this.state.notice=NOT_ANSWERED_NOTICE,this.updateAll();return}this.state.acceptPartialSubmit(),this.finish(outcome)}emitProgress(){let draft=this.state.refreshDraft();if(this.state.focus==="own-answer"){let live=this.ownAnswerInput.getValue().trim();live!==""&&(draft.answers={...draft.answers,[this.state.activeQuestion.id]:{selected:[],text:live}})}this.options.onProgress?.(draft)}finish(status,autoResolvedAfterMs){if(this.settled)return;this.settled=!0,this.countdown?.dispose(),this.state.comment=this.commentInput.getValue();let response=this.state.buildResponse(status,autoResolvedAfterMs);this.doneCallback(status==="cancelled"?{...response,cancelOrigin:"user"}:response)}applyFocusFlags(){this.ownAnswerInput.focused=this._focused&&this.state.focus==="own-answer",this.commentInput.focused=this._focused&&this.state.isCommentFocused}updateTitle(){this.titleText.setText(renderTitle(this.countdownLabel))}updateAll(){this.updateTitle(),this.applyFocusFlags(),this.tabText.setTabs(renderTabLabels(this.state)),this.questionText.setText(this.state.focus==="submit"?"Review your answers":renderQuestionLine(this.state.activeQuestion)),this.listContainer.clear();let lines=this.state.focus==="submit"?renderSubmitSummary(this.state):renderQuestionList(this.state,this._focused),optionIndex=0,description=!1;for(let line of lines){let text=new Text(line,1,0);if(this.state.focus==="submit"||description)this.listContainer.addChild(text),description=!1;else if(optionIndex<this.state.activeQuestion.options.length){let index=optionIndex++;this.listContainer.addChild(questionMouseRegion(text,()=>this.clickOption(index))),description=!!this.state.activeQuestion.options[index].description}else this.listContainer.addChild(questionMouseRegion(text,()=>this.openOwnAnswer()))}this.ownAnswerContainer.clear(),this.state.focus==="own-answer"&&(this.ownAnswerContainer.addChild(new Text(renderOwnAnswerLabel(),1,0)),this.ownAnswerContainer.addChild(this.ownAnswerInput)),this.submitContainer.clear(),this.state.focus==="submit"&&(this.submitContainer.addChild(new Spacer(1)),this.submitContainer.addChild(new Text(renderCommentLabel(),1,0)),this.submitContainer.addChild(this.commentInput)),this.noticeText.setText(renderNotice(this.state.notice)),this.submitText.setText(renderSubmitLine(this.state)),this.hintsText.setText(renderHintsLine(this.state))}};import{spawn as spawn2}from"node:child_process";import{mkdtempSync,readFileSync,rmSync,writeFileSync as writeFileSync2}from"node:fs";import{tmpdir as tmpdir2}from"node:os";import{join as join2}from"node:path";async function editInExternalEditor(options){let directory=mkdtempSync(join2(tmpdir2(),"pi-editor-")),filePath=join2(directory,"prompt.md");try{writeFileSync2(filePath,options.content,"utf-8");let[editor,...editorArgs]=options.command.split(" ");process.stdout.write(`Launching external editor: ${options.command}
Pi will resume when the editor exits.
`);let outcome=await new Promise(resolve=>{let child=spawn2(editor,[...editorArgs,filePath],{stdio:"inherit",shell:process.platform==="win32"});child.on("error",()=>resolve({launched:!1})),child.on("close",code=>resolve({launched:!0,code}))});return outcome.launched?outcome.code!==0?{status:"failed"}:{status:"complete",content:stripBom(readFileSync(filePath,"utf-8")).replace(/\n$/,"")}:{status:"launch-failed"}}finally{try{rmSync(directory,{recursive:!0,force:!0})}catch{}}}async function editFileInExternalEditor(options){let[editor,...editorArgs]=options.command.split(" "),outcome=await new Promise(resolve=>{let child=spawn2(editor,[...editorArgs,options.path],{stdio:"inherit",shell:process.platform==="win32"});child.on("error",()=>resolve({launched:!1})),child.on("close",code=>resolve({launched:!0,code}))});return outcome.launched?outcome.code===0?{status:"complete"}:{status:"exited",code:outcome.code??-1}:{status:"launch-failed"}}import*as fs from"node:fs";import*as path from"node:path";import{format}from"node:util";import{closeSync,openSync}from"node:fs";var STDERR_FD=2;async function loadStderrFdSyscalls(platform2=process.platform){if(platform2!=="darwin"&&platform2!=="linux"||typeof globalThis.Bun>"u")return;let{dlopen,FFIType}=await import("bun:ffi");try{let libc=dlopen(platform2==="darwin"?"libSystem.B.dylib":"libc.so.6",{dup:{args:[FFIType.i32],returns:FFIType.i32},dup2:{args:[FFIType.i32,FFIType.i32],returns:FFIType.i32},close:{args:[FFIType.i32],returns:FFIType.i32}});return{dup:fd=>libc.symbols.dup(fd),dup2:(source,target)=>libc.symbols.dup2(source,target),close:fd=>libc.symbols.close(fd)}}catch{return}}function redirectStderrFd(syscalls,logPath){let saved=syscalls.dup(STDERR_FD);if(saved<0)return;let target;try{target=openSync(logPath,"a",384)}catch{syscalls.close(saved);return}let moved=syscalls.dup2(target,STDERR_FD);if(closeSync(target),moved<0){syscalls.close(saved);return}let restored=!1;return{restore(){restored||(restored=!0,syscalls.dup2(saved,STDERR_FD),syscalls.close(saved))}}}import{closeSync as closeSync2,createWriteStream,openSync as openSync2}from"node:fs";import{isatty,WriteStream as TtyWriteStream}from"node:tty";var STDOUT_FD=1,terminal,ownWrites=new WeakSet,baseWrite;function terminalHandle(syscalls){if(terminal)return terminal;let fd=syscalls.dup(STDOUT_FD);if(fd<0)return;let stream=isatty(fd)?new TtyWriteStream(fd):createWriteStream("",{fd,autoClose:!1});return terminal={fd,stream},terminal}function redirectStdoutFd(syscalls,logPath,stdout=process.stdout){let handle=terminalHandle(syscalls);if(!handle)return;let target;try{target=openSync2(logPath,"a",384)}catch{return}let moved=syscalls.dup2(target,STDOUT_FD);if(closeSync2(target),!(moved<0))try{return installTerminalWriter(syscalls,handle,stdout)}catch{syscalls.dup2(handle.fd,STDOUT_FD);return}}function installTerminalWriter(syscalls,handle,stdout){let active=!0;ownWrites.has(stdout.write)||(baseWrite=stdout.write);let originalWrite=baseWrite??stdout.write,write=function(...args){return active?handle.stream.write.apply(handle.stream,args):originalWrite.apply(stdout,args)};ownWrites.add(write),stdout.write=write;let sizeProperties=["columns","rows"],ownDescriptors=new Map(sizeProperties.map(name=>[name,Object.getOwnPropertyDescriptor(stdout,name)]));for(let name of sizeProperties)Object.defineProperty(stdout,name,{configurable:!0,enumerable:!0,get:()=>handle.stream[name]});let onWindowChange=()=>{handle.stream._refreshSize?.(),stdout.emit("resize")};return process.on("SIGWINCH",onWindowChange),{restore(){if(active){active=!1,process.removeListener("SIGWINCH",onWindowChange),syscalls.dup2(handle.fd,STDOUT_FD),stdout.write===write&&(stdout.write=originalWrite);for(let name of sizeProperties){let descriptor=ownDescriptors.get(name);descriptor?Object.defineProperty(stdout,name,descriptor):delete stdout[name]}}}}}var consoleLevels=["error","info","warn"],interactiveConsoleState,stderrFdSyscalls,stderrFdRedirect,stdoutFdRedirect,hiddenOutputCapTimer,HIDDEN_OUTPUT_LOG_MAX_BYTES=32*1024*1024,HIDDEN_OUTPUT_LOG_KEPT_TAIL_BYTES=256*1024,HIDDEN_OUTPUT_CAP_CHECK_MS=5e3;function capHiddenOutputLog(logPath,maxBytes=HIDDEN_OUTPUT_LOG_MAX_BYTES){let size;try{size=fs.statSync(logPath).size}catch{return!1}if(size<=maxBytes)return!1;let keep=Math.min(HIDDEN_OUTPUT_LOG_KEPT_TAIL_BYTES,maxBytes),tail=Buffer.alloc(keep),fd=fs.openSync(logPath,"r"),read;try{read=fs.readSync(fd,tail,0,keep,size-keep)}finally{fs.closeSync(fd)}return fs.truncateSync(logPath,0),fs.appendFileSync(logPath,`[${new Date().toISOString()}] debug log cut at ${size} bytes (cap ${maxBytes}); the last ${keep} bytes follow
`),fs.appendFileSync(logPath,tail.subarray(0,read)),!0}function appendHiddenInteractiveStderr(text){if(text.length===0)return;let debugLogPath=getDebugLogPath(),prefix=`[${new Date().toISOString()}] hidden stderr while TUI active
`,redactedText=redactSensitiveOutput(text),suffix=redactedText.endsWith(`
`)?"":`
`;fs.mkdirSync(path.dirname(debugLogPath),{recursive:!0}),fs.appendFileSync(debugLogPath,`${prefix}${redactedText}${suffix}`,{mode:384}),fs.chmodSync(debugLogPath,384)}function replaceConsoleMethod(level,method){Object.defineProperty(console,level,{configurable:!0,value:method,writable:!0})}function takeOverInteractiveConsole(){if(interactiveConsoleState)return;interactiveConsoleState={error:console.error,info:console.info,warn:console.warn};let writeHiddenConsoleDiagnostic=(...data)=>{process.stderr.write(`${format(...data)}
`)};for(let level of consoleLevels)replaceConsoleMethod(level,writeHiddenConsoleDiagnostic)}function restoreInteractiveConsole(){if(interactiveConsoleState){for(let level of consoleLevels)replaceConsoleMethod(level,interactiveConsoleState[level]);interactiveConsoleState=void 0}}async function prepareInteractiveStderrCapture(){stderrFdSyscalls??=await loadStderrFdSyscalls().catch(()=>{})}function takeOverStderrFd(){if(!(!stderrFdSyscalls||stderrFdRedirect))try{appendHiddenInteractiveStderr("native stderr (fd 2) captured below until the TUI releases the terminal"),stderrFdRedirect=redirectStderrFd(stderrFdSyscalls,getDebugLogPath())}catch{stderrFdRedirect=void 0}}function takeOverStdoutFd(){if(!(!stderrFdSyscalls||stdoutFdRedirect||!process.stdout.isTTY))try{appendHiddenInteractiveStderr("native stdout (fd 1) writes outside the TUI captured below until it releases the terminal"),stdoutFdRedirect=redirectStdoutFd(stderrFdSyscalls,getDebugLogPath())}catch{stdoutFdRedirect=void 0}}function startHiddenOutputCap(){hiddenOutputCapTimer||!stderrFdRedirect&&!stdoutFdRedirect||(hiddenOutputCapTimer=setInterval(()=>{try{capHiddenOutputLog(getDebugLogPath())}catch{}},HIDDEN_OUTPUT_CAP_CHECK_MS),hiddenOutputCapTimer.unref?.())}function restoreStderrFd(){hiddenOutputCapTimer&&clearInterval(hiddenOutputCapTimer),hiddenOutputCapTimer=void 0,stdoutFdRedirect?.restore(),stdoutFdRedirect=void 0,stderrFdRedirect?.restore(),stderrFdRedirect=void 0}function takeOverInteractiveStderr(){takeOverStderr(appendHiddenInteractiveStderr,redactSensitiveOutput),takeOverInteractiveConsole(),takeOverStderrFd(),takeOverStdoutFd(),startHiddenOutputCap()}function restoreInteractiveStderr(){restoreStderrFd(),restoreInteractiveConsole(),restoreStderr()}var ExtensionEditorComponent=class extends Container{get focused(){return this._focused}set focused(value){this._focused=value,this.editor.focused=value}constructor(tui,keybindings,title,prefill,onSubmit,onCancel,options,externalEditorCommand){super(),this._focused=!1,this.tui=tui,this.keybindings=keybindings,this.externalEditorCommand=externalEditorCommand||process.env.VISUAL||process.env.EDITOR||(process.platform==="win32"?"notepad":"nano"),this.onSubmitCallback=onSubmit,this.onCancelCallback=onCancel;let{description,...editorOptions}=options??{};this.addChild(new DynamicBorder),this.addChild(new Spacer(1)),this.addChild(new Text(theme.fg("accent",title),1,0)),description&&(this.addChild(new Spacer(1)),this.addChild(new Text(theme.fg("text",description),1,0))),this.addChild(new Spacer(1)),this.editor=new Editor(tui,getEditorTheme(),editorOptions),prefill&&this.editor.setText(prefill),this.editor.onSubmit=text=>{this.onSubmitCallback(text)},this.addChild(this.editor),this.addChild(new Spacer(1));let hint=keyHint("tui.select.confirm","submit")+"  "+keyHint("tui.input.newLine","newline")+"  "+keyHint("tui.select.cancel","cancel")+`  ${keyHint("app.editor.external","external editor")}`;this.addChild(new Text(hint,1,0)),this.addChild(new Spacer(1)),this.addChild(new DynamicBorder)}handleInput(keyData){if(getKeybindings().matches(keyData,"tui.select.cancel")){this.onCancelCallback();return}if(this.keybindings.matches(keyData,"app.editor.external")){this.handleOpenExternalEditor();return}this.editor.handleInput(keyData)}async handleOpenExternalEditor(){let content=this.editor.getText();this.tui.stop(),restoreInteractiveStderr();try{let result=await editInExternalEditor({command:this.externalEditorCommand,content});result.status==="complete"&&this.editor.setText(result.content)}finally{takeOverInteractiveStderr(),this.tui.start(),this.tui.requestRender(!0)}}};function createChatViewport(options){let transcript=new ScrollView(options.document,{follow:"end",primary:!0,overscroll:"chain",scrollbar:options.scrollbar??"auto",...options.scrollbarTrackStyle===void 0?{}:{scrollbarTrackStyle:options.scrollbarTrackStyle},...options.scrollbarThumbStyle===void 0?{}:{scrollbarThumbStyle:options.scrollbarThumbStyle}}),dock=new VStack([{component:options.pendingMessages,shrink:1,minSize:0},{component:options.status,shrink:1,minSize:0},...options.hookStatus===void 0?[]:[{component:options.hookStatus,shrink:1,minSize:0}],...options.widgetsAbove===void 0?[]:[{component:options.widgetsAbove,shrink:1,minSize:0}],{component:options.editor,shrink:1,minSize:3},...options.widgetsBelow===void 0?[]:[{component:options.widgetsBelow,shrink:1,minSize:0}],{component:options.footer,shrink:1,minSize:0}]);return{transcript,root:new VStack([{component:transcript,basis:0,grow:1,shrink:1,minSize:1},{component:dock,basis:"auto",grow:0,shrink:1,minSize:1}])}}function configuredPadding(padding){return Number.isFinite(padding)?Math.max(0,Math.floor(padding??0)):0}var CustomEditor=class extends Editor{constructor(tui,theme2,keybindings,options){let configuredPaddingX=configuredPadding(options?.paddingX),promptPaddingX=Math.max(2,configuredPaddingX);super(tui,theme2,{...options,paddingX:promptPaddingX}),this.actionHandlers=new Map,this.keybindings=keybindings,this.configuredPaddingX=configuredPaddingX,this.promptPaddingX=promptPaddingX,this.embedWorkingStatus=options?.embedWorkingStatus??!1}getPaddingX(){return this.configuredPaddingX}setPaddingX(padding){this.configuredPaddingX=configuredPadding(padding),this.promptPaddingX=Math.max(2,this.configuredPaddingX),super.setPaddingX(this.promptPaddingX)}render(width){let lines=super.render(width);return width<5||lines[0]?.includes("\u2191")?lines:lines.map((line,index)=>index===1?`${this.borderColor("\u276F")} ${line.slice(this.promptPaddingX)}`:line)}setWorkingStatusIndicator(indicator){this.workingStatusIndicator=indicator}setReplyLabel(label){this.replyLabel=label}renderTopBorder(width,hiddenLineCount){if(this.replyLabel&&width>=5){let label=truncateToWidth(this.replyLabel,width-4,"\u2026");return this.borderColor("\u2500\u2500 ")+label+this.borderColor(` ${"\u2500".repeat(Math.max(0,width-visibleWidth(label)-4))}`)}if(!this.embedWorkingStatus||!this.workingStatusIndicator||width<=0)return super.renderTopBorder(width,hiddenLineCount);let status=this.workingStatusIndicator.renderInBorder(Math.max(1,width-5)),statusWidth=visibleWidth(status);if(statusWidth===0)return super.renderTopBorder(width,hiddenLineCount);let overflowLabel=hiddenLineCount>0?` \u2191 ${hiddenLineCount} more `:void 0,overflowLabelWidth=overflowLabel?visibleWidth(overflowLabel):0,overflowStart=Math.floor((width-overflowLabelWidth)/2),canFitOverflow=()=>overflowLabel!==void 0&&overflowLabelWidth+2<=width&&overflowStart-(3+statusWidth+1)>=1;if(overflowLabel&&!canFitOverflow()&&(status=this.workingStatusIndicator.renderSpinnerInBorder(width),statusWidth=visibleWidth(status)),canFitOverflow()){let leftBlockWidth=3+statusWidth+1;return this.borderColor("\u2500\u2500 ")+status+this.borderColor(` ${"\u2500".repeat(overflowStart-leftBlockWidth)}${overflowLabel}${"\u2500".repeat(width-overflowStart-overflowLabelWidth)}`)}if(width>=statusWidth+5)return this.borderColor("\u2500\u2500 ")+status+this.borderColor(` ${"\u2500".repeat(width-statusWidth-4)}`);status=this.workingStatusIndicator.renderSpinnerInBorder(width),statusWidth=visibleWidth(status);let prefixWidth=Math.min(3,Math.max(0,width-statusWidth));return this.borderColor("\u2500".repeat(prefixWidth))+status+this.borderColor("\u2500".repeat(Math.max(0,width-prefixWidth-statusWidth)))}onAction(action,handler){this.actionHandlers.set(action,handler)}handleInput(data){if(!this.onExtensionShortcut?.(data)){if(this.keybindings.matches(data,"app.clipboard.pasteImage")||data==="\x1B[200~\x1B[201~"&&isWarpWslSession()){this.onPasteImage?.();return}if(this.keybindings.matches(data,"app.interrupt")){if(!this.isShowingAutocomplete()){let handler=this.onEscape??this.actionHandlers.get("app.interrupt");if(handler){handler();return}}super.handleInput(data);return}if(this.keybindings.matches(data,"app.exit")&&this.getText().length===0){let handler=this.onCtrlD??this.actionHandlers.get("app.exit");handler&&handler();return}if(this.keybindings.matches(data,"tui.editor.historyPrevious")||this.keybindings.matches(data,"tui.editor.historyNext")){super.handleInput(data);return}for(let[action,handler]of this.actionHandlers)if(action!=="app.interrupt"&&action!=="app.exit"&&this.keybindings.matches(data,action)){handler();return}super.handleInput(data)}}};function describedProviderError(message){return message.errorCause?.type==="usage_limit"&&message.errorCause.scope==="account"?message.errorMessage:describeProviderFailureForUser(message.errorMessage,{model:`${message.provider}/${message.model}`,usageLimit:usageLimitScope(message)})}function endsInTextRun(message){return message.content.some(content=>content.type==="toolCall")&&message.content.at(-1)?.type!=="toolCall"}function headNoticeShownElsewhere(message){return endsInTextRun(message)}function failureAlreadyDescribed(messages){let last=messages.findLast(message=>message.role==="assistant");return last?.role!=="assistant"||last.stopReason!=="error"||last.content.at(-1)?.type==="toolCall"||last.diagnostics?.some(entry=>entry.type===SERVER_FALLBACK_ABORTED_DIAGNOSTIC)?!1:describedProviderError(last)!==void 0}var REQUIRED_COMPACTION_INTERACTIVE_MESSAGE="Context remains above the compaction threshold because compaction did not complete. Run /compact to retry, or /new to start a fresh session.";function interactiveErrorText(errorMessage){return errorMessage===REQUIRED_COMPACTION_ERROR_MESSAGE?REQUIRED_COMPACTION_INTERACTIVE_MESSAGE:errorMessage}function formatDuration(ms){return ms<1e3?`${ms}ms`:ms<6e4?`${(ms/1e3).toFixed(1)}s`:ms<36e5?`${Math.floor(ms/6e4)}m ${Math.floor(ms%6e4/1e3)}s`:ms<864e5?`${Math.floor(ms/36e5)}h ${Math.floor(ms%36e5/6e4)}m`:`${Math.floor(ms/864e5)}d ${Math.floor(ms%864e5/36e5)}h`}function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readRecord(record,key){let value=record?.[key];return isRecord2(value)?value:void 0}function readArray(record,key){let value=record?.[key];return Array.isArray(value)?value:[]}function readString(record,key){let value=record?.[key];return typeof value=="string"?value:void 0}function readStringArray(record,key){return readArray(record,key).filter(value=>typeof value=="string")}function formatProviderName(message){return message.provider?`${message.provider} \xB7 `:""}function pluralize(count,singular,plural=`${singular}s`){return`${count} ${count===1?singular:plural}`}function shorten(value,max){return value.length<=max?value:`${value.slice(0,max-1)}\u2026`}function quoted(value){return JSON.stringify(value)}function unique(values){return[...new Set(values)]}function getWebSearchResults(raw){if(!(!isRecord2(raw)||!Array.isArray(raw.content)))return raw.content.filter(isRecord2).filter(item=>readString(item,"type")==="web_search_result")}function sourceFromRecord(record){if(!record)return;let title=readString(record,"title")??readString(record,"name"),url=readString(record,"url")??readString(record,"uri")??readString(record,"retrievedUrl")??readString(record,"sourceUrl"),snippet=readString(record,"snippet")??readString(record,"text")??readString(record,"summary")??readString(record,"page_age"),status=readString(record,"status")??readString(record,"urlRetrievalStatus");if(!(!title&&!url&&!snippet&&!status))return{...title&&{title},...url&&{url},...snippet&&{snippet},...status&&{status}}}function sourceFromGoogleGroundingChunk(record){return sourceFromRecord(readRecord(record,"web")??record)}function formatQueries(queries){let values=unique(queries);return values.length===0?[]:values.length===1?[`query: ${quoted(values[0])}`]:["queries:",...values.map(query=>`- ${quoted(query)}`)]}function formatSources(sources,label,expanded){if(sources.length===0)return[];let visibleSources=expanded?sources:sources.slice(0,3),lines=[pluralize(sources.length,label)];for(let source of visibleSources){let title=source.title?shorten(source.title,100):void 0,url=source.url?shorten(source.url,120):void 0,status=source.status?` (${source.status})`:"";title&&url?lines.push(`${title} ${url}${status}`):title?lines.push(`${title}${status}`):url?lines.push(`${url}${status}`):source.status&&lines.push(source.status),source.snippet&&lines.push(`  ${shorten(source.snippet,160)}`)}return!expanded&&sources.length>visibleSources.length&&lines.push(`\u2026 ${sources.length-visibleSources.length} more ${label}s`),lines}function base64ByteLength(value){let padding=value.endsWith("==")?2:value.endsWith("=")?1:0;return Math.max(0,Math.floor(value.length/4)*3-padding)}function formatImageGenerationCallBody(raw){let record=isRecord2(raw)?raw:void 0;if(!record)return;let status=readString(record,"status"),result=readString(record,"result"),revisedPrompt=readString(record,"revised_prompt"),lines=[...status?[`status: ${status}`]:[],...result?[`${base64ByteLength(result)} bytes`]:[],...revisedPrompt?.trim()?[`revised prompt: ${shorten(revisedPrompt,200)}`]:[]];return lines.length>0?lines.join(`
`):void 0}function formatServerToolUseBody(raw){let record=isRecord2(raw)?raw:void 0,input=readRecord(record,"input"),query=readString(input,"query");if(query)return`query: ${quoted(query)}`;let name=readString(record,"name");if(name)return`name: ${name}`}function formatToolSearchResultBody(raw,expanded){let content=readRecord(isRecord2(raw)?raw:void 0,"content");if(!content)return;let errorCode=readString(content,"error_code");if(errorCode){let message=readString(content,"error_message");return message?`${errorCode}: ${shorten(message,200)}`:errorCode}let names=unique(readArray(content,"tool_references").flatMap(reference2=>{let name=readString(isRecord2(reference2)?reference2:void 0,"tool_name");return name?[name]:[]}));if(names.length===0)return"0 tools";let visible=expanded?names:names.slice(0,10),lines=[pluralize(names.length,"tool"),...visible.map(name=>shorten(name,100))];return names.length>visible.length&&lines.push(`\u2026 ${names.length-visible.length} more tools`),lines.join(`
`)}function formatAnthropicWebSearchResultBody(raw,expanded){let results=getWebSearchResults(raw);if(!results)return;if(results.length===0)return"0 results";let sources=results.flatMap(result=>{let source=sourceFromRecord(result);return source?[source]:[]});return formatSources(sources,"result",expanded).join(`
`)}function formatOpenAiWebSearchCallBody(raw,expanded){let record=isRecord2(raw)?raw:void 0;if(!record)return;let action=readRecord(record,"action"),status=readString(record,"status"),queries=[...readString(action,"query")?[readString(action,"query")]:[],...readStringArray(action,"queries")],sources=readArray(action,"sources").flatMap(rawSource=>{let source=sourceFromRecord(isRecord2(rawSource)?rawSource:void 0);return source?[source]:[]}),lines=[...status?[`status: ${status}`]:[],...formatQueries(queries),...formatSources(sources,"source",expanded)];return lines.length>0?lines.join(`
`):void 0}function formatGoogleGroundingMetadataBody(raw,expanded){let record=isRecord2(raw)?raw:void 0;if(!record)return;let queries=readStringArray(record,"webSearchQueries"),sources=readArray(record,"groundingChunks").flatMap(rawChunk=>{let source=isRecord2(rawChunk)?sourceFromGoogleGroundingChunk(rawChunk):void 0;return source?[source]:[]}),lines=[...formatQueries(queries),...formatSources(sources,"source",expanded)];return lines.length>0?lines.join(`
`):void 0}function formatGoogleUrlContextMetadataBody(raw,expanded){let record=isRecord2(raw)?raw:void 0;if(!record)return;let sources=readArray(record,"urlMetadata").flatMap(rawUrl=>{let source=sourceFromRecord(isRecord2(rawUrl)?rawUrl:void 0);return source?[source]:[]}),lines=formatSources(sources,"url",expanded);return lines.length>0?lines.join(`
`):void 0}function formatSpecializedProviderNativeSummary(message,content,expanded){let provider=formatProviderName(message),marker=expanded?"\u25BE":"\u25B8";if(content.subtype==="server_tool_use"){let raw=isRecord2(content.raw)?content.raw:void 0,name=readString(raw,"name");if(name)return`${marker} ${provider}${name} \xB7 server_tool_use`}if(content.subtype==="web_search_tool_result")return`${marker} ${provider}web_search results`;if(content.subtype==="tool_search_tool_result")return`${marker} ${provider}tool_search results`;if(content.subtype==="web_search_call"){let raw=isRecord2(content.raw)?content.raw:void 0,status=readString(raw,"status");return`${marker} ${provider}web_search${status?` \xB7 ${status}`:" \xB7 web_search_call"}`}if(content.subtype==="image_generation_call"){let raw=isRecord2(content.raw)?content.raw:void 0,status=readString(raw,"status");return`${marker} ${provider}image_generation${status?` \xB7 ${status}`:" \xB7 image_generation_call"}`}if(content.subtype==="groundingMetadata"&&formatGoogleGroundingMetadataBody(content.raw,expanded))return`${marker} ${provider}google_search results`;if(content.subtype==="urlContextMetadata"&&formatGoogleUrlContextMetadataBody(content.raw,expanded))return`${marker} ${provider}url_context results`}function formatSpecializedProviderNativeBody(content,expanded){if(content.subtype==="server_tool_use")return formatServerToolUseBody(content.raw);if(content.subtype==="web_search_tool_result")return formatAnthropicWebSearchResultBody(content.raw,expanded);if(content.subtype==="tool_search_tool_result")return formatToolSearchResultBody(content.raw,expanded);if(content.subtype==="web_search_call")return formatOpenAiWebSearchCallBody(content.raw,expanded);if(content.subtype==="image_generation_call")return formatImageGenerationCallBody(content.raw);if(content.subtype==="groundingMetadata")return formatGoogleGroundingMetadataBody(content.raw,expanded);if(content.subtype==="urlContextMetadata")return formatGoogleUrlContextMetadataBody(content.raw,expanded)}function stringifyProviderNative(raw){try{return JSON.stringify(raw,null,2)??"null"}catch{return String(raw)}}function formatProviderNativeSummary(message,content,expanded){let specialized=formatSpecializedProviderNativeSummary(message,content,expanded);if(specialized)return specialized;let provider=formatProviderName(message);return`${expanded?"\u25BE":"\u25B8"} ${provider}providerNative \xB7 ${content.subtype}`}function formatProviderNativeBody(content,expanded){let specialized=formatSpecializedProviderNativeBody(content,expanded);if(specialized)return specialized;let rawJson=stringifyProviderNative(content.raw);return expanded||rawJson.length<=2e3?rawJson:`${rawJson.slice(0,2e3)}\u2026`}var LABEL=/(?:\*{1,2})?\b(Ask|wanted|For you|You need|Now|Next)(?:\*{1,2})?\s*[:\uFF1A](?:\*{1,2})?/gu,CLAUDE_SHAPES=["Ask,wanted,For you,Now,Next","Ask,For you,Now,Next"],GPT_SHAPE="You need,Now,Next";function labelsOf(paragraph){return[...paragraph.matchAll(LABEL)].map(match=>({label:match[1]??"",start:match.index??0,end:(match.index??0)+match[0].length}))}function slot(paragraph,hits,label){let at=hits.findIndex(hit=>hit.label===label);if(at<0)return;let start=hits[at]?.end??0,end=hits[at+1]?.start??paragraph.length,text=paragraph.slice(start,end).trim().replace(/\s+-$/u,"");return text===""?void 0:text}function parseHandoff(paragraph){let hits=labelsOf(paragraph),shape=hits.map(hit=>hit.label).join(","),block={kind:"handoff",block:paragraph,now:slot(paragraph,hits,"Now"),next:slot(paragraph,hits,"Next")};if(CLAUDE_SHAPES.includes(shape))return paragraph.slice(0,hits[0]?.start??0).trim()!==""?void 0:{...block,answer:slot(paragraph,hits,"For you")};if(shape!==GPT_SHAPE)return;let outcome=paragraph.slice(0,hits[0]?.start??0).trim();if(outcome==="")return;let needs=slot(paragraph,hits,"You need");return{...block,answer:needs===void 0?outcome:`${outcome} ${needs}`}}function splitHandoffBlocks(text){let paragraphs=text.split(/\n[ \t]*\n/u),segments=[],prose=[],inFence=!1,flush=()=>{let joined=prose.join(`

`).trim();joined!==""&&segments.push({kind:"text",text:joined}),prose=[]};for(let paragraph of paragraphs){let fences=paragraph.match(/^\s*(?:```|~~~)/gmu)?.length??0,handoff=!inFence&&fences===0?parseHandoff(paragraph.trim()):void 0;if(fences%2===1&&(inFence=!inFence),!handoff){prose.push(paragraph);continue}flush(),segments.push(handoff)}return flush(),segments}var SPACER_DESCRIPTOR={kind:"spacer",text:""};function assertNever(value){throw new TypeError(`Unexpected assistant render variant: ${String(value)}`)}function pushHandoffDescriptors(descriptors,segment,handoffBlock,open){if(open){descriptors.push({kind:"handoff-line",text:theme.fg("dim","\u25BE Handoff"),handoffBlock},{kind:"handoff-body",text:theme.fg("dim",segment.block),handoffBlock});return}let parts=[segment.now===void 0?void 0:`Now: ${segment.now}`,segment.next===void 0?void 0:`Next: ${segment.next}`].filter(part=>part!==void 0);descriptors.push({kind:"handoff-line",text:theme.fg("dim",["\u25B8 Handoff",...parts].join(" \xB7 ")),handoffBlock}),segment.answer!==void 0&&descriptors.push(SPACER_DESCRIPTOR,{kind:"text-md",text:segment.answer})}function isVisibleContent(content,providerNativeVisible){switch(content.type){case"text":return!!content.text.trim();case"thinking":return!!content.thinking.trim();case"providerNative":return providerNativeVisible;case"toolCall":return!1;default:return assertNever(content)}}function createAssistantRenderDescriptors(message,options){let descriptors=[];message.content.some(content=>isVisibleContent(content,!0))&&descriptors.push(SPACER_DESCRIPTOR);let thinkingRunIndex=0,handoffBlockIndex=0;for(let i=0;i<message.content.length;i++){let content=message.content[i];switch(content.type){case"text":{let text=content.text.trim();if(!text)break;splitHandoffBlocks(text).forEach((segment,at)=>{if(at>0&&descriptors.push(SPACER_DESCRIPTOR),segment.kind==="text"){descriptors.push({kind:"text-md",text:segment.text});return}let handoffBlock=handoffBlockIndex++,open=options.handoffOpenOverrides?.get(handoffBlock)??options.expanded;pushHandoffDescriptors(descriptors,segment,handoffBlock,open)});break}case"thinking":{let thinkingBlocks=[],hasTiming=!1,isDone=!0,minStart=Number.POSITIVE_INFINITY,maxEnd=Number.NEGATIVE_INFINITY;for(;i<message.content.length;i++){let thinkingContent=message.content[i];if(thinkingContent.type!=="thinking")break;let startedAt=thinkingContent.startedAt;if(startedAt!==void 0){hasTiming=!0,minStart=Math.min(minStart,startedAt);let endedAt=thinkingContent.endedAt;endedAt===void 0?isDone=!1:maxEnd=Math.max(maxEnd,endedAt)}let thinking=thinkingContent.thinking.trim();thinking&&thinkingBlocks.push(thinking)}if(i--,thinkingBlocks.length===0)break;let thinkingRun=thinkingRunIndex++,hidden=options.thinkingVisibilityOverrides?.get(thinkingRun)??options.hideThinkingBlock;if(hasTiming){let label=isDone?theme.italic(theme.fg("thinkingText",`Thought: ${formatDuration(Math.max(0,maxEnd-minStart))}`)):theme.italic(theme.fg("thinkingText",options.hiddenThinkingLabel));hidden?descriptors.push({kind:"thinking-label",text:label,thinkingRun}):descriptors.push({kind:"thinking-label",text:label,thinkingRun},{kind:"thinking-md",text:thinkingBlocks.join(`

`),thinkingRun})}else{let text=hidden?theme.italic(theme.fg("thinkingText",options.hiddenThinkingLabel)):thinkingBlocks.join(`

`);descriptors.push({kind:hidden?"thinking-label":"thinking-md",text,thinkingRun})}message.content.slice(i+1).some(following=>isVisibleContent(following,!1))&&descriptors.push(SPACER_DESCRIPTOR);break}case"providerNative":descriptors.push({kind:"provider-native-summary",text:theme.fg("muted",formatProviderNativeSummary(message,content,options.expanded))},{kind:"provider-native-body",text:theme.fg("dim",formatProviderNativeBody(content,options.expanded))}),message.content.slice(i+1).some(following=>isVisibleContent(following,!0))&&descriptors.push(SPACER_DESCRIPTOR);break;case"toolCall":break;default:assertNever(content)}}let addError=text=>{descriptors.push(SPACER_DESCRIPTOR,{kind:"error-text",text:theme.fg("error",text)})};switch(message.stopReason){case"length":if(options.providerErrorOwned)break;addError("Error: Model stopped because it reached the maximum output token limit. The response may be incomplete.");break;case"aborted":{if(options.hasToolCalls&&!options.ownsTurnNotice||options.providerErrorOwned)break;let abortMessage=message.errorMessage&&message.errorMessage!=="Request was aborted"?stripTurnRetrySuppressionPrefix(message.errorMessage):"Operation aborted";addError(abortMessage);break}case"error":{if(options.hasToolCalls&&!options.ownsTurnNotice||options.providerErrorOwned||message.diagnostics?.some(entry=>entry.type===SERVER_FALLBACK_ABORTED_DIAGNOSTIC))break;let described=describedProviderError(message),commandHint=stripTurnRetrySuppressionPrefix(message.errorMessage??"").startsWith("Provider is not configured: ")?" Use /login to connect it, or /model to choose another model.":usageLimitScope(message)==="account"?message.provider==="anthropic"?" Use /login to connect Anthropic Subscription, or /model to choose another provider.":described?.includes(ACCOUNT_LIMIT_NEXT_STEP_LEAD)?"":" Use /model to choose another provider.":"";addError(described===void 0?`Error: ${interactiveErrorText(stripTurnRetrySuppressionPrefix(message.errorMessage??""))||"Unknown error"}`:`${described}${commandHint}`);break}case"pending":case"stop":case"toolUse":case"deferred":break;default:assertNever(message.stopReason)}return descriptors}function createMarkdownTransform(messageType,isStreaming,transformers){return(markdown,availableWidth)=>applyMarkdownTransformers(markdown,{messageType,isStreaming,availableWidth},transformers)}function applyMarkdownTransformers(markdown,context,transformers){let transformedMarkdown=markdown;for(let transformer of transformers)try{let transformed=transformer(transformedMarkdown,context);typeof transformed=="string"&&(transformedMarkdown=transformed)}catch{}return transformedMarkdown}function createBoundedRenderSignature(value){return JSON.stringify(summarizeSignatureValue(value))}function summarizeSignatureString(text){if(text.length<=160)return text;let sample=sampleSignatureString(text);return`[string length=${text.length} hash=${hashSignatureString(sample)}]`}function sampleSignatureString(text){let first=text.slice(0,64),last=text.slice(-64),middleStart=Math.max(0,Math.floor((text.length-64)/2)),quarterStart=Math.max(0,Math.floor((text.length-64)/4)),threeQuarterStart=Math.max(0,Math.floor((text.length-64)*3/4));return[first,text.slice(quarterStart,quarterStart+64),text.slice(middleStart,middleStart+64),text.slice(threeQuarterStart,threeQuarterStart+64),last].join("\0")}function updateSignatureHash(hash,source){for(let index=0;index<source.length;index++)hash^=source.charCodeAt(index),hash=Math.imul(hash,16777619);return hash}function formatSignatureHash(hash){return(hash>>>0).toString(36)}function hashSignatureString(source){return formatSignatureHash(updateSignatureHash(2166136261,source))}function hashSignatureEntry(hash,key,value,seen,serializerKey=key){let summarized=summarizeSignatureValue(value,serializerKey,1,seen);return updateSignatureHash(hash,JSON.stringify([key,summarized]))}function hashSignatureArrayTail(tail,seen){let hash=2166136261;for(let offset=0;offset<tail.length;offset++){let key=String(40+offset);if(!(offset in tail)){hash=updateSignatureHash(hash,JSON.stringify([key,null]));continue}hash=hashSignatureEntry(hash,key,tail[offset],seen,String(offset%40))}return formatSignatureHash(hash)}function hashSignatureEntries(entries,seen){let hash=2166136261;for(let[key,value]of entries)hash=hashSignatureEntry(hash,key,value,seen);return formatSignatureHash(hash)}function summarizeSignatureValue(value,key="",depth=0,seen=new WeakSet){if(typeof value=="string")return summarizeSignatureString(value);if(typeof value=="number"||typeof value=="boolean"||value===null)return value;if(typeof value>"u")return"[undefined]";if(typeof value=="bigint")return`[bigint ${value.toString()}]`;if(typeof value=="symbol")return`[symbol ${value.description??""}]`;if(typeof value=="function")return`[function ${value.name}]`;if(seen.has(value))return"[circular]";if(depth>=8)return Array.isArray(value)?`[array depth-limit length=${value.length}]`:"[object depth-limit]";seen.add(value);let jsonValue=hasJsonSerializer(value)?value.toJSON(key):value;if(jsonValue!==value){let summarized2=summarizeSignatureValue(jsonValue,key,depth,seen);return seen.delete(value),summarized2}if(Array.isArray(value)){let summarized2=value.slice(0,40).map((item,index)=>summarizeSignatureValue(item,String(index),depth+1,seen));if(value.length>40){let tail=value.slice(40),tailHash=hashSignatureArrayTail(tail,seen);return seen.delete(value),[...summarized2,`[+${tail.length} items hash=${tailHash}]`]}return seen.delete(value),summarized2}let summarized={},entries=Object.entries(value).sort(([left],[right])=>left.localeCompare(right));for(let[key2,item]of entries.slice(0,80))summarized[key2]=summarizeSignatureValue(item,key2,depth+1,seen);if(entries.length>80){let omitted=entries.slice(80);summarized.__truncatedKeys=`[+${omitted.length} keys hash=${hashSignatureEntries(omitted,seen)}]`}return seen.delete(value),summarized}function hasJsonSerializer(value){return"toJSON"in value&&typeof value.toJSON=="function"}var OSC133_ZONE_START="\x1B]133;A\x07",OSC133_ZONE_END="\x1B]133;B\x07",OSC133_ZONE_FINAL="\x1B]133;C\x07";function assertNever2(value){throw new TypeError(`Unexpected assistant render variant: ${String(value)}`)}var SingleLine=class{constructor(text,pad){this.revision=nextRenderRevision(),this.text=text,this.pad=pad}render(width){let room=Math.max(1,width-this.pad);return[`${" ".repeat(this.pad)}${truncateToWidth(this.text,room)}`]}invalidate(){}getRenderRevision(){return this.revision}},AssistantMessageComponent=class extends Container{constructor(message,hideThinkingBlock=!1,markdownTheme=sharedMarkdownTheme(),hiddenThinkingLabel="Thinking...",outputPad=1,markdownTransformers=[]){super(),this.renderDescriptors=[],this.hasToolCalls=!1,this.expanded=!1,this.providerErrorOwned=!1,this.ownsTurnNotice=!1,this.isStreaming=!1,this.thinkingVisibilityOverrides=new Map,this.handoffOpenOverrides=new Map,this.revision=nextRenderRevision(),this.hideThinkingBlock=hideThinkingBlock,this.markdownTheme=markdownTheme,this.hiddenThinkingLabel=hiddenThinkingLabel,this.outputPad=outputPad,this.markdownTransformers=markdownTransformers,this.contentContainer=new Container,this.addChild(this.contentContainer),message&&this.updateContent(message)}invalidate(){this.renderCache=void 0,this.revision=nextRenderRevision(),super.invalidate(),this.renderDescriptors=[],this.refreshContent()}setHideThinkingBlock(hide){this.hideThinkingBlock!==hide&&(this.hideThinkingBlock=hide,this.thinkingVisibilityOverrides.clear(),this.refreshContent())}setHiddenThinkingLabel(label){this.hiddenThinkingLabel!==label&&(this.hiddenThinkingLabel=label,this.refreshContent())}setExpanded(expanded){this.expanded!==expanded&&(this.expanded=expanded,this.handoffOpenOverrides.clear(),this.refreshContent())}setOwnsTurnNotice(owned){this.ownsTurnNotice!==owned&&(this.ownsTurnNotice=owned,this.refreshContent())}setProviderErrorOwned(owned){this.providerErrorOwned!==owned&&(this.providerErrorOwned=owned,this.refreshContent())}get isExplorationDetail(){return this.renderDescriptors.every(part=>part.kind==="spacer"||part.kind==="thinking-label")}setOutputPad(padding){this.outputPad=padding,this.renderDescriptors=[],this.refreshContent()}getRenderRevision(){return this.revision}render(width){let signature=this.lastMessageSignature??"";if(this.renderCache?.width===width&&this.renderCache.signature===signature)return copyLineSources(this.renderCache.lines,[...this.renderCache.lines]);let lines=super.render(width);return this.hasToolCalls||lines.length===0?(this.cacheRender(width,signature,lines),lines):(lines[0]=OSC133_ZONE_START+lines[0],lines[lines.length-1]=OSC133_ZONE_END+OSC133_ZONE_FINAL+lines[lines.length-1],this.cacheRender(width,signature,lines),lines)}updateContent(message,isStreaming=this.isStreaming){let previousMessage=this.lastMessage,streamingChanged=this.isStreaming!==isStreaming;this.isStreaming=isStreaming,this.lastMessage=message;let messageSignature=this.createMessageSignature(message);if(!streamingChanged&&previousMessage===message&&this.lastMessageSignature===messageSignature)return;this.lastMessageSignature=messageSignature,this.renderCache=void 0,this.revision=nextRenderRevision(),streamingChanged&&(this.renderDescriptors=[]),this.hasToolCalls=message.content.some(content=>content.type==="toolCall");let descriptors=createAssistantRenderDescriptors(message,{expanded:this.expanded,providerErrorOwned:this.providerErrorOwned,hiddenThinkingLabel:this.hiddenThinkingLabel,hideThinkingBlock:this.hideThinkingBlock,thinkingVisibilityOverrides:this.thinkingVisibilityOverrides,handoffOpenOverrides:this.handoffOpenOverrides,hasToolCalls:this.hasToolCalls,ownsTurnNotice:this.ownsTurnNotice});this.reconcileRenderDescriptors(descriptors)}reconcileRenderDescriptors(descriptors){let divergentIndex=0,sharedLength=Math.min(this.renderDescriptors.length,descriptors.length);for(;divergentIndex<sharedLength;){let previous=this.renderDescriptors[divergentIndex],next=descriptors[divergentIndex],child=this.contentContainer.children[divergentIndex];if(!previous||!next||!child||previous.kind!==next.kind)break;if(previous.text!==next.text)if((next.kind==="text-md"||next.kind==="thinking-md")&&child instanceof Markdown)child.setText(next.text);else break;divergentIndex++}for(let child of this.contentContainer.children.splice(divergentIndex))child.dispose?.();for(let descriptor of descriptors.slice(divergentIndex))this.contentContainer.addChild(this.createRenderChild(descriptor));this.renderDescriptors=descriptors}createRenderChild(descriptor){switch(descriptor.kind){case"spacer":return new Spacer(1);case"text-md":return new Markdown(descriptor.text,this.outputPad,0,this.markdownTheme,void 0,{transform:createMarkdownTransform("assistant",this.isStreaming,this.markdownTransformers)});case"thinking-md":return this.withThinkingToggle(new Markdown(descriptor.text,this.outputPad,0,this.markdownTheme,{color:text=>theme.fg("thinkingText",text),italic:!0},{transform:createMarkdownTransform("assistant-thinking",this.isStreaming,this.markdownTransformers)}),descriptor);case"thinking-label":return this.withThinkingToggle(new Text(descriptor.text,this.outputPad,0),descriptor);case"error-text":return new Text(descriptor.text,this.outputPad,0);case"provider-native-summary":return new Text(descriptor.text,1,0);case"provider-native-body":return new Text(descriptor.text,3,0);case"handoff-line":return this.withHandoffToggle(new SingleLine(descriptor.text,this.outputPad),descriptor);case"handoff-body":return this.withHandoffToggle(new Text(descriptor.text,this.outputPad,0),descriptor);default:return assertNever2(descriptor.kind)}}withThinkingToggle(component,descriptor){let runIndex=descriptor.thinkingRun;return runIndex===void 0||(component.handleMouse=event=>{if(event.type!=="click"||event.button!=="left")return;let hidden=this.thinkingVisibilityOverrides.get(runIndex)??this.hideThinkingBlock;return this.thinkingVisibilityOverrides.set(runIndex,!hidden),this.refreshContent(),{handled:!0}}),component}withHandoffToggle(component,descriptor){let block=descriptor.handoffBlock;return block===void 0||(component.handleMouse=event=>{if(event.type!=="click"||event.button!=="left")return;let open=this.handoffOpenOverrides.get(block)??this.expanded;return this.handoffOpenOverrides.set(block,!open),this.refreshContent(),{handled:!0}}),component}createMessageSignature(message){return createBoundedRenderSignature({content:message.content,hiddenThinkingLabel:this.hiddenThinkingLabel,hideThinkingBlock:this.hideThinkingBlock,thinkingVisibilityOverrides:[...this.thinkingVisibilityOverrides],handoffOpenOverrides:[...this.handoffOpenOverrides],expanded:this.expanded,errorState:[message.diagnostics,message.errorMessage],stopReason:message.stopReason})}cacheRender(width,signature,lines){this.renderCache={lines:copyLineSources(lines,[...lines]),signature,width}}refreshContent(){this.lastMessage&&(this.lastMessageSignature=void 0,this.updateContent(this.lastMessage))}};var ASK_USER_SETTLED_EVENT="ask-user:settled",ASK_USER_CLOSED_EVENT="ask-user:closed",ASK_USER_ASKED_EVENT="ask-user:asked",ASK_USER_QUESTION_ENTRY="ask-user:question",ASK_USER_SETTLEMENT_ENTRY="ask-user:settlement";function emitAskUserClosed(pi,requestId,response){pi.events.emit(ASK_USER_CLOSED_EVENT,{requestId,status:response.status,...response.resolvedBy!==void 0?{resolvedBy:response.resolvedBy}:{}})}function emitAskUserNotification(pi,ctx,request,response,variant){response.status!=="cancelled"&&pi.events.emit(ASK_USER_SETTLED_EVENT,{ctx,request,response,variant})}function ansiRegex({onlyFirst=!1}={}){let pattern="(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(pattern,onlyFirst?void 0:"g")}var regex=ansiRegex();function stripAnsi(value){if(typeof value!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof value}\``);return!value.includes("\x1B")&&!value.includes("\x9B")?value:value.replace(regex,"")}function getAskUserAnswerHeaders(entries,requestId){for(let index=entries.length-1;index>=0;index--){let entry=entries[index];if(entry.type!=="custom"||entry.customType!==ASK_USER_QUESTION_ENTRY)continue;let data=entry.data;if(typeof data!="object"||data===null||!("requestId"in data)||data.requestId!==requestId||!("headers"in data)||!Array.isArray(data.headers))continue;return data.headers.filter(header=>typeof header=="string")}return[]}function summaryRows(frame,headers){let fallbackHeaders=headers.length>0?headers:[frame.requestId];if(/^(?:The user did not answer|The user dismissed|The pending question|This session has no user)/.test(frame.body))return fallbackHeaders.map(header=>`\u21B3 ${header}: (no answer)`);let answers=[],comment,unanswered=[],lines=frame.body.split(`
`),cancelledAt=lines.findIndex(isCancelledWithAnswersLine);for(let line of lines.slice(cancelledAt+1)){let separator=line.indexOf(": ");if(separator<1)continue;let header=line.slice(0,separator),value=line.slice(separator+2);header==="The user responded"?comment=value:header==="Unanswered"?unanswered=value.split(", "):answers.push(`\u21B3 ${header}: ${value}`)}return comment!==void 0?answers.push(`\u21B3 ${headers[0]??unanswered[0]??frame.requestId}: ${JSON.stringify(comment)}`):answers.push(...unanswered.map(header=>`\u21B3 ${header}: (no answer)`)),cancelledAt>=0&&answers.unshift("\u21B3 (cancelled)"),answers.length>0?answers:fallbackHeaders.map(header=>`\u21B3 ${header}: (no answer)`)}var AskUserAnswerChip=class extends MouseRegion{constructor(frame,headers,fullBody){let rows=summaryRows(frame,headers).map(row=>stripAnsi(row).replace(/\s+/g," ")),summary={render:width=>rows.map(row=>theme.fg("muted",truncateToWidth(row,width,"\u2026"))),invalidate(){}},content=new Container;content.addChild(summary);let expanded=!1;super(content,event=>{if(event.button==="left"){if(event.type==="press")return{handled:!0,render:!1};if(!(event.type!=="click"||(event.clickCount??1)!==1))return expanded=!expanded,content.detachAll(),content.addChild(expanded?fullBody:summary),{handled:!0}}}),this.fullBody=fullBody}invalidate(){super.invalidate(),this.fullBody.invalidate()}dispose(){this.fullBody.dispose?.()}};var OSC133_ZONE_START2="\x1B]133;A\x07",OSC133_ZONE_END2="\x1B]133;B\x07",OSC133_ZONE_FINAL2="\x1B]133;C\x07",UserMessageComponent=class extends Container{constructor(text,markdownTheme=sharedMarkdownTheme(),outputPad=1,markdownTransformers=[],answerHeaders=[]){super(),this.text=text,this.markdownTheme=markdownTheme,this.outputPad=outputPad,this.markdownTransformers=markdownTransformers,this.answerHeaders=answerHeaders,this.rebuild()}setOutputPad(padding){this.outputPad=padding,this.rebuild()}rebuild(){this.clear();let contentBox=new Markdown(this.text,this.outputPad,1,this.markdownTheme,{color:content=>theme.fg("userMessageText",content),bgColor:content=>theme.bg("userMessageBg",content)},{preserveOrderedListMarkers:!0,preserveBackslashEscapes:!0,transform:createMarkdownTransform("user",!1,this.markdownTransformers)}),answer=parseAskUserAnswerFrame(this.text);this.addChild(answer?new AskUserAnswerChip(answer,this.answerHeaders,contentBox):contentBox)}getRenderRevision(){return this.childRenderRevision()}render(width){let lines=super.render(width);return lines.length===0?lines:lines.length===1?(lines[0]=OSC133_ZONE_START2+lines[0]+OSC133_ZONE_END2+OSC133_ZONE_FINAL2,lines):(lines[0]=OSC133_ZONE_START2+lines[0],lines[lines.length-1]=OSC133_ZONE_END2+OSC133_ZONE_FINAL2+lines[lines.length-1],lines)}};import{spawn as spawn3}from"node:child_process";function openBrowser(target){let[cmd,args]=process.platform==="darwin"?["open",[target]]:process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",target]]:["xdg-open",[target]];spawn3(cmd,args,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}function createInteractiveTui(options){let terminal2=options.terminal??new ProcessTerminal({onExternalStdoutWrite:appendHiddenTuiStdout,observeExternalStderrWrites:observeVisibleStderrWrites});if(options.tuiMode==="fullscreen"){let styleSearchMatch=text=>theme.bg("searchMatchBg",theme.fg("searchMatchText",text));return new TuiAltScreen(terminal2,options.showHardwareCursor,options.logDirectory,{mouse:options.mouse,searchMatchStyle:text=>theme.underline(styleSearchMatch(text)),searchCurrentMatchStyle:text=>theme.bold(theme.inverse(styleSearchMatch(text))),searchNavigationButtonStyle:(text,hovered)=>hovered?theme.underline(text):text,scrollToEndIndicator:()=>{let shortcut=keyDisplayText("tui.altScreen.bottom"),label=` \u2193 Jump to latest message${shortcut?` \xB7 ${shortcut}`:""} `;return theme.bg("selectedBg",theme.fg("text",label))},openUrl:openBrowser,onRightClickPaste:options.onRightClickPaste,copyOnSelect:options.fullscreenCopyOnSelect,wheelScrollLines:options.fullscreenWheelScrollLines??"auto",copySelection:async text=>{try{return await copyToClipboard(text),!0}catch(error){return error instanceof Error?error.message:String(error)}}})}return new TuiMainScreen(terminal2,options.showHardwareCursor,options.logDirectory)}function createInteractiveTuiReference(getTui){return new Proxy({},{get:(_target,property)=>{let tui=getTui(),value=Reflect.get(tui,property,tui);if(typeof value!="function")return value;let methodTui=tui,method=value;return(...args)=>{let currentTui=getTui();if(currentTui!==methodTui){let currentMethod=Reflect.get(currentTui,property,currentTui);if(typeof currentMethod!="function")throw new TypeError(`TUI property ${String(property)} is not callable`);methodTui=currentTui,method=currentMethod}return Reflect.apply(method,methodTui,args)}},set:(_target,property,value)=>{let tui=getTui();return Reflect.set(tui,property,value,tui)},has:(_target,property)=>Reflect.has(getTui(),property),getPrototypeOf:()=>Reflect.getPrototypeOf(getTui())})}export{stripAnsi,CODEX_PARAMS,CLAUDE_PARAMS,DEFAULT_ASK_USER_TIMEOUT_MS,AskUserSchemaError,toCanonical,resolveUserWordReferences,showsPartialAnswers,formatGatedCancellation,formatResultText,formatModelAnswer,formatUserMessage,askUserAnswerDisplayText,parseAskUserAnswerFrame,formatResultDetails,REQUIRED_COMPACTION_ERROR_MESSAGE,RequiredCompactionError,openBrowser,ASK_USER_SETTLED_EVENT,ASK_USER_ASKED_EVENT,ASK_USER_QUESTION_ENTRY,ASK_USER_SETTLEMENT_ENTRY,emitAskUserClosed,emitAskUserNotification,runClipboardCommand,readClipboardText,readClipboardFilePaths,copyToClipboard,formatProviderNativeSummary,formatProviderNativeBody,AskUserCountdown,formatCountdownLabel,AskUserQuestionComponent,editInExternalEditor,editFileInExternalEditor,prepareInteractiveStderrCapture,takeOverInteractiveStderr,restoreInteractiveStderr,ExtensionEditorComponent,createChatViewport,CustomEditor,formatDuration,describedProviderError,headNoticeShownElsewhere,failureAlreadyDescribed,interactiveErrorText,createBoundedRenderSignature,AssistantMessageComponent,getAskUserAnswerHeaders,UserMessageComponent,createInteractiveTui,createInteractiveTuiReference};